Watcher list support added.
[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;
47   SilcHashTableList htl;
48   SilcUInt32 mode;
49   unsigned char *tmp;
50   SilcUInt32 tmp_len;
51   bool local;
52
53   SILC_LOG_DEBUG(("Start"));
54
55   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
56       packet->src_id_type != SILC_ID_SERVER)
57     return;
58
59   if (!packet->dst_id)
60     return;
61
62   /* If the packet is destined directly to a client then relay the packet
63      before processing it. */
64   if (packet->dst_id_type == SILC_ID_CLIENT) {
65     SilcIDListData idata;
66     SilcSocketConnection dst_sock;
67
68     /* Get the route to the client */
69     dst_sock = silc_server_get_client_route(server, packet->dst_id,
70                                             packet->dst_id_len, NULL, 
71                                             &idata, NULL);
72     if (dst_sock)
73       /* Relay the packet */
74       silc_server_relay_packet(server, dst_sock, idata->send_key,
75                                idata->hmac_send, idata->psn_send++,
76                                packet, TRUE);
77   }
78
79   /* Parse the Notify Payload */
80   payload = silc_notify_payload_parse(packet->buffer->data,
81                                       packet->buffer->len);
82   if (!payload)
83     return;
84
85   /* If we are router and this packet is not already broadcast packet
86      we will broadcast it. The sending socket really cannot be router or
87      the router is buggy. If this packet is coming from router then it must
88      have the broadcast flag set already and we won't do anything. */
89   if (!server->standalone && server->server_type == SILC_ROUTER &&
90       sock->type == SILC_SOCKET_TYPE_SERVER &&
91       !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
92     SILC_LOG_DEBUG(("Broadcasting received Notify packet"));
93     if (packet->dst_id_type == SILC_ID_CHANNEL) {
94       /* Packet is destined to channel */
95       channel_id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
96                                   packet->dst_id_type);
97       if (!channel_id)
98         goto out;
99
100       silc_server_packet_send_dest(server, server->router->connection, 
101                                    packet->type,
102                                    packet->flags | SILC_PACKET_FLAG_BROADCAST, 
103                                    channel_id, SILC_ID_CHANNEL,
104                                    packet->buffer->data, packet->buffer->len, 
105                                    FALSE);
106       silc_server_backup_send_dest(server, (SilcServerEntry)sock->user_data, 
107                                    packet->type, packet->flags,
108                                    channel_id, SILC_ID_CHANNEL,
109                                    packet->buffer->data, packet->buffer->len, 
110                                    FALSE, TRUE);
111     } else {
112       /* Packet is destined to client or server */
113       silc_server_packet_send(server, server->router->connection, 
114                               packet->type,
115                               packet->flags | SILC_PACKET_FLAG_BROADCAST, 
116                               packet->buffer->data, packet->buffer->len, 
117                               FALSE);
118       silc_server_backup_send(server, (SilcServerEntry)sock->user_data,
119                               packet->type, packet->flags,
120                               packet->buffer->data, packet->buffer->len, 
121                               FALSE, TRUE);
122     }
123   }
124
125   type = silc_notify_get_type(payload);
126   args = silc_notify_get_args(payload);
127   if (!args)
128     goto out;
129
130   switch(type) {
131   case SILC_NOTIFY_TYPE_JOIN:
132     /* 
133      * Distribute the notify to local clients on the channel
134      */
135     SILC_LOG_DEBUG(("JOIN notify"));
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_free(channel_id);
153         goto out;
154       }
155     }
156     silc_free(channel_id);
157
158     /* Get client ID */
159     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
160     if (!tmp)
161       goto out;
162     client_id = silc_id_payload_parse_id(tmp, tmp_len, NULL);
163     if (!client_id)
164       goto out;
165
166     /* If the the client is not in local list we check global list (ie. the
167        channel will be global channel) and if it does not exist then create
168        entry for the client. */
169     client = silc_idlist_find_client_by_id(server->global_list, 
170                                            client_id, server->server_type, 
171                                            NULL);
172     if (!client) {
173       client = silc_idlist_find_client_by_id(server->local_list, 
174                                              client_id, server->server_type,
175                                              NULL);
176       if (!client) {
177         /* If router did not find the client the it is bogus */
178         if (server->server_type != SILC_SERVER)
179           goto out;
180
181         client = 
182           silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
183                                  silc_id_dup(client_id, SILC_ID_CLIENT), 
184                                  sock->user_data, NULL, 0);
185         if (!client) {
186           SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
187           silc_free(client_id);
188           goto out;
189         }
190
191         client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
192       }
193     }
194
195     /* Do not process the notify if the client is not registered */
196     if (!(client->data.status & SILC_IDLIST_STATUS_REGISTERED))
197       break;
198
199     /* Do not add client to channel if it is there already */
200     if (silc_server_client_on_channel(client, channel, NULL)) {
201       SILC_LOG_DEBUG(("Client already on channel"));
202       break;
203     }
204
205     /* Send to channel */
206     silc_server_packet_send_to_channel(server, sock, channel, packet->type, 
207                                        FALSE, packet->buffer->data, 
208                                        packet->buffer->len, FALSE);
209
210     if (server->server_type != SILC_ROUTER && 
211         sock->type == SILC_SOCKET_TYPE_ROUTER)
212       /* The channel is global now */
213       channel->global_users = TRUE;
214
215     SILC_LOG_DEBUG(("Joining to channel %s", channel->channel_name));
216
217     /* JOIN the global client to the channel (local clients (if router 
218        created the channel) is joined in the pending JOIN command). */
219     chl = silc_calloc(1, sizeof(*chl));
220     chl->client = client;
221     chl->channel = channel;
222
223     /* If this is the first one on the channel then it is the founder of
224        the channel. */
225     if (!silc_hash_table_count(channel->user_list))
226       chl->mode = (SILC_CHANNEL_UMODE_CHANOP | SILC_CHANNEL_UMODE_CHANFO);
227
228     silc_hash_table_add(channel->user_list, client, chl);
229     silc_hash_table_add(client->channels, channel, chl);
230     silc_free(client_id);
231     channel->user_count++;
232
233     break;
234
235   case SILC_NOTIFY_TYPE_LEAVE:
236     /* 
237      * Distribute the notify to local clients on the channel
238      */
239     SILC_LOG_DEBUG(("LEAVE notify"));
240
241     if (!channel_id) {
242       channel_id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
243                                   packet->dst_id_type);
244       if (!channel_id)
245         goto out;
246     }
247
248     /* Get channel entry */
249     channel = silc_idlist_find_channel_by_id(server->global_list, 
250                                              channel_id, NULL);
251     if (!channel) { 
252       channel = silc_idlist_find_channel_by_id(server->local_list, 
253                                                channel_id, NULL);
254       if (!channel) {
255         silc_free(channel_id);
256         goto out;
257       }
258     }
259
260     /* Get client ID */
261     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
262     if (!tmp) {
263       silc_free(channel_id);
264       goto out;
265     }
266     client_id = silc_id_payload_parse_id(tmp, tmp_len, NULL);
267     if (!client_id) {
268       silc_free(channel_id);
269       goto out;
270     }
271
272     /* Get client entry */
273     client = silc_idlist_find_client_by_id(server->global_list, 
274                                            client_id, TRUE, NULL);
275     if (!client) {
276       client = silc_idlist_find_client_by_id(server->local_list, 
277                                              client_id, TRUE, NULL);
278       if (!client) {
279         silc_free(client_id);
280         silc_free(channel_id);
281         goto out;
282       }
283     }
284     silc_free(client_id);
285
286     /* Check if on channel */
287     if (!silc_server_client_on_channel(client, channel, NULL))
288       break;
289
290     /* Send the leave notify to channel */
291     silc_server_packet_send_to_channel(server, sock, channel, packet->type, 
292                                        FALSE, packet->buffer->data, 
293                                        packet->buffer->len, FALSE);
294
295     /* Remove the user from channel */
296     silc_server_remove_from_one_channel(server, sock, channel, client, FALSE);
297     break;
298
299   case SILC_NOTIFY_TYPE_SIGNOFF:
300     /* 
301      * Distribute the notify to local clients on the channel
302      */
303     SILC_LOG_DEBUG(("SIGNOFF notify"));
304
305     /* Get client ID */
306     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
307     if (!tmp)
308       goto out;
309     client_id = silc_id_payload_parse_id(tmp, tmp_len, NULL);
310     if (!client_id)
311       goto out;
312
313     /* Get client entry */
314     client = silc_idlist_find_client_by_id(server->global_list, 
315                                            client_id, TRUE, &cache);
316     if (!client) {
317       client = silc_idlist_find_client_by_id(server->local_list, 
318                                              client_id, TRUE, &cache);
319       if (!client) {
320         silc_free(client_id);
321         goto out;
322       }
323     }
324     silc_free(client_id);
325
326     /* Get signoff message */
327     tmp = silc_argument_get_arg_type(args, 2, &tmp_len);
328     if (tmp_len > 128)
329       tmp = NULL;
330
331     /* Update statistics */
332     server->stat.clients--;
333     if (server->stat.cell_clients)
334       server->stat.cell_clients--;
335     SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
336     SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
337
338     /* Remove the client from all channels. */
339     silc_server_remove_from_channels(server, NULL, client, TRUE, tmp, FALSE);
340
341     /* Check if anyone is watching this nickname */
342     if (server->server_type == SILC_ROUTER)
343       silc_server_check_watcher_list(server, client, NULL,
344                                      SILC_NOTIFY_TYPE_SIGNOFF);
345
346     client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
347     cache->expire = SILC_ID_CACHE_EXPIRE_DEF;
348     break;
349
350   case SILC_NOTIFY_TYPE_TOPIC_SET:
351     /* 
352      * Distribute the notify to local clients on the channel
353      */
354
355     SILC_LOG_DEBUG(("TOPIC SET notify"));
356
357     /* Get client ID */
358     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
359     if (!tmp)
360       goto out;
361     client_id = silc_id_payload_parse_id(tmp, tmp_len, NULL);
362     if (!client_id)
363       goto out;
364
365     /* Get client entry */
366     client = silc_idlist_find_client_by_id(server->global_list, 
367                                            client_id, TRUE, &cache);
368     if (!client) {
369       client = silc_idlist_find_client_by_id(server->local_list, 
370                                              client_id, TRUE, &cache);
371       if (!client) {
372         silc_free(client_id);
373         goto out;
374       }
375     }
376     silc_free(client_id);
377
378     /* Get the topic */
379     tmp = silc_argument_get_arg_type(args, 2, &tmp_len);
380     if (!tmp) {
381       silc_free(channel_id);
382       goto out;
383     }
384
385     if (!channel_id) {
386       channel_id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
387                                   packet->dst_id_type);
388       if (!channel_id)
389         goto out;
390     }
391
392     /* Get channel entry */
393     channel = silc_idlist_find_channel_by_id(server->global_list, 
394                                              channel_id, NULL);
395     if (!channel) {
396       channel = silc_idlist_find_channel_by_id(server->local_list, 
397                                                channel_id, NULL);
398       if (!channel) {
399         silc_free(channel_id);
400         goto out;
401       }
402     }
403
404     if (channel->topic && !strcmp(channel->topic, tmp))
405       goto out;
406
407     /* Get user's channel entry and check that topic set is allowed. */
408     if (!silc_server_client_on_channel(client, channel, &chl))
409       goto out;
410     if (channel->mode & SILC_CHANNEL_MODE_TOPIC &&
411         !(chl->mode & SILC_CHANNEL_UMODE_CHANOP) &&
412         !(chl->mode & SILC_CHANNEL_UMODE_CHANFO)) {
413       SILC_LOG_DEBUG(("Topic change is not allowed"));
414       goto out;
415     }
416
417     /* Change the topic */
418     silc_free(channel->topic);
419     channel->topic = strdup(tmp);
420
421     /* Send the same notify to the channel */
422     silc_server_packet_send_to_channel(server, sock, channel, packet->type, 
423                                        FALSE, packet->buffer->data, 
424                                        packet->buffer->len, FALSE);
425     silc_free(channel_id);
426     break;
427
428   case SILC_NOTIFY_TYPE_NICK_CHANGE:
429     {
430       /* 
431        * Distribute the notify to local clients on the channel
432        */
433       unsigned char *id, *id2;
434       char *nickname;
435       SilcUInt32 nickname_len;
436
437       SILC_LOG_DEBUG(("NICK CHANGE notify"));
438       
439       /* Get old client ID */
440       id = silc_argument_get_arg_type(args, 1, &tmp_len);
441       if (!id)
442         goto out;
443       client_id = silc_id_payload_parse_id(id, tmp_len, NULL);
444       if (!client_id)
445         goto out;
446       
447       /* Get new client ID */
448       id2 = silc_argument_get_arg_type(args, 2, &tmp_len);
449       if (!id2)
450         goto out;
451       client_id2 = silc_id_payload_parse_id(id2, tmp_len, NULL);
452       if (!client_id2)
453         goto out;
454       
455       SILC_LOG_DEBUG(("Old Client ID id(%s)", 
456                       silc_id_render(client_id, SILC_ID_CLIENT)));
457       SILC_LOG_DEBUG(("New Client ID id(%s)", 
458                       silc_id_render(client_id2, SILC_ID_CLIENT)));
459
460       /* From protocol version 1.1 we also get the new nickname */
461       nickname = silc_argument_get_arg_type(args, 3, &nickname_len);;
462
463       /* Replace the Client ID */
464       client = silc_idlist_replace_client_id(server,
465                                              server->global_list, client_id,
466                                              client_id2, nickname);
467       if (!client)
468         client = silc_idlist_replace_client_id(server,
469                                                server->local_list, client_id, 
470                                                client_id2, nickname);
471
472       if (client) {
473         /* Send the NICK_CHANGE notify type to local clients on the channels
474            this client is joined to. */
475         silc_server_send_notify_on_channels(server, client, client,
476                                             SILC_NOTIFY_TYPE_NICK_CHANGE, 3,
477                                             id, tmp_len, id2, tmp_len,
478                                             nickname, nickname ?
479                                             nickname_len : 0);
480       }
481
482       silc_free(client_id);
483       if (!client)
484         silc_free(client_id2);
485       break;
486     }
487
488   case SILC_NOTIFY_TYPE_CMODE_CHANGE:
489     /* 
490      * Distribute the notify to local clients on the channel
491      */
492     
493     SILC_LOG_DEBUG(("CMODE CHANGE notify"));
494       
495     /* Get client ID */
496     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
497     if (!tmp)
498       goto out;
499     client_id = silc_id_payload_parse_id(tmp, tmp_len, &id_type);
500     if (!client_id)
501       goto out;
502
503     /* Get client entry */
504     if (id_type == SILC_ID_CLIENT) {
505       client = silc_idlist_find_client_by_id(server->global_list, 
506                                              client_id, TRUE, &cache);
507       if (!client) {
508         client = silc_idlist_find_client_by_id(server->local_list, 
509                                                client_id, TRUE, &cache);
510         if (!client) {
511           silc_free(client_id);
512           goto out;
513         }
514       }
515       silc_free(client_id);
516     }
517
518     if (!channel_id) {
519       channel_id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
520                                   packet->dst_id_type);
521       if (!channel_id)
522         goto out;
523     }
524
525     /* Get channel entry */
526     channel = silc_idlist_find_channel_by_id(server->global_list, 
527                                              channel_id, NULL);
528     if (!channel) {
529       channel = silc_idlist_find_channel_by_id(server->local_list, 
530                                                channel_id, NULL);
531       if (!channel) {
532         silc_free(channel_id);
533         goto out;
534       }
535     }
536     silc_free(channel_id);
537
538     /* Get the mode */
539     tmp = silc_argument_get_arg_type(args, 2, &tmp_len);
540     if (!tmp)
541       goto out;
542     SILC_GET32_MSB(mode, tmp);
543
544     /* Check if mode changed */
545     if (channel->mode == mode)
546       break;
547
548     /* Get user's channel entry and check that mode change is allowed */
549     if (client) {
550       if (!silc_server_client_on_channel(client, channel, &chl))
551         goto out;
552       if (!silc_server_check_cmode_rights(server, channel, chl, mode)) {
553         SILC_LOG_DEBUG(("CMODE change is not allowed"));
554         goto out;
555       }
556     }
557
558     /* Send the same notify to the channel */
559     silc_server_packet_send_to_channel(server, sock, channel, packet->type, 
560                                        FALSE, packet->buffer->data, 
561                                        packet->buffer->len, FALSE);
562
563     /* If the channel had private keys set and the mode was removed then
564        we must re-generate and re-distribute a new channel key */
565     if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY &&
566         !(mode & SILC_CHANNEL_MODE_PRIVKEY)) {
567       /* Re-generate channel key */
568       if (!silc_server_create_channel_key(server, channel, 0))
569         goto out;
570       
571       /* Send the channel key. This sends it to our local clients and if
572          we are normal server to our router as well. */
573       silc_server_send_channel_key(server, NULL, channel, 
574                                    server->server_type == SILC_ROUTER ? 
575                                    FALSE : !server->standalone);
576     }
577
578     /* Change mode */
579     channel->mode = mode;
580
581     /* Get the hmac */
582     tmp = silc_argument_get_arg_type(args, 4, &tmp_len);
583     if (tmp) {
584       unsigned char hash[32];
585
586       if (channel->hmac)
587         silc_hmac_free(channel->hmac);
588       if (!silc_hmac_alloc(tmp, NULL, &channel->hmac))
589         goto out;
590
591       /* Set the HMAC key out of current channel key. The client must do
592          this locally. */
593       silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, 
594                      channel->key_len / 8, hash);
595       silc_hmac_set_key(channel->hmac, hash, 
596                         silc_hash_len(silc_hmac_get_hash(channel->hmac)));
597       memset(hash, 0, sizeof(hash));
598     }
599
600     /* Get the passphrase */
601     tmp = silc_argument_get_arg_type(args, 5, &tmp_len);
602     if (tmp) {
603       silc_free(channel->passphrase);
604       channel->passphrase = silc_memdup(tmp, tmp_len);
605     }
606
607     break;
608
609   case SILC_NOTIFY_TYPE_CUMODE_CHANGE:
610     {
611       /* 
612        * Distribute the notify to local clients on the channel
613        */
614       SilcChannelClientEntry chl2 = NULL;
615       bool notify_sent = FALSE;
616       
617       SILC_LOG_DEBUG(("CUMODE CHANGE notify"));
618       
619       /* Get client ID */
620       tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
621       if (!tmp)
622         goto out;
623       client_id = silc_id_payload_parse_id(tmp, tmp_len, &id_type);
624       if (!client_id)
625         goto out;
626
627       /* Get client entry */
628       if (id_type == SILC_ID_CLIENT) {
629         client = silc_idlist_find_client_by_id(server->global_list, 
630                                                client_id, TRUE, &cache);
631         if (!client) {
632           client = silc_idlist_find_client_by_id(server->local_list, 
633                                                  client_id, TRUE, &cache);
634           if (!client) {
635             silc_free(client_id);
636             goto out;
637           }
638         }
639         silc_free(client_id);
640       }
641
642       if (!channel_id) {
643         channel_id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
644                                     packet->dst_id_type);
645         if (!channel_id)
646           goto out;
647       }
648
649       /* Get channel entry */
650       channel = silc_idlist_find_channel_by_id(server->global_list, 
651                                                channel_id, NULL);
652       if (!channel) {
653         channel = silc_idlist_find_channel_by_id(server->local_list, 
654                                                  channel_id, NULL);
655         if (!channel) {
656           silc_free(channel_id);
657           goto out;
658         }
659       }
660
661       /* Get the mode */
662       tmp = silc_argument_get_arg_type(args, 2, &tmp_len);
663       if (!tmp) {
664         silc_free(channel_id);
665         goto out;
666       }
667       
668       SILC_GET32_MSB(mode, tmp);
669       
670       /* Get target client */
671       tmp = silc_argument_get_arg_type(args, 3, &tmp_len);
672       if (!tmp)
673         goto out;
674       client_id = silc_id_payload_parse_id(tmp, tmp_len, NULL);
675       if (!client_id)
676         goto out;
677       
678       /* Get client entry */
679       client2 = silc_idlist_find_client_by_id(server->global_list, 
680                                               client_id, TRUE, NULL);
681       if (!client2) {
682         client2 = silc_idlist_find_client_by_id(server->local_list, 
683                                                 client_id, TRUE, NULL);
684         if (!client2) {
685           silc_free(client_id);
686           goto out;
687         }
688       }
689       silc_free(client_id);
690
691       if (client) {
692         /* Check that sender is on channel */
693         if (!silc_server_client_on_channel(client, channel, &chl))
694           goto out;
695         
696         if (client != client2) {
697           /* Sender must be operator */
698           if (!(chl->mode & SILC_CHANNEL_UMODE_CHANOP) &&
699               !(chl->mode & SILC_CHANNEL_UMODE_CHANFO)) {
700             SILC_LOG_DEBUG(("CUMODE change is not allowed"));
701             goto out;
702           }
703
704           /* Check that target is on channel */
705           if (!silc_server_client_on_channel(client2, channel, &chl))
706             goto out;
707
708           /* If target is founder mode change is not allowed. */
709           if (chl->mode & SILC_CHANNEL_UMODE_CHANFO) {
710             SILC_LOG_DEBUG(("CUMODE change is not allowed"));
711             goto out;
712           }
713         }
714       }
715
716       /* Get entry to the channel user list */
717       silc_hash_table_list(channel->user_list, &htl);
718       while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
719         /* If the mode is channel founder and we already find a client 
720            to have that mode on the channel we will enforce the sender
721            to change the channel founder mode away. There can be only one
722            channel founder on the channel. */
723         if (server->server_type == SILC_ROUTER &&
724             mode & SILC_CHANNEL_UMODE_CHANFO &&
725             chl->mode & SILC_CHANNEL_UMODE_CHANFO) {
726           SilcBuffer idp;
727           unsigned char cumode[4];
728
729           if (chl->client == client && chl->mode == mode) {
730             notify_sent = TRUE;
731             break;
732           }
733
734           mode &= ~SILC_CHANNEL_UMODE_CHANFO;
735           silc_server_send_notify_cumode(server, sock, FALSE, channel, mode,
736                                          client2->id, SILC_ID_CLIENT,
737                                          client2->id);
738           
739           idp = silc_id_payload_encode(client2->id, SILC_ID_CLIENT);
740           SILC_PUT32_MSB(mode, cumode);
741           silc_server_send_notify_to_channel(server, sock, channel, FALSE, 
742                                              SILC_NOTIFY_TYPE_CUMODE_CHANGE,
743                                              3, idp->data, idp->len,
744                                              cumode, 4,
745                                              idp->data, idp->len);
746           silc_buffer_free(idp);
747           notify_sent = TRUE;
748
749           /* Force the mode change if we alredy set the mode */
750           if (chl2) {
751             chl2->mode = mode;
752             silc_free(channel_id);
753             silc_hash_table_list_reset(&htl);
754             goto out;
755           }
756         }
757         
758         if (chl->client == client2) {
759           if (chl->mode == mode) {
760             notify_sent = TRUE;
761             break;
762           }
763
764           SILC_LOG_DEBUG(("Changing the channel user mode"));
765
766           /* Change the mode */
767           chl->mode = mode;
768           if (!(mode & SILC_CHANNEL_UMODE_CHANFO))
769             break;
770           
771           chl2 = chl;
772         }
773       }
774       silc_hash_table_list_reset(&htl);
775       
776       /* Send the same notify to the channel */
777       if (!notify_sent)
778         silc_server_packet_send_to_channel(server, sock, channel, 
779                                            packet->type, 
780                                            FALSE, packet->buffer->data, 
781                                            packet->buffer->len, FALSE);
782       
783       silc_free(channel_id);
784       break;
785     }
786
787   case SILC_NOTIFY_TYPE_INVITE:
788
789     if (packet->dst_id_type == SILC_ID_CLIENT)
790       goto out;
791
792     SILC_LOG_DEBUG(("INVITE notify"));
793
794     /* Get Channel ID */
795     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
796     if (!tmp)
797       goto out;
798     channel_id = silc_id_payload_parse_id(tmp, tmp_len, NULL);
799     if (!channel_id)
800       goto out;
801
802     /* Get channel entry */
803     channel = silc_idlist_find_channel_by_id(server->global_list, 
804                                              channel_id, NULL);
805     if (!channel) {
806       channel = silc_idlist_find_channel_by_id(server->local_list, 
807                                                channel_id, NULL);
808       if (!channel) {
809         silc_free(channel_id);
810         goto out;
811       }
812     }
813     silc_free(channel_id);
814
815     /* Get client ID */
816     tmp = silc_argument_get_arg_type(args, 3, &tmp_len);
817     if (!tmp)
818       goto out;
819     client_id = silc_id_payload_parse_id(tmp, tmp_len, NULL);
820     if (!client_id)
821       goto out;
822
823     /* Get client entry */
824     client = silc_idlist_find_client_by_id(server->global_list, 
825                                            client_id, TRUE, &cache);
826     if (!client) {
827       client = silc_idlist_find_client_by_id(server->local_list, 
828                                              client_id, TRUE, &cache);
829       if (!client) {
830         silc_free(client_id);
831         goto out;
832       }
833     }
834     silc_free(client_id);
835
836     /* Get user's channel entry and check that inviting is allowed. */
837     if (!silc_server_client_on_channel(client, channel, &chl))
838       goto out;
839     if (channel->mode & SILC_CHANNEL_MODE_INVITE &&
840         !(chl->mode & SILC_CHANNEL_UMODE_CHANOP) &&
841         !(chl->mode & SILC_CHANNEL_UMODE_CHANFO)) {
842       SILC_LOG_DEBUG(("Inviting is not allowed"));
843       goto out;
844     }
845
846     /* Get the added invite */
847     tmp = silc_argument_get_arg_type(args, 4, &tmp_len);
848     if (tmp) {
849       if (!channel->invite_list)
850         channel->invite_list = silc_calloc(tmp_len + 2, 
851                                            sizeof(*channel->invite_list));
852       else
853         channel->invite_list = silc_realloc(channel->invite_list, 
854                                             sizeof(*channel->invite_list) * 
855                                             (tmp_len + 
856                                              strlen(channel->invite_list) + 
857                                              2));
858       if (tmp[tmp_len - 1] == ',')
859         tmp[tmp_len - 1] = '\0';
860       
861       strncat(channel->invite_list, tmp, tmp_len);
862       strncat(channel->invite_list, ",", 1);
863     }
864
865     /* Get the deleted invite */
866     tmp = silc_argument_get_arg_type(args, 5, &tmp_len);
867     if (tmp && channel->invite_list) {
868       char *start, *end, *n;
869       
870       if (!strncmp(channel->invite_list, tmp, 
871                    strlen(channel->invite_list) - 1)) {
872         silc_free(channel->invite_list);
873         channel->invite_list = NULL;
874       } else {
875         start = strstr(channel->invite_list, tmp);
876         if (start && strlen(start) >= tmp_len) {
877           end = start + tmp_len;
878           n = silc_calloc(strlen(channel->invite_list) - tmp_len, sizeof(*n));
879           strncat(n, channel->invite_list, start - channel->invite_list);
880           strncat(n, end + 1, ((channel->invite_list + 
881                                 strlen(channel->invite_list)) - end) - 1);
882           silc_free(channel->invite_list);
883           channel->invite_list = n;
884         }
885       }
886     }
887
888     break;
889
890   case SILC_NOTIFY_TYPE_CHANNEL_CHANGE:
891     /*
892      * Distribute to the local clients on the channel and change the
893      * channel ID.
894      */
895
896     SILC_LOG_DEBUG(("CHANNEL CHANGE"));
897
898     if (sock->type != SILC_SOCKET_TYPE_ROUTER)
899       break;
900
901     /* Get the old Channel ID */
902     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
903     if (!tmp)
904       goto out;
905     channel_id = silc_id_payload_parse_id(tmp, tmp_len, NULL);
906     if (!channel_id)
907       goto out;
908
909     /* Get the channel entry */
910     channel = silc_idlist_find_channel_by_id(server->local_list, 
911                                              channel_id, NULL);
912     if (!channel) {
913       channel = silc_idlist_find_channel_by_id(server->global_list, 
914                                                channel_id, NULL);
915       if (!channel) {
916         silc_free(channel_id);
917         goto out;
918       }
919     }
920
921     /* Send the notify to the channel */
922     silc_server_packet_send_to_channel(server, sock, channel, packet->type, 
923                                        FALSE, packet->buffer->data, 
924                                        packet->buffer->len, FALSE);
925
926     /* Get the new Channel ID */
927     tmp = silc_argument_get_arg_type(args, 2, &tmp_len);
928     if (!tmp)
929       goto out;
930     channel_id2 = silc_id_payload_parse_id(tmp, tmp_len, NULL);
931     if (!channel_id2)
932       goto out;
933
934     SILC_LOG_DEBUG(("Old Channel ID id(%s)", 
935                     silc_id_render(channel_id, SILC_ID_CHANNEL)));
936     SILC_LOG_DEBUG(("New Channel ID id(%s)", 
937                     silc_id_render(channel_id2, SILC_ID_CHANNEL)));
938
939     /* Replace the Channel ID */
940     if (!silc_idlist_replace_channel_id(server->local_list, channel_id,
941                                         channel_id2))
942       if (!silc_idlist_replace_channel_id(server->global_list, channel_id,
943                                           channel_id2)) {
944         silc_free(channel_id2);
945         channel_id2 = NULL;
946       }
947
948     if (channel_id2) {
949       SilcBuffer users = NULL, users_modes = NULL;
950
951       /* Re-announce this channel which ID was changed. */
952       silc_server_send_new_channel(server, sock, FALSE, channel->channel_name,
953                                    channel->id, 
954                                    silc_id_get_len(channel->id, 
955                                                    SILC_ID_CHANNEL),
956                                    channel->mode);
957
958       /* Re-announce our clients on the channel as the ID has changed now */
959       silc_server_announce_get_channel_users(server, channel, &users,
960                                              &users_modes);
961       if (users) {
962         silc_buffer_push(users, users->data - users->head);
963         silc_server_packet_send(server, sock,
964                                 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
965                                 users->data, users->len, FALSE);
966         silc_buffer_free(users);
967       }
968       if (users_modes) {
969         silc_buffer_push(users_modes, users_modes->data - users_modes->head);
970         silc_server_packet_send_dest(server, sock,
971                                      SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
972                                      channel->id, SILC_ID_CHANNEL,
973                                      users_modes->data, 
974                                      users_modes->len, FALSE);
975         silc_buffer_free(users_modes);
976       }
977
978       /* Re-announce channel's topic */
979       if (channel->topic) {
980         silc_server_send_notify_topic_set(server, sock,
981                                           server->server_type == SILC_ROUTER ?
982                                           TRUE : FALSE, channel, 
983                                           channel->id, SILC_ID_CHANNEL,
984                                           channel->topic);
985       }
986     }
987
988     silc_free(channel_id);
989
990     break;
991
992   case SILC_NOTIFY_TYPE_SERVER_SIGNOFF:
993     /* 
994      * Remove the server entry and all clients that this server owns.
995      */
996
997     SILC_LOG_DEBUG(("SERVER SIGNOFF notify"));
998
999     /* Get Server ID */
1000     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
1001     if (!tmp)
1002       goto out;
1003     server_id = silc_id_payload_parse_id(tmp, tmp_len, NULL);
1004     if (!server_id)
1005       goto out;
1006
1007     /* Get server entry */
1008     server_entry = silc_idlist_find_server_by_id(server->global_list, 
1009                                                  server_id, TRUE, NULL);
1010     local = TRUE;
1011     if (!server_entry) {
1012       server_entry = silc_idlist_find_server_by_id(server->local_list, 
1013                                                    server_id, TRUE, NULL);
1014       local = TRUE;
1015       if (!server_entry) {
1016         /* If we are normal server then we might not have the server. Check
1017            whether router was kind enough to send the list of all clients
1018            that actually was to be removed. Remove them if the list is
1019            available. */
1020         if (server->server_type != SILC_ROUTER &&
1021             silc_argument_get_arg_num(args) > 1) {
1022           int i;
1023
1024           for (i = 1; i < silc_argument_get_arg_num(args); i++) {
1025             /* Get Client ID */
1026             tmp = silc_argument_get_arg_type(args, i + 1, &tmp_len);
1027             if (!tmp)
1028               continue;
1029             client_id = silc_id_payload_parse_id(tmp, tmp_len, NULL);
1030             if (!client_id)
1031               continue;
1032
1033             /* Get client entry */
1034             client = silc_idlist_find_client_by_id(server->global_list, 
1035                                                    client_id, TRUE, &cache);
1036             local = TRUE;
1037             if (!client) {
1038               client = silc_idlist_find_client_by_id(server->local_list, 
1039                                                      client_id, TRUE, &cache);
1040               local = FALSE;
1041               if (!client) {
1042                 silc_free(client_id);
1043                 continue;
1044               }
1045             }
1046             silc_free(client_id);
1047
1048             /* Update statistics */
1049             server->stat.clients--;
1050             if (server->stat.cell_clients)
1051               server->stat.cell_clients--;
1052             SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
1053             SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
1054
1055             /* Remove the client from all channels. */
1056             silc_server_remove_from_channels(server, NULL, client, 
1057                                              TRUE, NULL, FALSE);
1058
1059             /* Check if anyone is watching this nickname */
1060             if (server->server_type == SILC_ROUTER)
1061               silc_server_check_watcher_list(server, client, NULL,
1062                                              SILC_NOTIFY_TYPE_SERVER_SIGNOFF);
1063
1064             /* Remove this client from watcher list if it is */
1065             if (local)
1066               silc_server_del_from_watcher_list(server, client);
1067
1068             /* Remove the client */
1069             silc_idlist_del_client(local ? server->local_list :
1070                                    server->global_list, client);
1071           }
1072         }
1073
1074         silc_free(server_id);
1075         goto out;
1076       }
1077     }
1078     silc_free(server_id);
1079
1080     /* Free all client entries that this server owns as they will
1081        become invalid now as well. */
1082     silc_server_remove_clients_by_server(server, server_entry, TRUE);
1083
1084     /* Remove the server entry */
1085     silc_idlist_del_server(local ? server->local_list :
1086                            server->global_list, server_entry);
1087
1088     /* XXX update statistics */
1089
1090     break;
1091
1092   case SILC_NOTIFY_TYPE_KICKED:
1093     /* 
1094      * Distribute the notify to local clients on the channel
1095      */
1096     
1097     SILC_LOG_DEBUG(("KICKED notify"));
1098       
1099     if (!channel_id) {
1100       channel_id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
1101                                   packet->dst_id_type);
1102       if (!channel_id)
1103         goto out;
1104     }
1105
1106     /* Get channel entry */
1107     channel = silc_idlist_find_channel_by_id(server->global_list, 
1108                                              channel_id, NULL);
1109     if (!channel) {
1110       channel = silc_idlist_find_channel_by_id(server->local_list, 
1111                                                channel_id, NULL);
1112       if (!channel) {
1113         silc_free(channel_id);
1114         goto out;
1115       }
1116     }
1117     silc_free(channel_id);
1118
1119     /* Get client ID */
1120     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
1121     if (!tmp)
1122       goto out;
1123     client_id = silc_id_payload_parse_id(tmp, tmp_len, NULL);
1124     if (!client_id)
1125       goto out;
1126
1127     /* If the the client is not in local list we check global list */
1128     client = silc_idlist_find_client_by_id(server->global_list, 
1129                                            client_id, TRUE, NULL);
1130     if (!client) {
1131       client = silc_idlist_find_client_by_id(server->local_list, 
1132                                              client_id, TRUE, NULL);
1133       if (!client) {
1134         silc_free(client_id);
1135         goto out;
1136       }
1137     }
1138     silc_free(client_id);
1139
1140     /* If target is founder they cannot be kicked */
1141     if (!silc_server_client_on_channel(client, channel, &chl))
1142       goto out;
1143     if (chl->mode & SILC_CHANNEL_UMODE_CHANFO)
1144       goto out;
1145     
1146     /* From protocol version 1.1 we get the kicker's ID as well. */
1147     tmp = silc_argument_get_arg_type(args, 3, &tmp_len);
1148     if (tmp) {
1149       client_id = silc_id_payload_parse_id(tmp, tmp_len, NULL);
1150       if (!client_id)
1151         goto out;
1152
1153       /* If the the client is not in local list we check global list */
1154       client2 = silc_idlist_find_client_by_id(server->global_list, 
1155                                               client_id, TRUE, NULL);
1156       if (!client2) {
1157         client2 = silc_idlist_find_client_by_id(server->local_list, 
1158                                                 client_id, TRUE, NULL);
1159         if (!client2) {
1160           silc_free(client_id);
1161           goto out;
1162         }
1163       }
1164       silc_free(client_id);
1165
1166       /* Kicker must be operator on channel */
1167       if (!silc_server_client_on_channel(client2, channel, &chl))
1168         goto out;
1169       if (!(chl->mode & SILC_CHANNEL_UMODE_CHANOP) &&
1170           !(chl->mode & SILC_CHANNEL_UMODE_CHANFO)) {
1171         SILC_LOG_DEBUG(("Kicking is not allowed"));
1172         goto out;
1173       }
1174     }
1175
1176     /* Send to channel */
1177     silc_server_packet_send_to_channel(server, sock, channel, packet->type, 
1178                                        FALSE, packet->buffer->data, 
1179                                        packet->buffer->len, FALSE);
1180
1181     /* Remove the client from channel */
1182     silc_server_remove_from_one_channel(server, sock, channel, client, FALSE);
1183
1184     break;
1185
1186   case SILC_NOTIFY_TYPE_KILLED:
1187     {
1188       /* 
1189        * Distribute the notify to local clients on channels
1190        */
1191       unsigned char *id, *comment;
1192       SilcUInt32 id_len, comment_len;
1193     
1194       SILC_LOG_DEBUG(("KILLED notify"));
1195       
1196       /* Get client ID */
1197       id = silc_argument_get_arg_type(args, 1, &id_len);
1198       if (!id)
1199         goto out;
1200       client_id = silc_id_payload_parse_id(id, id_len, NULL);
1201       if (!client_id)
1202         goto out;
1203
1204       /* If the the client is not in local list we check global list */
1205       client = silc_idlist_find_client_by_id(server->global_list, 
1206                                              client_id, TRUE, NULL);
1207       if (!client) {
1208         client = silc_idlist_find_client_by_id(server->local_list, 
1209                                                client_id, TRUE, NULL);
1210         if (!client) {
1211           silc_free(client_id);
1212           goto out;
1213         }
1214       }
1215       silc_free(client_id);
1216
1217       /* If the client is one of ours, then close the connection to the
1218          client now. This removes the client from all channels as well. */
1219       if (packet->dst_id_type == SILC_ID_CLIENT && client->connection) {
1220         sock = client->connection;
1221         silc_server_free_client_data(server, NULL, client, FALSE, NULL);
1222         silc_server_close_connection(server, sock);
1223         break;
1224       }
1225
1226       /* Get comment */
1227       comment = silc_argument_get_arg_type(args, 2, &comment_len);
1228       if (comment_len > 128)
1229         comment_len = 127;
1230
1231       /* From protocol version 1.1 we get the killer's ID as well. */
1232       tmp = silc_argument_get_arg_type(args, 3, &tmp_len);
1233       if (tmp) {
1234         client_id = silc_id_payload_parse_id(tmp, tmp_len, &id_type);
1235         if (!client_id)
1236           goto out;
1237
1238         if (id_type == SILC_ID_CLIENT) {
1239           /* If the the client is not in local list we check global list */
1240           client2 = silc_idlist_find_client_by_id(server->global_list, 
1241                                                   client_id, TRUE, NULL);
1242           if (!client2) {
1243             client2 = silc_idlist_find_client_by_id(server->local_list, 
1244                                                     client_id, TRUE, NULL);
1245             if (!client2) {
1246               silc_free(client_id);
1247               goto out;
1248             }
1249           }
1250           silc_free(client_id);
1251
1252           /* Killer must be router operator */
1253           if (!(client2->mode & SILC_UMODE_ROUTER_OPERATOR)) {
1254             SILC_LOG_DEBUG(("Killing is not allowed"));
1255             goto out;
1256           }
1257         }
1258       }
1259
1260       /* Send the notify to local clients on the channels except to the
1261          client who is killed. */
1262       silc_server_send_notify_on_channels(server, client, client,
1263                                           SILC_NOTIFY_TYPE_KILLED, 3,
1264                                           id, id_len, comment, comment_len,
1265                                           tmp, tmp_len);
1266
1267       /* Remove the client from all channels */
1268       silc_server_remove_from_channels(server, NULL, client, FALSE, NULL, 
1269                                        FALSE);
1270
1271       /* Check if anyone is watching this nickname */
1272       if (server->server_type == SILC_ROUTER)
1273         silc_server_check_watcher_list(server, client, NULL,
1274                                        SILC_NOTIFY_TYPE_KILLED);
1275
1276       break;
1277     }
1278
1279   case SILC_NOTIFY_TYPE_UMODE_CHANGE:
1280     /*
1281      * Save the mode of the client.
1282      */
1283
1284     SILC_LOG_DEBUG(("UMODE_CHANGE notify"));
1285
1286     /* Get client ID */
1287     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
1288     if (!tmp)
1289       goto out;
1290     client_id = silc_id_payload_parse_id(tmp, tmp_len, NULL);
1291     if (!client_id)
1292       goto out;
1293
1294     /* Get client entry */
1295     client = silc_idlist_find_client_by_id(server->global_list, 
1296                                            client_id, TRUE, NULL);
1297     if (!client) {
1298       client = silc_idlist_find_client_by_id(server->local_list, 
1299                                              client_id, TRUE, NULL);
1300       if (!client) {
1301         silc_free(client_id);
1302         goto out;
1303       }
1304     }
1305     silc_free(client_id);
1306
1307     /* Get the mode */
1308     tmp = silc_argument_get_arg_type(args, 2, &tmp_len);
1309     if (!tmp)
1310       goto out;
1311     SILC_GET32_MSB(mode, tmp);
1312
1313     /* Check that mode changing is allowed. */
1314     if (!silc_server_check_umode_rights(server, client, mode)) {
1315       SILC_LOG_DEBUG(("UMODE change is not allowed"));
1316       goto out;
1317     }
1318
1319     /* Remove internal resumed flag if client is marked detached now */
1320     if (mode & SILC_UMODE_DETACHED)
1321       client->data.status &= ~SILC_IDLIST_STATUS_RESUMED;
1322
1323     /* Change the mode */
1324     client->mode = mode;
1325
1326     /* Check if anyone is watching this nickname */
1327     if (server->server_type == SILC_ROUTER)
1328       silc_server_check_watcher_list(server, client, NULL,
1329                                      SILC_NOTIFY_TYPE_UMODE_CHANGE);
1330
1331     break;
1332
1333   case SILC_NOTIFY_TYPE_BAN:
1334     /*
1335      * Save the ban
1336      */
1337
1338     SILC_LOG_DEBUG(("BAN notify"));
1339     
1340     /* Get Channel ID */
1341     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
1342     if (!tmp)
1343       goto out;
1344     channel_id = silc_id_payload_parse_id(tmp, tmp_len, NULL);
1345     if (!channel_id)
1346       goto out;
1347     
1348     /* Get channel entry */
1349     channel = silc_idlist_find_channel_by_id(server->global_list, 
1350                                              channel_id, NULL);
1351     if (!channel) {
1352       channel = silc_idlist_find_channel_by_id(server->local_list, 
1353                                                channel_id, NULL);
1354       if (!channel) {
1355         silc_free(channel_id);
1356         goto out;
1357       }
1358     }
1359     silc_free(channel_id);
1360
1361     /* Get the new ban and add it to the ban list */
1362     tmp = silc_argument_get_arg_type(args, 2, &tmp_len);
1363     if (tmp) {
1364       if (!channel->ban_list)
1365         channel->ban_list = silc_calloc(tmp_len + 2, 
1366                                         sizeof(*channel->ban_list));
1367       else
1368         channel->ban_list = silc_realloc(channel->ban_list, 
1369                                          sizeof(*channel->ban_list) * 
1370                                          (tmp_len + 
1371                                           strlen(channel->ban_list) + 2));
1372       strncat(channel->ban_list, tmp, tmp_len);
1373       strncat(channel->ban_list, ",", 1);
1374     }
1375
1376     /* Get the ban to be removed and remove it from the list */
1377     tmp = silc_argument_get_arg_type(args, 3, &tmp_len);
1378     if (tmp && channel->ban_list) {
1379       char *start, *end, *n;
1380       
1381       if (!strncmp(channel->ban_list, tmp, strlen(channel->ban_list) - 1)) {
1382         silc_free(channel->ban_list);
1383         channel->ban_list = NULL;
1384       } else {
1385         start = strstr(channel->ban_list, tmp);
1386         if (start && strlen(start) >= tmp_len) {
1387           end = start + tmp_len;
1388           n = silc_calloc(strlen(channel->ban_list) - tmp_len, sizeof(*n));
1389           strncat(n, channel->ban_list, start - channel->ban_list);
1390           strncat(n, end + 1, ((channel->ban_list + 
1391                                 strlen(channel->ban_list)) - end) - 1);
1392           silc_free(channel->ban_list);
1393           channel->ban_list = n;
1394         }
1395       }
1396     }
1397     break;
1398
1399   case SILC_NOTIFY_TYPE_ERROR:
1400     {
1401       /*
1402        * Error notify
1403        */
1404       SilcStatus error;
1405
1406       tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
1407       if (!tmp && tmp_len != 1)
1408         goto out;
1409       error = (SilcStatus)tmp[0];
1410
1411       SILC_LOG_DEBUG(("ERROR notify (%d)", error));
1412
1413       if (error == SILC_STATUS_ERR_NO_SUCH_CLIENT_ID &&
1414           sock->type == SILC_SOCKET_TYPE_ROUTER) {
1415         tmp = silc_argument_get_arg_type(args, 2, &tmp_len);
1416         if (tmp) {
1417           SILC_LOG_DEBUG(("Received invalid client ID notification, deleting "
1418                           "the entry from cache"));
1419           client_id = silc_id_payload_parse_id(tmp, tmp_len, NULL);
1420           if (!client_id)
1421             goto out;
1422           client = silc_idlist_find_client_by_id(server->global_list, 
1423                                                  client_id, FALSE, NULL);
1424           if (client) {
1425             silc_server_remove_from_channels(server, NULL, client, TRUE, 
1426                                              NULL, TRUE);
1427             silc_idlist_del_client(server->global_list, client);
1428           }
1429           silc_free(client_id);
1430         }
1431       }
1432     }
1433     break;
1434
1435     /* Ignore rest of the notify types for now */
1436   case SILC_NOTIFY_TYPE_NONE:
1437   case SILC_NOTIFY_TYPE_MOTD:
1438     break;
1439   default:
1440     break;
1441   }
1442
1443  out:
1444   silc_notify_payload_free(payload);
1445 }
1446
1447 void silc_server_notify_list(SilcServer server,
1448                              SilcSocketConnection sock,
1449                              SilcPacketContext *packet)
1450 {
1451   SilcPacketContext *new;
1452   SilcBuffer buffer;
1453   SilcUInt16 len;
1454
1455   SILC_LOG_DEBUG(("Processing Notify List"));
1456
1457   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
1458       packet->src_id_type != SILC_ID_SERVER)
1459     return;
1460
1461   /* Make copy of the original packet context, except for the actual
1462      data buffer, which we will here now fetch from the original buffer. */
1463   new = silc_packet_context_alloc();
1464   new->type = SILC_PACKET_NOTIFY;
1465   new->flags = packet->flags;
1466   new->src_id = packet->src_id;
1467   new->src_id_len = packet->src_id_len;
1468   new->src_id_type = packet->src_id_type;
1469   new->dst_id = packet->dst_id;
1470   new->dst_id_len = packet->dst_id_len;
1471   new->dst_id_type = packet->dst_id_type;
1472
1473   buffer = silc_buffer_alloc(1024);
1474   new->buffer = buffer;
1475
1476   while (packet->buffer->len) {
1477     SILC_GET16_MSB(len, packet->buffer->data + 2);
1478     if (len > packet->buffer->len)
1479       break;
1480
1481     if (len > buffer->truelen) {
1482       silc_buffer_free(buffer);
1483       buffer = silc_buffer_alloc(1024 + len);
1484     }
1485
1486     silc_buffer_pull_tail(buffer, len);
1487     silc_buffer_put(buffer, packet->buffer->data, len);
1488
1489     /* Process the Notify */
1490     silc_server_notify(server, sock, new);
1491
1492     silc_buffer_push_tail(buffer, len);
1493     silc_buffer_pull(packet->buffer, len);
1494   }
1495
1496   silc_buffer_free(buffer);
1497   silc_free(new);
1498 }
1499
1500 /* Received private message. This resolves the destination of the message 
1501    and sends the packet. This is used by both server and router.  If the
1502    destination is our locally connected client this sends the packet to
1503    the client. This may also send the message for further routing if
1504    the destination is not in our server (or router). */
1505
1506 void silc_server_private_message(SilcServer server,
1507                                  SilcSocketConnection sock,
1508                                  SilcPacketContext *packet)
1509 {
1510   SilcSocketConnection dst_sock;
1511   SilcIDListData idata;
1512   SilcClientEntry client;
1513
1514   SILC_LOG_DEBUG(("Start"));
1515
1516   if (packet->src_id_type != SILC_ID_CLIENT ||
1517       packet->dst_id_type != SILC_ID_CLIENT || !packet->dst_id)
1518     return;
1519
1520   /* Get the route to the client */
1521   dst_sock = silc_server_get_client_route(server, packet->dst_id,
1522                                           packet->dst_id_len, NULL, 
1523                                           &idata, &client);
1524   if (!dst_sock) {
1525     SilcBuffer idp;
1526     unsigned char error;
1527
1528     if (client && client->mode & SILC_UMODE_DETACHED) {
1529       SILC_LOG_DEBUG(("Client is detached, discarding packet"));
1530       return;
1531     }
1532
1533     /* Send SILC_NOTIFY_TYPE_ERROR to indicate that such destination ID
1534        does not exist or is invalid. */
1535     idp = silc_id_payload_encode_data(packet->dst_id,
1536                                       packet->dst_id_len,
1537                                       packet->dst_id_type);
1538     if (!idp)
1539       return;
1540
1541     error = SILC_STATUS_ERR_NO_SUCH_CLIENT_ID;
1542     if (packet->src_id_type == SILC_ID_CLIENT) {
1543       SilcClientID *client_id = silc_id_str2id(packet->src_id,
1544                                                packet->src_id_len,
1545                                                packet->src_id_type);
1546       silc_server_send_notify_dest(server, sock, FALSE,
1547                                    client_id, SILC_ID_CLIENT,
1548                                    SILC_NOTIFY_TYPE_ERROR, 2,
1549                                    &error, 1,
1550                                    idp->data, idp->len);
1551       silc_free(client_id);
1552     } else {
1553       silc_server_send_notify(server, sock, FALSE,
1554                               SILC_NOTIFY_TYPE_ERROR, 2,
1555                               &error, 1,
1556                               idp->data, idp->len);
1557     }
1558
1559     silc_buffer_free(idp);
1560     return;
1561   }
1562
1563   /* Check whether destination client wishes to receive private messages */
1564   if (client && !(packet->flags & SILC_PACKET_FLAG_PRIVMSG_KEY) &&
1565       client->mode & SILC_UMODE_BLOCK_PRIVMSG) {
1566     SILC_LOG_DEBUG(("Client blocks private messages, discarding packet"));
1567     return;
1568   }
1569
1570   /* Send the private message */
1571   silc_server_send_private_message(server, dst_sock, idata->send_key,
1572                                    idata->hmac_send, idata->psn_send++,
1573                                    packet);
1574 }
1575
1576 /* Received private message key packet.. This packet is never for us. It is to
1577    the client in the packet's destination ID. Sending of this sort of packet
1578    equals sending private message, ie. it is sent point to point from
1579    one client to another. */
1580
1581 void silc_server_private_message_key(SilcServer server,
1582                                      SilcSocketConnection sock,
1583                                      SilcPacketContext *packet)
1584 {
1585   SilcSocketConnection dst_sock;
1586   SilcIDListData idata;
1587
1588   SILC_LOG_DEBUG(("Start"));
1589
1590   if (packet->src_id_type != SILC_ID_CLIENT ||
1591       packet->dst_id_type != SILC_ID_CLIENT)
1592     return;
1593
1594   if (!packet->dst_id)
1595     return;
1596
1597   /* Get the route to the client */
1598   dst_sock = silc_server_get_client_route(server, packet->dst_id,
1599                                           packet->dst_id_len, NULL, 
1600                                           &idata, NULL);
1601   if (!dst_sock)
1602     return;
1603
1604   /* Relay the packet */
1605   silc_server_relay_packet(server, dst_sock, idata->send_key,
1606                            idata->hmac_send, idata->psn_send++, packet, FALSE);
1607 }
1608
1609 /* Processes incoming command reply packet. The command reply packet may
1610    be destined to one of our clients or it may directly for us. We will 
1611    call the command reply routine after processing the packet. */
1612
1613 void silc_server_command_reply(SilcServer server,
1614                                SilcSocketConnection sock,
1615                                SilcPacketContext *packet)
1616 {
1617   SilcBuffer buffer = packet->buffer;
1618   SilcClientEntry client = NULL;
1619   SilcSocketConnection dst_sock;
1620   SilcIDListData idata;
1621   SilcClientID *id = NULL;
1622
1623   SILC_LOG_DEBUG(("Start"));
1624
1625   /* Source must be server or router */
1626   if (packet->src_id_type != SILC_ID_SERVER &&
1627       sock->type != SILC_SOCKET_TYPE_ROUTER)
1628     return;
1629
1630   if (packet->dst_id_type == SILC_ID_CHANNEL)
1631     return;
1632
1633   if (packet->dst_id_type == SILC_ID_CLIENT) {
1634     /* Destination must be one of ours */
1635     id = silc_id_str2id(packet->dst_id, packet->dst_id_len, SILC_ID_CLIENT);
1636     if (!id)
1637       return;
1638     client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
1639     if (!client) {
1640       SILC_LOG_ERROR(("Cannot process command reply to unknown client"));
1641       silc_free(id);
1642       return;
1643     }
1644   }
1645
1646   if (packet->dst_id_type == SILC_ID_SERVER) {
1647     /* For now this must be for us */
1648     if (memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
1649       SILC_LOG_ERROR(("Cannot process command reply to unknown server"));
1650       return;
1651     }
1652   }
1653
1654   /* Execute command reply locally for the command */
1655   silc_server_command_reply_process(server, sock, buffer);
1656
1657   if (packet->dst_id_type == SILC_ID_CLIENT && client && id) {
1658     /* Relay the packet to the client */
1659     const SilcBufferStruct p;
1660     
1661     dst_sock = (SilcSocketConnection)client->connection;
1662     idata = (SilcIDListData)client;
1663     
1664     silc_buffer_push(buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len 
1665                      + packet->dst_id_len + packet->padlen);
1666     if (!silc_packet_send_prepare(dst_sock, 0, 0, buffer->len,
1667                                   idata->hmac_send, (const SilcBuffer)&p)) {
1668       SILC_LOG_ERROR(("Cannot send packet"));
1669       return;
1670     }
1671     silc_buffer_put((SilcBuffer)&p, buffer->data, buffer->len);
1672     
1673     /* Encrypt packet */
1674     silc_packet_encrypt(idata->send_key, idata->hmac_send, idata->psn_send++,
1675                         (SilcBuffer)&p, buffer->len);
1676     
1677     /* Send the packet */
1678     silc_server_packet_send_real(server, dst_sock, TRUE);
1679
1680     silc_free(id);
1681   }
1682 }
1683
1684 /* Process received channel message. The message can be originated from
1685    client or server. */
1686
1687 void silc_server_channel_message(SilcServer server,
1688                                  SilcSocketConnection sock,
1689                                  SilcPacketContext *packet)
1690 {
1691   SilcChannelEntry channel = NULL;
1692   SilcChannelID *id = NULL;
1693   void *sender_id = NULL;
1694   SilcClientEntry sender_entry = NULL;
1695   SilcChannelClientEntry chl;
1696   bool local = TRUE;
1697
1698   SILC_LOG_DEBUG(("Processing channel message"));
1699
1700   /* Sanity checks */
1701   if (packet->dst_id_type != SILC_ID_CHANNEL) {
1702     SILC_LOG_DEBUG(("Received bad message for channel, dropped"));
1703     goto out;
1704   }
1705
1706   /* Find channel entry */
1707   id = silc_id_str2id(packet->dst_id, packet->dst_id_len, SILC_ID_CHANNEL);
1708   if (!id)
1709     goto out;
1710   channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
1711   if (!channel) {
1712     channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
1713     if (!channel) {
1714       SilcBuffer idp;
1715       unsigned char error;
1716
1717       /* Send SILC_NOTIFY_TYPE_ERROR to indicate that such destination ID
1718          does not exist or is invalid. */
1719       idp = silc_id_payload_encode_data(packet->dst_id,
1720                                         packet->dst_id_len,
1721                                         packet->dst_id_type);
1722       if (!idp)
1723         goto out;
1724
1725       error = SILC_STATUS_ERR_NO_SUCH_CHANNEL_ID;
1726       if (packet->src_id_type == SILC_ID_CLIENT) {
1727         SilcClientID *client_id = silc_id_str2id(packet->src_id,
1728                                                  packet->src_id_len,
1729                                                  packet->src_id_type);
1730         silc_server_send_notify_dest(server, sock, FALSE,
1731                                      client_id, SILC_ID_CLIENT,
1732                                      SILC_NOTIFY_TYPE_ERROR, 2,
1733                                      &error, 1, idp->data, idp->len);
1734         silc_free(client_id);
1735       } else {
1736         silc_server_send_notify(server, sock, FALSE,
1737                                 SILC_NOTIFY_TYPE_ERROR, 2,
1738                                 &error, 1, idp->data, idp->len);
1739       }
1740       
1741       silc_buffer_free(idp);
1742       goto out;
1743     }
1744   }
1745
1746   /* See that this client is on the channel. If the original sender is
1747      not client (as it can be server as well) we don't do the check. */
1748   sender_id = silc_id_str2id(packet->src_id, packet->src_id_len, 
1749                              packet->src_id_type);
1750   if (!sender_id)
1751     goto out;
1752   if (packet->src_id_type == SILC_ID_CLIENT) {
1753     sender_entry = silc_idlist_find_client_by_id(server->local_list, 
1754                                                  sender_id, TRUE, NULL);
1755     if (!sender_entry) {
1756       local = FALSE;
1757       sender_entry = silc_idlist_find_client_by_id(server->global_list, 
1758                                                    sender_id, TRUE, NULL);
1759     }
1760     if (!sender_entry || !silc_server_client_on_channel(sender_entry, 
1761                                                         channel, &chl)) {
1762       SILC_LOG_DEBUG(("Client not on channel"));
1763       goto out;
1764     }
1765
1766     /* If channel is moderated check that client is allowed to send
1767        messages. */
1768     if (channel->mode & SILC_CHANNEL_MODE_SILENCE_USERS && 
1769         !(chl->mode & SILC_CHANNEL_UMODE_CHANOP) &&
1770         !(chl->mode & SILC_CHANNEL_UMODE_CHANFO)) {
1771       SILC_LOG_DEBUG(("Channel is silenced from normal users"));
1772       goto out;
1773     }
1774     if (channel->mode & SILC_CHANNEL_MODE_SILENCE_OPERS && 
1775         chl->mode & SILC_CHANNEL_UMODE_CHANOP &&
1776         !(chl->mode & SILC_CHANNEL_UMODE_CHANFO)) {
1777       SILC_LOG_DEBUG(("Channel is silenced from operators"));
1778       goto out;
1779     }
1780
1781     /* If the packet is coming from router, but the client entry is local 
1782        entry to us then some router is rerouting this to us and it is not 
1783        allowed. When the client is local to us it means that we've routed
1784        this packet to network, and now someone is routing it back to us. */
1785     if (server->server_type == SILC_ROUTER &&
1786         sock->type == SILC_SOCKET_TYPE_ROUTER && local) {
1787       SILC_LOG_DEBUG(("Channel message rerouted to the sender, drop it"));
1788       goto out;
1789     }
1790   }
1791
1792   /* Distribute the packet to our local clients. This will send the
1793      packet for further routing as well, if needed. */
1794   silc_server_packet_relay_to_channel(server, sock, channel, sender_id,
1795                                       packet->src_id_type, sender_entry,
1796                                       packet->buffer->data,
1797                                       packet->buffer->len, FALSE);
1798
1799  out:
1800   silc_free(sender_id);
1801   silc_free(id);
1802 }
1803
1804 /* Received channel key packet. We distribute the key to all of our locally
1805    connected clients on the channel. */
1806
1807 void silc_server_channel_key(SilcServer server,
1808                              SilcSocketConnection sock,
1809                              SilcPacketContext *packet)
1810 {
1811   SilcBuffer buffer = packet->buffer;
1812   SilcChannelEntry channel;
1813
1814   if (packet->src_id_type != SILC_ID_SERVER ||
1815       (server->server_type == SILC_ROUTER &&
1816        sock->type == SILC_SOCKET_TYPE_ROUTER))
1817     return;
1818
1819   /* Save the channel key */
1820   channel = silc_server_save_channel_key(server, buffer, NULL);
1821   if (!channel)
1822     return;
1823
1824   /* Distribute the key to everybody who is on the channel. If we are router
1825      we will also send it to locally connected servers. */
1826   silc_server_send_channel_key(server, sock, channel, FALSE);
1827   
1828   if (server->server_type != SILC_BACKUP_ROUTER) {
1829     /* Distribute to local cell backup routers. */
1830     silc_server_backup_send(server, (SilcServerEntry)sock->user_data, 
1831                             SILC_PACKET_CHANNEL_KEY, 0,
1832                             buffer->data, buffer->len, FALSE, TRUE);
1833   }
1834 }
1835
1836 /* Received New Client packet and processes it.  Creates Client ID for the
1837    client. Client becomes registered after calling this functions. */
1838
1839 SilcClientEntry silc_server_new_client(SilcServer server,
1840                                        SilcSocketConnection sock,
1841                                        SilcPacketContext *packet)
1842 {
1843   SilcBuffer buffer = packet->buffer;
1844   SilcClientEntry client;
1845   SilcClientID *client_id;
1846   SilcIDListData idata;
1847   char *username = NULL, *realname = NULL;
1848   SilcUInt16 username_len;
1849   SilcUInt32 id_len;
1850   int ret;
1851   char *hostname, *nickname;
1852   int nickfail = 0;
1853
1854   SILC_LOG_DEBUG(("Creating new client"));
1855
1856   if (sock->type != SILC_SOCKET_TYPE_CLIENT)
1857     return NULL;
1858
1859   /* Take client entry */
1860   client = (SilcClientEntry)sock->user_data;
1861   idata = (SilcIDListData)client;
1862
1863   /* Remove the old cache entry. */
1864   if (!silc_idcache_del_by_context(server->local_list->clients, client)) {
1865     SILC_LOG_INFO(("Unauthenticated client attempted to register to network"));
1866     silc_server_disconnect_remote(server, sock, "Server closed connection: "
1867                                   "You have not been authenticated");
1868     return NULL;
1869   }
1870
1871   /* Parse incoming packet */
1872   ret = silc_buffer_unformat(buffer,
1873                              SILC_STR_UI16_NSTRING_ALLOC(&username, 
1874                                                          &username_len),
1875                              SILC_STR_UI16_STRING_ALLOC(&realname),
1876                              SILC_STR_END);
1877   if (ret == -1) {
1878     silc_free(username);
1879     silc_free(realname);
1880     SILC_LOG_ERROR(("Client %s (%s) sent incomplete information, closing "
1881                     "connection", sock->hostname, sock->ip));
1882     silc_server_disconnect_remote(server, sock, "Server closed connection: "
1883                                   "Incomplete client information");
1884     return NULL;
1885   }
1886
1887   if (!username) {
1888     silc_free(username);
1889     silc_free(realname);
1890     SILC_LOG_ERROR(("Client %s (%s) did not send its username, closing "
1891                     "connection", sock->hostname, sock->ip));
1892     silc_server_disconnect_remote(server, sock, "Server closed connection: "
1893                                   "Incomplete client information");
1894     return NULL;
1895   }
1896
1897   if (username_len > 128)
1898     username[128] = '\0';
1899
1900   /* Check for bad characters for nickname, and modify the nickname if
1901      it includes those. */
1902   if (silc_server_name_bad_chars(username, username_len)) {
1903     nickname = silc_server_name_modify_bad(username, username_len);
1904   } else {
1905     nickname = strdup(username);
1906   }
1907
1908   /* Make sanity checks for the hostname of the client. If the hostname
1909      is provided in the `username' check that it is the same than the
1910      resolved hostname, or if not resolved the hostname that appears in
1911      the client's public key. If the hostname is not present then put
1912      it from the resolved name or from the public key. */
1913   if (strchr(username, '@')) {
1914     SilcPublicKeyIdentifier pident;
1915     int tlen = strcspn(username, "@");
1916     char *phostname = NULL;
1917
1918     hostname = silc_memdup(username + tlen + 1, strlen(username) - tlen - 1);
1919
1920     if (strcmp(sock->hostname, sock->ip) && 
1921         strcmp(sock->hostname, hostname)) {
1922       silc_free(username);
1923       silc_free(hostname);
1924       silc_free(realname);
1925       SILC_LOG_ERROR(("Client %s (%s) sent incomplete information, closing "
1926                       "connection", sock->hostname, sock->ip));
1927       silc_server_disconnect_remote(server, sock, 
1928                                     "Server closed connection: "
1929                                     "Incomplete client information");
1930       return NULL;
1931     }
1932     
1933     pident = silc_pkcs_decode_identifier(client->data.public_key->identifier);
1934     if (pident) {
1935       phostname = strdup(pident->host);
1936       silc_pkcs_free_identifier(pident);
1937     }
1938
1939     if (!strcmp(sock->hostname, sock->ip) && 
1940         phostname && strcmp(phostname, hostname)) {
1941       silc_free(username);
1942       silc_free(hostname);
1943       silc_free(phostname);
1944       silc_free(realname);
1945       SILC_LOG_ERROR(("Client %s (%s) sent incomplete information, closing "
1946                       "connection", sock->hostname, sock->ip));
1947       silc_server_disconnect_remote(server, sock, 
1948                                     "Server closed connection: "
1949                                     "Incomplete client information");
1950       return NULL;
1951     }
1952     
1953     silc_free(phostname);
1954   } else {
1955     /* The hostname is not present, add it. */
1956     char *newusername;
1957     /* XXX For now we cannot take the host name from the public key since
1958        they are not trusted or we cannot verify them as trusted. Just take
1959        what the resolved name or address is. */
1960 #if 0
1961     if (strcmp(sock->hostname, sock->ip)) {
1962 #endif
1963       newusername = silc_calloc(strlen(username) + 
1964                                 strlen(sock->hostname) + 2,
1965                                 sizeof(*newusername));
1966       strncat(newusername, username, strlen(username));
1967       strncat(newusername, "@", 1);
1968       strncat(newusername, sock->hostname, strlen(sock->hostname));
1969       silc_free(username);
1970       username = newusername;
1971 #if 0
1972     } else {
1973       SilcPublicKeyIdentifier pident = 
1974         silc_pkcs_decode_identifier(client->data.public_key->identifier);
1975       
1976       if (pident) {
1977         newusername = silc_calloc(strlen(username) + 
1978                                   strlen(pident->host) + 2,
1979                                   sizeof(*newusername));
1980         strncat(newusername, username, strlen(username));
1981         strncat(newusername, "@", 1);
1982         strncat(newusername, pident->host, strlen(pident->host));
1983         silc_free(username);
1984         username = newusername;
1985         silc_pkcs_free_identifier(pident);
1986       }
1987     }
1988 #endif
1989   }
1990
1991   /* Create Client ID */
1992   while (!silc_id_create_client_id(server, server->id, server->rng, 
1993                                    server->md5hash, nickname, &client_id)) {
1994     nickfail++;
1995     if (nickfail > 9) {
1996       silc_server_disconnect_remote(server, sock, 
1997                                     "Server closed connection: Bad nickname");
1998       return NULL;
1999     }
2000     snprintf(&nickname[strlen(nickname) - 1], 1, "%d", nickfail);
2001   }
2002
2003   /* Update client entry */
2004   idata->status |= SILC_IDLIST_STATUS_REGISTERED;
2005   client->nickname = nickname;
2006   client->username = username;
2007   client->userinfo = realname ? realname : strdup(" ");
2008   client->id = client_id;
2009   id_len = silc_id_get_len(client_id, SILC_ID_CLIENT);
2010
2011   /* Add the client again to the ID cache */
2012   silc_idcache_add(server->local_list->clients, client->nickname,
2013                    client_id, client, 0, NULL);
2014
2015   /* Notify our router about new client on the SILC network */
2016   if (!server->standalone)
2017     silc_server_send_new_id(server, (SilcSocketConnection) 
2018                             server->router->connection, 
2019                             server->server_type == SILC_ROUTER ? TRUE : FALSE,
2020                             client->id, SILC_ID_CLIENT, id_len);
2021   
2022   /* Send the new client ID to the client. */
2023   silc_server_send_new_id(server, sock, FALSE, client->id, SILC_ID_CLIENT,
2024                           silc_id_get_len(client->id, SILC_ID_CLIENT));
2025
2026   /* Send some nice info to the client */
2027   silc_server_send_connect_notifys(server, sock, client);
2028
2029   /* Check if anyone is watching this nickname */
2030   if (server->server_type == SILC_ROUTER)
2031     silc_server_check_watcher_list(server, client, NULL, 0);
2032
2033   return client;
2034 }
2035
2036 /* Create new server. This processes received New Server packet and
2037    saves the received Server ID. The server is our locally connected
2038    server thus we save all the information and save it to local list. 
2039    This funtion can be used by both normal server and router server.
2040    If normal server uses this it means that its router has connected
2041    to the server. If router uses this it means that one of the cell's
2042    servers is connected to the router. */
2043
2044 SilcServerEntry silc_server_new_server(SilcServer server,
2045                                        SilcSocketConnection sock,
2046                                        SilcPacketContext *packet)
2047 {
2048   SilcBuffer buffer = packet->buffer;
2049   SilcServerEntry new_server, server_entry;
2050   SilcServerID *server_id;
2051   SilcIDListData idata;
2052   unsigned char *server_name, *id_string;
2053   SilcUInt16 id_len, name_len;
2054   int ret;
2055   bool local = TRUE;
2056
2057   SILC_LOG_DEBUG(("Creating new server"));
2058
2059   if (sock->type != SILC_SOCKET_TYPE_SERVER &&
2060       sock->type != SILC_SOCKET_TYPE_ROUTER)
2061     return NULL;
2062
2063   /* Take server entry */
2064   new_server = (SilcServerEntry)sock->user_data;
2065   idata = (SilcIDListData)new_server;
2066
2067   /* Remove the old cache entry */
2068   if (!silc_idcache_del_by_context(server->local_list->servers, new_server)) {
2069     if (!silc_idcache_del_by_context(server->global_list->servers, 
2070                                      new_server)) {
2071       SILC_LOG_INFO(("Unauthenticated %s attempted to register to "
2072                      "network", (sock->type == SILC_SOCKET_TYPE_SERVER ?
2073                                  "server" : "router")));
2074       silc_server_disconnect_remote(server, sock, "Server closed connection: "
2075                                     "You have not been authenticated");
2076       return NULL;
2077     }
2078     local = FALSE;
2079   }
2080
2081   /* Parse the incoming packet */
2082   ret = silc_buffer_unformat(buffer,
2083                              SILC_STR_UI16_NSTRING_ALLOC(&id_string, &id_len),
2084                              SILC_STR_UI16_NSTRING_ALLOC(&server_name, 
2085                                                          &name_len),
2086                              SILC_STR_END);
2087   if (ret == -1) {
2088     if (id_string)
2089       silc_free(id_string);
2090     if (server_name)
2091       silc_free(server_name);
2092     return NULL;
2093   }
2094
2095   if (id_len > buffer->len) {
2096     silc_free(id_string);
2097     silc_free(server_name);
2098     return NULL;
2099   }
2100
2101   if (name_len > 256)
2102     server_name[255] = '\0';
2103
2104   /* Get Server ID */
2105   server_id = silc_id_str2id(id_string, id_len, SILC_ID_SERVER);
2106   if (!server_id) {
2107     silc_free(id_string);
2108     silc_free(server_name);
2109     return NULL;
2110   }
2111   silc_free(id_string);
2112
2113   /* Check for valid server ID */
2114   if (!silc_id_is_valid_server_id(server, server_id, sock)) {
2115     SILC_LOG_INFO(("Invalid server ID sent by %s (%s)",
2116                    sock->ip, sock->hostname));
2117     silc_server_disconnect_remote(server, sock, "Server closed connection: "
2118                                   "Your Server ID is not valid");
2119     silc_free(server_name);
2120     return NULL;
2121   }
2122
2123   /* Check that we do not have this ID already */
2124   server_entry = silc_idlist_find_server_by_id(server->local_list, 
2125                                                server_id, TRUE, NULL);
2126   if (server_entry) {
2127     silc_idcache_del_by_context(server->local_list->servers, server_entry);
2128   } else {
2129     server_entry = silc_idlist_find_server_by_id(server->global_list, 
2130                                                  server_id, TRUE, NULL);
2131     if (server_entry) 
2132       silc_idcache_del_by_context(server->global_list->servers, server_entry);
2133   }
2134
2135   /* Update server entry */
2136   idata->status |= SILC_IDLIST_STATUS_REGISTERED;
2137   new_server->server_name = server_name;
2138   new_server->id = server_id;
2139   
2140   SILC_LOG_DEBUG(("New server id(%s)",
2141                   silc_id_render(server_id, SILC_ID_SERVER)));
2142
2143   /* Add again the entry to the ID cache. */
2144   silc_idcache_add(local ? server->local_list->servers : 
2145                    server->global_list->servers, server_name, server_id, 
2146                    new_server, 0, NULL);
2147
2148   /* Distribute the information about new server in the SILC network
2149      to our router. If we are normal server we won't send anything
2150      since this connection must be our router connection. */
2151   if (server->server_type == SILC_ROUTER && !server->standalone &&
2152       server->router->connection != sock)
2153     silc_server_send_new_id(server, server->router->connection,
2154                             TRUE, new_server->id, SILC_ID_SERVER, 
2155                             silc_id_get_len(server_id, SILC_ID_SERVER));
2156
2157   if (server->server_type == SILC_ROUTER)
2158     server->stat.cell_servers++;
2159
2160   /* Check whether this router connection has been replaced by an
2161      backup router. If it has been then we'll disable the server and will
2162      ignore everything it will send until the backup router resuming
2163      protocol has been completed. */
2164   if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
2165       silc_server_backup_replaced_get(server, server_id, NULL)) {
2166     /* Send packet to the server indicating that it cannot use this
2167        connection as it has been replaced by backup router. */
2168     SilcBuffer packet = silc_buffer_alloc(2);
2169     silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
2170     silc_buffer_format(packet,
2171                        SILC_STR_UI_CHAR(SILC_SERVER_BACKUP_REPLACED),
2172                        SILC_STR_UI_CHAR(0),
2173                        SILC_STR_END);
2174     silc_server_packet_send(server, sock, 
2175                             SILC_PACKET_RESUME_ROUTER, 0, 
2176                             packet->data, packet->len, TRUE);
2177     silc_buffer_free(packet);
2178
2179     /* Mark the router disabled. The data sent earlier will go but nothing
2180        after this does not go to this connection. */
2181     idata->status |= SILC_IDLIST_STATUS_DISABLED;
2182   } else {
2183     /* If it is router announce our stuff to it. */
2184     if (sock->type == SILC_SOCKET_TYPE_ROUTER && 
2185         server->server_type == SILC_ROUTER) {
2186       silc_server_announce_servers(server, FALSE, 0, sock);
2187       silc_server_announce_clients(server, 0, sock);
2188       silc_server_announce_channels(server, 0, sock);
2189     }
2190   }
2191
2192   return new_server;
2193 }
2194
2195 /* Processes incoming New ID packet. New ID Payload is used to distribute
2196    information about newly registered clients and servers. */
2197
2198 static void silc_server_new_id_real(SilcServer server, 
2199                                     SilcSocketConnection sock,
2200                                     SilcPacketContext *packet,
2201                                     int broadcast)
2202 {
2203   SilcBuffer buffer = packet->buffer;
2204   SilcIDList id_list;
2205   SilcServerEntry router, server_entry;
2206   SilcSocketConnection router_sock;
2207   SilcIDPayload idp;
2208   SilcIdType id_type;
2209   void *id;
2210
2211   SILC_LOG_DEBUG(("Processing new ID"));
2212
2213   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
2214       server->server_type == SILC_SERVER ||
2215       packet->src_id_type != SILC_ID_SERVER)
2216     return;
2217
2218   idp = silc_id_payload_parse(buffer->data, buffer->len);
2219   if (!idp)
2220     return;
2221
2222   id_type = silc_id_payload_get_type(idp);
2223
2224   /* Normal server cannot have other normal server connections */
2225   server_entry = (SilcServerEntry)sock->user_data;
2226   if (id_type == SILC_ID_SERVER && sock->type == SILC_SOCKET_TYPE_SERVER &&
2227       server_entry->server_type == SILC_SERVER)
2228     goto out;
2229
2230   id = silc_id_payload_get_id(idp);
2231   if (!id)
2232     goto out;
2233
2234   /* If the packet is coming from server then use the sender as the
2235      origin of the the packet. If it came from router then check the real
2236      sender of the packet and use that as the origin. */
2237   if (sock->type == SILC_SOCKET_TYPE_SERVER) {
2238     id_list = server->local_list;
2239     router_sock = sock;
2240     router = sock->user_data;
2241
2242     /* If the sender is backup router and ID is server (and we are not
2243        backup router) then switch the entry to global list. */
2244     if (server_entry->server_type == SILC_BACKUP_ROUTER && 
2245         id_type == SILC_ID_SERVER && 
2246         server->id_entry->server_type != SILC_BACKUP_ROUTER) {
2247       id_list = server->global_list;
2248       router_sock = server->router ? server->router->connection : sock;
2249     }
2250   } else {
2251     void *sender_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2252                                      packet->src_id_type);
2253     router = silc_idlist_find_server_by_id(server->global_list,
2254                                            sender_id, TRUE, NULL);
2255     if (!router)
2256       router = silc_idlist_find_server_by_id(server->local_list,
2257                                              sender_id, TRUE, NULL);
2258     silc_free(sender_id);
2259     router_sock = sock;
2260     id_list = server->global_list;
2261   }
2262
2263   if (!router)
2264     goto out;
2265
2266   switch(id_type) {
2267   case SILC_ID_CLIENT:
2268     {
2269       SilcClientEntry entry;
2270
2271       /* Check that we do not have this client already */
2272       entry = silc_idlist_find_client_by_id(server->global_list, 
2273                                             id, server->server_type, 
2274                                             NULL);
2275       if (!entry)
2276         entry = silc_idlist_find_client_by_id(server->local_list, 
2277                                               id, server->server_type,
2278                                               NULL);
2279       if (entry) {
2280         SILC_LOG_DEBUG(("Ignoring client that we already have"));
2281         goto out;
2282       }
2283
2284       SILC_LOG_DEBUG(("New client id(%s) from [%s] %s",
2285                       silc_id_render(id, SILC_ID_CLIENT),
2286                       sock->type == SILC_SOCKET_TYPE_SERVER ?
2287                       "Server" : "Router", sock->hostname));
2288     
2289       /* As a router we keep information of all global information in our
2290          global list. Cell wide information however is kept in the local
2291          list. */
2292       entry = silc_idlist_add_client(id_list, NULL, NULL, NULL, 
2293                                      id, router, NULL, 0);
2294       if (!entry) {
2295         SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
2296
2297         /* Inform the sender that the ID is not usable */
2298         silc_server_send_notify_signoff(server, sock, FALSE, id, NULL);
2299         goto out;
2300       }
2301       entry->nickname = NULL;
2302       entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
2303
2304       if (sock->type == SILC_SOCKET_TYPE_SERVER)
2305         server->stat.cell_clients++;
2306       server->stat.clients++;
2307
2308       /* Check if anyone is watching this nickname */
2309       if (server->server_type == SILC_ROUTER && id_list == server->local_list)
2310         silc_server_check_watcher_list(server, entry, NULL, 0);
2311     }
2312     break;
2313
2314   case SILC_ID_SERVER:
2315     {
2316       SilcServerEntry entry;
2317
2318       /* If the ID is mine, ignore it. */
2319       if (SILC_ID_SERVER_COMPARE(id, server->id)) {
2320         SILC_LOG_DEBUG(("Ignoring my own ID as new ID"));
2321         break;
2322       }
2323
2324       /* If the ID is the sender's ID, ignore it (we have it already) */
2325       if (SILC_ID_SERVER_COMPARE(id, router->id)) {
2326         SILC_LOG_DEBUG(("Ignoring sender's own ID"));
2327         break;
2328       }
2329       
2330       /* Check that we do not have this server already */
2331       entry = silc_idlist_find_server_by_id(server->global_list, 
2332                                             id, server->server_type, 
2333                                             NULL);
2334       if (!entry)
2335         entry = silc_idlist_find_server_by_id(server->local_list, 
2336                                               id, server->server_type,
2337                                               NULL);
2338       if (entry) {
2339         SILC_LOG_DEBUG(("Ignoring server that we already have"));
2340         goto out;
2341       }
2342
2343       SILC_LOG_DEBUG(("New server id(%s) from [%s] %s",
2344                       silc_id_render(id, SILC_ID_SERVER),
2345                       sock->type == SILC_SOCKET_TYPE_SERVER ?
2346                       "Server" : "Router", sock->hostname));
2347       
2348       /* As a router we keep information of all global information in our 
2349          global list. Cell wide information however is kept in the local
2350          list. */
2351       entry = silc_idlist_add_server(id_list, NULL, 0, id, router, 
2352                                      router_sock);
2353       if (!entry) {
2354         SILC_LOG_ERROR(("Could not add new server to the ID Cache"));
2355         goto out;
2356       }
2357       entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
2358       
2359       if (sock->type == SILC_SOCKET_TYPE_SERVER)
2360         server->stat.cell_servers++;
2361       server->stat.servers++;
2362     }
2363     break;
2364
2365   case SILC_ID_CHANNEL:
2366     SILC_LOG_ERROR(("Channel cannot be registered with NEW_ID packet"));
2367     goto out;
2368     break;
2369
2370   default:
2371     goto out;
2372     break;
2373   }
2374
2375   /* If the sender of this packet is server and we are router we need to
2376      broadcast this packet to other routers in the network. */
2377   if (broadcast && !server->standalone && server->server_type == SILC_ROUTER &&
2378       sock->type == SILC_SOCKET_TYPE_SERVER &&
2379       !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
2380     SILC_LOG_DEBUG(("Broadcasting received New ID packet"));
2381     silc_server_packet_send(server, server->router->connection,
2382                             packet->type, 
2383                             packet->flags | SILC_PACKET_FLAG_BROADCAST,
2384                             buffer->data, buffer->len, FALSE);
2385     silc_server_backup_send(server, (SilcServerEntry)sock->user_data, 
2386                             packet->type, packet->flags,
2387                             packet->buffer->data, packet->buffer->len, 
2388                             FALSE, TRUE);
2389   }
2390
2391  out:
2392   silc_id_payload_free(idp);
2393 }
2394
2395
2396 /* Processes incoming New ID packet. New ID Payload is used to distribute
2397    information about newly registered clients and servers. */
2398
2399 void silc_server_new_id(SilcServer server, SilcSocketConnection sock,
2400                         SilcPacketContext *packet)
2401 {
2402   silc_server_new_id_real(server, sock, packet, TRUE);
2403 }
2404
2405 /* Receoved New Id List packet, list of New ID payloads inside one
2406    packet. Process the New ID payloads one by one. */
2407
2408 void silc_server_new_id_list(SilcServer server, SilcSocketConnection sock,
2409                              SilcPacketContext *packet)
2410 {
2411   SilcPacketContext *new_id;
2412   SilcBuffer idp;
2413   SilcUInt16 id_len;
2414
2415   SILC_LOG_DEBUG(("Processing New ID List"));
2416
2417   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
2418       packet->src_id_type != SILC_ID_SERVER)
2419     return;
2420
2421   /* If the sender of this packet is server and we are router we need to
2422      broadcast this packet to other routers in the network. Broadcast
2423      this list packet instead of multiple New ID packets. */
2424   if (!server->standalone && server->server_type == SILC_ROUTER &&
2425       sock->type == SILC_SOCKET_TYPE_SERVER &&
2426       !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
2427     SILC_LOG_DEBUG(("Broadcasting received New ID List packet"));
2428     silc_server_packet_send(server, server->router->connection,
2429                             packet->type, 
2430                             packet->flags | SILC_PACKET_FLAG_BROADCAST,
2431                             packet->buffer->data, packet->buffer->len, FALSE);
2432     silc_server_backup_send(server, (SilcServerEntry)sock->user_data, 
2433                             packet->type, packet->flags,
2434                             packet->buffer->data, packet->buffer->len, 
2435                             FALSE, TRUE);
2436   }
2437
2438   /* Make copy of the original packet context, except for the actual
2439      data buffer, which we will here now fetch from the original buffer. */
2440   new_id = silc_packet_context_alloc();
2441   new_id->type = SILC_PACKET_NEW_ID;
2442   new_id->flags = packet->flags;
2443   new_id->src_id = packet->src_id;
2444   new_id->src_id_len = packet->src_id_len;
2445   new_id->src_id_type = packet->src_id_type;
2446   new_id->dst_id = packet->dst_id;
2447   new_id->dst_id_len = packet->dst_id_len;
2448   new_id->dst_id_type = packet->dst_id_type;
2449
2450   idp = silc_buffer_alloc(256);
2451   new_id->buffer = idp;
2452
2453   while (packet->buffer->len) {
2454     SILC_GET16_MSB(id_len, packet->buffer->data + 2);
2455     if ((id_len > packet->buffer->len) ||
2456         (id_len > idp->truelen))
2457       break;
2458
2459     silc_buffer_pull_tail(idp, 4 + id_len);
2460     silc_buffer_put(idp, packet->buffer->data, 4 + id_len);
2461
2462     /* Process the New ID */
2463     silc_server_new_id_real(server, sock, new_id, FALSE);
2464
2465     silc_buffer_push_tail(idp, 4 + id_len);
2466     silc_buffer_pull(packet->buffer, 4 + id_len);
2467   }
2468
2469   silc_buffer_free(idp);
2470   silc_free(new_id);
2471 }
2472
2473 /* Received New Channel packet. Information about new channels in the 
2474    network are distributed using this packet. Save the information about
2475    the new channel. This usually comes from router but also normal server
2476    can send this to notify channels it has when it connects to us. */
2477
2478 void silc_server_new_channel(SilcServer server,
2479                              SilcSocketConnection sock,
2480                              SilcPacketContext *packet)
2481 {
2482   SilcChannelPayload payload;
2483   SilcChannelID *channel_id;
2484   char *channel_name;
2485   SilcUInt32 name_len;
2486   unsigned char *id;
2487   SilcUInt32 id_len;
2488   SilcUInt32 mode;
2489   SilcServerEntry server_entry;
2490   SilcChannelEntry channel;
2491
2492   SILC_LOG_DEBUG(("Processing New Channel"));
2493
2494   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
2495       packet->src_id_type != SILC_ID_SERVER ||
2496       server->server_type == SILC_SERVER)
2497     return;
2498
2499   /* Parse the channel payload */
2500   payload = silc_channel_payload_parse(packet->buffer->data,
2501                                        packet->buffer->len);
2502   if (!payload)
2503     return;
2504     
2505   /* Get the channel ID */
2506   channel_id = silc_channel_get_id_parse(payload);
2507   if (!channel_id) {
2508     silc_channel_payload_free(payload);
2509     return;
2510   }
2511
2512   channel_name = silc_channel_get_name(payload, &name_len);
2513   if (name_len > 256)
2514     channel_name[255] = '\0';
2515
2516   id = silc_channel_get_id(payload, &id_len);
2517
2518   server_entry = (SilcServerEntry)sock->user_data;
2519
2520   if (sock->type == SILC_SOCKET_TYPE_ROUTER) {
2521     /* Add the channel to global list as it is coming from router. It 
2522        cannot be our own channel as it is coming from router. */
2523
2524     /* Check that we don't already have this channel */
2525     channel = silc_idlist_find_channel_by_name(server->local_list, 
2526                                                channel_name, NULL);
2527     if (!channel)
2528       channel = silc_idlist_find_channel_by_name(server->global_list, 
2529                                                  channel_name, NULL);
2530     if (!channel) {
2531       SILC_LOG_DEBUG(("New channel id(%s) from [Router] %s",
2532                       silc_id_render(channel_id, SILC_ID_CHANNEL), 
2533                       sock->hostname));
2534     
2535       channel = 
2536         silc_idlist_add_channel(server->global_list, strdup(channel_name), 
2537                                 0, channel_id, sock->user_data, NULL, NULL, 0);
2538       if (!channel)
2539         return;
2540
2541       server->stat.channels++;
2542       if (server->server_type == SILC_ROUTER)
2543         channel->users_resolved = TRUE;
2544     }
2545   } else {
2546     /* The channel is coming from our server, thus it is in our cell
2547        we will add it to our local list. */
2548     SilcBuffer chk;
2549
2550     SILC_LOG_DEBUG(("Channel id(%s) from [Server] %s",
2551                     silc_id_render(channel_id, SILC_ID_CHANNEL), 
2552                     sock->hostname));
2553
2554     /* Check that we don't already have this channel */
2555     channel = silc_idlist_find_channel_by_name(server->local_list, 
2556                                                channel_name, NULL);
2557     if (!channel)
2558       channel = silc_idlist_find_channel_by_name(server->global_list, 
2559                                                  channel_name, NULL);
2560
2561     /* If the channel does not exist, then create it. This creates a new
2562        key to the channel as well that we will send to the server. */
2563     if (!channel) {
2564       /* The protocol says that the Channel ID's IP address must be based
2565          on the router's IP address.  Check whether the ID is based in our
2566          IP and if it is not then create a new ID and enforce the server
2567          to switch the ID. */
2568       if (server_entry->server_type != SILC_BACKUP_ROUTER &&
2569           !SILC_ID_COMPARE(channel_id, server->id, server->id->ip.data_len)) {
2570         SilcChannelID *tmp;
2571         SILC_LOG_DEBUG(("Forcing the server to change Channel ID"));
2572         
2573         if (silc_id_create_channel_id(server, server->id, server->rng, &tmp)) {
2574           silc_server_send_notify_channel_change(server, sock, FALSE, 
2575                                                  channel_id, tmp);
2576           silc_free(channel_id);
2577           channel_id = tmp;
2578         }
2579       }
2580
2581       /* Create the channel with the provided Channel ID */
2582       channel = silc_server_create_new_channel_with_id(server, NULL, NULL,
2583                                                        channel_name,
2584                                                        channel_id, FALSE);
2585       if (!channel) {
2586         silc_channel_payload_free(payload);
2587         silc_free(channel_id);
2588         return;
2589       }
2590
2591       /* Get the mode and set it to the channel */
2592       channel->mode = silc_channel_get_mode(payload);
2593
2594       /* Send the new channel key to the server */
2595       id = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
2596       id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
2597       chk = silc_channel_key_payload_encode(id_len, id,
2598                                             strlen(channel->channel_key->
2599                                                    cipher->name),
2600                                             channel->channel_key->cipher->name,
2601                                             channel->key_len / 8, 
2602                                             channel->key);
2603       silc_server_packet_send(server, sock, SILC_PACKET_CHANNEL_KEY, 0, 
2604                               chk->data, chk->len, FALSE);
2605       silc_buffer_free(chk);
2606
2607     } else {
2608       /* The channel exist by that name, check whether the ID's match.
2609          If they don't then we'll force the server to use the ID we have.
2610          We also create a new key for the channel. */
2611       SilcBuffer users = NULL, users_modes = NULL;
2612
2613       if (!SILC_ID_CHANNEL_COMPARE(channel_id, channel->id)) {
2614         /* They don't match, send CHANNEL_CHANGE notify to the server to
2615            force the ID change. */
2616         SILC_LOG_DEBUG(("Forcing the server to change Channel ID"));
2617         silc_server_send_notify_channel_change(server, sock, FALSE, 
2618                                                channel_id, channel->id);
2619       }
2620
2621       /* If the mode is different from what we have then enforce the
2622          mode change. */
2623       mode = silc_channel_get_mode(payload);
2624       if (channel->mode != mode) {
2625         SILC_LOG_DEBUG(("Forcing the server to change channel mode"));
2626         silc_server_send_notify_cmode(server, sock, FALSE, channel,
2627                                       channel->mode, server->id,
2628                                       SILC_ID_SERVER,
2629                                       channel->cipher, channel->hmac_name,
2630                                       channel->passphrase);
2631       }
2632
2633       /* Create new key for the channel and send it to the server and
2634          everybody else possibly on the channel. */
2635
2636       if (!(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
2637         if (!silc_server_create_channel_key(server, channel, 0))
2638           return;
2639         
2640         /* Send to the channel */
2641         silc_server_send_channel_key(server, sock, channel, FALSE);
2642         id = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
2643         id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
2644
2645         /* Send to the server */
2646         chk = silc_channel_key_payload_encode(id_len, id,
2647                                               strlen(channel->channel_key->
2648                                                      cipher->name),
2649                                               channel->channel_key->
2650                                               cipher->name,
2651                                               channel->key_len / 8, 
2652                                               channel->key);
2653         silc_server_packet_send(server, sock, SILC_PACKET_CHANNEL_KEY, 0, 
2654                                 chk->data, chk->len, FALSE);
2655         silc_buffer_free(chk);
2656         silc_free(id);
2657       }
2658
2659       silc_free(channel_id);
2660
2661       /* Since the channel is coming from server and we also know about it
2662          then send the JOIN notify to the server so that it see's our
2663          users on the channel "joining" the channel. */
2664       silc_server_announce_get_channel_users(server, channel, &users,
2665                                              &users_modes);
2666       if (users) {
2667         silc_buffer_push(users, users->data - users->head);
2668         silc_server_packet_send(server, sock,
2669                                 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
2670                                 users->data, users->len, FALSE);
2671         silc_buffer_free(users);
2672       }
2673       if (users_modes) {
2674         silc_buffer_push(users_modes, users_modes->data - users_modes->head);
2675         silc_server_packet_send_dest(server, sock,
2676                                      SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
2677                                      channel->id, SILC_ID_CHANNEL,
2678                                      users_modes->data, 
2679                                      users_modes->len, FALSE);
2680         silc_buffer_free(users_modes);
2681       }
2682     }
2683   }
2684
2685   silc_channel_payload_free(payload);
2686 }
2687
2688 /* Received New Channel List packet, list of New Channel List payloads inside
2689    one packet. Process the New Channel payloads one by one. */
2690
2691 void silc_server_new_channel_list(SilcServer server,
2692                                   SilcSocketConnection sock,
2693                                   SilcPacketContext *packet)
2694 {
2695   SilcPacketContext *new;
2696   SilcBuffer buffer;
2697   SilcUInt16 len1, len2;
2698
2699   SILC_LOG_DEBUG(("Processing New Channel List"));
2700
2701   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
2702       packet->src_id_type != SILC_ID_SERVER ||
2703       server->server_type == SILC_SERVER)
2704     return;
2705
2706   /* If the sender of this packet is server and we are router we need to
2707      broadcast this packet to other routers in the network. Broadcast
2708      this list packet instead of multiple New Channel packets. */
2709   if (!server->standalone && server->server_type == SILC_ROUTER &&
2710       sock->type == SILC_SOCKET_TYPE_SERVER &&
2711       !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
2712     SILC_LOG_DEBUG(("Broadcasting received New Channel List packet"));
2713     silc_server_packet_send(server, server->router->connection,
2714                             packet->type, 
2715                             packet->flags | SILC_PACKET_FLAG_BROADCAST,
2716                             packet->buffer->data, packet->buffer->len, FALSE);
2717     silc_server_backup_send(server, (SilcServerEntry)sock->user_data, 
2718                             packet->type, packet->flags,
2719                             packet->buffer->data, packet->buffer->len, 
2720                             FALSE, TRUE);
2721   }
2722
2723   /* Make copy of the original packet context, except for the actual
2724      data buffer, which we will here now fetch from the original buffer. */
2725   new = silc_packet_context_alloc();
2726   new->type = SILC_PACKET_NEW_CHANNEL;
2727   new->flags = packet->flags;
2728   new->src_id = packet->src_id;
2729   new->src_id_len = packet->src_id_len;
2730   new->src_id_type = packet->src_id_type;
2731   new->dst_id = packet->dst_id;
2732   new->dst_id_len = packet->dst_id_len;
2733   new->dst_id_type = packet->dst_id_type;
2734
2735   buffer = silc_buffer_alloc(512);
2736   new->buffer = buffer;
2737
2738   while (packet->buffer->len) {
2739     SILC_GET16_MSB(len1, packet->buffer->data);
2740     if ((len1 > packet->buffer->len) ||
2741         (len1 > buffer->truelen))
2742       break;
2743
2744     SILC_GET16_MSB(len2, packet->buffer->data + 2 + len1);
2745     if ((len2 > packet->buffer->len) ||
2746         (len2 > buffer->truelen))
2747       break;
2748
2749     silc_buffer_pull_tail(buffer, 8 + len1 + len2);
2750     silc_buffer_put(buffer, packet->buffer->data, 8 + len1 + len2);
2751
2752     /* Process the New Channel */
2753     silc_server_new_channel(server, sock, new);
2754
2755     silc_buffer_push_tail(buffer, 8 + len1 + len2);
2756     silc_buffer_pull(packet->buffer, 8 + len1 + len2);
2757   }
2758
2759   silc_buffer_free(buffer);
2760   silc_free(new);
2761 }
2762
2763 /* Received key agreement packet. This packet is never for us. It is to
2764    the client in the packet's destination ID. Sending of this sort of packet
2765    equals sending private message, ie. it is sent point to point from
2766    one client to another. */
2767
2768 void silc_server_key_agreement(SilcServer server,
2769                                SilcSocketConnection sock,
2770                                SilcPacketContext *packet)
2771 {
2772   SilcSocketConnection dst_sock;
2773   SilcIDListData idata;
2774
2775   SILC_LOG_DEBUG(("Start"));
2776
2777   if (packet->src_id_type != SILC_ID_CLIENT ||
2778       packet->dst_id_type != SILC_ID_CLIENT)
2779     return;
2780
2781   if (!packet->dst_id)
2782     return;
2783
2784   /* Get the route to the client */
2785   dst_sock = silc_server_get_client_route(server, packet->dst_id,
2786                                           packet->dst_id_len, NULL, 
2787                                           &idata, NULL);
2788   if (!dst_sock)
2789     return;
2790
2791   /* Relay the packet */
2792   silc_server_relay_packet(server, dst_sock, idata->send_key,
2793                            idata->hmac_send, idata->psn_send++,
2794                            packet, FALSE);
2795 }
2796
2797 /* Received connection auth request packet that is used during connection
2798    phase to resolve the mandatory authentication method.  This packet can
2799    actually be received at anytime but usually it is used only during
2800    the connection authentication phase. Now, protocol says that this packet
2801    can come from client or server, however, we support only this coming
2802    from client and expect that server always knows what authentication
2803    method to use. */
2804
2805 void silc_server_connection_auth_request(SilcServer server,
2806                                          SilcSocketConnection sock,
2807                                          SilcPacketContext *packet)
2808 {
2809   SilcServerConfigClient *client = NULL;
2810   SilcUInt16 conn_type;
2811   int ret;
2812   SilcAuthMethod auth_meth = SILC_AUTH_NONE;
2813
2814   SILC_LOG_DEBUG(("Start"));
2815
2816   if (packet->src_id_type && packet->src_id_type != SILC_ID_CLIENT)
2817     return;
2818
2819   /* Parse the payload */
2820   ret = silc_buffer_unformat(packet->buffer,
2821                              SILC_STR_UI_SHORT(&conn_type),
2822                              SILC_STR_UI_SHORT(NULL),
2823                              SILC_STR_END);
2824   if (ret == -1)
2825     return;
2826
2827   if (conn_type != SILC_SOCKET_TYPE_CLIENT)
2828     return;
2829
2830   /* Get the authentication method for the client */
2831   auth_meth = SILC_AUTH_NONE;
2832   client = silc_server_config_find_client(server, sock->ip);
2833   if (!client)
2834     client = silc_server_config_find_client(server, sock->hostname);
2835   if (client) {
2836     if (client->passphrase) {
2837       if (client->publickeys && !server->config->prefer_passphrase_auth)
2838         auth_meth = SILC_AUTH_PUBLIC_KEY;
2839       else
2840         auth_meth = SILC_AUTH_PASSWORD;
2841     } else if (client->publickeys)
2842       auth_meth = SILC_AUTH_PUBLIC_KEY;
2843   }
2844
2845   /* Send it back to the client */
2846   silc_server_send_connection_auth_request(server, sock, conn_type, auth_meth);
2847 }
2848
2849 /* Received REKEY packet. The sender of the packet wants to regenerate
2850    its session keys. This starts the REKEY protocol. */
2851
2852 void silc_server_rekey(SilcServer server,
2853                        SilcSocketConnection sock,
2854                        SilcPacketContext *packet)
2855 {
2856   SilcProtocol protocol;
2857   SilcServerRekeyInternalContext *proto_ctx;
2858   SilcIDListData idata = (SilcIDListData)sock->user_data;
2859
2860   SILC_LOG_DEBUG(("Start"));
2861
2862   /* Allocate internal protocol context. This is sent as context
2863      to the protocol. */
2864   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
2865   proto_ctx->server = (void *)server;
2866   proto_ctx->sock = sock;
2867   proto_ctx->responder = TRUE;
2868   proto_ctx->pfs = idata->rekey->pfs;
2869       
2870   /* Perform rekey protocol. Will call the final callback after the
2871      protocol is over. */
2872   silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY, 
2873                       &protocol, proto_ctx, silc_server_rekey_final);
2874   sock->protocol = protocol;
2875
2876   if (proto_ctx->pfs == FALSE)
2877     /* Run the protocol */
2878     silc_protocol_execute(protocol, server->schedule, 0, 0);
2879 }
2880
2881 /* Received file transger packet. This packet is never for us. It is to
2882    the client in the packet's destination ID. Sending of this sort of packet
2883    equals sending private message, ie. it is sent point to point from
2884    one client to another. */
2885
2886 void silc_server_ftp(SilcServer server,
2887                      SilcSocketConnection sock,
2888                      SilcPacketContext *packet)
2889 {
2890   SilcSocketConnection dst_sock;
2891   SilcIDListData idata;
2892
2893   SILC_LOG_DEBUG(("Start"));
2894
2895   if (packet->src_id_type != SILC_ID_CLIENT ||
2896       packet->dst_id_type != SILC_ID_CLIENT)
2897     return;
2898
2899   if (!packet->dst_id)
2900     return;
2901
2902   /* Get the route to the client */
2903   dst_sock = silc_server_get_client_route(server, packet->dst_id,
2904                                           packet->dst_id_len, NULL, 
2905                                           &idata, NULL);
2906   if (!dst_sock)
2907     return;
2908
2909   /* Relay the packet */
2910   silc_server_relay_packet(server, dst_sock, idata->send_key,
2911                            idata->hmac_send, idata->psn_send++,
2912                            packet, FALSE);
2913 }
2914
2915 typedef struct {
2916   SilcServer server;
2917   SilcSocketConnection sock;
2918   SilcPacketContext *packet;
2919   void *data;
2920 } *SilcServerResumeResolve;
2921
2922 SILC_SERVER_CMD_FUNC(resume_resolve)
2923 {
2924   SilcServerResumeResolve r = (SilcServerResumeResolve)context;
2925   SilcServer server = r->server;
2926   SilcSocketConnection sock = r->sock;
2927   SilcServerCommandReplyContext reply = context2;
2928   SilcClientEntry client;
2929
2930   SILC_LOG_DEBUG(("Start"));
2931
2932   if (!reply || !silc_command_get_status(reply->payload, NULL, NULL)) {
2933     SILC_LOG_ERROR(("Client %s (%s) tried to resume unknown client, "
2934                     "closing connection", sock->hostname, sock->ip));
2935     silc_server_disconnect_remote(server, sock, 
2936                                   "Server closed connection: "
2937                                   "Incomplete resume information");
2938     goto out;
2939   }
2940
2941   if (reply && silc_command_get(reply->payload) == SILC_COMMAND_WHOIS) {
2942     /* Get entry to the client, and resolve it if we don't have it. */
2943     client = silc_idlist_find_client_by_id(server->local_list, 
2944                                            r->data, TRUE, NULL);
2945     if (!client) {
2946       client = silc_idlist_find_client_by_id(server->global_list,
2947                                              r->data, TRUE, NULL);
2948       if (!client) {
2949         SILC_LOG_ERROR(("Client %s (%s) tried to resume unknown client, "
2950                         "closing connection", sock->hostname, sock->ip));
2951         silc_server_disconnect_remote(server, sock, 
2952                                       "Server closed connection: "
2953                                       "Incomplete resume information");
2954         goto out;
2955       }
2956     }
2957
2958     if (!(client->mode & SILC_UMODE_DETACHED)) {
2959       SILC_LOG_ERROR(("Client %s (%s) tried to resume un-detached client, "
2960                       "closing connection", sock->hostname, sock->ip));
2961       silc_server_disconnect_remote(server, sock, 
2962                                     "Server closed connection: "
2963                                     "Incomplete resume information");
2964       goto out;
2965     }
2966   }
2967
2968   /* Reprocess the packet */
2969   silc_server_resume_client(server, sock, r->packet);
2970
2971  out:
2972   silc_socket_free(r->sock);
2973   silc_packet_context_free(r->packet);
2974   silc_free(r->data);
2975   silc_free(r);
2976 }
2977
2978 /* Received client resuming packet.  This is used to resume detached
2979    client session.  It can be sent by the client who wishes to resume
2980    but this is also sent by servers and routers to notify other routers
2981    that the client is not detached anymore. */
2982
2983 void silc_server_resume_client(SilcServer server,
2984                                SilcSocketConnection sock,
2985                                SilcPacketContext *packet)
2986 {
2987   SilcBuffer buffer = packet->buffer, buf;
2988   SilcIDListData idata;
2989   SilcClientEntry detached_client;
2990   SilcClientID *client_id = NULL;
2991   unsigned char *id_string, *auth = NULL;
2992   SilcUInt16 id_len, auth_len = 0;
2993   int ret, nickfail = 0;
2994   bool resolved, local, nick_change = FALSE;
2995   SilcChannelEntry channel;
2996   SilcHashTableList htl;
2997   SilcChannelClientEntry chl;
2998   SilcServerResumeResolve r;
2999
3000   SILC_LOG_DEBUG(("Start"));
3001
3002   ret = silc_buffer_unformat(buffer,
3003                              SILC_STR_UI16_NSTRING(&id_string, &id_len),
3004                              SILC_STR_END);
3005   if (ret != -1)
3006     client_id = silc_id_str2id(id_string, id_len, SILC_ID_CLIENT);
3007
3008   if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
3009     /* Client send this and is attempting to resume to old client session */
3010     SilcClientEntry client;
3011     SilcBuffer keyp;
3012
3013     if (ret != -1) {
3014       silc_buffer_pull(buffer, 2 + id_len);
3015       auth = buffer->data;
3016       auth_len = buffer->len;
3017       silc_buffer_push(buffer, 2 + id_len);
3018     }
3019
3020     if (!client_id || auth_len < 128) {
3021       SILC_LOG_ERROR(("Client %s (%s) sent incomplete resume information, "
3022                       "closing connection", sock->hostname, sock->ip));
3023       silc_server_disconnect_remote(server, sock, "Server closed connection: "
3024                                     "Incomplete resume information");
3025       return;
3026     }
3027
3028     /* Take client entry of this connection */
3029     client = (SilcClientEntry)sock->user_data;
3030     idata = (SilcIDListData)client;
3031
3032     /* Get entry to the client, and resolve it if we don't have it. */
3033     detached_client = silc_server_get_client_resolve(server, client_id, FALSE,
3034                                                      &resolved);
3035     if (!detached_client) {
3036       if (resolved) {
3037         /* The client info is being resolved. Reprocess this packet after
3038            receiving the reply to the query. */
3039         SILC_LOG_DEBUG(("Resolving client"));
3040         r = silc_calloc(1, sizeof(*r));
3041         if (!r)
3042           return;
3043         r->server = server;
3044         r->sock = silc_socket_dup(sock);
3045         r->packet = silc_packet_context_dup(packet);
3046         r->data = silc_id_dup(client_id, SILC_ID_CLIENT);
3047         silc_server_command_pending(server, SILC_COMMAND_WHOIS,
3048                                     server->cmd_ident,
3049                                     silc_server_command_resume_resolve, r);
3050       } else {
3051         SILC_LOG_ERROR(("Client %s (%s) tried to resume unknown client, "
3052                         "closing connection", sock->hostname, sock->ip));
3053         silc_server_disconnect_remote(server, sock, 
3054                                       "Server closed connection: "
3055                                       "Incomplete resume information");
3056       }
3057       return;
3058     }
3059
3060     /* Check that the client is detached, and that we have other info too */
3061     if (!(detached_client->mode & SILC_UMODE_DETACHED) ||
3062         !silc_hash_table_count(detached_client->channels) ||
3063         !detached_client->nickname) {
3064       if (server->server_type == SILC_SERVER && !server->standalone) {
3065         /* The client info is being resolved. Reprocess this packet after
3066            receiving the reply to the query. */
3067         SILC_LOG_DEBUG(("Resolving client info"));
3068         silc_server_get_client_resolve(server, client_id, TRUE, NULL);
3069         r = silc_calloc(1, sizeof(*r));
3070         if (!r)
3071           return;
3072         r->server = server;
3073         r->sock = silc_socket_dup(sock);
3074         r->packet = silc_packet_context_dup(packet);
3075         r->data = silc_id_dup(client_id, SILC_ID_CLIENT);
3076         silc_server_command_pending(server, SILC_COMMAND_WHOIS,
3077                                     server->cmd_ident,
3078                                     silc_server_command_resume_resolve, r);
3079         return;
3080       }
3081       if (server->server_type == SILC_SERVER) {
3082         SILC_LOG_ERROR(("Client %s (%s) tried to resume un-detached client, "
3083                         "closing connection", sock->hostname, sock->ip));
3084         silc_server_disconnect_remote(server, sock, 
3085                                       "Server closed connection: "
3086                                       "Incomplete resume information");
3087         return;
3088       }
3089     }
3090
3091     /* Check that we have the public key of the client, if not then we must
3092        resolve it first. */
3093     if (!detached_client->data.public_key) {
3094       if (server->standalone) {
3095         silc_server_disconnect_remote(server, sock, 
3096                                       "Server closed connection: "
3097                                       "Incomplete resume information");
3098       } else {
3099         /* We must retrieve the detached client's public key by sending
3100            GETKEY command. Reprocess this packet after receiving the key */
3101         SilcBuffer idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
3102         SilcSocketConnection dest_sock = 
3103           silc_server_get_client_route(server, NULL, 0, client_id, NULL, NULL);
3104
3105         SILC_LOG_DEBUG(("Resolving client public key"));
3106
3107         silc_server_send_command(server, dest_sock ? dest_sock : 
3108                                  server->router->connection,
3109                                  SILC_COMMAND_GETKEY, ++server->cmd_ident,
3110                                  1, 1, idp->data, idp->len);
3111
3112         r = silc_calloc(1, sizeof(*r));
3113         if (!r)
3114           return;
3115
3116         r->server = server;
3117         r->sock = silc_socket_dup(sock);
3118         r->packet = silc_packet_context_dup(packet);
3119         silc_server_command_pending(server, SILC_COMMAND_GETKEY,
3120                                     server->cmd_ident,
3121                                     silc_server_command_resume_resolve, r);
3122
3123         silc_buffer_free(idp);
3124       }
3125       return;
3126     } else if (!silc_pkcs_public_key_compare(detached_client->data.public_key,
3127                                              idata->public_key)) {
3128       /* We require that the connection and resuming authentication data
3129          must be using same key pair. */
3130       silc_server_disconnect_remote(server, sock, 
3131                                     "Server closed connection: "
3132                                     "Incomplete resume information");
3133       return;
3134     }
3135
3136     /* Verify the authentication payload.  This has to be successful in
3137        order to allow the resuming */
3138     if (!silc_auth_verify_data(auth, auth_len, SILC_AUTH_PUBLIC_KEY,
3139                                detached_client->data.public_key, 0,
3140                                idata->hash, detached_client->id, 
3141                                SILC_ID_CLIENT)) {
3142       SILC_LOG_ERROR(("Client %s (%s) resume authentication failed, "
3143                       "closing connection", sock->hostname, sock->ip));
3144       silc_server_disconnect_remote(server, sock, "Server closed connection: "
3145                                     "Incomplete resume information");
3146       return;
3147     }
3148
3149     /* Now resume the client to the network */
3150
3151     silc_schedule_task_del_by_context(server->schedule, detached_client);
3152     sock->user_data = detached_client;
3153     detached_client->connection = sock;
3154
3155     /* Take new keys and stuff into use in the old entry */
3156     silc_idlist_del_data(detached_client);
3157     silc_idlist_add_data(detached_client, idata);
3158     detached_client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
3159     detached_client->data.status |= SILC_IDLIST_STATUS_RESUMED;
3160     detached_client->mode &= ~SILC_UMODE_DETACHED;
3161
3162     /* Send the RESUME_CLIENT packet to our primary router so that others
3163        know this client isn't detached anymore. */
3164     buf = silc_buffer_alloc_size(2 + id_len);
3165     silc_buffer_format(buf,
3166                        SILC_STR_UI_SHORT(id_len),
3167                        SILC_STR_UI_XNSTRING(id_string, id_len),
3168                        SILC_STR_END);
3169
3170     /* Send to primary router */
3171     if (!server->standalone)
3172       silc_server_packet_send(server, server->router->connection,
3173                               SILC_PACKET_RESUME_CLIENT, 0, 
3174                               buf->data, buf->len, TRUE);
3175
3176     /* As router we must deliver this packet directly to the original
3177        server whom this client was earlier. */
3178     if (server->server_type == SILC_ROUTER && detached_client->router &&
3179         detached_client->router->server_type != SILC_ROUTER)
3180       silc_server_packet_send(server, detached_client->router->connection,
3181                               SILC_PACKET_RESUME_CLIENT, 0, 
3182                               buf->data, buf->len, TRUE);
3183     silc_buffer_free(buf);
3184
3185     detached_client->router = NULL;
3186
3187     /* Delete this client entry since we're resuming to old one. */
3188     server->stat.my_clients--;
3189     server->stat.clients--;
3190     if (server->stat.cell_clients)
3191       server->stat.cell_clients--;
3192     silc_idlist_del_client(server->local_list, client);
3193     client = detached_client;
3194
3195     /* If the ID is not based in our ID then change it */
3196     if (!SILC_ID_COMPARE(client->id, server->id, server->id->ip.data_len)) {
3197       while (!silc_id_create_client_id(server, server->id, server->rng, 
3198                                        server->md5hash, client->nickname, 
3199                                        &client_id)) {
3200         nickfail++;
3201         if (nickfail > 9) {
3202           silc_server_disconnect_remote(server, sock, 
3203                                         "Server closed connection: "
3204                                         "Bad nickname");
3205           return;
3206         }
3207         snprintf(&client->nickname[strlen(client->nickname) - 1], 1, 
3208                  "%d", nickfail);
3209       }
3210       nick_change = TRUE;
3211     }
3212
3213     if (nick_change) {
3214       /* Notify about Client ID change, nickname doesn't actually change. */
3215       if (!server->standalone)
3216         silc_server_send_notify_nick_change(server, server->router->connection,
3217                                             FALSE, client->id, client_id,
3218                                             client->nickname);
3219     }
3220
3221     /* Resolve users on those channels that client has joined but we
3222        haven't resolved user list yet. */
3223     if (server->server_type == SILC_SERVER && !server->standalone) {
3224       silc_hash_table_list(client->channels, &htl);
3225       while (silc_hash_table_get(&htl, NULL, (void **)&chl)) {
3226         channel = chl->channel;
3227         SILC_LOG_DEBUG(("Resolving users for %s channel", 
3228                         channel->channel_name));
3229         if (channel->disabled || !channel->users_resolved) {
3230           silc_server_send_command(server, server->router->connection,
3231                                    SILC_COMMAND_USERS, ++server->cmd_ident,
3232                                    1, 2, channel->channel_name,
3233                                    strlen(channel->channel_name));
3234         }
3235       }
3236       silc_hash_table_list_reset(&htl);
3237     }
3238
3239     /* Send the new client ID to the client. After this client may start
3240        receiving other packets, and may start sending packets too. */
3241     silc_server_send_new_id(server, sock, FALSE, client_id, SILC_ID_CLIENT,
3242                             silc_id_get_len(client_id, SILC_ID_CLIENT));
3243
3244     if (nick_change) {
3245       /* Send NICK change notify to channels as well. */
3246       SilcBuffer oidp, nidp;
3247       oidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3248       nidp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
3249       silc_server_send_notify_on_channels(server, NULL, client, 
3250                                           SILC_NOTIFY_TYPE_NICK_CHANGE, 3,
3251                                           oidp->data, oidp->len, 
3252                                           nidp->data, nidp->len,
3253                                           client->nickname, 
3254                                           strlen(client->nickname));
3255       silc_buffer_free(oidp);
3256       silc_buffer_free(nidp);
3257     }
3258
3259     /* Add the client again to the ID cache to get it to correct list */
3260     if (!silc_idcache_del_by_context(server->local_list->clients, client))
3261       silc_idcache_del_by_context(server->global_list->clients, client);
3262     silc_free(client->id);
3263     client->id = client_id;
3264     client_id = NULL;
3265     silc_idcache_add(server->local_list->clients, client->nickname,
3266                      client->id, client, 0, NULL);
3267
3268     /* Send some nice info to the client */
3269     silc_server_send_connect_notifys(server, sock, client);
3270
3271     /* Send all channel keys of channels the client has joined */
3272     silc_hash_table_list(client->channels, &htl);
3273     while (silc_hash_table_get(&htl, NULL, (void **)&chl)) {
3274       bool created = FALSE;
3275       channel = chl->channel;
3276
3277       if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY)
3278         continue;
3279
3280       /* If we don't have channel key, then create one */
3281       if (!channel->channel_key) {
3282         if (!silc_server_create_channel_key(server, channel, 0))
3283           continue;
3284         created = TRUE;
3285       }
3286
3287       id_string = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3288       keyp = 
3289         silc_channel_key_payload_encode(silc_id_get_len(channel->id,
3290                                                         SILC_ID_CHANNEL), 
3291                                         id_string,
3292                                         strlen(channel->channel_key->
3293                                                cipher->name),
3294                                         channel->channel_key->cipher->name,
3295                                         channel->key_len / 8, channel->key);
3296       silc_free(id_string);
3297
3298       /* Send the key packet to client */
3299       silc_server_packet_send(server, sock, SILC_PACKET_CHANNEL_KEY, 0, 
3300                               keyp->data, keyp->len, FALSE);
3301
3302       if (created && server->server_type == SILC_SERVER && 
3303           !server->standalone)
3304         silc_server_packet_send(server, server->router->connection, 
3305                                 SILC_PACKET_CHANNEL_KEY, 0, 
3306                                 keyp->data, keyp->len, FALSE);
3307
3308       silc_buffer_free(keyp);
3309     }
3310     silc_hash_table_list_reset(&htl);
3311
3312   } else if (sock->type != SILC_SOCKET_TYPE_CLIENT) {
3313     /* Server or router sent this to us to notify that that a client has
3314        been resumed. */
3315     SilcServerEntry server_entry;
3316     SilcServerID *server_id;
3317
3318     if (!client_id)
3319       return;
3320
3321     /* Get entry to the client, and resolve it if we don't have it. */
3322     detached_client = silc_idlist_find_client_by_id(server->local_list, 
3323                                                     client_id, TRUE, NULL);
3324     if (!detached_client) {
3325       detached_client = silc_idlist_find_client_by_id(server->global_list,
3326                                                       client_id, TRUE, NULL);
3327       if (!detached_client)
3328         return;
3329     }
3330
3331     /* Check that the client has not been resumed already because it is
3332        protocol error to attempt to resume more than once.  The client
3333        will be killed if this protocol error occurs. */
3334     if (detached_client->data.status & SILC_IDLIST_STATUS_RESUMED &&
3335         !(detached_client->mode & SILC_UMODE_DETACHED)) {
3336       /* The client is clearly attempting to resume more than once and
3337          perhaps playing around by resuming from several different places
3338          at the same time. */
3339       silc_server_kill_client(server, detached_client, NULL,
3340                               server->id, SILC_ID_SERVER);
3341       return;
3342     }
3343
3344     /* Check whether client is detached at all */
3345     if (!(detached_client->mode & SILC_UMODE_DETACHED))
3346       return;
3347
3348     /* Client is detached, and now it is resumed.  Remove the detached
3349        mode and mark that it is resumed. */
3350     detached_client->mode &= ~SILC_UMODE_DETACHED;
3351     detached_client->data.status |= SILC_IDLIST_STATUS_RESUMED;
3352
3353     /* Get the new owner of the resumed client */
3354     server_id = silc_id_str2id(packet->src_id, packet->src_id_len,
3355                                packet->src_id_type);
3356     if (!server_id)
3357       return;
3358
3359     /* Get server entry */
3360     server_entry = silc_idlist_find_server_by_id(server->global_list, 
3361                                                  server_id, TRUE, NULL);
3362     local = TRUE;
3363     if (!server_entry) {
3364       server_entry = silc_idlist_find_server_by_id(server->local_list, 
3365                                                    server_id, TRUE, NULL);
3366       local = FALSE;
3367       if (!server_entry) {
3368         silc_free(server_id);
3369         return;
3370       }
3371     }
3372
3373     if (server->server_type == SILC_ROUTER &&
3374         sock->type == SILC_SOCKET_TYPE_ROUTER && 
3375         server_entry->server_type == SILC_ROUTER)
3376       local = FALSE;
3377
3378     SILC_LOG_DEBUG(("Resuming detached client"));
3379
3380     /* Change the client to correct list. */
3381     if (!silc_idcache_del_by_context(server->local_list->clients,
3382                                      detached_client))
3383       silc_idcache_del_by_context(server->global_list->clients,
3384                                   detached_client);
3385     silc_idcache_add(local && server->server_type == SILC_ROUTER ? 
3386                      server->local_list->clients : 
3387                      server->global_list->clients, 
3388                      detached_client->nickname,
3389                      detached_client->id, detached_client, FALSE, NULL);
3390
3391     /* Change the owner of the client if needed */
3392     if (detached_client->router != server_entry)
3393       detached_client->router = server_entry;
3394
3395     /* Update channel information regarding global clients on channel. */
3396     if (server->server_type == SILC_SERVER) {
3397       silc_hash_table_list(detached_client->channels, &htl);
3398       while (silc_hash_table_get(&htl, NULL, (void **)&chl))
3399         chl->channel->global_users = 
3400           silc_server_channel_has_global(chl->channel);
3401       silc_hash_table_list_reset(&htl);
3402     }
3403
3404     silc_schedule_task_del_by_context(server->schedule, detached_client);
3405
3406     /* If the sender of this packet is server and we are router we need to
3407        broadcast this packet to other routers in the network. */
3408     if (!server->standalone && server->server_type == SILC_ROUTER &&
3409         sock->type == SILC_SOCKET_TYPE_SERVER &&
3410         !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
3411       SILC_LOG_DEBUG(("Broadcasting received Resume Client packet"));
3412       silc_server_packet_send(server, server->router->connection,
3413                               packet->type, 
3414                               packet->flags | SILC_PACKET_FLAG_BROADCAST,
3415                               buffer->data, buffer->len, FALSE);
3416       silc_server_backup_send(server, (SilcServerEntry)sock->user_data, 
3417                               packet->type, packet->flags,
3418                               packet->buffer->data, packet->buffer->len, 
3419                               FALSE, TRUE);
3420     }
3421
3422     silc_free(server_id);
3423   }
3424
3425   silc_free(client_id);
3426 }