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