Added support for WATCH list announcing in backup protocol.
[silc.git] / apps / silcd / packet_receive.c
1 /*
2
3   packet_receive.c
4
5   Author: Pekka Riikonen <priikone@silcnet.org>
6
7   Copyright (C) 1997 - 2005 Pekka Riikonen
8
9   This program is free software; you can redistribute it and/or modify
10   it under the terms of the GNU General Public License as published by
11   the Free Software Foundation; either version 2 of the License, or
12   (at your option) any later version.
13
14   This program is distributed in the hope that it will be useful,
15   but WITHOUT ANY WARRANTY; without even the implied warranty of
16   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17   GNU General Public License for more details.
18
19 */
20 /*
21  * Server packet routines to handle received packets.
22  */
23 /* $Id$ */
24
25 #include "serverincludes.h"
26 #include "server_internal.h"
27
28 /* Received notify packet. Server can receive notify packets from router.
29    Server then relays the notify messages to clients if needed. */
30
31 void silc_server_notify(SilcServer server,
32                         SilcSocketConnection sock,
33                         SilcPacketContext *packet)
34 {
35   SilcNotifyPayload payload;
36   SilcNotifyType type;
37   SilcArgumentPayload args;
38   SilcChannelID *channel_id = NULL, *channel_id2;
39   SilcClientID *client_id, *client_id2;
40   SilcServerID *server_id;
41   SilcIdType id_type;
42   SilcChannelEntry channel = NULL;
43   SilcClientEntry client = NULL, client2 = NULL;
44   SilcServerEntry server_entry = NULL;
45   SilcChannelClientEntry chl;
46   SilcIDCacheEntry cache = NULL;
47   SilcHashTableList htl;
48   SilcUInt32 mode;
49   unsigned char *tmp;
50   SilcUInt32 tmp_len;
51   bool local;
52
53   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
54       packet->src_id_type != SILC_ID_SERVER || !packet->dst_id) {
55     SILC_LOG_DEBUG(("Bad notify packet received"));
56     return;
57   }
58
59   /* If the packet is destined directly to a client then relay the packet
60      before processing it. */
61   if (packet->dst_id_type == SILC_ID_CLIENT) {
62     SilcIDListData idata;
63     SilcSocketConnection dst_sock;
64
65     /* Get the route to the client */
66     dst_sock = silc_server_get_client_route(server, packet->dst_id,
67                                             packet->dst_id_len, NULL,
68                                             &idata, NULL);
69     if (dst_sock)
70       /* Relay the packet */
71       silc_server_relay_packet(server, dst_sock, idata->send_key,
72                                idata->hmac_send, idata->psn_send++,
73                                packet, TRUE);
74   }
75
76   /* Parse the Notify Payload */
77   payload = silc_notify_payload_parse(packet->buffer->data,
78                                       packet->buffer->len);
79   if (!payload)
80     return;
81
82   /* If we are router and this packet is not already broadcast packet
83      we will broadcast it. The sending socket really cannot be router or
84      the router is buggy. If this packet is coming from router then it must
85      have the broadcast flag set already and we won't do anything. */
86   if (server->server_type == SILC_ROUTER &&
87       sock->type == SILC_SOCKET_TYPE_SERVER &&
88       !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
89     SILC_LOG_DEBUG(("Broadcasting received Notify packet"));
90     if (packet->dst_id_type == SILC_ID_CHANNEL) {
91       /* Packet is destined to channel */
92       channel_id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
93                                   packet->dst_id_type);
94       if (!channel_id)
95         goto out;
96
97       silc_server_packet_send_dest(server, SILC_PRIMARY_ROUTE(server),
98                                    packet->type, packet->flags |
99                                    SILC_PACKET_FLAG_BROADCAST,
100                                    channel_id, SILC_ID_CHANNEL,
101                                    packet->buffer->data,
102                                    packet->buffer->len, FALSE);
103       silc_server_backup_send_dest(server, sock->user_data,
104                                    packet->type, packet->flags,
105                                    channel_id, SILC_ID_CHANNEL,
106                                    packet->buffer->data, packet->buffer->len,
107                                    FALSE, TRUE);
108     } else {
109       /* Packet is destined to client or server */
110       silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
111                               packet->type,
112                               packet->flags | SILC_PACKET_FLAG_BROADCAST,
113                               packet->buffer->data, packet->buffer->len,
114                               FALSE);
115       silc_server_backup_send(server, sock->user_data,
116                               packet->type, packet->flags,
117                               packet->buffer->data, packet->buffer->len,
118                               FALSE, TRUE);
119     }
120   }
121
122   type = silc_notify_get_type(payload);
123   args = silc_notify_get_args(payload);
124   if (!args)
125     goto out;
126
127   switch(type) {
128   case SILC_NOTIFY_TYPE_JOIN:
129     /*
130      * Distribute the notify to local clients on the channel
131      */
132     SILC_LOG_DEBUG(("JOIN notify"));
133
134     if (channel_id)
135       silc_free(channel_id);
136
137     /* Get Channel ID */
138     tmp = silc_argument_get_arg_type(args, 2, &tmp_len);
139     if (!tmp)
140       goto out;
141     channel_id = silc_id_payload_parse_id(tmp, tmp_len, NULL);
142     if (!channel_id)
143       goto out;
144
145     /* Get channel entry */
146     channel = silc_idlist_find_channel_by_id(server->global_list,
147                                              channel_id, NULL);
148     if (!channel) {
149       channel = silc_idlist_find_channel_by_id(server->local_list,
150                                                channel_id, NULL);
151       if (!channel) {
152         SILC_LOG_DEBUG(("Notify for unknown channel"));
153         silc_free(channel_id);
154         goto out;
155       }
156     }
157     silc_free(channel_id);
158
159     /* Get client ID */
160     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
161     if (!tmp)
162       goto out;
163     client_id = silc_id_payload_parse_id(tmp, tmp_len, NULL);
164     if (!client_id)
165       goto out;
166
167     /* If the the client is not in local list we check global list (ie. the
168        channel will be global channel) and if it does not exist then create
169        entry for the client. */
170     client = silc_idlist_find_client_by_id(server->global_list,
171                                            client_id, server->server_type,
172                                            &cache);
173     if (!client) {
174       client = silc_idlist_find_client_by_id(server->local_list,
175                                              client_id, server->server_type,
176                                              &cache);
177       if (!client) {
178         /* If router did not find the client the it is bogus */
179         if (server->server_type != SILC_SERVER) {
180           silc_free(client_id);
181           goto out;
182         }
183
184         client =
185           silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
186                                  silc_id_dup(client_id, SILC_ID_CLIENT),
187                                  sock->user_data, NULL, 0);
188         if (!client) {
189           SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
190           silc_free(client_id);
191           goto out;
192         }
193
194         client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
195       }
196     }
197     silc_free(client_id);
198
199     /* Do not process the notify if the client is not registered */
200     if (!(client->data.status & SILC_IDLIST_STATUS_REGISTERED))
201       break;
202
203     /* Do not add client to channel if it is there already */
204     if (silc_server_client_on_channel(client, channel, NULL)) {
205       SILC_LOG_DEBUG(("Client already on channel %s",
206                       channel->channel_name));
207       break;
208     }
209
210     /* Send to channel */
211     silc_server_packet_send_to_channel(server, sock, channel, packet->type,
212                                        FALSE, TRUE, packet->buffer->data,
213                                        packet->buffer->len, FALSE);
214
215     if (server->server_type != SILC_ROUTER &&
216         sock->type == SILC_SOCKET_TYPE_ROUTER)
217       /* The channel is global now */
218       channel->global_users = TRUE;
219
220     SILC_LOG_DEBUG(("Joining to channel %s", channel->channel_name));
221
222     /* JOIN the global client to the channel (local clients (if router
223        created the channel) is joined in the pending JOIN command). */
224     chl = silc_calloc(1, sizeof(*chl));
225     chl->client = client;
226     chl->channel = channel;
227
228     if (server->server_type != SILC_ROUTER ||
229         sock->type == SILC_SOCKET_TYPE_ROUTER) {
230       /* If this is the first one on the channel then it is the founder of
231          the channel. This is done on normal server and on router if this
232          notify is coming from router */
233       if (!silc_hash_table_count(channel->user_list)) {
234         SILC_LOG_DEBUG(("Client %s is founder on channel",
235                         silc_id_render(chl->client->id, SILC_ID_CLIENT)));
236         chl->mode = (SILC_CHANNEL_UMODE_CHANOP | SILC_CHANNEL_UMODE_CHANFO);
237       }
238     }
239
240     silc_hash_table_add(channel->user_list, client, chl);
241     silc_hash_table_add(client->channels, channel, chl);
242     channel->user_count++;
243     channel->disabled = FALSE;
244
245     /* Make sure we don't expire clients that are on channel */
246     if (cache)
247       cache->expire = 0;
248
249     /* Update statistics */
250     if (server->server_type == SILC_ROUTER) {
251       if (sock->type != SILC_SOCKET_TYPE_ROUTER)
252         server->stat.cell_chanclients++;
253       server->stat.chanclients++;
254     }
255
256     break;
257
258   case SILC_NOTIFY_TYPE_LEAVE:
259     /*
260      * Distribute the notify to local clients on the channel
261      */
262     SILC_LOG_DEBUG(("LEAVE notify"));
263
264     if (!channel_id) {
265       channel_id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
266                                   packet->dst_id_type);
267       if (!channel_id)
268         goto out;
269     }
270
271     /* Get channel entry */
272     channel = silc_idlist_find_channel_by_id(server->global_list,
273                                              channel_id, NULL);
274     if (!channel) {
275       channel = silc_idlist_find_channel_by_id(server->local_list,
276                                                channel_id, NULL);
277       if (!channel) {
278         SILC_LOG_DEBUG(("Notify for unknown channel"));
279         silc_free(channel_id);
280         goto out;
281       }
282     }
283
284     /* Get client ID */
285     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
286     if (!tmp) {
287       silc_free(channel_id);
288       goto out;
289     }
290     client_id = silc_id_payload_parse_id(tmp, tmp_len, NULL);
291     if (!client_id) {
292       silc_free(channel_id);
293       goto out;
294     }
295
296     /* Get client entry */
297     client = silc_idlist_find_client_by_id(server->global_list,
298                                            client_id, TRUE, NULL);
299     if (!client) {
300       client = silc_idlist_find_client_by_id(server->local_list,
301                                              client_id, TRUE, NULL);
302       if (!client) {
303         silc_free(client_id);
304         silc_free(channel_id);
305         goto out;
306       }
307     }
308     silc_free(client_id);
309     silc_free(channel_id);
310
311     /* Check if on channel */
312     if (!silc_server_client_on_channel(client, channel, NULL))
313       break;
314
315     /* Send the leave notify to channel */
316     silc_server_packet_send_to_channel(server, sock, channel, packet->type,
317                                        FALSE, TRUE, packet->buffer->data,
318                                        packet->buffer->len, FALSE);
319
320     /* Remove the user from channel */
321     silc_server_remove_from_one_channel(server, sock, channel, client, FALSE);
322     break;
323
324   case SILC_NOTIFY_TYPE_SIGNOFF:
325     /*
326      * Distribute the notify to local clients on the channel
327      */
328     SILC_LOG_DEBUG(("SIGNOFF notify"));
329
330     /* Get client ID */
331     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
332     if (!tmp)
333       goto out;
334     client_id = silc_id_payload_parse_id(tmp, tmp_len, NULL);
335     if (!client_id)
336       goto out;
337
338     /* Get client entry */
339     client = silc_idlist_find_client_by_id(server->global_list,
340                                            client_id, TRUE, &cache);
341     if (!client) {
342       client = silc_idlist_find_client_by_id(server->local_list,
343                                              client_id, TRUE, &cache);
344       if (!client) {
345         silc_free(client_id);
346         goto out;
347       }
348     }
349     silc_free(client_id);
350
351     /* Get signoff message */
352     tmp = silc_argument_get_arg_type(args, 2, &tmp_len);
353     if (tmp_len > 128)
354       tmp = NULL;
355
356     /* Update statistics */
357     server->stat.clients--;
358     if (server->stat.cell_clients)
359       server->stat.cell_clients--;
360     SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
361     SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
362     silc_schedule_task_del_by_context(server->schedule, client);
363
364     /* Remove from public key hash table. */
365     if (client->data.public_key)
366       silc_hash_table_del_by_context(server->pk_hash, client->data.public_key,
367                                      client);
368
369     /* Remove the client from all channels. */
370     silc_server_remove_from_channels(server, NULL, client, TRUE,
371                                      tmp, FALSE, FALSE);
372
373     /* Check if anyone is watching this nickname */
374     if (server->server_type == SILC_ROUTER)
375       silc_server_check_watcher_list(server, client, NULL,
376                                      SILC_NOTIFY_TYPE_SIGNOFF);
377
378     /* Remove this client from watcher list if it is */
379     silc_server_del_from_watcher_list(server, client);
380
381     client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
382     client->mode = 0;
383     client->router = NULL;
384     client->connection = NULL;
385     cache->expire = SILC_ID_CACHE_EXPIRE_DEF;
386     break;
387
388   case SILC_NOTIFY_TYPE_TOPIC_SET:
389     /*
390      * Distribute the notify to local clients on the channel
391      */
392
393     SILC_LOG_DEBUG(("TOPIC SET notify"));
394
395     /* Get client ID */
396     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
397     if (!tmp)
398       goto out;
399     client_id = silc_id_payload_parse_id(tmp, tmp_len, &id_type);
400     if (!client_id)
401       goto out;
402
403     /* Get client entry */
404     if (id_type == SILC_ID_CLIENT) {
405       client = silc_idlist_find_client_by_id(server->global_list,
406                                              client_id, TRUE, &cache);
407       if (!client) {
408         client = silc_idlist_find_client_by_id(server->local_list,
409                                                client_id, TRUE, &cache);
410         if (!client) {
411           silc_free(client_id);
412           goto out;
413         }
414       }
415       silc_free(client_id);
416     }
417
418     /* Get the topic */
419     tmp = silc_argument_get_arg_type(args, 2, &tmp_len);
420     if (!tmp) {
421       silc_free(channel_id);
422       goto out;
423     }
424
425     if (!channel_id) {
426       channel_id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
427                                   packet->dst_id_type);
428       if (!channel_id)
429         goto out;
430     }
431
432     /* Get channel entry */
433     channel = silc_idlist_find_channel_by_id(server->global_list,
434                                              channel_id, NULL);
435     if (!channel) {
436       channel = silc_idlist_find_channel_by_id(server->local_list,
437                                                channel_id, NULL);
438       if (!channel) {
439         SILC_LOG_DEBUG(("Notify for unknown channel"));
440         silc_free(channel_id);
441         goto out;
442       }
443     }
444     silc_free(channel_id);
445
446     if (channel->topic && !strcmp(channel->topic, tmp)) {
447       SILC_LOG_DEBUG(("Topic is already set and same"));
448       goto out;
449     }
450
451     if (client) {
452       /* Get user's channel entry and check that topic set is allowed. */
453       if (!silc_server_client_on_channel(client, channel, &chl))
454         goto out;
455       if (channel->mode & SILC_CHANNEL_MODE_TOPIC &&
456           !(chl->mode & SILC_CHANNEL_UMODE_CHANOP) &&
457           !(chl->mode & SILC_CHANNEL_UMODE_CHANFO)) {
458         SILC_LOG_DEBUG(("Topic change is not allowed"));
459         goto out;
460       }
461     }
462
463     /* Change the topic */
464     silc_free(channel->topic);
465     channel->topic = strdup(tmp);
466
467     /* Send the same notify to the channel */
468     silc_server_packet_send_to_channel(server, NULL, channel, packet->type,
469                                        FALSE, TRUE, packet->buffer->data,
470                                        packet->buffer->len, FALSE);
471     break;
472
473   case SILC_NOTIFY_TYPE_NICK_CHANGE:
474     {
475       /*
476        * Distribute the notify to local clients on the channel
477        */
478       unsigned char *id, *id2;
479       char *nickname;
480       SilcUInt32 nickname_len;
481
482       SILC_LOG_DEBUG(("NICK CHANGE notify"));
483
484       /* Get old client ID */
485       id = silc_argument_get_arg_type(args, 1, &tmp_len);
486       if (!id)
487         goto out;
488       client_id = silc_id_payload_parse_id(id, tmp_len, NULL);
489       if (!client_id)
490         goto out;
491
492       /* Get new client ID */
493       id2 = silc_argument_get_arg_type(args, 2, &tmp_len);
494       if (!id2)
495         goto out;
496       client_id2 = silc_id_payload_parse_id(id2, tmp_len, NULL);
497       if (!client_id2) {
498         silc_free(client_id);
499         goto out;
500       }
501
502       SILC_LOG_DEBUG(("Old Client ID id(%s)",
503                       silc_id_render(client_id, SILC_ID_CLIENT)));
504       SILC_LOG_DEBUG(("New Client ID id(%s)",
505                       silc_id_render(client_id2, SILC_ID_CLIENT)));
506
507       /* From protocol version 1.1 we also get the new nickname */
508       nickname = silc_argument_get_arg_type(args, 3, &nickname_len);;
509
510       /* Replace the Client ID */
511       client = silc_idlist_replace_client_id(server,
512                                              server->global_list, client_id,
513                                              client_id2, nickname);
514       if (!client)
515         client = silc_idlist_replace_client_id(server,
516                                                server->local_list, client_id,
517                                                client_id2, nickname);
518
519       if (client) {
520         /* Send the NICK_CHANGE notify type to local clients on the channels
521            this client is joined to. */
522         silc_server_send_notify_on_channels(server, client, client,
523                                             SILC_NOTIFY_TYPE_NICK_CHANGE, 3,
524                                             id, tmp_len, id2, tmp_len,
525                                             nickname, nickname ?
526                                             nickname_len : 0);
527       }
528
529       silc_free(client_id);
530       if (!client)
531         silc_free(client_id2);
532       break;
533     }
534
535   case SILC_NOTIFY_TYPE_CMODE_CHANGE:
536     /*
537      * Distribute the notify to local clients on the channel
538      */
539
540     SILC_LOG_DEBUG(("CMODE CHANGE notify"));
541
542     /* Get client ID */
543     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
544     if (!tmp)
545       goto out;
546     client_id = silc_id_payload_parse_id(tmp, tmp_len, &id_type);
547     if (!client_id)
548       goto out;
549
550     /* Get client entry */
551     if (id_type == SILC_ID_CLIENT) {
552       client = silc_idlist_find_client_by_id(server->global_list,
553                                              client_id, TRUE, &cache);
554       if (!client) {
555         client = silc_idlist_find_client_by_id(server->local_list,
556                                                client_id, TRUE, &cache);
557         if (!client) {
558           silc_free(client_id);
559           goto out;
560         }
561       }
562     }
563     silc_free(client_id);
564
565     if (!channel_id) {
566       channel_id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
567                                   packet->dst_id_type);
568       if (!channel_id)
569         goto out;
570     }
571
572     /* Get channel entry */
573     channel = silc_idlist_find_channel_by_id(server->global_list,
574                                              channel_id, NULL);
575     if (!channel) {
576       channel = silc_idlist_find_channel_by_id(server->local_list,
577                                                channel_id, NULL);
578       if (!channel) {
579         SILC_LOG_DEBUG(("Notify for unknown channel"));
580         silc_free(channel_id);
581         goto out;
582       }
583     }
584     silc_free(channel_id);
585
586     /* Get the mode */
587     tmp = silc_argument_get_arg_type(args, 2, &tmp_len);
588     if (!tmp)
589       goto out;
590     SILC_GET32_MSB(mode, tmp);
591
592     /* Check if mode changed */
593     if (channel->mode == mode) {
594       SILC_LOG_DEBUG(("Mode is changed already"));
595
596       /* If this mode change has founder mode then we'll enforce the
597          change so that the server gets the real founder public key */
598       if (server->server_type != SILC_SERVER &&
599           sock != SILC_PRIMARY_ROUTE(server) &&
600           mode & SILC_CHANNEL_MODE_FOUNDER_AUTH && channel->founder_key) {
601         SILC_LOG_DEBUG(("Sending founder public key to server"));
602         silc_server_send_notify_cmode(server, sock, FALSE, channel,
603                                       channel->mode, server->id,
604                                       SILC_ID_SERVER, channel->cipher,
605                                       channel->hmac_name,
606                                       channel->passphrase,
607                                       channel->founder_key, NULL);
608       }
609
610       /* If we received same mode from our primary check whether founder
611          mode and key in the notify is set.  We update the founder key
612          here since we may have wrong one */
613       if (server->server_type == SILC_SERVER &&
614           sock == SILC_PRIMARY_ROUTE(server) &&
615           mode & SILC_CHANNEL_MODE_FOUNDER_AUTH) {
616         SILC_LOG_DEBUG(("Founder public key received from router"));
617         tmp = silc_argument_get_arg_type(args, 6, &tmp_len);
618         if (!tmp)
619           break;
620
621         if (channel->founder_key)
622           silc_pkcs_public_key_free(channel->founder_key);
623         channel->founder_key = NULL;
624         silc_pkcs_public_key_payload_decode(tmp, tmp_len,
625                                             &channel->founder_key);
626       }
627
628       /* Check also for channel public key list */
629       if (server->server_type == SILC_SERVER &&
630           sock == SILC_PRIMARY_ROUTE(server) &&
631           mode & SILC_CHANNEL_MODE_CHANNEL_AUTH) {
632         SilcBuffer chpklist;
633         SilcBuffer sidp;
634         unsigned char mask[4], ulimit[4];
635
636         SILC_LOG_DEBUG(("Channel public key list received from router"));
637         tmp = silc_argument_get_arg_type(args, 7, &tmp_len);
638         if (!tmp)
639           break;
640
641         /* Set the router's list, and send the notify to channel too so that
642            channel gets the list */
643         silc_server_set_channel_pk_list(server, sock, channel, tmp, tmp_len);
644         chpklist = silc_server_get_channel_pk_list(server, channel,
645                                                    FALSE, FALSE);
646         if (!chpklist)
647           break;
648         sidp = silc_id_payload_encode(server->router->id, SILC_ID_SERVER);
649         SILC_PUT32_MSB(channel->mode, mask);
650         if (channel->mode & SILC_CHANNEL_MODE_ULIMIT)
651           SILC_PUT32_MSB(channel->user_limit, ulimit);
652         silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
653                                            SILC_NOTIFY_TYPE_CMODE_CHANGE, 8,
654                                            sidp->data, sidp->len,
655                                            mask, 4,
656                                            channel->cipher,
657                                            channel->cipher ?
658                                            strlen(channel->cipher) : 0,
659                                            channel->hmac_name,
660                                            channel->hmac_name ?
661                                            strlen(channel->hmac_name) : 0,
662                                            channel->passphrase,
663                                            channel->passphrase ?
664                                            strlen(channel->passphrase) : 0,
665                                            NULL, 0,
666                                            chpklist->data, chpklist->len,
667                                            (channel->mode &
668                                             SILC_CHANNEL_MODE_ULIMIT ?
669                                             ulimit : NULL),
670                                            (channel->mode &
671                                             SILC_CHANNEL_MODE_ULIMIT ?
672                                             sizeof(ulimit) : 0));
673         silc_buffer_free(sidp);
674         silc_buffer_free(chpklist);
675         goto out;
676       }
677
678       break;
679     }
680
681     /* Get user's channel entry and check that mode change is allowed */
682     if (client) {
683       if (!silc_server_client_on_channel(client, channel, &chl))
684         goto out;
685       if (!silc_server_check_cmode_rights(server, channel, chl, mode)) {
686         SILC_LOG_DEBUG(("CMODE change is not allowed"));
687         silc_server_send_notify_cmode(server, sock, FALSE, channel,
688                                       channel->mode, server->id,
689                                       SILC_ID_SERVER, channel->cipher,
690                                       channel->hmac_name,
691                                       channel->passphrase,
692                                       channel->founder_key, NULL);
693         goto out;
694       }
695     } else {
696       /* Assure that server is not removing founder mode from us */
697       if (server->server_type == SILC_ROUTER &&
698           sock != SILC_PRIMARY_ROUTE(server) &&
699           channel->mode & SILC_CHANNEL_MODE_FOUNDER_AUTH &&
700           !(mode & SILC_CHANNEL_MODE_FOUNDER_AUTH)) {
701         SILC_LOG_DEBUG(("Enforcing sender to change channel mode"));
702         silc_server_send_notify_cmode(server, sock, FALSE, channel,
703                                       channel->mode, server->id,
704                                       SILC_ID_SERVER, channel->cipher,
705                                       channel->hmac_name,
706                                       channel->passphrase,
707                                       channel->founder_key, NULL);
708         goto out;
709       }
710
711       /* If server is adding founder mode, check whether there is founder
712          on channel already and is not from this server */
713       if (server->server_type == SILC_ROUTER &&
714           sock != SILC_PRIMARY_ROUTE(server) &&
715           mode & SILC_CHANNEL_MODE_FOUNDER_AUTH) {
716         silc_hash_table_list(channel->user_list, &htl);
717         while (silc_hash_table_get(&htl, NULL, (void *)&chl))
718           if (chl->mode & SILC_CHANNEL_UMODE_CHANFO &&
719               chl->client->router != sock->user_data) {
720             SILC_LOG_DEBUG(("Enforcing sender to change channel mode"));
721             silc_server_send_notify_cmode(server, sock, FALSE, channel,
722                                           channel->mode, server->id,
723                                           SILC_ID_SERVER, channel->cipher,
724                                           channel->hmac_name,
725                                           channel->passphrase,
726                                           channel->founder_key, NULL);
727             silc_hash_table_list_reset(&htl);
728             goto out;
729           }
730         silc_hash_table_list_reset(&htl);
731       }
732     }
733
734     /* If the channel had private keys set and the mode was removed then
735        we must re-generate and re-distribute a new channel key */
736     if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY &&
737         !(mode & SILC_CHANNEL_MODE_PRIVKEY)) {
738       /* Re-generate channel key */
739       if (!silc_server_create_channel_key(server, channel, 0))
740         goto out;
741
742       /* Send the channel key. This sends it to our local clients and if
743          we are normal server to our router as well. */
744       silc_server_send_channel_key(server, NULL, channel,
745                                    server->server_type == SILC_ROUTER ?
746                                    FALSE : !server->standalone);
747     }
748
749     /* Get the hmac */
750     tmp = silc_argument_get_arg_type(args, 4, &tmp_len);
751     if (tmp) {
752       unsigned char hash[32];
753
754       if (channel->hmac)
755         silc_hmac_free(channel->hmac);
756       if (!silc_hmac_alloc(tmp, NULL, &channel->hmac))
757         goto out;
758
759       /* Set the HMAC key out of current channel key. The client must do
760          this locally. */
761       silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key,
762                      channel->key_len / 8, hash);
763       silc_hmac_set_key(channel->hmac, hash,
764                         silc_hash_len(silc_hmac_get_hash(channel->hmac)));
765       memset(hash, 0, sizeof(hash));
766     }
767
768     /* Get the passphrase */
769     tmp = silc_argument_get_arg_type(args, 5, &tmp_len);
770     if (tmp) {
771       silc_free(channel->passphrase);
772       channel->passphrase = silc_memdup(tmp, tmp_len);
773     }
774
775     /* Get founder public key */
776     tmp = silc_argument_get_arg_type(args, 6, &tmp_len);
777     if (tmp && mode & SILC_CHANNEL_MODE_FOUNDER_AUTH) {
778       if (channel->founder_key)
779         silc_pkcs_public_key_free(channel->founder_key);
780       channel->founder_key = NULL;
781       if (!silc_pkcs_public_key_payload_decode(tmp, tmp_len,
782                                                &channel->founder_key)) {
783         SILC_LOG_DEBUG(("Enforcing sender to change channel mode"));
784         mode &= ~SILC_CHANNEL_MODE_FOUNDER_AUTH;
785         silc_server_send_notify_cmode(server, sock, FALSE, channel,
786                                       mode, server->id, SILC_ID_SERVER,
787                                       channel->cipher,
788                                       channel->hmac_name,
789                                       channel->passphrase, NULL, NULL);
790         if (channel->founder_key)
791           silc_pkcs_public_key_free(channel->founder_key);
792         channel->founder_key = NULL;
793       }
794     }
795
796     if (mode & SILC_CHANNEL_MODE_FOUNDER_AUTH && !channel->founder_key &&
797         server->server_type == SILC_ROUTER) {
798       SILC_LOG_DEBUG(("Enforcing sender to change channel mode"));
799       mode &= ~SILC_CHANNEL_MODE_FOUNDER_AUTH;
800       silc_server_send_notify_cmode(server, sock, FALSE, channel,
801                                     mode, server->id, SILC_ID_SERVER,
802                                     channel->cipher,
803                                     channel->hmac_name,
804                                     channel->passphrase, NULL, NULL);
805     }
806
807     /* Process channel public key(s). */
808     tmp = silc_argument_get_arg_type(args, 7, &tmp_len);
809     if (tmp && mode & SILC_CHANNEL_MODE_CHANNEL_AUTH) {
810       SilcStatus ret =
811         silc_server_set_channel_pk_list(server, sock, channel, tmp, tmp_len);
812
813       /* If list was set already we will enforce the same list to server. */
814       if (ret == SILC_STATUS_ERR_OPERATION_ALLOWED) {
815         SilcBuffer chpklist = silc_server_get_channel_pk_list(server, channel,
816                                                               TRUE, FALSE);
817         silc_server_send_notify_cmode(server, sock, FALSE, channel,
818                                       mode, server->id, SILC_ID_SERVER,
819                                       channel->cipher,
820                                       channel->hmac_name,
821                                       channel->passphrase, NULL,
822                                       chpklist);
823         silc_buffer_free(chpklist);
824       }
825     }
826
827     /* Get the user limit */
828     tmp = silc_argument_get_arg_type(args, 8, &tmp_len);
829     if (tmp && tmp_len == 4 && mode & SILC_CHANNEL_MODE_ULIMIT)
830       SILC_GET32_MSB(channel->user_limit, tmp);
831
832     /* Send the same notify to the channel */
833     silc_server_packet_send_to_channel(server, NULL, channel, packet->type,
834                                        FALSE, TRUE, packet->buffer->data,
835                                        packet->buffer->len, FALSE);
836
837     /* Change mode */
838     channel->mode = mode;
839
840     /* Cleanup if some modes are removed */
841
842     if (!(channel->mode & SILC_CHANNEL_MODE_FOUNDER_AUTH) &&
843         channel->founder_key) {
844       silc_pkcs_public_key_free(channel->founder_key);
845       channel->founder_key = NULL;
846     }
847
848     if (!(channel->mode & SILC_CHANNEL_MODE_CHANNEL_AUTH) &&
849         channel->channel_pubkeys) {
850       silc_hash_table_free(channel->channel_pubkeys);
851       channel->channel_pubkeys = NULL;
852     }
853
854     break;
855
856   case SILC_NOTIFY_TYPE_CUMODE_CHANGE:
857     {
858       /*
859        * Distribute the notify to local clients on the channel
860        */
861       SilcChannelClientEntry chl2 = NULL;
862       bool notify_sent = FALSE;
863
864       SILC_LOG_DEBUG(("CUMODE CHANGE notify"));
865
866       /* Get client ID */
867       tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
868       if (!tmp)
869         goto out;
870       client_id = silc_id_payload_parse_id(tmp, tmp_len, &id_type);
871       if (!client_id)
872         goto out;
873
874       /* Get client entry */
875       if (id_type == SILC_ID_CLIENT) {
876         client = silc_idlist_find_client_by_id(server->global_list,
877                                                client_id, TRUE, &cache);
878         if (!client) {
879           client = silc_idlist_find_client_by_id(server->local_list,
880                                                  client_id, TRUE, &cache);
881           if (!client) {
882             silc_free(client_id);
883             goto out;
884           }
885         }
886       }
887       silc_free(client_id);
888
889       if (!channel_id) {
890         channel_id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
891                                     packet->dst_id_type);
892         if (!channel_id)
893           goto out;
894       }
895
896       /* Get channel entry */
897       channel = silc_idlist_find_channel_by_id(server->global_list,
898                                                channel_id, NULL);
899       if (!channel) {
900         channel = silc_idlist_find_channel_by_id(server->local_list,
901                                                  channel_id, NULL);
902         if (!channel) {
903           SILC_LOG_DEBUG(("Notify for unknown channel"));
904           silc_free(channel_id);
905           goto out;
906         }
907       }
908
909       /* Get the mode */
910       tmp = silc_argument_get_arg_type(args, 2, &tmp_len);
911       if (!tmp) {
912         silc_free(channel_id);
913         goto out;
914       }
915
916       SILC_GET32_MSB(mode, tmp);
917
918       /* Get target client */
919       tmp = silc_argument_get_arg_type(args, 3, &tmp_len);
920       if (!tmp)
921         goto out;
922       client_id = silc_id_payload_parse_id(tmp, tmp_len, NULL);
923       if (!client_id)
924         goto out;
925
926       /* Get client entry */
927       client2 = silc_idlist_find_client_by_id(server->global_list,
928                                               client_id, TRUE, NULL);
929       if (!client2) {
930         client2 = silc_idlist_find_client_by_id(server->local_list,
931                                                 client_id, TRUE, NULL);
932         if (!client2) {
933           silc_free(client_id);
934           goto out;
935         }
936       }
937       silc_free(client_id);
938
939       if (client) {
940         /* Check that sender is on channel */
941         if (!silc_server_client_on_channel(client, channel, &chl))
942           goto out;
943
944         if (client != client2 && server->server_type == SILC_ROUTER) {
945           /* Sender must be operator */
946           if (!(chl->mode & SILC_CHANNEL_UMODE_CHANOP) &&
947               !(chl->mode & SILC_CHANNEL_UMODE_CHANFO)) {
948             SILC_LOG_DEBUG(("CUMODE change is not allowed"));
949             goto out;
950           }
951
952           if (!silc_server_client_on_channel(client2, channel, &chl))
953             goto out;
954
955           /* If target is founder mode change is not allowed. */
956           if (chl->mode & SILC_CHANNEL_UMODE_CHANFO) {
957             SILC_LOG_DEBUG(("CUMODE change is not allowed"));
958             goto out;
959           }
960         }
961       }
962
963       /* Get target channel user entry */
964       if (!silc_server_client_on_channel(client2, channel, &chl))
965         goto out;
966
967       if (server->server_type == SILC_SERVER && chl->mode == mode) {
968         SILC_LOG_DEBUG(("Mode is changed already"));
969         break;
970       }
971
972       /* Check whether to give founder rights to this user or not.  The
973          problem here is that we get only the public key of the client,
974          but no authentication data.  We must assume that server has
975          already authenticated the user (and thus we must trust the
976          server). */
977       if (mode & SILC_CHANNEL_UMODE_CHANFO &&
978           !(chl->mode & SILC_CHANNEL_UMODE_CHANFO) &&
979           server->server_type == SILC_ROUTER &&
980           sock != SILC_PRIMARY_ROUTE(server)) {
981         SilcPublicKey founder_key = NULL;
982
983         /* If channel doesn't have founder auth mode then it's impossible
984            that someone would be getting founder rights with CUMODE command.
985            In that case there already either is founder or there isn't
986            founder at all on the channel (valid only when 'client' is
987            valid). */
988         if (client && !(channel->mode & SILC_CHANNEL_MODE_FOUNDER_AUTH)) {
989           /* Force the mode to not have founder mode */
990           chl->mode = mode &= ~SILC_CHANNEL_UMODE_CHANFO;
991           silc_server_force_cumode_change(server, sock, channel, chl, mode);
992           notify_sent = TRUE;
993           break;
994         }
995
996         /* Get the founder of the channel and if found then this client
997            cannot be the founder since there already is one. */
998         silc_hash_table_list(channel->user_list, &htl);
999         while (silc_hash_table_get(&htl, NULL, (void *)&chl2))
1000           if (chl2->mode & SILC_CHANNEL_UMODE_CHANFO) {
1001             SILC_LOG_DEBUG(("Founder already on channel"));
1002             chl->mode = mode &= ~SILC_CHANNEL_UMODE_CHANFO;
1003             silc_server_force_cumode_change(server, sock, channel,
1004                                             chl, mode);
1005             notify_sent = TRUE;
1006             break;
1007           }
1008         silc_hash_table_list_reset(&htl);
1009         if (!(mode & SILC_CHANNEL_UMODE_CHANFO))
1010           break;
1011
1012         /* Founder not found on the channel.  Since the founder auth mode
1013            is set on the channel now check whether this is the client that
1014            originally set the mode. */
1015
1016         if (channel->founder_key) {
1017           /* Get public key that must be present in notify */
1018           tmp = silc_argument_get_arg_type(args, 4, &tmp_len);
1019           if (!tmp || !silc_pkcs_public_key_payload_decode(tmp, tmp_len,
1020                                                            &founder_key)) {
1021             chl->mode = mode &= ~SILC_CHANNEL_UMODE_CHANFO;
1022             SILC_LOG_DEBUG(("Founder public key not present"));
1023             silc_server_force_cumode_change(server, sock, channel, chl, mode);
1024             notify_sent = TRUE;
1025             break;
1026           }
1027
1028           /* Now match the public key we have cached and public key sent.
1029              They must match. */
1030           if (!silc_pkcs_public_key_compare(channel->founder_key,
1031                                             founder_key)) {
1032             chl->mode = mode &= ~SILC_CHANNEL_UMODE_CHANFO;
1033             SILC_LOG_DEBUG(("Founder public key mismatch"));
1034             silc_server_force_cumode_change(server, sock, channel, chl, mode);
1035             notify_sent = TRUE;
1036             break;
1037           }
1038         }
1039
1040         /* There cannot be anyone else as founder on the channel now.  This
1041            client is definitely the founder due to this 'authentication'.
1042            We trust the server did the actual signature verification
1043            earlier (bad, yes). */
1044         silc_hash_table_list(channel->user_list, &htl);
1045         while (silc_hash_table_get(&htl, NULL, (void *)&chl2))
1046           if (chl2->mode & SILC_CHANNEL_UMODE_CHANFO) {
1047             chl2->mode &= ~SILC_CHANNEL_UMODE_CHANFO;
1048             SILC_LOG_DEBUG(("Removing old founder rights, new authenticated"));
1049             silc_server_force_cumode_change(server, NULL, channel, chl2,
1050                                             chl2->mode);
1051             break;
1052           }
1053         silc_hash_table_list_reset(&htl);
1054
1055         if (founder_key)
1056           silc_pkcs_public_key_free(founder_key);
1057       }
1058
1059       if (server->server_type != SILC_SERVER && chl->mode == mode) {
1060         SILC_LOG_DEBUG(("Mode is changed already"));
1061         break;
1062       }
1063
1064       SILC_LOG_DEBUG(("Changing %s channel user mode",
1065                       chl->client->nickname ? chl->client->nickname :
1066                       (unsigned char *)""));
1067
1068       /* Change the mode */
1069       chl->mode = mode;
1070
1071       /* Send the same notify to the channel */
1072       if (!notify_sent)
1073         silc_server_packet_send_to_channel(server, NULL, channel,
1074                                            packet->type,
1075                                            FALSE, TRUE, packet->buffer->data,
1076                                            packet->buffer->len, FALSE);
1077
1078       silc_free(channel_id);
1079       break;
1080     }
1081
1082   case SILC_NOTIFY_TYPE_INVITE:
1083
1084     if (packet->dst_id_type == SILC_ID_CLIENT)
1085       goto out;
1086
1087     SILC_LOG_DEBUG(("INVITE notify"));
1088
1089     /* Get Channel ID */
1090     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
1091     if (!tmp)
1092       goto out;
1093     channel_id = silc_id_payload_parse_id(tmp, tmp_len, NULL);
1094     if (!channel_id)
1095       goto out;
1096
1097     /* Get channel entry */
1098     channel = silc_idlist_find_channel_by_id(server->global_list,
1099                                              channel_id, NULL);
1100     if (!channel) {
1101       channel = silc_idlist_find_channel_by_id(server->local_list,
1102                                                channel_id, NULL);
1103       if (!channel) {
1104         SILC_LOG_DEBUG(("Notify for unknown channel"));
1105         silc_free(channel_id);
1106         goto out;
1107       }
1108     }
1109     silc_free(channel_id);
1110
1111 #if 0 /* These aren't actually used anywhere or needed, since this
1112          notify is for handling the invite list (direct invite
1113          goes to client and is not handled here at all). */
1114
1115     /* Get client ID */
1116     tmp = silc_argument_get_arg_type(args, 3, &tmp_len);
1117     if (!tmp)
1118       goto out;
1119     client_id = silc_id_payload_parse_id(tmp, tmp_len, NULL);
1120     if (!client_id)
1121       goto out;
1122
1123     /* Get client entry */
1124     client = silc_idlist_find_client_by_id(server->global_list,
1125                                            client_id, TRUE, &cache);
1126     if (!client) {
1127       client = silc_idlist_find_client_by_id(server->local_list,
1128                                              client_id, TRUE, &cache);
1129       if (!client) {
1130         silc_free(client_id);
1131         goto out;
1132       }
1133     }
1134     silc_free(client_id);
1135
1136     /* Get user's channel entry and check that inviting is allowed. */
1137     if (server->server_type == SILC_ROUTER) {
1138       if (!silc_server_client_on_channel(client, channel, &chl))
1139         goto out;
1140       if (channel->mode & SILC_CHANNEL_MODE_INVITE &&
1141           !(chl->mode & SILC_CHANNEL_UMODE_CHANOP) &&
1142           !(chl->mode & SILC_CHANNEL_UMODE_CHANFO)) {
1143         SILC_LOG_DEBUG(("Inviting is not allowed"));
1144         goto out;
1145       }
1146     }
1147 #endif
1148
1149     /* Get the invite action */
1150     tmp = silc_argument_get_arg_type(args, 4, &tmp_len);
1151     if (tmp && tmp_len == 1) {
1152       SilcUInt8 action = (SilcUInt8)tmp[0];
1153       SilcUInt16 iargc = 0;
1154       SilcArgumentPayload iargs;
1155
1156       /* Get invite list */
1157       tmp = silc_argument_get_arg_type(args, 5, &tmp_len);
1158       if (!tmp || tmp_len < 2)
1159         goto out;
1160
1161       /* Parse the arguments to see they are constructed correctly */
1162       SILC_GET16_MSB(iargc, tmp);
1163       iargs = silc_argument_payload_parse(tmp + 2, tmp_len - 2, iargc);
1164       if (!iargs)
1165         goto out;
1166
1167       if (action != 0x01 && !channel->invite_list)
1168         channel->invite_list =
1169           silc_hash_table_alloc(0, silc_hash_ptr,
1170                                 NULL, NULL, NULL,
1171                                 silc_server_inviteban_destruct, channel, TRUE);
1172
1173       /* Proces the invite action */
1174       silc_server_inviteban_process(server, channel->invite_list, action,
1175                                     iargs);
1176       silc_argument_payload_free(iargs);
1177
1178       /* If we are router we must send this notify to our local servers on
1179          the channel.  Normal server does nothing.  The notify is not
1180          sent to clients. */
1181       if (server->server_type == SILC_ROUTER)
1182         silc_server_packet_send_to_channel(server, sock, channel,
1183                                            packet->type, FALSE, FALSE,
1184                                            packet->buffer->data,
1185                                            packet->buffer->len, FALSE);
1186     }
1187
1188     break;
1189
1190   case SILC_NOTIFY_TYPE_CHANNEL_CHANGE:
1191     /*
1192      * Distribute to the local clients on the channel and change the
1193      * channel ID.
1194      */
1195
1196     SILC_LOG_DEBUG(("CHANNEL CHANGE"));
1197
1198     if (sock->type != SILC_SOCKET_TYPE_ROUTER)
1199       break;
1200
1201     /* Get the old Channel ID */
1202     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
1203     if (!tmp)
1204       goto out;
1205     channel_id = silc_id_payload_parse_id(tmp, tmp_len, NULL);
1206     if (!channel_id)
1207       goto out;
1208
1209     /* Get the channel entry */
1210     channel = silc_idlist_find_channel_by_id(server->local_list,
1211                                              channel_id, NULL);
1212     if (!channel) {
1213       channel = silc_idlist_find_channel_by_id(server->global_list,
1214                                                channel_id, NULL);
1215       if (!channel) {
1216         SILC_LOG_DEBUG(("Notify for unknown channel"));
1217         silc_free(channel_id);
1218         goto out;
1219       }
1220     }
1221
1222     /* Send the notify to the channel */
1223     silc_server_packet_send_to_channel(server, sock, channel, packet->type,
1224                                        FALSE, TRUE, packet->buffer->data,
1225                                        packet->buffer->len, FALSE);
1226
1227     /* Get the new Channel ID */
1228     tmp = silc_argument_get_arg_type(args, 2, &tmp_len);
1229     if (!tmp)
1230       goto out;
1231     channel_id2 = silc_id_payload_parse_id(tmp, tmp_len, NULL);
1232     if (!channel_id2)
1233       goto out;
1234
1235     SILC_LOG_DEBUG(("Old Channel ID id(%s)",
1236                     silc_id_render(channel_id, SILC_ID_CHANNEL)));
1237     SILC_LOG_DEBUG(("New Channel ID id(%s)",
1238                     silc_id_render(channel_id2, SILC_ID_CHANNEL)));
1239
1240     /* Replace the Channel ID */
1241     if (!silc_idlist_replace_channel_id(server->local_list, channel_id,
1242                                         channel_id2))
1243       if (!silc_idlist_replace_channel_id(server->global_list, channel_id,
1244                                           channel_id2)) {
1245         silc_free(channel_id2);
1246         channel_id2 = NULL;
1247       }
1248
1249     if (channel_id2) {
1250       SilcBuffer modes = NULL, users = NULL, users_modes = NULL;
1251
1252       /* Re-announce this channel which ID was changed. */
1253       silc_server_send_new_channel(server, sock, FALSE, channel->channel_name,
1254                                    channel->id,
1255                                    silc_id_get_len(channel->id,
1256                                                    SILC_ID_CHANNEL),
1257                                    channel->mode);
1258
1259       /* Re-announce our clients on the channel as the ID has changed now */
1260       silc_server_announce_get_channel_users(server, channel, &modes, &users,
1261                                              &users_modes);
1262       if (users) {
1263         silc_buffer_push(users, users->data - users->head);
1264         silc_server_packet_send(server, sock,
1265                                 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
1266                                 users->data, users->len, FALSE);
1267         silc_buffer_free(users);
1268       }
1269       if (modes) {
1270         silc_buffer_push(modes, modes->data - modes->head);
1271         silc_server_packet_send_dest(server, sock,
1272                                      SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
1273                                      channel->id, SILC_ID_CHANNEL,
1274                                      modes->data, modes->len, FALSE);
1275         silc_buffer_free(modes);
1276       }
1277       if (users_modes) {
1278         silc_buffer_push(users_modes, users_modes->data - users_modes->head);
1279         silc_server_packet_send_dest(server, sock,
1280                                      SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
1281                                      channel->id, SILC_ID_CHANNEL,
1282                                      users_modes->data,
1283                                      users_modes->len, FALSE);
1284         silc_buffer_free(users_modes);
1285       }
1286
1287       /* Re-announce channel's topic */
1288       if (channel->topic) {
1289         silc_server_send_notify_topic_set(server, sock,
1290                                           server->server_type == SILC_ROUTER ?
1291                                           TRUE : FALSE, channel,
1292                                           server->id, SILC_ID_SERVER,
1293                                           channel->topic);
1294       }
1295     }
1296
1297     silc_free(channel_id);
1298
1299     break;
1300
1301   case SILC_NOTIFY_TYPE_SERVER_SIGNOFF:
1302     /*
1303      * Remove the server entry and all clients that this server owns.
1304      */
1305
1306     SILC_LOG_DEBUG(("SERVER SIGNOFF notify"));
1307
1308     /* Backup router shouldn't accept SERVER_SIGNOFF's from normal routers
1309        when the backup isn't acting as primary router. */
1310     if (sock->type == SILC_SOCKET_TYPE_SERVER &&
1311         server->backup_router && server->server_type == SILC_BACKUP_ROUTER)
1312       return;
1313
1314     /* Get Server ID */
1315     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
1316     if (!tmp)
1317       goto out;
1318     server_id = silc_id_payload_parse_id(tmp, tmp_len, NULL);
1319     if (!server_id)
1320       goto out;
1321
1322     /* If the ID is mine, this notify is not allowed. */
1323     if (SILC_ID_SERVER_COMPARE(server_id, server->id)) {
1324       SILC_LOG_DEBUG(("Ignoring my own ID for SERVER_SIGNOFF"));
1325       break;
1326     }
1327
1328     /* Get server entry */
1329     server_entry = silc_idlist_find_server_by_id(server->global_list,
1330                                                  server_id, TRUE, NULL);
1331     local = FALSE;
1332     if (!server_entry) {
1333       server_entry = silc_idlist_find_server_by_id(server->local_list,
1334                                                    server_id, TRUE, NULL);
1335       local = TRUE;
1336       if (!server_entry) {
1337         /* If we are normal server then we might not have the server. Check
1338            whether router was kind enough to send the list of all clients
1339            that actually was to be removed. Remove them if the list is
1340            available. */
1341         if (server->server_type != SILC_ROUTER &&
1342             silc_argument_get_arg_num(args) > 1) {
1343           int i;
1344
1345           for (i = 1; i < silc_argument_get_arg_num(args); i++) {
1346             /* Get Client ID */
1347             tmp = silc_argument_get_arg_type(args, i + 1, &tmp_len);
1348             if (!tmp)
1349               continue;
1350             client_id = silc_id_payload_parse_id(tmp, tmp_len, NULL);
1351             if (!client_id)
1352               continue;
1353
1354             /* Get client entry */
1355             client = silc_idlist_find_client_by_id(server->global_list,
1356                                                    client_id, TRUE, &cache);
1357             local = FALSE;
1358             if (!client) {
1359               client = silc_idlist_find_client_by_id(server->local_list,
1360                                                      client_id, TRUE, &cache);
1361               local = TRUE;
1362               if (!client) {
1363                 silc_free(client_id);
1364                 continue;
1365               }
1366             }
1367             silc_free(client_id);
1368
1369             /* Update statistics */
1370             server->stat.clients--;
1371             if (server->stat.cell_clients)
1372               server->stat.cell_clients--;
1373             SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
1374             SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
1375
1376             /* Remove the client from all channels. */
1377             silc_server_remove_from_channels(server, NULL, client,
1378                                              TRUE, NULL, FALSE, FALSE);
1379
1380             /* Check if anyone is watching this nickname */
1381             if (server->server_type == SILC_ROUTER)
1382               silc_server_check_watcher_list(server, client, NULL,
1383                                              SILC_NOTIFY_TYPE_SERVER_SIGNOFF);
1384
1385             /* Remove this client from watcher list if it is */
1386             if (local)
1387               silc_server_del_from_watcher_list(server, client);
1388
1389             /* Remove from public key hash table. */
1390             if (client->data.public_key)
1391               silc_hash_table_del_by_context(server->pk_hash,
1392                                              client->data.public_key,
1393                                              client);
1394
1395             /* Remove the client */
1396             silc_idlist_del_data(client);
1397             silc_idlist_del_client(local ? server->local_list :
1398                                    server->global_list, client);
1399           }
1400         }
1401
1402         silc_free(server_id);
1403         goto out;
1404       }
1405     }
1406     silc_free(server_id);
1407
1408     /* For local entrys SERVER_SIGNOFF is processed only on backup router.
1409        It is possible that router sends server signoff for a server.  If
1410        backup router has it as local connection it will be closed. */
1411     if (SILC_IS_LOCAL(server_entry)) {
1412       if (server->server_type == SILC_BACKUP_ROUTER) {
1413         sock = server_entry->connection;
1414         SILC_LOG_DEBUG(("Closing connection %s after SERVER_SIGNOFF",
1415                        sock->hostname));
1416         if (sock->user_data)
1417           silc_server_free_sock_user_data(server, sock, NULL);
1418         SILC_SET_DISCONNECTING(sock);
1419         silc_server_close_connection(server, sock);
1420       }
1421
1422       break;
1423     }
1424
1425     /* Remove all servers that are originated from this server, and
1426        remove the clients of those servers too. */
1427     silc_server_remove_servers_by_server(server, server_entry, TRUE);
1428
1429     /* Remove the clients that this server owns as they will become
1430        invalid now too. */
1431     silc_server_remove_clients_by_server(server, server_entry->router,
1432                                          server_entry, TRUE);
1433     silc_server_backup_del(server, server_entry);
1434
1435     /* Remove the server entry */
1436     silc_idlist_del_server(local ? server->local_list :
1437                            server->global_list, server_entry);
1438
1439     /* Update statistics */
1440     if (server->server_type == SILC_ROUTER)
1441       server->stat.servers--;
1442
1443     break;
1444
1445   case SILC_NOTIFY_TYPE_KICKED:
1446     /*
1447      * Distribute the notify to local clients on the channel
1448      */
1449
1450     SILC_LOG_DEBUG(("KICKED notify"));
1451
1452     if (!channel_id) {
1453       channel_id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
1454                                   packet->dst_id_type);
1455       if (!channel_id)
1456         goto out;
1457     }
1458
1459     /* Get channel entry */
1460     channel = silc_idlist_find_channel_by_id(server->global_list,
1461                                              channel_id, NULL);
1462     if (!channel) {
1463       channel = silc_idlist_find_channel_by_id(server->local_list,
1464                                                channel_id, NULL);
1465       if (!channel) {
1466         SILC_LOG_DEBUG(("Notify for unknown channel"));
1467         silc_free(channel_id);
1468         goto out;
1469       }
1470     }
1471     silc_free(channel_id);
1472
1473     /* Get client ID */
1474     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
1475     if (!tmp)
1476       goto out;
1477     client_id = silc_id_payload_parse_id(tmp, tmp_len, NULL);
1478     if (!client_id)
1479       goto out;
1480
1481     /* If the the client is not in local list we check global list */
1482     client = silc_idlist_find_client_by_id(server->global_list,
1483                                            client_id, TRUE, NULL);
1484     if (!client) {
1485       client = silc_idlist_find_client_by_id(server->local_list,
1486                                              client_id, TRUE, NULL);
1487       if (!client) {
1488         silc_free(client_id);
1489         goto out;
1490       }
1491     }
1492     silc_free(client_id);
1493
1494     /* If target is founder they cannot be kicked */
1495     if (!silc_server_client_on_channel(client, channel, &chl))
1496       goto out;
1497     if (chl->mode & SILC_CHANNEL_UMODE_CHANFO)
1498       goto out;
1499
1500     /* Get the kicker's Client ID */
1501     tmp = silc_argument_get_arg_type(args, 3, &tmp_len);
1502     if (!tmp)
1503       goto out;
1504     client_id = silc_id_payload_parse_id(tmp, tmp_len, NULL);
1505     if (!client_id)
1506       goto out;
1507
1508     /* If the the client is not in local list we check global list */
1509     client2 = silc_idlist_find_client_by_id(server->global_list,
1510                                             client_id, TRUE, NULL);
1511     if (!client2) {
1512       client2 = silc_idlist_find_client_by_id(server->local_list,
1513                                               client_id, TRUE, NULL);
1514       if (!client2) {
1515         silc_free(client_id);
1516         goto out;
1517       }
1518     }
1519     silc_free(client_id);
1520
1521     /* Kicker must be operator on channel */
1522     if (!silc_server_client_on_channel(client2, channel, &chl))
1523       goto out;
1524     if (!(chl->mode & SILC_CHANNEL_UMODE_CHANOP) &&
1525         !(chl->mode & SILC_CHANNEL_UMODE_CHANFO)) {
1526       SILC_LOG_DEBUG(("Kicking is not allowed"));
1527       goto out;
1528     }
1529
1530     /* Send to channel */
1531     silc_server_packet_send_to_channel(server, sock, channel, packet->type,
1532                                        FALSE, TRUE, packet->buffer->data,
1533                                        packet->buffer->len, FALSE);
1534
1535     /* Remove the client from channel's invite list */
1536     if (channel->invite_list && silc_hash_table_count(channel->invite_list)) {
1537       SilcBuffer ab;
1538       SilcArgumentPayload iargs;
1539       tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
1540       ab = silc_argument_payload_encode_one(NULL, tmp, tmp_len, 3);
1541       iargs = silc_argument_payload_parse(ab->data, ab->len, 1);
1542       silc_server_inviteban_process(server, channel->invite_list, 1, iargs);
1543       silc_buffer_free(ab);
1544       silc_argument_payload_free(iargs);
1545     }
1546
1547     /* Remove the client from channel */
1548     silc_server_remove_from_one_channel(server, sock, channel, client, FALSE);
1549
1550     break;
1551
1552   case SILC_NOTIFY_TYPE_KILLED:
1553     {
1554       /*
1555        * Distribute the notify to local clients on channels
1556        */
1557       unsigned char *id, *comment;
1558       SilcUInt32 id_len, comment_len;
1559
1560       SILC_LOG_DEBUG(("KILLED notify"));
1561
1562       /* Get client ID */
1563       id = silc_argument_get_arg_type(args, 1, &id_len);
1564       if (!id)
1565         goto out;
1566       client_id = silc_id_payload_parse_id(id, id_len, NULL);
1567       if (!client_id)
1568         goto out;
1569
1570       /* If the the client is not in local list we check global list */
1571       client = silc_idlist_find_client_by_id(server->global_list,
1572                                              client_id, TRUE, &cache);
1573       if (!client) {
1574         client = silc_idlist_find_client_by_id(server->local_list,
1575                                                client_id, TRUE, &cache);
1576         if (!client) {
1577           silc_free(client_id);
1578           goto out;
1579         }
1580       }
1581       silc_free(client_id);
1582
1583       /* If the client is one of ours, then close the connection to the
1584          client now. This removes the client from all channels as well. */
1585       if (packet->dst_id_type == SILC_ID_CLIENT && client->connection) {
1586         sock = client->connection;
1587         silc_server_free_client_data(server, NULL, client, FALSE, NULL);
1588         silc_server_close_connection(server, sock);
1589         break;
1590       }
1591
1592       /* Get comment */
1593       comment = silc_argument_get_arg_type(args, 2, &comment_len);
1594       if (comment_len > 128)
1595         comment_len = 127;
1596
1597       /* Get the killer's Client ID */
1598       tmp = silc_argument_get_arg_type(args, 3, &tmp_len);
1599       if (!tmp)
1600         goto out;
1601       client_id = silc_id_payload_parse_id(tmp, tmp_len, &id_type);
1602       if (!client_id)
1603         goto out;
1604
1605       if (id_type == SILC_ID_CLIENT) {
1606         /* If the the client is not in local list we check global list */
1607         client2 = silc_idlist_find_client_by_id(server->global_list,
1608                                                 client_id, TRUE, NULL);
1609         if (!client2) {
1610           client2 = silc_idlist_find_client_by_id(server->local_list,
1611                                                   client_id, TRUE, NULL);
1612           if (!client2) {
1613             silc_free(client_id);
1614             goto out;
1615           }
1616         }
1617         silc_free(client_id);
1618
1619         /* Killer must be router operator */
1620         if (server->server_type != SILC_SERVER &&
1621             !(client2->mode & SILC_UMODE_ROUTER_OPERATOR)) {
1622           SILC_LOG_DEBUG(("Killing is not allowed"));
1623           goto out;
1624         }
1625       }
1626
1627       /* Send the notify to local clients on the channels except to the
1628          client who is killed. */
1629       silc_server_send_notify_on_channels(server, client, client,
1630                                           SILC_NOTIFY_TYPE_KILLED, 3,
1631                                           id, id_len, comment, comment_len,
1632                                           tmp, tmp_len);
1633
1634       /* Remove the client from all channels */
1635       silc_server_remove_from_channels(server, NULL, client, FALSE, NULL,
1636                                        FALSE, TRUE);
1637
1638       /* Check if anyone is watching this nickname */
1639       if (server->server_type == SILC_ROUTER)
1640         silc_server_check_watcher_list(server, client, NULL,
1641                                        SILC_NOTIFY_TYPE_KILLED);
1642
1643       /* Remove from public key hash table. */
1644       if (client->data.public_key)
1645         silc_hash_table_del_by_context(server->pk_hash,
1646                                        client->data.public_key,
1647                                        client);
1648
1649       /* Update statistics */
1650       server->stat.clients--;
1651       if (server->stat.cell_clients)
1652         server->stat.cell_clients--;
1653       SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
1654       SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
1655
1656       if (SILC_IS_LOCAL(client)) {
1657         server->stat.my_clients--;
1658         silc_schedule_task_del_by_context(server->schedule, client);
1659         silc_idlist_del_data(client);
1660         client->mode = 0;
1661       }
1662
1663       client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
1664       client->mode = 0;
1665       client->router = NULL;
1666       client->connection = NULL;
1667       cache->expire = SILC_ID_CACHE_EXPIRE_DEF;
1668       break;
1669     }
1670
1671   case SILC_NOTIFY_TYPE_UMODE_CHANGE:
1672     /*
1673      * Save the mode of the client.
1674      */
1675
1676     SILC_LOG_DEBUG(("UMODE_CHANGE notify"));
1677
1678     /* Get client ID */
1679     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
1680     if (!tmp)
1681       goto out;
1682     client_id = silc_id_payload_parse_id(tmp, tmp_len, NULL);
1683     if (!client_id)
1684       goto out;
1685
1686     /* Get client entry */
1687     client = silc_idlist_find_client_by_id(server->global_list,
1688                                            client_id, TRUE, NULL);
1689     if (!client) {
1690       client = silc_idlist_find_client_by_id(server->local_list,
1691                                              client_id, TRUE, NULL);
1692       if (!client) {
1693         silc_free(client_id);
1694         goto out;
1695       }
1696     }
1697     silc_free(client_id);
1698
1699     /* Get the mode */
1700     tmp = silc_argument_get_arg_type(args, 2, &tmp_len);
1701     if (!tmp)
1702       goto out;
1703     SILC_GET32_MSB(mode, tmp);
1704
1705     /* Remove internal resumed flag if client is marked detached now */
1706     if (mode & SILC_UMODE_DETACHED)
1707       client->data.status &= ~SILC_IDLIST_STATUS_RESUMED;
1708
1709     /* Update statistics */
1710     if (server->server_type == SILC_ROUTER) {
1711       if (mode & SILC_UMODE_GONE) {
1712         if (!(client->mode & SILC_UMODE_GONE))
1713           server->stat.aways++;
1714       } else {
1715         if (client->mode & SILC_UMODE_GONE)
1716           server->stat.aways--;
1717       }
1718       if (mode & SILC_UMODE_DETACHED) {
1719         if (!(client->mode & SILC_UMODE_DETACHED))
1720           server->stat.detached++;
1721       } else {
1722         if (client->mode & SILC_UMODE_DETACHED)
1723           server->stat.detached--;
1724       }
1725     }
1726     SILC_UMODE_STATS_UPDATE(server, SILC_UMODE_SERVER_OPERATOR);
1727     SILC_UMODE_STATS_UPDATE(router, SILC_UMODE_ROUTER_OPERATOR);
1728
1729     /* Change the mode */
1730     client->mode = mode;
1731
1732     /* Check if anyone is watching this nickname */
1733     if (server->server_type == SILC_ROUTER)
1734       silc_server_check_watcher_list(server, client, NULL,
1735                                      SILC_NOTIFY_TYPE_UMODE_CHANGE);
1736
1737     break;
1738
1739   case SILC_NOTIFY_TYPE_BAN:
1740     /*
1741      * Save the ban
1742      */
1743
1744     SILC_LOG_DEBUG(("BAN notify"));
1745
1746     /* Get Channel ID */
1747     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
1748     if (!tmp)
1749       goto out;
1750     channel_id = silc_id_payload_parse_id(tmp, tmp_len, NULL);
1751     if (!channel_id)
1752       goto out;
1753
1754     /* Get channel entry */
1755     channel = silc_idlist_find_channel_by_id(server->global_list,
1756                                              channel_id, NULL);
1757     if (!channel) {
1758       channel = silc_idlist_find_channel_by_id(server->local_list,
1759                                                channel_id, NULL);
1760       if (!channel) {
1761         SILC_LOG_DEBUG(("Notify for unknown channel"));
1762         silc_free(channel_id);
1763         goto out;
1764       }
1765     }
1766     silc_free(channel_id);
1767
1768     /* Get the ban action */
1769     tmp = silc_argument_get_arg_type(args, 2, &tmp_len);
1770     if (tmp && tmp_len == 1) {
1771       SilcUInt8 action = (SilcUInt8)tmp[0];
1772       SilcUInt16 iargc = 0;
1773       SilcArgumentPayload iargs;
1774
1775       /* Get ban list */
1776       tmp = silc_argument_get_arg_type(args, 3, &tmp_len);
1777       if (!tmp || tmp_len < 2)
1778         goto out;
1779
1780       /* Parse the arguments to see they are constructed correctly */
1781       SILC_GET16_MSB(iargc, tmp);
1782       iargs = silc_argument_payload_parse(tmp + 2, tmp_len - 2, iargc);
1783       if (!iargs)
1784         goto out;
1785
1786       if (action != 0x01 && !channel->ban_list)
1787         channel->ban_list =
1788           silc_hash_table_alloc(0, silc_hash_ptr,
1789                                 NULL, NULL, NULL,
1790                                 silc_server_inviteban_destruct, channel, TRUE);
1791
1792       /* Proces the ban action */
1793       silc_server_inviteban_process(server, channel->ban_list, action,
1794                                     iargs);
1795       silc_argument_payload_free(iargs);
1796
1797       /* If we are router we must send this notify to our local servers on
1798          the channel.  Normal server does nothing.  The notify is not
1799          sent to clients. */
1800       if (server->server_type == SILC_ROUTER)
1801         silc_server_packet_send_to_channel(server, sock, channel,
1802                                            packet->type, FALSE, FALSE,
1803                                            packet->buffer->data,
1804                                            packet->buffer->len, FALSE);
1805     }
1806     break;
1807
1808   case SILC_NOTIFY_TYPE_ERROR:
1809     {
1810       /*
1811        * Error notify
1812        */
1813       SilcStatus error;
1814
1815       tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
1816       if (!tmp && tmp_len != 1)
1817         goto out;
1818       error = (SilcStatus)tmp[0];
1819
1820       SILC_LOG_DEBUG(("ERROR notify (%d)", error));
1821
1822       if (error == SILC_STATUS_ERR_NO_SUCH_CLIENT_ID &&
1823           sock->type == SILC_SOCKET_TYPE_ROUTER) {
1824         tmp = silc_argument_get_arg_type(args, 2, &tmp_len);
1825         if (tmp) {
1826           SILC_LOG_DEBUG(("Received invalid client ID notification, deleting "
1827                           "the entry from cache"));
1828           client_id = silc_id_payload_parse_id(tmp, tmp_len, NULL);
1829           if (!client_id)
1830             goto out;
1831           client = silc_idlist_find_client_by_id(server->global_list,
1832                                                  client_id, FALSE, NULL);
1833           if (client) {
1834             if (client->data.public_key)
1835               silc_hash_table_del_by_context(server->pk_hash,
1836                                              client->data.public_key,
1837                                              client);
1838
1839             silc_server_remove_from_channels(server, NULL, client, TRUE,
1840                                              NULL, TRUE, FALSE);
1841             silc_idlist_del_data(client);
1842             silc_idlist_del_client(server->global_list, client);
1843           }
1844           silc_free(client_id);
1845         }
1846       }
1847     }
1848     break;
1849
1850     /* Ignore rest of the notify types for now */
1851   case SILC_NOTIFY_TYPE_NONE:
1852   case SILC_NOTIFY_TYPE_MOTD:
1853     break;
1854   default:
1855     break;
1856   }
1857
1858  out:
1859   silc_notify_payload_free(payload);
1860 }
1861
1862 void silc_server_notify_list(SilcServer server,
1863                              SilcSocketConnection sock,
1864                              SilcPacketContext *packet)
1865 {
1866   SilcPacketContext *new;
1867   SilcBuffer buffer;
1868   SilcUInt16 len;
1869
1870   SILC_LOG_DEBUG(("Processing Notify List"));
1871
1872   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
1873       packet->src_id_type != SILC_ID_SERVER)
1874     return;
1875
1876   /* Make copy of the original packet context, except for the actual
1877      data buffer, which we will here now fetch from the original buffer. */
1878   new = silc_packet_context_alloc();
1879   new->type = SILC_PACKET_NOTIFY;
1880   new->flags = packet->flags;
1881   new->src_id = packet->src_id;
1882   new->src_id_len = packet->src_id_len;
1883   new->src_id_type = packet->src_id_type;
1884   new->dst_id = packet->dst_id;
1885   new->dst_id_len = packet->dst_id_len;
1886   new->dst_id_type = packet->dst_id_type;
1887
1888   buffer = silc_buffer_alloc(1024);
1889   new->buffer = buffer;
1890
1891   while (packet->buffer->len) {
1892     SILC_GET16_MSB(len, packet->buffer->data + 2);
1893     if (len > packet->buffer->len)
1894       break;
1895
1896     if (len > buffer->truelen) {
1897       silc_buffer_free(buffer);
1898       buffer = silc_buffer_alloc(1024 + len);
1899     }
1900
1901     silc_buffer_pull_tail(buffer, len);
1902     silc_buffer_put(buffer, packet->buffer->data, len);
1903
1904     /* Process the Notify */
1905     silc_server_notify(server, sock, new);
1906
1907     silc_buffer_push_tail(buffer, len);
1908     silc_buffer_pull(packet->buffer, len);
1909   }
1910
1911   silc_buffer_free(buffer);
1912   silc_free(new);
1913 }
1914
1915 /* Received private message. This resolves the destination of the message
1916    and sends the packet. This is used by both server and router.  If the
1917    destination is our locally connected client this sends the packet to
1918    the client. This may also send the message for further routing if
1919    the destination is not in our server (or router). */
1920
1921 void silc_server_private_message(SilcServer server,
1922                                  SilcSocketConnection sock,
1923                                  SilcPacketContext *packet)
1924 {
1925   SilcSocketConnection dst_sock;
1926   SilcIDListData idata;
1927   SilcClientEntry client;
1928
1929   SILC_LOG_DEBUG(("Start"));
1930
1931   if (packet->src_id_type != SILC_ID_CLIENT ||
1932       packet->dst_id_type != SILC_ID_CLIENT || !packet->dst_id)
1933     return;
1934
1935   /* Get the route to the client */
1936   dst_sock = silc_server_get_client_route(server, packet->dst_id,
1937                                           packet->dst_id_len, NULL,
1938                                           &idata, &client);
1939   if (!dst_sock) {
1940     SilcBuffer idp;
1941     unsigned char error;
1942
1943     if (client && client->mode & SILC_UMODE_DETACHED) {
1944       SILC_LOG_DEBUG(("Client is detached, discarding packet"));
1945       return;
1946     }
1947
1948     /* Send SILC_NOTIFY_TYPE_ERROR to indicate that such destination ID
1949        does not exist or is invalid. */
1950     idp = silc_id_payload_encode_data(packet->dst_id,
1951                                       packet->dst_id_len,
1952                                       packet->dst_id_type);
1953     if (!idp)
1954       return;
1955
1956     error = SILC_STATUS_ERR_NO_SUCH_CLIENT_ID;
1957     if (packet->src_id_type == SILC_ID_CLIENT) {
1958       SilcClientID *client_id = silc_id_str2id(packet->src_id,
1959                                                packet->src_id_len,
1960                                                packet->src_id_type);
1961       silc_server_send_notify_dest(server, sock, FALSE,
1962                                    client_id, SILC_ID_CLIENT,
1963                                    SILC_NOTIFY_TYPE_ERROR, 2,
1964                                    &error, 1,
1965                                    idp->data, idp->len);
1966       silc_free(client_id);
1967     } else {
1968       silc_server_send_notify(server, sock, FALSE,
1969                               SILC_NOTIFY_TYPE_ERROR, 2,
1970                               &error, 1,
1971                               idp->data, idp->len);
1972     }
1973
1974     silc_buffer_free(idp);
1975     return;
1976   }
1977
1978   /* Check whether destination client wishes to receive private messages */
1979   if (client && !(packet->flags & SILC_PACKET_FLAG_PRIVMSG_KEY) &&
1980       client->mode & SILC_UMODE_BLOCK_PRIVMSG) {
1981     SILC_LOG_DEBUG(("Client blocks private messages, discarding packet"));
1982     return;
1983   }
1984
1985   /* Send the private message */
1986   silc_server_send_private_message(server, dst_sock, idata->send_key,
1987                                    idata->hmac_send, idata->psn_send++,
1988                                    packet);
1989 }
1990
1991 /* Received private message key packet.. This packet is never for us. It is to
1992    the client in the packet's destination ID. Sending of this sort of packet
1993    equals sending private message, ie. it is sent point to point from
1994    one client to another. */
1995
1996 void silc_server_private_message_key(SilcServer server,
1997                                      SilcSocketConnection sock,
1998                                      SilcPacketContext *packet)
1999 {
2000   SilcSocketConnection dst_sock;
2001   SilcIDListData idata;
2002
2003   SILC_LOG_DEBUG(("Start"));
2004
2005   if (packet->src_id_type != SILC_ID_CLIENT ||
2006       packet->dst_id_type != SILC_ID_CLIENT)
2007     return;
2008
2009   if (!packet->dst_id)
2010     return;
2011
2012   /* Get the route to the client */
2013   dst_sock = silc_server_get_client_route(server, packet->dst_id,
2014                                           packet->dst_id_len, NULL,
2015                                           &idata, NULL);
2016   if (!dst_sock)
2017     return;
2018
2019   /* Relay the packet */
2020   silc_server_relay_packet(server, dst_sock, idata->send_key,
2021                            idata->hmac_send, idata->psn_send++, packet, FALSE);
2022 }
2023
2024 /* Processes incoming command reply packet. The command reply packet may
2025    be destined to one of our clients or it may directly for us. We will
2026    call the command reply routine after processing the packet. */
2027
2028 void silc_server_command_reply(SilcServer server,
2029                                SilcSocketConnection sock,
2030                                SilcPacketContext *packet)
2031 {
2032   SilcBuffer buffer = packet->buffer;
2033   SilcClientEntry client = NULL;
2034   SilcSocketConnection dst_sock;
2035   SilcIDListData idata;
2036   SilcClientID *id = NULL;
2037
2038   SILC_LOG_DEBUG(("Start"));
2039
2040   if (packet->dst_id_type == SILC_ID_CHANNEL)
2041     return;
2042
2043   if (packet->dst_id_type == SILC_ID_CLIENT) {
2044     /* Destination must be one of ours */
2045     id = silc_id_str2id(packet->dst_id, packet->dst_id_len, SILC_ID_CLIENT);
2046     if (!id)
2047       return;
2048     client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
2049     if (!client) {
2050       SILC_LOG_ERROR(("Cannot process command reply to unknown client"));
2051       silc_free(id);
2052       return;
2053     }
2054   }
2055
2056   if (packet->dst_id_type == SILC_ID_SERVER) {
2057     /* For now this must be for us */
2058     if (memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
2059       SILC_LOG_ERROR(("Cannot process command reply to unknown server"));
2060       return;
2061     }
2062   }
2063
2064   /* Execute command reply locally for the command */
2065   silc_server_command_reply_process(server, sock, buffer);
2066
2067   if (packet->dst_id_type == SILC_ID_CLIENT && client && id) {
2068     /* Relay the packet to the client */
2069     const SilcBufferStruct p;
2070
2071     dst_sock = (SilcSocketConnection)client->connection;
2072     idata = (SilcIDListData)client;
2073
2074     silc_buffer_push(buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len
2075                      + packet->dst_id_len + packet->padlen);
2076     if (!silc_packet_send_prepare(dst_sock, 0, 0, buffer->len,
2077                                   idata->hmac_send, (const SilcBuffer)&p)) {
2078       SILC_LOG_ERROR(("Cannot send packet"));
2079       return;
2080     }
2081     silc_buffer_put((SilcBuffer)&p, buffer->data, buffer->len);
2082
2083     /* Encrypt packet */
2084     silc_packet_encrypt(idata->send_key, idata->hmac_send, idata->psn_send++,
2085                         (SilcBuffer)&p, buffer->len);
2086
2087     /* Send the packet */
2088     silc_server_packet_send_real(server, dst_sock, TRUE);
2089
2090     silc_free(id);
2091   }
2092 }
2093
2094 /* Process received channel message. The message can be originated from
2095    client or server. */
2096
2097 void silc_server_channel_message(SilcServer server,
2098                                  SilcSocketConnection sock,
2099                                  SilcPacketContext *packet)
2100 {
2101   SilcChannelEntry channel = NULL;
2102   SilcChannelID *id = NULL;
2103   void *sender_id = NULL;
2104   SilcClientEntry sender_entry = NULL;
2105   SilcChannelClientEntry chl;
2106   bool local = TRUE;
2107
2108   SILC_LOG_DEBUG(("Processing channel message"));
2109
2110   /* Sanity checks */
2111   if (packet->dst_id_type != SILC_ID_CHANNEL) {
2112     SILC_LOG_DEBUG(("Received bad message for channel, dropped"));
2113     goto out;
2114   }
2115
2116   /* Find channel entry */
2117   id = silc_id_str2id(packet->dst_id, packet->dst_id_len, SILC_ID_CHANNEL);
2118   if (!id)
2119     goto out;
2120   channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
2121   if (!channel) {
2122     channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
2123     if (!channel) {
2124       SilcBuffer idp;
2125       unsigned char error;
2126
2127       /* Send SILC_NOTIFY_TYPE_ERROR to indicate that such destination ID
2128          does not exist or is invalid. */
2129       idp = silc_id_payload_encode_data(packet->dst_id,
2130                                         packet->dst_id_len,
2131                                         packet->dst_id_type);
2132       if (!idp)
2133         goto out;
2134
2135       error = SILC_STATUS_ERR_NO_SUCH_CHANNEL_ID;
2136       if (packet->src_id_type == SILC_ID_CLIENT) {
2137         SilcClientID *client_id = silc_id_str2id(packet->src_id,
2138                                                  packet->src_id_len,
2139                                                  packet->src_id_type);
2140         silc_server_send_notify_dest(server, sock, FALSE,
2141                                      client_id, SILC_ID_CLIENT,
2142                                      SILC_NOTIFY_TYPE_ERROR, 2,
2143                                      &error, 1, idp->data, idp->len);
2144         silc_free(client_id);
2145       } else {
2146         silc_server_send_notify(server, sock, FALSE,
2147                                 SILC_NOTIFY_TYPE_ERROR, 2,
2148                                 &error, 1, idp->data, idp->len);
2149       }
2150
2151       silc_buffer_free(idp);
2152       goto out;
2153     }
2154   }
2155
2156   /* See that this client is on the channel. If the original sender is
2157      not client (as it can be server as well) we don't do the check. */
2158   sender_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2159                              packet->src_id_type);
2160   if (!sender_id)
2161     goto out;
2162   if (packet->src_id_type == SILC_ID_CLIENT) {
2163     sender_entry = silc_idlist_find_client_by_id(server->local_list,
2164                                                  sender_id, TRUE, NULL);
2165     if (!sender_entry) {
2166       local = FALSE;
2167       sender_entry = silc_idlist_find_client_by_id(server->global_list,
2168                                                    sender_id, TRUE, NULL);
2169     }
2170     if (!sender_entry || !silc_server_client_on_channel(sender_entry,
2171                                                         channel, &chl)) {
2172       SILC_LOG_DEBUG(("Client not on channel"));
2173       goto out;
2174     }
2175
2176     /* If channel is moderated check that client is allowed to send
2177        messages. */
2178     if (channel->mode & SILC_CHANNEL_MODE_SILENCE_USERS &&
2179         !(chl->mode & SILC_CHANNEL_UMODE_CHANOP) &&
2180         !(chl->mode & SILC_CHANNEL_UMODE_CHANFO)) {
2181       SILC_LOG_DEBUG(("Channel is silenced from normal users"));
2182       goto out;
2183     }
2184     if (channel->mode & SILC_CHANNEL_MODE_SILENCE_OPERS &&
2185         chl->mode & SILC_CHANNEL_UMODE_CHANOP &&
2186         !(chl->mode & SILC_CHANNEL_UMODE_CHANFO)) {
2187       SILC_LOG_DEBUG(("Channel is silenced from operators"));
2188       goto out;
2189     }
2190     if (chl->mode & SILC_CHANNEL_UMODE_QUIET) {
2191       SILC_LOG_DEBUG(("Sender is quieted on the channel"));
2192       goto out;
2193     }
2194
2195     /* If the packet is coming from router, but the client entry is local
2196        entry to us then some router is rerouting this to us and it is not
2197        allowed. When the client is local to us it means that we've routed
2198        this packet to network, and now someone is routing it back to us. */
2199     if (server->server_type == SILC_ROUTER &&
2200         sock->type == SILC_SOCKET_TYPE_ROUTER && local) {
2201       SILC_LOG_DEBUG(("Channel message rerouted to the sender, drop it"));
2202       goto out;
2203     }
2204   }
2205
2206   /* Distribute the packet to our local clients. This will send the
2207      packet for further routing as well, if needed. */
2208   silc_server_packet_relay_to_channel(server, sock, channel, sender_id,
2209                                       packet->src_id_type, sender_entry,
2210                                       packet->buffer->data,
2211                                       packet->buffer->len, FALSE);
2212
2213  out:
2214   silc_free(sender_id);
2215   silc_free(id);
2216 }
2217
2218 /* Received channel key packet. We distribute the key to all of our locally
2219    connected clients on the channel. */
2220
2221 void silc_server_channel_key(SilcServer server,
2222                              SilcSocketConnection sock,
2223                              SilcPacketContext *packet)
2224 {
2225   SilcBuffer buffer = packet->buffer;
2226   SilcChannelEntry channel;
2227
2228   if (packet->src_id_type != SILC_ID_SERVER ||
2229       (server->server_type == SILC_ROUTER && !server->backup_router &&
2230        sock->type == SILC_SOCKET_TYPE_ROUTER))
2231     return;
2232
2233   /* Save the channel key */
2234   channel = silc_server_save_channel_key(server, buffer, NULL);
2235   if (!channel) {
2236     SILC_LOG_ERROR(("Bad channel key from %s (%s)",
2237                     sock->hostname, sock->ip));
2238     return;
2239   }
2240
2241   /* Distribute the key to everybody who is on the channel. If we are router
2242      we will also send it to locally connected servers. */
2243   silc_server_send_channel_key(server, sock, channel, FALSE);
2244
2245   if (server->server_type != SILC_BACKUP_ROUTER) {
2246     /* Distribute to local cell backup routers. */
2247     silc_server_backup_send(server, sock->user_data,
2248                             SILC_PACKET_CHANNEL_KEY, 0,
2249                             buffer->data, buffer->len, FALSE, TRUE);
2250   }
2251 }
2252
2253 /* Received New Client packet and processes it.  Creates Client ID for the
2254    client. Client becomes registered after calling this functions. */
2255
2256 SilcClientEntry silc_server_new_client(SilcServer server,
2257                                        SilcSocketConnection sock,
2258                                        SilcPacketContext *packet)
2259 {
2260   SilcBuffer buffer = packet->buffer;
2261   SilcClientEntry client;
2262   SilcClientID *client_id;
2263   SilcIDListData idata;
2264   char *username = NULL, *realname = NULL;
2265   SilcUInt16 username_len;
2266   SilcUInt32 id_len, tmp_len;
2267   int ret;
2268   char *hostname, *nickname, *nicknamec;
2269
2270   SILC_LOG_DEBUG(("Creating new client"));
2271
2272   if (sock->type != SILC_SOCKET_TYPE_CLIENT)
2273     return NULL;
2274
2275   /* Take client entry */
2276   client = (SilcClientEntry)sock->user_data;
2277   idata = (SilcIDListData)client;
2278
2279   /* Remove the old cache entry. */
2280   if (!silc_idcache_del_by_context(server->local_list->clients, client)) {
2281     SILC_LOG_INFO(("Unauthenticated client attempted to register to network"));
2282     silc_server_disconnect_remote(server, sock,
2283                                   SILC_STATUS_ERR_NOT_AUTHENTICATED, NULL);
2284     if (sock->user_data)
2285       silc_server_free_sock_user_data(server, sock, NULL);
2286     return NULL;
2287   }
2288
2289   /* Make sure this client hasn't registered already */
2290   if (idata->status & SILC_IDLIST_STATUS_REGISTERED) {
2291     silc_server_disconnect_remote(server, sock,
2292                                   SILC_STATUS_ERR_OPERATION_ALLOWED,
2293                                   "Too many registrations");
2294     if (sock->user_data)
2295       silc_server_free_sock_user_data(server, sock, NULL);
2296     return NULL;
2297   }
2298
2299   /* Parse incoming packet */
2300   ret = silc_buffer_unformat(buffer,
2301                              SILC_STR_UI16_NSTRING_ALLOC(&username,
2302                                                          &username_len),
2303                              SILC_STR_UI16_STRING_ALLOC(&realname),
2304                              SILC_STR_END);
2305   if (ret == -1) {
2306     silc_free(username);
2307     silc_free(realname);
2308     SILC_LOG_ERROR(("Client %s (%s) sent incomplete information, closing "
2309                     "connection", sock->hostname, sock->ip));
2310     silc_server_disconnect_remote(server, sock,
2311                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2312                                   NULL);
2313     if (sock->user_data)
2314       silc_server_free_sock_user_data(server, sock, NULL);
2315     return NULL;
2316   }
2317
2318   if (!username) {
2319     silc_free(username);
2320     silc_free(realname);
2321     SILC_LOG_ERROR(("Client %s (%s) did not send its username, closing "
2322                     "connection", sock->hostname, sock->ip));
2323     silc_server_disconnect_remote(server, sock,
2324                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2325                                   NULL);
2326     if (sock->user_data)
2327       silc_server_free_sock_user_data(server, sock, NULL);
2328     return NULL;
2329   }
2330
2331   if (username_len > 128) {
2332     username[128] = '\0';
2333     username_len = 128;
2334   }
2335
2336   /* Check for valid username string */
2337   nicknamec = silc_identifier_check(username, username_len,
2338                                     SILC_STRING_UTF8, 128, &tmp_len);
2339   if (!nicknamec) {
2340     silc_free(username);
2341     silc_free(realname);
2342     SILC_LOG_ERROR(("Client %s (%s) sent bad username string, closing "
2343                     "connection", sock->hostname, sock->ip));
2344     silc_server_disconnect_remote(server, sock,
2345                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2346                                   NULL);
2347     if (sock->user_data)
2348       silc_server_free_sock_user_data(server, sock, NULL);
2349     return NULL;
2350   }
2351
2352   /* Nickname is initially same as username */
2353   nickname = strdup(username);
2354
2355   /* Make sanity checks for the hostname of the client. If the hostname
2356      is provided in the `username' check that it is the same than the
2357      resolved hostname, or if not resolved the hostname that appears in
2358      the client's public key. If the hostname is not present then put
2359      it from the resolved name or from the public key. */
2360   if (strchr(username, '@')) {
2361     SilcPublicKeyIdentifier pident;
2362     int tlen = strcspn(username, "@");
2363     char *phostname = NULL;
2364
2365     hostname = silc_memdup(username + tlen + 1, strlen(username) - tlen - 1);
2366
2367     if (strcmp(sock->hostname, sock->ip) &&
2368         strcmp(sock->hostname, hostname)) {
2369       silc_free(username);
2370       silc_free(hostname);
2371       silc_free(realname);
2372       SILC_LOG_ERROR(("Client %s (%s) sent incomplete information, closing "
2373                       "connection", sock->hostname, sock->ip));
2374       silc_server_disconnect_remote(server, sock,
2375                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2376                                     NULL);
2377       if (sock->user_data)
2378         silc_server_free_sock_user_data(server, sock, NULL);
2379       return NULL;
2380     }
2381
2382     pident = silc_pkcs_decode_identifier(client->data.public_key->identifier);
2383     if (pident) {
2384       phostname = strdup(pident->host);
2385       silc_pkcs_free_identifier(pident);
2386     }
2387
2388     if (!strcmp(sock->hostname, sock->ip) &&
2389         phostname && strcmp(phostname, hostname)) {
2390       silc_free(username);
2391       silc_free(hostname);
2392       silc_free(phostname);
2393       silc_free(realname);
2394       SILC_LOG_ERROR(("Client %s (%s) sent incomplete information, closing "
2395                       "connection", sock->hostname, sock->ip));
2396       silc_server_disconnect_remote(server, sock,
2397                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2398                                     NULL);
2399       if (sock->user_data)
2400         silc_server_free_sock_user_data(server, sock, NULL);
2401       return NULL;
2402     }
2403
2404     silc_free(phostname);
2405   } else {
2406     /* The hostname is not present, add it. */
2407     char *newusername;
2408     /* XXX For now we cannot take the host name from the public key since
2409        they are not trusted or we cannot verify them as trusted. Just take
2410        what the resolved name or address is. */
2411 #if 0
2412     if (strcmp(sock->hostname, sock->ip)) {
2413 #endif
2414       newusername = silc_calloc(strlen(username) +
2415                                 strlen(sock->hostname) + 2,
2416                                 sizeof(*newusername));
2417       strncat(newusername, username, strlen(username));
2418       strncat(newusername, "@", 1);
2419       strncat(newusername, sock->hostname, strlen(sock->hostname));
2420       silc_free(username);
2421       username = newusername;
2422 #if 0
2423     } else {
2424       SilcPublicKeyIdentifier pident =
2425         silc_pkcs_decode_identifier(client->data.public_key->identifier);
2426
2427       if (pident) {
2428         newusername = silc_calloc(strlen(username) +
2429                                   strlen(pident->host) + 2,
2430                                   sizeof(*newusername));
2431         strncat(newusername, username, strlen(username));
2432         strncat(newusername, "@", 1);
2433         strncat(newusername, pident->host, strlen(pident->host));
2434         silc_free(username);
2435         username = newusername;
2436         silc_pkcs_free_identifier(pident);
2437       }
2438     }
2439 #endif
2440   }
2441
2442   /* Create Client ID */
2443   if (!silc_id_create_client_id(server, server->id, server->rng,
2444                                 server->md5hash, nicknamec,
2445                                 strlen(nicknamec), &client_id)) {
2446     silc_server_disconnect_remote(server, sock,
2447                                   SILC_STATUS_ERR_BAD_NICKNAME, NULL);
2448     if (sock->user_data)
2449       silc_server_free_sock_user_data(server, sock, NULL);
2450     return NULL;
2451   }
2452
2453   /* If client marked as anonymous, scramble the username and hostname */
2454   if (client->mode & SILC_UMODE_ANONYMOUS) {
2455     char *scramble;
2456
2457     if (strlen(username) >= 2) {
2458       username[0] = silc_rng_get_byte_fast(server->rng);
2459       username[1] = silc_rng_get_byte_fast(server->rng);
2460     }
2461
2462     scramble = silc_hash_babbleprint(server->sha1hash, username,
2463                                      strlen(username));
2464     scramble[5] = '@';
2465     scramble[11] = '.';
2466     memcpy(&scramble[16], ".silc", 5);
2467     scramble[21] = '\0';
2468     silc_free(username);
2469     username = scramble;
2470   }
2471
2472   /* Update client entry */
2473   idata->status |= SILC_IDLIST_STATUS_REGISTERED;
2474   client->nickname = nickname;
2475   client->username = username;
2476   client->userinfo = realname ? realname : strdup(username);
2477   client->id = client_id;
2478   id_len = silc_id_get_len(client_id, SILC_ID_CLIENT);
2479
2480   /* Add the client again to the ID cache */
2481   silc_idcache_add(server->local_list->clients, nicknamec,
2482                    client_id, client, 0, NULL);
2483
2484   /* Notify our router about new client on the SILC network */
2485   silc_server_send_new_id(server, SILC_PRIMARY_ROUTE(server),
2486                           SILC_BROADCAST(server), client->id,
2487                           SILC_ID_CLIENT, id_len);
2488
2489   /* Distribute to backup routers */
2490   if (server->server_type == SILC_ROUTER) {
2491     SilcBuffer idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2492     silc_server_backup_send(server, sock->user_data, SILC_PACKET_NEW_ID, 0,
2493                             idp->data, idp->len, FALSE, TRUE);
2494     silc_buffer_free(idp);
2495   }
2496
2497   /* Send the new client ID to the client. */
2498   silc_server_send_new_id(server, sock, FALSE, client->id, SILC_ID_CLIENT,
2499                           silc_id_get_len(client->id, SILC_ID_CLIENT));
2500
2501   /* Send some nice info to the client */
2502   silc_server_send_connect_notifys(server, sock, client);
2503
2504   /* Check if anyone is watching this nickname */
2505   if (server->server_type == SILC_ROUTER)
2506     silc_server_check_watcher_list(server, client, NULL, 0);
2507
2508   return client;
2509 }
2510
2511 /* Create new server. This processes received New Server packet and
2512    saves the received Server ID. The server is our locally connected
2513    server thus we save all the information and save it to local list.
2514    This funtion can be used by both normal server and router server.
2515    If normal server uses this it means that its router has connected
2516    to the server. If router uses this it means that one of the cell's
2517    servers is connected to the router. */
2518
2519 SilcServerEntry silc_server_new_server(SilcServer server,
2520                                        SilcSocketConnection sock,
2521                                        SilcPacketContext *packet)
2522 {
2523   SilcBuffer buffer = packet->buffer;
2524   SilcServerEntry new_server, server_entry;
2525   SilcServerID *server_id;
2526   SilcIDListData idata;
2527   unsigned char *server_name, *server_namec, *id_string;
2528   SilcUInt16 id_len, name_len;
2529   int ret;
2530   bool local = TRUE;
2531
2532   SILC_LOG_DEBUG(("Creating new server"));
2533
2534   if (sock->type != SILC_SOCKET_TYPE_SERVER &&
2535       sock->type != SILC_SOCKET_TYPE_ROUTER)
2536     return NULL;
2537
2538   /* Take server entry */
2539   new_server = (SilcServerEntry)sock->user_data;
2540   idata = (SilcIDListData)new_server;
2541
2542   /* Statistics */
2543   if (server->server_type == SILC_ROUTER)
2544     server->stat.cell_servers++;
2545
2546   /* Remove the old cache entry */
2547   if (!silc_idcache_del_by_context(server->local_list->servers, new_server)) {
2548     if (!silc_idcache_del_by_context(server->global_list->servers,
2549                                      new_server)) {
2550       SILC_LOG_INFO(("Unauthenticated %s attempted to register to "
2551                      "network", (sock->type == SILC_SOCKET_TYPE_SERVER ?
2552                                  "server" : "router")));
2553       silc_server_disconnect_remote(server, sock,
2554                                     SILC_STATUS_ERR_NOT_AUTHENTICATED, NULL);
2555       if (sock->user_data)
2556         silc_server_free_sock_user_data(server, sock, NULL);
2557       return NULL;
2558     }
2559     local = FALSE;
2560   }
2561
2562   /* Make sure this server hasn't registered already */
2563   if (idata->status & SILC_IDLIST_STATUS_REGISTERED) {
2564     silc_server_disconnect_remote(server, sock,
2565                                   SILC_STATUS_ERR_OPERATION_ALLOWED,
2566                                   "Too many registrations");
2567     if (sock->user_data)
2568       silc_server_free_sock_user_data(server, sock, NULL);
2569     return NULL;
2570   }
2571
2572   /* Parse the incoming packet */
2573   ret = silc_buffer_unformat(buffer,
2574                              SILC_STR_UI16_NSTRING_ALLOC(&id_string, &id_len),
2575                              SILC_STR_UI16_NSTRING_ALLOC(&server_name,
2576                                                          &name_len),
2577                              SILC_STR_END);
2578   if (ret == -1) {
2579     silc_free(id_string);
2580     silc_free(server_name);
2581     silc_server_disconnect_remote(server, sock,
2582                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2583                                   NULL);
2584     if (sock->user_data)
2585       silc_server_free_sock_user_data(server, sock, NULL);
2586     return NULL;
2587   }
2588
2589   if (id_len > buffer->len) {
2590     silc_free(id_string);
2591     silc_free(server_name);
2592     silc_server_disconnect_remote(server, sock,
2593                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2594                                   NULL);
2595     if (sock->user_data)
2596       silc_server_free_sock_user_data(server, sock, NULL);
2597     return NULL;
2598   }
2599
2600   if (name_len > 256) {
2601     server_name[256] = '\0';
2602     name_len = 256;
2603   }
2604
2605   /* Get Server ID */
2606   server_id = silc_id_str2id(id_string, id_len, SILC_ID_SERVER);
2607   if (!server_id) {
2608     silc_free(id_string);
2609     silc_free(server_name);
2610     silc_server_disconnect_remote(server, sock,
2611                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2612                                   NULL);
2613     if (sock->user_data)
2614       silc_server_free_sock_user_data(server, sock, NULL);
2615     return NULL;
2616   }
2617   silc_free(id_string);
2618
2619   /* Check for valid server ID */
2620   if (!silc_id_is_valid_server_id(server, server_id, sock)) {
2621     SILC_LOG_INFO(("Invalid server ID sent by %s (%s)",
2622                    sock->ip, sock->hostname));
2623     silc_server_disconnect_remote(server, sock,
2624                                   SILC_STATUS_ERR_BAD_SERVER_ID, NULL);
2625     if (sock->user_data)
2626       silc_server_free_sock_user_data(server, sock, NULL);
2627     silc_free(server_name);
2628     return NULL;
2629   }
2630
2631   /* Check that we do not have this ID already */
2632   server_entry = silc_idlist_find_server_by_id(server->local_list,
2633                                                server_id, TRUE, NULL);
2634   if (server_entry) {
2635     if (SILC_IS_LOCAL(server_entry)) {
2636       SILC_LOG_ERROR(("Too many registrations from %s (%s)",
2637                       sock->ip, sock->hostname));
2638       silc_server_disconnect_remote(server, sock,
2639                                     SILC_STATUS_ERR_OPERATION_ALLOWED,
2640                                     "Too many registrations");
2641       if (sock->user_data)
2642         silc_server_free_sock_user_data(server, sock, NULL);
2643       return NULL;
2644     } else {
2645       silc_idcache_del_by_context(server->local_list->servers, server_entry);
2646     }
2647   } else {
2648     server_entry = silc_idlist_find_server_by_id(server->global_list,
2649                                                  server_id, TRUE, NULL);
2650     if (server_entry) {
2651       if (SILC_IS_LOCAL(server_entry)) {
2652         SILC_LOG_ERROR(("Too many registrations from %s (%s)",
2653                         sock->ip, sock->hostname));
2654         silc_server_disconnect_remote(server, sock,
2655                                       SILC_STATUS_ERR_OPERATION_ALLOWED,
2656                                       "Too many registrations");
2657         if (sock->user_data)
2658           silc_server_free_sock_user_data(server, sock, NULL);
2659         return NULL;
2660       } else {
2661         silc_idcache_del_by_context(server->global_list->servers,
2662                                     server_entry);
2663       }
2664     }
2665   }
2666
2667   /* Check server name */
2668   server_namec = silc_identifier_check(server_name, strlen(server_name),
2669                                        SILC_STRING_UTF8, 256, NULL);
2670   if (!server_namec) {
2671     SILC_LOG_ERROR(("Malformed server name from %s (%s)",
2672                     sock->ip, sock->hostname));
2673     silc_server_disconnect_remote(server, sock,
2674                                   SILC_STATUS_ERR_OPERATION_ALLOWED,
2675                                   "Malfromed server name");
2676     if (sock->user_data)
2677       silc_server_free_sock_user_data(server, sock, NULL);
2678     return NULL;
2679   }
2680
2681   /* Update server entry */
2682   idata->status |= SILC_IDLIST_STATUS_REGISTERED;
2683   new_server->server_name = server_name;
2684   new_server->id = server_id;
2685
2686   SILC_LOG_DEBUG(("New server id(%s)",
2687                   silc_id_render(server_id, SILC_ID_SERVER)));
2688
2689   /* Add again the entry to the ID cache. */
2690   silc_idcache_add(local ? server->local_list->servers :
2691                    server->global_list->servers, server_namec, server_id,
2692                    new_server, 0, NULL);
2693
2694   /* Distribute the information about new server in the SILC network
2695      to our router. If we are normal server we won't send anything
2696      since this connection must be our router connection. */
2697   if (server->server_type == SILC_ROUTER && !server->standalone &&
2698       SILC_PRIMARY_ROUTE(server) != sock)
2699     silc_server_send_new_id(server, SILC_PRIMARY_ROUTE(server),
2700                             TRUE, new_server->id, SILC_ID_SERVER,
2701                             silc_id_get_len(server_id, SILC_ID_SERVER));
2702
2703   if (server->server_type == SILC_ROUTER) {
2704     /* Distribute to backup routers */
2705     SilcBuffer idp = silc_id_payload_encode(new_server->id, SILC_ID_SERVER);
2706     silc_server_backup_send(server, sock->user_data, SILC_PACKET_NEW_ID, 0,
2707                             idp->data, idp->len, FALSE, TRUE);
2708     silc_buffer_free(idp);
2709   }
2710
2711   /* Check whether this router connection has been replaced by an
2712      backup router. If it has been then we'll disable the server and will
2713      ignore everything it will send until the backup router resuming
2714      protocol has been completed. */
2715   if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
2716       silc_server_backup_replaced_get(server, server_id, NULL)) {
2717     /* Send packet to the router indicating that it cannot use this
2718        connection as it has been replaced by backup router. */
2719     SILC_LOG_DEBUG(("Remote router has been replaced by backup router, "
2720                     "disabling its connection"));
2721
2722     silc_server_backup_send_replaced(server, sock);
2723
2724     /* Mark the router disabled. The data sent earlier will go but nothing
2725        after this goes to this connection. */
2726     idata->status |= SILC_IDLIST_STATUS_DISABLED;
2727   } else {
2728     /* If it is router announce our stuff to it. */
2729     if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
2730         server->server_type == SILC_ROUTER) {
2731       silc_server_announce_servers(server, FALSE, 0, sock);
2732       silc_server_announce_clients(server, 0, sock);
2733       silc_server_announce_channels(server, 0, sock);
2734     }
2735
2736     /* Announce our information to backup router */
2737     if (new_server->server_type == SILC_BACKUP_ROUTER &&
2738         sock->type == SILC_SOCKET_TYPE_SERVER &&
2739         server->server_type == SILC_ROUTER) {
2740       silc_server_announce_servers(server, TRUE, 0, sock);
2741       silc_server_announce_clients(server, 0, sock);
2742       silc_server_announce_channels(server, 0, sock);
2743     }
2744
2745     /* If backup router, mark it as one of ours.  This server is considered
2746        to be backup router after this setting. */
2747     if (new_server->server_type == SILC_BACKUP_ROUTER) {
2748       SilcServerConfigRouter *backup;
2749       backup = silc_server_config_find_backup_conn(server, sock->ip);
2750       if (!backup)
2751         backup = silc_server_config_find_backup_conn(server, sock->hostname);
2752       if (backup) {
2753         /* Add as our backup router */
2754         silc_server_backup_add(server, new_server, backup->backup_replace_ip,
2755                                backup->backup_replace_port,
2756                                backup->backup_local);
2757       }
2758     }
2759
2760     /* By default the servers connected to backup router are disabled
2761        until backup router has become the primary */
2762     if (server->server_type == SILC_BACKUP_ROUTER &&
2763         sock->type == SILC_SOCKET_TYPE_SERVER)
2764       idata->status |= SILC_IDLIST_STATUS_DISABLED;
2765   }
2766
2767   return new_server;
2768 }
2769
2770 /* Processes incoming New ID packet. New ID Payload is used to distribute
2771    information about newly registered clients and servers. */
2772
2773 static void silc_server_new_id_real(SilcServer server,
2774                                     SilcSocketConnection sock,
2775                                     SilcPacketContext *packet,
2776                                     int broadcast)
2777 {
2778   SilcBuffer buffer = packet->buffer;
2779   SilcIDList id_list;
2780   SilcServerEntry router, server_entry;
2781   SilcSocketConnection router_sock;
2782   SilcIDPayload idp;
2783   SilcIdType id_type;
2784   void *id;
2785
2786   SILC_LOG_DEBUG(("Processing new ID"));
2787
2788   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
2789       server->server_type == SILC_SERVER ||
2790       packet->src_id_type != SILC_ID_SERVER)
2791     return;
2792
2793   idp = silc_id_payload_parse(buffer->data, buffer->len);
2794   if (!idp)
2795     return;
2796
2797   id_type = silc_id_payload_get_type(idp);
2798
2799   /* Normal server cannot have other normal server connections */
2800   server_entry = (SilcServerEntry)sock->user_data;
2801   if (id_type == SILC_ID_SERVER && sock->type == SILC_SOCKET_TYPE_SERVER &&
2802       server_entry->server_type == SILC_SERVER)
2803     goto out;
2804
2805   id = silc_id_payload_get_id(idp);
2806   if (!id)
2807     goto out;
2808
2809   /* If the packet is coming from server then use the sender as the
2810      origin of the the packet. If it came from router then check the real
2811      sender of the packet and use that as the origin. */
2812   if (sock->type == SILC_SOCKET_TYPE_SERVER) {
2813     id_list = server->local_list;
2814     router_sock = sock;
2815     router = sock->user_data;
2816
2817     /* If the sender is backup router and ID is server (and we are not
2818        backup router) then switch the entry to global list. */
2819     if (server_entry->server_type == SILC_BACKUP_ROUTER &&
2820         id_type == SILC_ID_SERVER &&
2821         server->id_entry->server_type != SILC_BACKUP_ROUTER) {
2822       id_list = server->global_list;
2823       router_sock = server->router ? SILC_PRIMARY_ROUTE(server) : sock;
2824     }
2825   } else {
2826     void *sender_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2827                                      packet->src_id_type);
2828     router = silc_idlist_find_server_by_id(server->global_list,
2829                                            sender_id, TRUE, NULL);
2830     if (!router)
2831       router = silc_idlist_find_server_by_id(server->local_list,
2832                                              sender_id, TRUE, NULL);
2833     silc_free(sender_id);
2834     router_sock = sock;
2835     id_list = server->global_list;
2836   }
2837
2838   if (!router)
2839     goto out;
2840
2841   switch(id_type) {
2842   case SILC_ID_CLIENT:
2843     {
2844       SilcClientEntry entry;
2845
2846       /* Check that we do not have this client already */
2847       entry = silc_idlist_find_client_by_id(server->global_list,
2848                                             id, server->server_type,
2849                                             NULL);
2850       if (!entry)
2851         entry = silc_idlist_find_client_by_id(server->local_list,
2852                                               id, server->server_type,
2853                                               NULL);
2854       if (entry) {
2855         SILC_LOG_DEBUG(("Ignoring client that we already have"));
2856         goto out;
2857       }
2858
2859       SILC_LOG_DEBUG(("New client id(%s) from [%s] %s",
2860                       silc_id_render(id, SILC_ID_CLIENT),
2861                       sock->type == SILC_SOCKET_TYPE_SERVER ?
2862                       "Server" : "Router", sock->hostname));
2863
2864       /* As a router we keep information of all global information in our
2865          global list. Cell wide information however is kept in the local
2866          list. */
2867       entry = silc_idlist_add_client(id_list, NULL, NULL, NULL,
2868                                      id, router, NULL, 0);
2869       if (!entry) {
2870         SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
2871
2872         /* Inform the sender that the ID is not usable */
2873         silc_server_send_notify_signoff(server, sock, FALSE, id, NULL);
2874         goto out;
2875       }
2876       entry->nickname = NULL;
2877       entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
2878
2879       if (sock->type == SILC_SOCKET_TYPE_SERVER)
2880         server->stat.cell_clients++;
2881       server->stat.clients++;
2882
2883       /* Check if anyone is watching this nickname */
2884       if (server->server_type == SILC_ROUTER && id_list == server->local_list)
2885         silc_server_check_watcher_list(server, entry, NULL, 0);
2886
2887       if (server->server_type == SILC_ROUTER) {
2888         /* Add the client's public key to hash table or get the key with
2889            GETKEY command. */
2890         if (entry->data.public_key)
2891           silc_hash_table_add(server->pk_hash, entry->data.public_key, entry);
2892         else
2893           silc_server_send_command(server, router_sock,
2894                                    SILC_COMMAND_GETKEY, ++server->cmd_ident,
2895                                    1, 1, buffer->data, buffer->len);
2896       }
2897     }
2898     break;
2899
2900   case SILC_ID_SERVER:
2901     {
2902       SilcServerEntry entry;
2903
2904       /* If the ID is mine, ignore it. */
2905       if (SILC_ID_SERVER_COMPARE(id, server->id)) {
2906         SILC_LOG_DEBUG(("Ignoring my own ID as new ID"));
2907         break;
2908       }
2909
2910       /* If the ID is the sender's ID, ignore it (we have it already) */
2911       if (SILC_ID_SERVER_COMPARE(id, router->id)) {
2912         SILC_LOG_DEBUG(("Ignoring sender's own ID"));
2913         break;
2914       }
2915
2916       /* Check that we do not have this server already */
2917       entry = silc_idlist_find_server_by_id(server->global_list,
2918                                             id, server->server_type,
2919                                             NULL);
2920       if (!entry)
2921         entry = silc_idlist_find_server_by_id(server->local_list,
2922                                               id, server->server_type,
2923                                               NULL);
2924       if (entry) {
2925         SILC_LOG_DEBUG(("Ignoring server that we already have"));
2926         goto out;
2927       }
2928
2929       SILC_LOG_DEBUG(("New server id(%s) from [%s] %s",
2930                       silc_id_render(id, SILC_ID_SERVER),
2931                       sock->type == SILC_SOCKET_TYPE_SERVER ?
2932                       "Server" : "Router", sock->hostname));
2933
2934       /* As a router we keep information of all global information in our
2935          global list. Cell wide information however is kept in the local
2936          list. */
2937       entry = silc_idlist_add_server(id_list, NULL, 0, id, router,
2938                                      router_sock);
2939       if (!entry) {
2940         SILC_LOG_ERROR(("Could not add new server to the ID Cache"));
2941         goto out;
2942       }
2943       entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
2944
2945       if (sock->type == SILC_SOCKET_TYPE_SERVER)
2946         server->stat.cell_servers++;
2947       server->stat.servers++;
2948     }
2949     break;
2950
2951   case SILC_ID_CHANNEL:
2952     SILC_LOG_ERROR(("Channel cannot be registered with NEW_ID packet"));
2953     goto out;
2954     break;
2955
2956   default:
2957     goto out;
2958     break;
2959   }
2960
2961   /* If the sender of this packet is server and we are router we need to
2962      broadcast this packet to other routers in the network. */
2963   if (broadcast && server->server_type == SILC_ROUTER &&
2964       sock->type == SILC_SOCKET_TYPE_SERVER &&
2965       !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
2966     SILC_LOG_DEBUG(("Broadcasting received New ID packet"));
2967     silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
2968                             packet->type,
2969                             packet->flags | SILC_PACKET_FLAG_BROADCAST,
2970                             buffer->data, buffer->len, FALSE);
2971     silc_server_backup_send(server, sock->user_data,
2972                             packet->type, packet->flags,
2973                             packet->buffer->data, packet->buffer->len,
2974                             FALSE, TRUE);
2975   }
2976
2977  out:
2978   silc_id_payload_free(idp);
2979 }
2980
2981
2982 /* Processes incoming New ID packet. New ID Payload is used to distribute
2983    information about newly registered clients and servers. */
2984
2985 void silc_server_new_id(SilcServer server, SilcSocketConnection sock,
2986                         SilcPacketContext *packet)
2987 {
2988   silc_server_new_id_real(server, sock, packet, TRUE);
2989 }
2990
2991 /* Receoved New Id List packet, list of New ID payloads inside one
2992    packet. Process the New ID payloads one by one. */
2993
2994 void silc_server_new_id_list(SilcServer server, SilcSocketConnection sock,
2995                              SilcPacketContext *packet)
2996 {
2997   SilcPacketContext *new_id;
2998   SilcBuffer idp;
2999   SilcUInt16 id_len;
3000
3001   SILC_LOG_DEBUG(("Processing New ID List"));
3002
3003   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
3004       packet->src_id_type != SILC_ID_SERVER)
3005     return;
3006
3007   /* If the sender of this packet is server and we are router we need to
3008      broadcast this packet to other routers in the network. Broadcast
3009      this list packet instead of multiple New ID packets. */
3010   if (server->server_type == SILC_ROUTER &&
3011       sock->type == SILC_SOCKET_TYPE_SERVER &&
3012       !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
3013     SILC_LOG_DEBUG(("Broadcasting received New ID List packet"));
3014     silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
3015                             packet->type,
3016                             packet->flags | SILC_PACKET_FLAG_BROADCAST,
3017                             packet->buffer->data,
3018                             packet->buffer->len, FALSE);
3019     silc_server_backup_send(server, sock->user_data,
3020                             packet->type, packet->flags,
3021                             packet->buffer->data, packet->buffer->len,
3022                             FALSE, TRUE);
3023   }
3024
3025   /* Make copy of the original packet context, except for the actual
3026      data buffer, which we will here now fetch from the original buffer. */
3027   new_id = silc_packet_context_alloc();
3028   new_id->type = SILC_PACKET_NEW_ID;
3029   new_id->flags = packet->flags & (~SILC_PACKET_FLAG_LIST);
3030   new_id->src_id = packet->src_id;
3031   new_id->src_id_len = packet->src_id_len;
3032   new_id->src_id_type = packet->src_id_type;
3033   new_id->dst_id = packet->dst_id;
3034   new_id->dst_id_len = packet->dst_id_len;
3035   new_id->dst_id_type = packet->dst_id_type;
3036
3037   idp = silc_buffer_alloc(256);
3038   new_id->buffer = idp;
3039
3040   while (packet->buffer->len) {
3041     SILC_GET16_MSB(id_len, packet->buffer->data + 2);
3042     if ((id_len > packet->buffer->len) ||
3043         (id_len > idp->truelen))
3044       break;
3045
3046     silc_buffer_pull_tail(idp, 4 + id_len);
3047     silc_buffer_put(idp, packet->buffer->data, 4 + id_len);
3048
3049     /* Process the New ID */
3050     silc_server_new_id_real(server, sock, new_id, FALSE);
3051
3052     silc_buffer_push_tail(idp, 4 + id_len);
3053     silc_buffer_pull(packet->buffer, 4 + id_len);
3054   }
3055
3056   silc_buffer_free(idp);
3057   silc_free(new_id);
3058 }
3059
3060 /* Received New Channel packet. Information about new channels in the
3061    network are distributed using this packet. Save the information about
3062    the new channel. This usually comes from router but also normal server
3063    can send this to notify channels it has when it connects to us. */
3064
3065 void silc_server_new_channel(SilcServer server,
3066                              SilcSocketConnection sock,
3067                              SilcPacketContext *packet)
3068 {
3069   SilcChannelPayload payload;
3070   SilcChannelID *channel_id;
3071   char *channel_name, *channel_namec = NULL;
3072   SilcUInt32 name_len;
3073   unsigned char *id;
3074   SilcUInt32 id_len, cipher_len;
3075   SilcServerEntry server_entry;
3076   SilcChannelEntry channel;
3077   const char *cipher;
3078
3079   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
3080       packet->src_id_type != SILC_ID_SERVER ||
3081       server->server_type == SILC_SERVER)
3082     return;
3083
3084   /* Parse the channel payload */
3085   payload = silc_channel_payload_parse(packet->buffer->data,
3086                                        packet->buffer->len);
3087   if (!payload)
3088     return;
3089
3090   /* Get the channel ID */
3091   channel_id = silc_channel_get_id_parse(payload);
3092   if (!channel_id) {
3093     silc_channel_payload_free(payload);
3094     return;
3095   }
3096
3097   channel_name = silc_channel_get_name(payload, &name_len);
3098   if (name_len > 256) {
3099     channel_name[256] = '\0';
3100     name_len = 256;
3101   }
3102
3103   /* Check channel name */
3104   channel_namec = silc_identifier_check(channel_name, strlen(channel_name),
3105                                         SILC_STRING_UTF8, 256, NULL);
3106   if (!channel_namec)
3107     return;
3108
3109   id = silc_channel_get_id(payload, &id_len);
3110
3111   server_entry = (SilcServerEntry)sock->user_data;
3112
3113   if (sock->type == SILC_SOCKET_TYPE_ROUTER) {
3114     /* Add the channel to global list as it is coming from router. It
3115        cannot be our own channel as it is coming from router. */
3116
3117     /* Check that we don't already have this channel */
3118     channel = silc_idlist_find_channel_by_name(server->local_list,
3119                                                channel_namec, NULL);
3120     if (!channel)
3121       channel = silc_idlist_find_channel_by_name(server->global_list,
3122                                                  channel_namec, NULL);
3123     if (!channel) {
3124       SILC_LOG_DEBUG(("New channel id(%s) from [Router] %s",
3125                       silc_id_render(channel_id, SILC_ID_CHANNEL),
3126                       sock->hostname));
3127
3128       channel =
3129         silc_idlist_add_channel(server->global_list, strdup(channel_name),
3130                                 0, channel_id, sock->user_data, NULL, NULL, 0);
3131       if (!channel) {
3132         silc_channel_payload_free(payload);
3133         silc_free(channel_id);
3134         return;
3135       }
3136       channel->disabled = TRUE;    /* Disabled until someone JOINs */
3137
3138       server->stat.channels++;
3139       if (server->server_type == SILC_ROUTER)
3140         channel->users_resolved = TRUE;
3141     }
3142   } else {
3143     /* The channel is coming from our server, thus it is in our cell
3144        we will add it to our local list. */
3145     SilcBuffer chk;
3146
3147     SILC_LOG_DEBUG(("Channel id(%s) from [Server] %s",
3148                     silc_id_render(channel_id, SILC_ID_CHANNEL),
3149                     sock->hostname));
3150
3151     /* Check that we don't already have this channel */
3152     channel = silc_idlist_find_channel_by_name(server->local_list,
3153                                                channel_namec, NULL);
3154     if (!channel)
3155       channel = silc_idlist_find_channel_by_name(server->global_list,
3156                                                  channel_namec, NULL);
3157
3158     /* If the channel does not exist, then create it. This creates a new
3159        key to the channel as well that we will send to the server. */
3160     if (!channel) {
3161       SILC_LOG_DEBUG(("Channel is new to us"));
3162
3163       /* The protocol says that the Channel ID's IP address must be based
3164          on the router's IP address.  Check whether the ID is based in our
3165          IP and if it is not then create a new ID and enforce the server
3166          to switch the ID. */
3167       if (server_entry->server_type != SILC_BACKUP_ROUTER &&
3168           !SILC_ID_COMPARE(channel_id, server->id, server->id->ip.data_len)) {
3169         SilcChannelID *tmp;
3170         SILC_LOG_DEBUG(("Forcing the server to change Channel ID"));
3171         if (silc_id_create_channel_id(server, server->id, server->rng, &tmp)) {
3172           silc_server_send_notify_channel_change(server, sock, FALSE,
3173                                                  channel_id, tmp);
3174           silc_channel_payload_free(payload);
3175           silc_free(channel_id);
3176           silc_free(tmp);
3177         }
3178
3179         /* Wait that server re-announces this channel */
3180         return;
3181       }
3182
3183       /* Create the channel with the provided Channel ID */
3184       channel = silc_server_create_new_channel_with_id(server, NULL, NULL,
3185                                                        channel_name,
3186                                                        channel_id, FALSE);
3187       if (!channel) {
3188         silc_channel_payload_free(payload);
3189         silc_free(channel_id);
3190         return;
3191       }
3192       channel->disabled = TRUE;    /* Disabled until someone JOINs */
3193
3194 #if 0 /* We assume that CMODE_CHANGE notify is sent to us after this. */
3195
3196       /* XXX Dunno if this is supposed to be set in any server type.  If set
3197          here the CMODE_CHANGE that may follow sets mode that we already
3198          have, and we may loose data from the CMODE_CHANGE notify. */
3199       if (server_entry->server_type != SILC_BACKUP_ROUTER)
3200         channel->mode = silc_channel_get_mode(payload);
3201 #endif
3202
3203       /* Send the new channel key to the server */
3204       id = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3205       id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3206       cipher = silc_cipher_get_name(channel->channel_key);
3207       cipher_len = strlen(cipher);
3208       chk = silc_channel_key_payload_encode(id_len, id,
3209                                             cipher_len, cipher,
3210                                             channel->key_len / 8,
3211                                             channel->key);
3212       silc_server_packet_send(server, sock, SILC_PACKET_CHANNEL_KEY, 0,
3213                               chk->data, chk->len, FALSE);
3214       silc_buffer_free(chk);
3215       silc_free(id);
3216     } else {
3217       /* The channel exist by that name, check whether the ID's match.
3218          If they don't then we'll force the server to use the ID we have.
3219          We also create a new key for the channel. */
3220       SilcBuffer modes = NULL, users = NULL, users_modes = NULL;
3221
3222       SILC_LOG_DEBUG(("Channel already exists"));
3223
3224       if (!SILC_ID_CHANNEL_COMPARE(channel_id, channel->id)) {
3225         /* They don't match, send CHANNEL_CHANGE notify to the server to
3226            force the ID change. */
3227         SILC_LOG_DEBUG(("Forcing the server to change Channel ID"));
3228         silc_server_send_notify_channel_change(server, sock, FALSE,
3229                                                channel_id, channel->id);
3230         silc_channel_payload_free(payload);
3231         silc_free(channel_id);
3232
3233         /* Wait that server re-announces this channel */
3234         return;
3235       }
3236
3237 #if 0 /* We will announce our CMODE anyway for this channel, so no need
3238          to check it (implicit enforce). */
3239
3240       /* If the mode is different from what we have then enforce the
3241          mode change. */
3242       mode = silc_channel_get_mode(payload);
3243       if (channel->mode != mode) {
3244         SILC_LOG_DEBUG(("Forcing the server to change channel mode"));
3245         silc_server_send_notify_cmode(server, sock, FALSE, channel,
3246                                       channel->mode, server->id,
3247                                       SILC_ID_SERVER, channel->cipher,
3248                                       channel->hmac_name,
3249                                       channel->passphrase,
3250                                       channel->founder_key);
3251       }
3252 #endif
3253
3254       /* Create new key for the channel and send it to the server and
3255          everybody else possibly on the channel. */
3256       if (!(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
3257
3258         if (silc_hash_table_count(channel->user_list)) {
3259           if (!silc_server_create_channel_key(server, channel, 0)) {
3260             silc_channel_payload_free(payload);
3261             silc_free(channel_id);
3262             return;
3263           }
3264
3265           /* Send to the channel */
3266           silc_server_send_channel_key(server, sock, channel, FALSE);
3267         }
3268
3269         /* Send to the server */
3270         id = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3271         id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3272         cipher = silc_cipher_get_name(channel->channel_key);
3273         cipher_len = strlen(cipher);
3274         chk = silc_channel_key_payload_encode(id_len, id,
3275                                               cipher_len, cipher,
3276                                               channel->key_len / 8,
3277                                               channel->key);
3278         silc_server_packet_send(server, sock, SILC_PACKET_CHANNEL_KEY, 0,
3279                                 chk->data, chk->len, FALSE);
3280         silc_buffer_free(chk);
3281         silc_free(id);
3282       }
3283
3284       silc_free(channel_id);
3285
3286       /* Since the channel is coming from server and we also know about it
3287          then send the JOIN notify to the server so that it see's our
3288          users on the channel "joining" the channel. */
3289       silc_server_announce_get_channel_users(server, channel, &modes, &users,
3290                                              &users_modes);
3291       if (users) {
3292         silc_buffer_push(users, users->data - users->head);
3293         silc_server_packet_send(server, sock,
3294                                 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3295                                 users->data, users->len, FALSE);
3296         silc_buffer_free(users);
3297       }
3298       if (modes) {
3299         silc_buffer_push(modes, modes->data - modes->head);
3300         silc_server_packet_send_dest(server, sock,
3301                                      SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3302                                      channel->id, SILC_ID_CHANNEL,
3303                                      modes->data, modes->len, FALSE);
3304         silc_buffer_free(modes);
3305       }
3306       if (users_modes) {
3307         silc_buffer_push(users_modes, users_modes->data - users_modes->head);
3308         silc_server_packet_send_dest(server, sock,
3309                                      SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3310                                      channel->id, SILC_ID_CHANNEL,
3311                                      users_modes->data,
3312                                      users_modes->len, FALSE);
3313         silc_buffer_free(users_modes);
3314       }
3315       if (channel->topic) {
3316         silc_server_send_notify_topic_set(server, sock,
3317                                           server->server_type == SILC_ROUTER ?
3318                                           TRUE : FALSE, channel,
3319                                           server->id, SILC_ID_SERVER,
3320                                           channel->topic);
3321       }
3322     }
3323   }
3324
3325   /* If the sender of this packet is server and we are router we need to
3326      broadcast this packet to other routers in the network. Broadcast
3327      this list packet instead of multiple New Channel packets. */
3328   if (server->server_type == SILC_ROUTER &&
3329       sock->type == SILC_SOCKET_TYPE_SERVER &&
3330       !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
3331     SILC_LOG_DEBUG(("Broadcasting received New Channel packet"));
3332     silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
3333                             packet->type,
3334                             packet->flags | SILC_PACKET_FLAG_BROADCAST,
3335                             packet->buffer->data,
3336                             packet->buffer->len, FALSE);
3337     silc_server_backup_send(server, sock->user_data,
3338                             packet->type, packet->flags,
3339                             packet->buffer->data, packet->buffer->len,
3340                             FALSE, TRUE);
3341   }
3342
3343   silc_free(channel_namec);
3344   silc_channel_payload_free(payload);
3345 }
3346
3347 /* Received New Channel List packet, list of New Channel List payloads inside
3348    one packet. Process the New Channel payloads one by one. */
3349
3350 void silc_server_new_channel_list(SilcServer server,
3351                                   SilcSocketConnection sock,
3352                                   SilcPacketContext *packet)
3353 {
3354   SilcPacketContext *new;
3355   SilcBuffer buffer;
3356   SilcUInt16 len1, len2;
3357
3358   SILC_LOG_DEBUG(("Processing New Channel List"));
3359
3360   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
3361       packet->src_id_type != SILC_ID_SERVER ||
3362       server->server_type == SILC_SERVER)
3363     return;
3364
3365   /* Make copy of the original packet context, except for the actual
3366      data buffer, which we will here now fetch from the original buffer. */
3367   new = silc_packet_context_alloc();
3368   new->type = SILC_PACKET_NEW_CHANNEL;
3369   new->flags = packet->flags & (~SILC_PACKET_FLAG_LIST);
3370   new->src_id = packet->src_id;
3371   new->src_id_len = packet->src_id_len;
3372   new->src_id_type = packet->src_id_type;
3373   new->dst_id = packet->dst_id;
3374   new->dst_id_len = packet->dst_id_len;
3375   new->dst_id_type = packet->dst_id_type;
3376
3377   buffer = silc_buffer_alloc(512);
3378   new->buffer = buffer;
3379
3380   while (packet->buffer->len) {
3381     SILC_GET16_MSB(len1, packet->buffer->data);
3382     if ((len1 > packet->buffer->len) ||
3383         (len1 > buffer->truelen))
3384       break;
3385
3386     SILC_GET16_MSB(len2, packet->buffer->data + 2 + len1);
3387     if ((len2 > packet->buffer->len) ||
3388         (len2 > buffer->truelen))
3389       break;
3390
3391     silc_buffer_pull_tail(buffer, 8 + len1 + len2);
3392     silc_buffer_put(buffer, packet->buffer->data, 8 + len1 + len2);
3393
3394     /* Process the New Channel */
3395     silc_server_new_channel(server, sock, new);
3396
3397     silc_buffer_push_tail(buffer, 8 + len1 + len2);
3398     silc_buffer_pull(packet->buffer, 8 + len1 + len2);
3399   }
3400
3401   silc_buffer_free(buffer);
3402   silc_free(new);
3403 }
3404
3405 /* Received key agreement packet. This packet is never for us. It is to
3406    the client in the packet's destination ID. Sending of this sort of packet
3407    equals sending private message, ie. it is sent point to point from
3408    one client to another. */
3409
3410 void silc_server_key_agreement(SilcServer server,
3411                                SilcSocketConnection sock,
3412                                SilcPacketContext *packet)
3413 {
3414   SilcSocketConnection dst_sock;
3415   SilcIDListData idata;
3416
3417   SILC_LOG_DEBUG(("Start"));
3418
3419   if (packet->src_id_type != SILC_ID_CLIENT ||
3420       packet->dst_id_type != SILC_ID_CLIENT)
3421     return;
3422
3423   if (!packet->dst_id)
3424     return;
3425
3426   /* Get the route to the client */
3427   dst_sock = silc_server_get_client_route(server, packet->dst_id,
3428                                           packet->dst_id_len, NULL,
3429                                           &idata, NULL);
3430   if (!dst_sock)
3431     return;
3432
3433   /* Relay the packet */
3434   silc_server_relay_packet(server, dst_sock, idata->send_key,
3435                            idata->hmac_send, idata->psn_send++,
3436                            packet, FALSE);
3437 }
3438
3439 /* Received connection auth request packet that is used during connection
3440    phase to resolve the mandatory authentication method.  This packet can
3441    actually be received at anytime but usually it is used only during
3442    the connection authentication phase. Now, protocol says that this packet
3443    can come from client or server, however, we support only this coming
3444    from client and expect that server always knows what authentication
3445    method to use. */
3446
3447 void silc_server_connection_auth_request(SilcServer server,
3448                                          SilcSocketConnection sock,
3449                                          SilcPacketContext *packet)
3450 {
3451   SilcServerConfigClient *client = NULL;
3452   SilcUInt16 conn_type;
3453   int ret;
3454   SilcAuthMethod auth_meth = SILC_AUTH_NONE;
3455
3456   if (packet->src_id_type && packet->src_id_type != SILC_ID_CLIENT) {
3457     SILC_LOG_DEBUG(("Request not from client"));
3458     return;
3459   }
3460
3461   /* Parse the payload */
3462   ret = silc_buffer_unformat(packet->buffer,
3463                              SILC_STR_UI_SHORT(&conn_type),
3464                              SILC_STR_UI_SHORT(NULL),
3465                              SILC_STR_END);
3466   if (ret == -1)
3467     return;
3468
3469   if (conn_type != SILC_SOCKET_TYPE_CLIENT)
3470     return;
3471
3472   /* Get the authentication method for the client */
3473   auth_meth = SILC_AUTH_NONE;
3474   client = silc_server_config_find_client(server, sock->ip);
3475   if (!client)
3476     client = silc_server_config_find_client(server, sock->hostname);
3477   if (client) {
3478     if (client->passphrase) {
3479       if (client->publickeys && !server->config->prefer_passphrase_auth)
3480         auth_meth = SILC_AUTH_PUBLIC_KEY;
3481       else
3482         auth_meth = SILC_AUTH_PASSWORD;
3483     } else if (client->publickeys)
3484       auth_meth = SILC_AUTH_PUBLIC_KEY;
3485   }
3486
3487   SILC_LOG_DEBUG(("Authentication method is [%s]",
3488                   (auth_meth == SILC_AUTH_NONE ? "None" :
3489                    auth_meth == SILC_AUTH_PASSWORD ? "Passphrase" :
3490                    "Digital signatures")));
3491
3492   /* Send it back to the client */
3493   silc_server_send_connection_auth_request(server, sock, conn_type, auth_meth);
3494 }
3495
3496 /* Received REKEY packet. The sender of the packet wants to regenerate
3497    its session keys. This starts the REKEY protocol. */
3498
3499 void silc_server_rekey(SilcServer server,
3500                        SilcSocketConnection sock,
3501                        SilcPacketContext *packet)
3502 {
3503   SilcProtocol protocol;
3504   SilcServerRekeyInternalContext *proto_ctx;
3505   SilcIDListData idata = (SilcIDListData)sock->user_data;
3506
3507   SILC_LOG_DEBUG(("Received rekey request"));
3508
3509   /* If we have other protocol executing we have no other choice but to
3510      not execute rekey. XXX This is very bad thing.  Let's hope this
3511      doesn't happen often. */
3512   if (sock->protocol) {
3513     SILC_LOG_WARNING(("Cannot execute REKEY protocol because other protocol "
3514                       "is executing at the same time"));
3515     return;
3516   }
3517
3518   /* Allocate internal protocol context. This is sent as context
3519      to the protocol. */
3520   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
3521   proto_ctx->server = (void *)server;
3522   proto_ctx->sock = silc_socket_dup(sock);
3523   proto_ctx->responder = TRUE;
3524   proto_ctx->pfs = idata->rekey->pfs;
3525
3526   /* Perform rekey protocol. Will call the final callback after the
3527      protocol is over. */
3528   silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
3529                       &protocol, proto_ctx, silc_server_rekey_final);
3530   sock->protocol = protocol;
3531
3532   if (proto_ctx->pfs == FALSE)
3533     /* Run the protocol */
3534     silc_protocol_execute(protocol, server->schedule, 0, 0);
3535 }
3536
3537 /* Received file transger packet. This packet is never for us. It is to
3538    the client in the packet's destination ID. Sending of this sort of packet
3539    equals sending private message, ie. it is sent point to point from
3540    one client to another. */
3541
3542 void silc_server_ftp(SilcServer server,
3543                      SilcSocketConnection sock,
3544                      SilcPacketContext *packet)
3545 {
3546   SilcSocketConnection dst_sock;
3547   SilcIDListData idata;
3548
3549   SILC_LOG_DEBUG(("Start"));
3550
3551   if (packet->src_id_type != SILC_ID_CLIENT ||
3552       packet->dst_id_type != SILC_ID_CLIENT)
3553     return;
3554
3555   if (!packet->dst_id)
3556     return;
3557
3558   /* Get the route to the client */
3559   dst_sock = silc_server_get_client_route(server, packet->dst_id,
3560                                           packet->dst_id_len, NULL,
3561                                           &idata, NULL);
3562   if (!dst_sock)
3563     return;
3564
3565   /* Relay the packet */
3566   silc_server_relay_packet(server, dst_sock, idata->send_key,
3567                            idata->hmac_send, idata->psn_send++,
3568                            packet, FALSE);
3569 }
3570
3571 typedef struct {
3572   SilcServer server;
3573   SilcSocketConnection sock;
3574   SilcPacketContext *packet;
3575   void *data;
3576 } *SilcServerResumeResolve;
3577
3578 SILC_SERVER_CMD_FUNC(resume_resolve)
3579 {
3580   SilcServerResumeResolve r = (SilcServerResumeResolve)context;
3581   SilcServer server = r->server;
3582   SilcSocketConnection sock = r->sock;
3583   SilcServerCommandReplyContext reply = context2;
3584   SilcClientEntry client;
3585
3586   SILC_LOG_DEBUG(("Start"));
3587
3588   if (!reply || !silc_command_get_status(reply->payload, NULL, NULL)) {
3589     SILC_LOG_ERROR(("Client %s (%s) tried to resume unknown client, "
3590                     "closing connection", sock->hostname, sock->ip));
3591     silc_server_disconnect_remote(server, sock,
3592                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3593                                   "Resuming not possible");
3594     if (sock->user_data)
3595       silc_server_free_sock_user_data(server, sock, NULL);
3596     goto out;
3597   }
3598
3599   if (reply && silc_command_get(reply->payload) == SILC_COMMAND_WHOIS) {
3600     /* Get entry to the client, and resolve it if we don't have it. */
3601     client = silc_idlist_find_client_by_id(server->local_list,
3602                                            r->data, TRUE, NULL);
3603     if (!client) {
3604       client = silc_idlist_find_client_by_id(server->global_list,
3605                                              r->data, TRUE, NULL);
3606       if (!client) {
3607         SILC_LOG_ERROR(("Client %s (%s) tried to resume unknown client, "
3608                         "closing connection", sock->hostname, sock->ip));
3609         silc_server_disconnect_remote(server, sock,
3610                                       SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3611                                       "Resuming not possible");
3612         if (sock->user_data)
3613           silc_server_free_sock_user_data(server, sock, NULL);
3614         goto out;
3615       }
3616     }
3617
3618     if (!(client->mode & SILC_UMODE_DETACHED)) {
3619       SILC_LOG_ERROR(("Client %s (%s) tried to resume un-detached client, "
3620                       "closing connection", sock->hostname, sock->ip));
3621       silc_server_disconnect_remote(server, sock,
3622                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3623                                     "Resuming not possible");
3624       if (sock->user_data)
3625         silc_server_free_sock_user_data(server, sock, NULL);
3626       goto out;
3627     }
3628
3629     client->data.status |= SILC_IDLIST_STATUS_RESUME_RES;
3630   }
3631
3632   /* Reprocess the packet */
3633   silc_server_resume_client(server, sock, r->packet);
3634
3635  out:
3636   silc_socket_free(r->sock);
3637   silc_packet_context_free(r->packet);
3638   silc_free(r->data);
3639   silc_free(r);
3640 }
3641
3642 /* Received client resuming packet.  This is used to resume detached
3643    client session.  It can be sent by the client who wishes to resume
3644    but this is also sent by servers and routers to notify other routers
3645    that the client is not detached anymore. */
3646
3647 void silc_server_resume_client(SilcServer server,
3648                                SilcSocketConnection sock,
3649                                SilcPacketContext *packet)
3650 {
3651   SilcBuffer buffer = packet->buffer, buf;
3652   SilcIDListData idata;
3653   SilcIDCacheEntry id_cache = NULL;
3654   SilcClientEntry detached_client;
3655   SilcClientID *client_id = NULL;
3656   unsigned char *id_string, *auth = NULL, *nicknamec = NULL;
3657   SilcUInt16 id_len, auth_len = 0;
3658   int ret;
3659   bool resolved, local, nick_change = FALSE, resolve = FALSE;
3660   SilcChannelEntry channel;
3661   SilcHashTableList htl;
3662   SilcChannelClientEntry chl;
3663   SilcServerResumeResolve r;
3664   const char *cipher;
3665
3666   ret = silc_buffer_unformat(buffer,
3667                              SILC_STR_UI16_NSTRING(&id_string, &id_len),
3668                              SILC_STR_END);
3669   if (ret != -1)
3670     client_id = silc_id_str2id(id_string, id_len, SILC_ID_CLIENT);
3671
3672   if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
3673     /* Client send this and is attempting to resume to old client session */
3674     SilcClientEntry client;
3675     SilcBuffer keyp;
3676
3677     if (ret != -1) {
3678       silc_buffer_pull(buffer, 2 + id_len);
3679       auth = buffer->data;
3680       auth_len = buffer->len;
3681       silc_buffer_push(buffer, 2 + id_len);
3682     }
3683
3684     if (!client_id || auth_len < 128) {
3685       SILC_LOG_ERROR(("Client %s (%s) sent incomplete resume information, "
3686                       "closing connection", sock->hostname, sock->ip));
3687       silc_server_disconnect_remote(server, sock,
3688                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3689                                     "Resuming not possible");
3690       if (sock->user_data)
3691         silc_server_free_sock_user_data(server, sock, NULL);
3692       silc_free(client_id);
3693       return;
3694     }
3695
3696     /* Take client entry of this connection */
3697     client = (SilcClientEntry)sock->user_data;
3698     idata = (SilcIDListData)client;
3699
3700     /* Get entry to the client, and resolve it if we don't have it. */
3701     detached_client = silc_server_query_client(server, client_id, FALSE,
3702                                                &resolved);
3703     if (!detached_client) {
3704       if (resolved) {
3705         /* The client info is being resolved. Reprocess this packet after
3706            receiving the reply to the query. */
3707         SILC_LOG_DEBUG(("Resolving client"));
3708         r = silc_calloc(1, sizeof(*r));
3709         if (!r)
3710           return;
3711         r->server = server;
3712         r->sock = silc_socket_dup(sock);
3713         r->packet = silc_packet_context_dup(packet);
3714         r->data = client_id;
3715         silc_server_command_pending(server, SILC_COMMAND_WHOIS,
3716                                     server->cmd_ident,
3717                                     silc_server_command_resume_resolve, r);
3718       } else {
3719         SILC_LOG_ERROR(("Client %s (%s) tried to resume unknown client, "
3720                         "closing connection", sock->hostname, sock->ip));
3721         silc_server_disconnect_remote(server, sock,
3722                                       SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3723                                       "Resuming not possible");
3724         if (sock->user_data)
3725           silc_server_free_sock_user_data(server, sock, NULL);
3726         silc_free(client_id);
3727       }
3728       return;
3729     }
3730
3731     if (detached_client->data.status & SILC_IDLIST_STATUS_RESUMED) {
3732       SILC_LOG_ERROR(("Client %s (%s) tried to attach more than once, "
3733                       "closing connection", sock->hostname, sock->ip));
3734       silc_server_disconnect_remote(server, sock,
3735                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3736                                     "Resuming not possible");
3737       if (sock->user_data)
3738         silc_server_free_sock_user_data(server, sock, NULL);
3739       silc_free(client_id);
3740
3741       return;
3742     }
3743
3744     if (detached_client->resuming_client &&
3745         detached_client->resuming_client != client) {
3746       SILC_LOG_ERROR(("Client %s (%s) tried to attach more than once, "
3747                       "closing connection", sock->hostname, sock->ip));
3748       silc_server_disconnect_remote(server, sock,
3749                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3750                                     "Resuming not possible");
3751       if (sock->user_data)
3752         silc_server_free_sock_user_data(server, sock, NULL);
3753       silc_free(client_id);
3754
3755       return;
3756     }
3757
3758     if (!detached_client->resuming_client)
3759       detached_client->resuming_client = client;
3760
3761     if (!(detached_client->mode & SILC_UMODE_DETACHED))
3762       resolve = TRUE;
3763     if (!silc_hash_table_count(detached_client->channels) &&
3764         detached_client->router)
3765       resolve = TRUE;
3766     if (!detached_client->nickname)
3767       resolve = TRUE;
3768     if (detached_client->data.status & SILC_IDLIST_STATUS_RESUME_RES)
3769       resolve = FALSE;
3770
3771     if (resolve) {
3772       if (server->server_type == SILC_SERVER && !server->standalone) {
3773         /* The client info is being resolved. Reprocess this packet after
3774            receiving the reply to the query. */
3775         SILC_LOG_DEBUG(("Resolving client info"));
3776         silc_server_query_client(server, client_id, TRUE, NULL);
3777         r = silc_calloc(1, sizeof(*r));
3778         if (!r)
3779           return;
3780         r->server = server;
3781         r->sock = silc_socket_dup(sock);
3782         r->packet = silc_packet_context_dup(packet);
3783         r->data = client_id;
3784         silc_server_command_pending(server, SILC_COMMAND_WHOIS,
3785                                     server->cmd_ident,
3786                                     silc_server_command_resume_resolve, r);
3787         return;
3788       }
3789       if (server->server_type == SILC_SERVER) {
3790         SILC_LOG_ERROR(("Client %s (%s) tried to resume un-detached client, "
3791                         "closing connection", sock->hostname, sock->ip));
3792         silc_server_disconnect_remote(server, sock,
3793                                       SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3794                                       "Resuming not possible");
3795         if (sock->user_data)
3796           silc_server_free_sock_user_data(server, sock, NULL);
3797         silc_free(client_id);
3798         return;
3799       }
3800     }
3801
3802     /* Check that we have the public key of the client, if not then we must
3803        resolve it first. */
3804     if (!detached_client->data.public_key) {
3805       if (server->server_type == SILC_SERVER && server->standalone) {
3806         SILC_LOG_ERROR(("Detached client's public key not present, "
3807                         "closing connection"));
3808         silc_server_disconnect_remote(server, sock,
3809                                       SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3810                                       "Resuming not possible");
3811         if (sock->user_data)
3812           silc_server_free_sock_user_data(server, sock, NULL);
3813         silc_free(client_id);
3814       } else {
3815         /* We must retrieve the detached client's public key by sending
3816            GETKEY command. Reprocess this packet after receiving the key */
3817         SilcBuffer idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
3818         SilcSocketConnection dest_sock =
3819           silc_server_get_client_route(server, NULL, 0, client_id, NULL, NULL);
3820
3821         SILC_LOG_DEBUG(("Resolving client public key"));
3822
3823         silc_server_send_command(server, dest_sock ? dest_sock :
3824                                  SILC_PRIMARY_ROUTE(server),
3825                                  SILC_COMMAND_GETKEY, ++server->cmd_ident,
3826                                  1, 1, idp->data, idp->len);
3827
3828         r = silc_calloc(1, sizeof(*r));
3829         if (!r) {
3830           silc_free(client_id);
3831           return;
3832         }
3833
3834         r->server = server;
3835         r->sock = silc_socket_dup(sock);
3836         r->packet = silc_packet_context_dup(packet);
3837         silc_server_command_pending(server, SILC_COMMAND_GETKEY,
3838                                     server->cmd_ident,
3839                                     silc_server_command_resume_resolve, r);
3840
3841         silc_buffer_free(idp);
3842       }
3843       silc_free(client_id);
3844       return;
3845     } else if (!silc_pkcs_public_key_compare(detached_client->data.public_key,
3846                                              idata->public_key)) {
3847       /* We require that the connection and resuming authentication data
3848          must be using same key pair. */
3849       SILC_LOG_ERROR(("Resuming attempted with wrong public key, "
3850                       "closing connection"));
3851       silc_server_disconnect_remote(server, sock,
3852                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3853                                     "Resuming not possible");
3854       if (sock->user_data)
3855         silc_server_free_sock_user_data(server, sock, NULL);
3856       silc_free(client_id);
3857       return;
3858     }
3859
3860     /* Verify the authentication payload.  This has to be successful in
3861        order to allow the resuming */
3862     if (!idata->hash ||
3863         !silc_auth_verify_data(auth, auth_len, SILC_AUTH_PUBLIC_KEY,
3864                                detached_client->data.public_key, 0,
3865                                idata->hash, detached_client->id,
3866                                SILC_ID_CLIENT)) {
3867       SILC_LOG_ERROR(("Client %s (%s) resume authentication failed, "
3868                       "closing connection", sock->hostname, sock->ip));
3869       silc_server_disconnect_remote(server, sock,
3870                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3871                                     "Resuming not possible");
3872       if (sock->user_data)
3873         silc_server_free_sock_user_data(server, sock, NULL);
3874       silc_free(client_id);
3875       return;
3876     }
3877
3878     /* Check nickname */
3879     nicknamec = silc_identifier_check(detached_client->nickname,
3880                                       strlen(detached_client->nickname),
3881                                       SILC_STRING_UTF8, 128, NULL);
3882     if (!nicknamec) {
3883       silc_server_disconnect_remote(server, sock,
3884                                     SILC_STATUS_ERR_BAD_NICKNAME,
3885                                     "Malformed nickname, cannot resume");
3886       if (sock->user_data)
3887         silc_server_free_sock_user_data(server, sock, NULL);
3888       return;
3889     }
3890
3891     /* If the ID is not based in our ID then change it */
3892     if (!SILC_ID_COMPARE(detached_client->id, server->id,
3893                          server->id->ip.data_len)) {
3894       silc_free(client_id);
3895       if (!silc_id_create_client_id(server, server->id, server->rng,
3896                                     server->md5hash, nicknamec,
3897                                     strlen(nicknamec), &client_id)) {
3898         silc_server_disconnect_remote(server, sock,
3899                                       SILC_STATUS_ERR_BAD_NICKNAME,
3900                                       "Resuming not possible");
3901         if (sock->user_data)
3902           silc_server_free_sock_user_data(server, sock, NULL);
3903         return;
3904       }
3905       nick_change = TRUE;
3906     }
3907
3908     /* Now resume the client to the network */
3909
3910     silc_schedule_task_del_by_context(server->schedule, detached_client);
3911     sock->user_data = detached_client;
3912     detached_client->connection = sock;
3913
3914     if (detached_client->data.public_key)
3915       silc_hash_table_del_by_context(server->pk_hash,
3916                                      detached_client->data.public_key,
3917                                      detached_client);
3918     if (idata->public_key)
3919       silc_hash_table_del_by_context(server->pk_hash,
3920                                      idata->public_key, idata);
3921
3922     /* Take new keys and stuff into use in the old entry */
3923     silc_idlist_del_data(detached_client);
3924     silc_idlist_add_data(detached_client, idata);
3925
3926     if (detached_client->data.public_key)
3927       silc_hash_table_add(server->pk_hash,
3928                           detached_client->data.public_key, detached_client);
3929
3930     detached_client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
3931     detached_client->data.status |= SILC_IDLIST_STATUS_RESUMED;
3932     detached_client->data.status |= SILC_IDLIST_STATUS_LOCAL;
3933     detached_client->data.status &= ~SILC_IDLIST_STATUS_RESUME_RES;
3934     detached_client->mode &= ~SILC_UMODE_DETACHED;
3935     server->stat.my_detached--;
3936
3937     /* We are finished - reset resuming client */
3938     detached_client->resuming_client = NULL;
3939
3940     /* Check if anyone is watching this client */
3941     if (server->server_type == SILC_ROUTER)
3942       silc_server_check_watcher_list(server, detached_client, NULL,
3943                                      SILC_NOTIFY_TYPE_UMODE_CHANGE);
3944
3945     /* Delete this current client entry since we're resuming to old one. */
3946     server->stat.my_clients--;
3947     server->stat.clients--;
3948     if (server->stat.cell_clients)
3949       server->stat.cell_clients--;
3950     silc_server_remove_from_channels(server, NULL, client, FALSE,
3951                                      NULL, FALSE, FALSE);
3952     silc_server_del_from_watcher_list(server, client);
3953     if (!silc_idlist_del_client(server->local_list, client))
3954       silc_idlist_del_client(server->global_list, client);
3955     client = detached_client;
3956     silc_free(client->servername);
3957     client->servername = strdup(server->server_name);
3958
3959     /* Send the RESUME_CLIENT packet to our primary router so that others
3960        know this client isn't detached anymore. */
3961     buf = silc_buffer_alloc_size(2 + id_len);
3962     silc_buffer_format(buf,
3963                        SILC_STR_UI_SHORT(id_len),
3964                        SILC_STR_UI_XNSTRING(id_string, id_len),
3965                        SILC_STR_END);
3966
3967     /* Send to primary router */
3968     silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
3969                             SILC_PACKET_RESUME_CLIENT, 0,
3970                             buf->data, buf->len, TRUE);
3971     silc_server_backup_send(server, client->router,
3972                             SILC_PACKET_RESUME_CLIENT, 0,
3973                             buf->data, buf->len, TRUE, TRUE);
3974
3975     /* As router we must deliver this packet directly to the original
3976        server whom this client was earlier. */
3977     if (server->server_type == SILC_ROUTER && client->router &&
3978         client->router->server_type != SILC_ROUTER)
3979       silc_server_packet_send(server, client->router->connection,
3980                               SILC_PACKET_RESUME_CLIENT, 0,
3981                               buf->data, buf->len, TRUE);
3982     silc_buffer_free(buf);
3983     client->router = NULL;
3984
3985     if (nick_change) {
3986       /* Notify about Client ID change, nickname doesn't actually change. */
3987       silc_server_send_notify_nick_change(server, SILC_PRIMARY_ROUTE(server),
3988                                           SILC_BROADCAST(server),
3989                                           client->id, client_id,
3990                                           client->nickname);
3991     }
3992
3993     /* Resolve users on those channels that client has joined but we
3994        haven't resolved user list yet. */
3995     if (server->server_type == SILC_SERVER && !server->standalone) {
3996       silc_hash_table_list(client->channels, &htl);
3997       while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3998         channel = chl->channel;
3999         SILC_LOG_DEBUG(("Resolving users for %s channel",
4000                         channel->channel_name));
4001         if (channel->disabled || !channel->users_resolved) {
4002           silc_server_send_command(server, SILC_PRIMARY_ROUTE(server),
4003                                    SILC_COMMAND_USERS, ++server->cmd_ident,
4004                                    1, 2, channel->channel_name,
4005                                    strlen(channel->channel_name));
4006         }
4007       }
4008       silc_hash_table_list_reset(&htl);
4009     }
4010
4011     /* Send the new client ID to the client. After this client may start
4012        receiving other packets, and may start sending packets too. */
4013     silc_server_send_new_id(server, sock, FALSE, client_id, SILC_ID_CLIENT,
4014                             silc_id_get_len(client_id, SILC_ID_CLIENT));
4015
4016     if (nick_change) {
4017       /* Send NICK change notify to channels as well. */
4018       SilcBuffer oidp, nidp;
4019       oidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
4020       nidp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
4021       silc_server_send_notify_on_channels(server, NULL, client,
4022                                           SILC_NOTIFY_TYPE_NICK_CHANGE, 3,
4023                                           oidp->data, oidp->len,
4024                                           nidp->data, nidp->len,
4025                                           client->nickname,
4026                                           strlen(client->nickname));
4027       silc_buffer_free(oidp);
4028       silc_buffer_free(nidp);
4029     }
4030
4031     /* Add the client again to the ID cache to get it to correct list */
4032     if (!silc_idcache_del_by_context(server->local_list->clients, client))
4033       silc_idcache_del_by_context(server->global_list->clients, client);
4034     silc_free(client->id);
4035     client->id = client_id;
4036     client_id = NULL;
4037     silc_idcache_add(server->local_list->clients, nicknamec,
4038                      client->id, client, 0, NULL);
4039
4040     /* Send some nice info to the client */
4041     silc_server_send_connect_notifys(server, sock, client);
4042
4043     /* Send all channel keys of channels the client has joined */
4044     silc_hash_table_list(client->channels, &htl);
4045     while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4046       bool created = FALSE;
4047       channel = chl->channel;
4048
4049       if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY)
4050         continue;
4051
4052       /* If we don't have channel key, then create one */
4053       if (!channel->channel_key) {
4054         if (!silc_server_create_channel_key(server, channel, 0))
4055           continue;
4056         created = TRUE;
4057       }
4058
4059       id_string = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
4060       cipher = silc_cipher_get_name(channel->channel_key);
4061       keyp =
4062         silc_channel_key_payload_encode(silc_id_get_len(channel->id,
4063                                                         SILC_ID_CHANNEL),
4064                                         id_string,
4065                                         strlen(cipher), cipher,
4066                                         channel->key_len / 8, channel->key);
4067       silc_free(id_string);
4068
4069       /* Send the channel key to the client */
4070       silc_server_packet_send(server, sock, SILC_PACKET_CHANNEL_KEY, 0,
4071                               keyp->data, keyp->len, FALSE);
4072
4073       /* Distribute the channel key to channel */
4074       if (created) {
4075         silc_server_send_channel_key(server, NULL, channel,
4076                                      server->server_type == SILC_ROUTER ?
4077                                      FALSE : !server->standalone);
4078         silc_server_backup_send(server, NULL, SILC_PACKET_CHANNEL_KEY, 0,
4079                                 keyp->data, keyp->len, FALSE, TRUE);
4080       }
4081
4082       silc_buffer_free(keyp);
4083     }
4084     silc_hash_table_list_reset(&htl);
4085
4086   } else if (sock->type != SILC_SOCKET_TYPE_CLIENT) {
4087     /* Server or router sent this to us to notify that that a client has
4088        been resumed. */
4089     SilcServerEntry server_entry;
4090     SilcServerID *server_id;
4091
4092     if (!client_id) {
4093       SILC_LOG_DEBUG(("Malformed resuming packet"));
4094       return;
4095     }
4096
4097     /* Get entry to the client, and resolve it if we don't have it. */
4098     detached_client = silc_idlist_find_client_by_id(server->local_list,
4099                                                     client_id, TRUE,
4100                                                     &id_cache);
4101     if (!detached_client) {
4102       detached_client = silc_idlist_find_client_by_id(server->global_list,
4103                                                       client_id, TRUE,
4104                                                       &id_cache);
4105       if (!detached_client) {
4106         SILC_LOG_DEBUG(("Resuming client is unknown"));
4107         silc_free(client_id);
4108         return;
4109       }
4110     }
4111
4112     /* Check that the client has not been resumed already because it is
4113        protocol error to attempt to resume more than once.  The client
4114        will be killed if this protocol error occurs. */
4115     if (detached_client->data.status & SILC_IDLIST_STATUS_RESUMED &&
4116         !(detached_client->mode & SILC_UMODE_DETACHED)) {
4117       /* The client is clearly attempting to resume more than once and
4118          perhaps playing around by resuming from several different places
4119          at the same time. */
4120       SILC_LOG_DEBUG(("Attempting to re-resume client, killing both"));
4121       silc_server_kill_client(server, detached_client, NULL,
4122                               server->id, SILC_ID_SERVER);
4123       silc_free(client_id);
4124       return;
4125     }
4126
4127     /* Check whether client is detached at all */
4128     if (!(detached_client->mode & SILC_UMODE_DETACHED)) {
4129       SILC_LOG_DEBUG(("Client is not detached"));
4130       silc_free(client_id);
4131       return;
4132     }
4133
4134     /* Check nickname */
4135     if (detached_client->nickname) {
4136       nicknamec = silc_identifier_check(detached_client->nickname,
4137                                         strlen(detached_client->nickname),
4138                                         SILC_STRING_UTF8, 128, NULL);
4139       if (!nicknamec) {
4140         silc_free(client_id);
4141         return;
4142       }
4143     }
4144
4145     SILC_LOG_DEBUG(("Resuming detached client"));
4146
4147     /* If the sender of this packet is server and we are router we need to
4148        broadcast this packet to other routers in the network. */
4149     if (server->server_type == SILC_ROUTER &&
4150         sock->type == SILC_SOCKET_TYPE_SERVER &&
4151         !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
4152       SILC_LOG_DEBUG(("Broadcasting received Resume Client packet"));
4153       silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
4154                               packet->type,
4155                               packet->flags | SILC_PACKET_FLAG_BROADCAST,
4156                               buffer->data, buffer->len, FALSE);
4157       silc_server_backup_send(server, sock->user_data,
4158                               packet->type, packet->flags,
4159                               packet->buffer->data, packet->buffer->len,
4160                               FALSE, TRUE);
4161     }
4162
4163     /* Client is detached, and now it is resumed.  Remove the detached
4164        mode and mark that it is resumed. */
4165
4166     if (detached_client->data.public_key)
4167       silc_hash_table_del_by_context(server->pk_hash,
4168                                      detached_client->data.public_key,
4169                                      detached_client);
4170
4171     silc_idlist_del_data(detached_client);
4172     detached_client->mode &= ~SILC_UMODE_DETACHED;
4173     detached_client->data.status |= SILC_IDLIST_STATUS_RESUMED;
4174     detached_client->data.status &= ~SILC_IDLIST_STATUS_LOCAL;
4175     id_cache->expire = 0;
4176
4177     /* Check if anyone is watching this client */
4178     if (server->server_type == SILC_ROUTER)
4179       silc_server_check_watcher_list(server, detached_client, NULL,
4180                                      SILC_NOTIFY_TYPE_UMODE_CHANGE);
4181
4182     silc_schedule_task_del_by_context(server->schedule, detached_client);
4183
4184     /* Get the new owner of the resumed client */
4185     server_id = silc_id_str2id(packet->src_id, packet->src_id_len,
4186                                packet->src_id_type);
4187     if (!server_id) {
4188       silc_free(client_id);
4189       return;
4190     }
4191
4192     /* Get server entry */
4193     server_entry = silc_idlist_find_server_by_id(server->global_list,
4194                                                  server_id, TRUE, NULL);
4195     local = FALSE;
4196     if (!server_entry) {
4197       server_entry = silc_idlist_find_server_by_id(server->local_list,
4198                                                    server_id, TRUE, NULL);
4199       local = TRUE;
4200       if (!server_entry) {
4201         silc_free(server_id);
4202         silc_free(client_id);
4203         return;
4204       }
4205     }
4206
4207     if (server->server_type == SILC_ROUTER &&
4208         sock->type == SILC_SOCKET_TYPE_ROUTER &&
4209         server_entry->server_type == SILC_ROUTER)
4210       local = FALSE;
4211
4212     /* Change the client to correct list. */
4213     if (!silc_idcache_del_by_context(server->local_list->clients,
4214                                      detached_client))
4215       silc_idcache_del_by_context(server->global_list->clients,
4216                                   detached_client);
4217     silc_idcache_add(local && server->server_type == SILC_ROUTER ?
4218                      server->local_list->clients :
4219                      server->global_list->clients, nicknamec,
4220                      detached_client->id, detached_client, FALSE, NULL);
4221
4222     /* Change the owner of the client */
4223     detached_client->router = server_entry;
4224
4225     /* Update channel information regarding global clients on channel. */
4226     if (server->server_type != SILC_ROUTER) {
4227       silc_hash_table_list(detached_client->channels, &htl);
4228       while (silc_hash_table_get(&htl, NULL, (void *)&chl))
4229         chl->channel->global_users =
4230           silc_server_channel_has_global(chl->channel);
4231       silc_hash_table_list_reset(&htl);
4232     }
4233
4234     silc_free(server_id);
4235   }
4236
4237   silc_free(client_id);
4238 }