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