updates.
[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, 
1867                                   SILC_STATUS_ERR_NOT_AUTHENTICATED, NULL);
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, 
1883                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION, 
1884                                   NULL);
1885     return NULL;
1886   }
1887
1888   if (!username) {
1889     silc_free(username);
1890     silc_free(realname);
1891     SILC_LOG_ERROR(("Client %s (%s) did not send its username, closing "
1892                     "connection", sock->hostname, sock->ip));
1893     silc_server_disconnect_remote(server, sock, 
1894                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
1895                                   NULL);
1896     return NULL;
1897   }
1898
1899   if (username_len > 128)
1900     username[128] = '\0';
1901
1902   /* Check for bad characters for nickname, and modify the nickname if
1903      it includes those. */
1904   if (silc_server_name_bad_chars(username, username_len)) {
1905     nickname = silc_server_name_modify_bad(username, username_len);
1906   } else {
1907     nickname = strdup(username);
1908   }
1909
1910   /* Make sanity checks for the hostname of the client. If the hostname
1911      is provided in the `username' check that it is the same than the
1912      resolved hostname, or if not resolved the hostname that appears in
1913      the client's public key. If the hostname is not present then put
1914      it from the resolved name or from the public key. */
1915   if (strchr(username, '@')) {
1916     SilcPublicKeyIdentifier pident;
1917     int tlen = strcspn(username, "@");
1918     char *phostname = NULL;
1919
1920     hostname = silc_memdup(username + tlen + 1, strlen(username) - tlen - 1);
1921
1922     if (strcmp(sock->hostname, sock->ip) && 
1923         strcmp(sock->hostname, hostname)) {
1924       silc_free(username);
1925       silc_free(hostname);
1926       silc_free(realname);
1927       SILC_LOG_ERROR(("Client %s (%s) sent incomplete information, closing "
1928                       "connection", sock->hostname, sock->ip));
1929       silc_server_disconnect_remote(server, sock, 
1930                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
1931                                     NULL);
1932       return NULL;
1933     }
1934     
1935     pident = silc_pkcs_decode_identifier(client->data.public_key->identifier);
1936     if (pident) {
1937       phostname = strdup(pident->host);
1938       silc_pkcs_free_identifier(pident);
1939     }
1940
1941     if (!strcmp(sock->hostname, sock->ip) && 
1942         phostname && strcmp(phostname, hostname)) {
1943       silc_free(username);
1944       silc_free(hostname);
1945       silc_free(phostname);
1946       silc_free(realname);
1947       SILC_LOG_ERROR(("Client %s (%s) sent incomplete information, closing "
1948                       "connection", sock->hostname, sock->ip));
1949       silc_server_disconnect_remote(server, sock, 
1950                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
1951                                     NULL);
1952       return NULL;
1953     }
1954     
1955     silc_free(phostname);
1956   } else {
1957     /* The hostname is not present, add it. */
1958     char *newusername;
1959     /* XXX For now we cannot take the host name from the public key since
1960        they are not trusted or we cannot verify them as trusted. Just take
1961        what the resolved name or address is. */
1962 #if 0
1963     if (strcmp(sock->hostname, sock->ip)) {
1964 #endif
1965       newusername = silc_calloc(strlen(username) + 
1966                                 strlen(sock->hostname) + 2,
1967                                 sizeof(*newusername));
1968       strncat(newusername, username, strlen(username));
1969       strncat(newusername, "@", 1);
1970       strncat(newusername, sock->hostname, strlen(sock->hostname));
1971       silc_free(username);
1972       username = newusername;
1973 #if 0
1974     } else {
1975       SilcPublicKeyIdentifier pident = 
1976         silc_pkcs_decode_identifier(client->data.public_key->identifier);
1977       
1978       if (pident) {
1979         newusername = silc_calloc(strlen(username) + 
1980                                   strlen(pident->host) + 2,
1981                                   sizeof(*newusername));
1982         strncat(newusername, username, strlen(username));
1983         strncat(newusername, "@", 1);
1984         strncat(newusername, pident->host, strlen(pident->host));
1985         silc_free(username);
1986         username = newusername;
1987         silc_pkcs_free_identifier(pident);
1988       }
1989     }
1990 #endif
1991   }
1992
1993   /* Create Client ID */
1994   while (!silc_id_create_client_id(server, server->id, server->rng, 
1995                                    server->md5hash, nickname, &client_id)) {
1996     nickfail++;
1997     if (nickfail > 9) {
1998       silc_server_disconnect_remote(server, sock, 
1999                                     SILC_STATUS_ERR_BAD_NICKNAME, NULL);
2000       return NULL;
2001     }
2002     snprintf(&nickname[strlen(nickname) - 1], 1, "%d", nickfail);
2003   }
2004
2005   /* Update client entry */
2006   idata->status |= SILC_IDLIST_STATUS_REGISTERED;
2007   client->nickname = nickname;
2008   client->username = username;
2009   client->userinfo = realname ? realname : strdup(" ");
2010   client->id = client_id;
2011   id_len = silc_id_get_len(client_id, SILC_ID_CLIENT);
2012
2013   /* Add the client again to the ID cache */
2014   silc_idcache_add(server->local_list->clients, client->nickname,
2015                    client_id, client, 0, NULL);
2016
2017   /* Notify our router about new client on the SILC network */
2018   if (!server->standalone)
2019     silc_server_send_new_id(server, (SilcSocketConnection) 
2020                             server->router->connection, 
2021                             server->server_type == SILC_ROUTER ? TRUE : FALSE,
2022                             client->id, SILC_ID_CLIENT, id_len);
2023   
2024   /* Send the new client ID to the client. */
2025   silc_server_send_new_id(server, sock, FALSE, client->id, SILC_ID_CLIENT,
2026                           silc_id_get_len(client->id, SILC_ID_CLIENT));
2027
2028   /* Send some nice info to the client */
2029   silc_server_send_connect_notifys(server, sock, client);
2030
2031   /* Check if anyone is watching this nickname */
2032   if (server->server_type == SILC_ROUTER)
2033     silc_server_check_watcher_list(server, client, NULL, 0);
2034
2035   return client;
2036 }
2037
2038 /* Create new server. This processes received New Server packet and
2039    saves the received Server ID. The server is our locally connected
2040    server thus we save all the information and save it to local list. 
2041    This funtion can be used by both normal server and router server.
2042    If normal server uses this it means that its router has connected
2043    to the server. If router uses this it means that one of the cell's
2044    servers is connected to the router. */
2045
2046 SilcServerEntry silc_server_new_server(SilcServer server,
2047                                        SilcSocketConnection sock,
2048                                        SilcPacketContext *packet)
2049 {
2050   SilcBuffer buffer = packet->buffer;
2051   SilcServerEntry new_server, server_entry;
2052   SilcServerID *server_id;
2053   SilcIDListData idata;
2054   unsigned char *server_name, *id_string;
2055   SilcUInt16 id_len, name_len;
2056   int ret;
2057   bool local = TRUE;
2058
2059   SILC_LOG_DEBUG(("Creating new server"));
2060
2061   if (sock->type != SILC_SOCKET_TYPE_SERVER &&
2062       sock->type != SILC_SOCKET_TYPE_ROUTER)
2063     return NULL;
2064
2065   /* Take server entry */
2066   new_server = (SilcServerEntry)sock->user_data;
2067   idata = (SilcIDListData)new_server;
2068
2069   /* Remove the old cache entry */
2070   if (!silc_idcache_del_by_context(server->local_list->servers, new_server)) {
2071     if (!silc_idcache_del_by_context(server->global_list->servers, 
2072                                      new_server)) {
2073       SILC_LOG_INFO(("Unauthenticated %s attempted to register to "
2074                      "network", (sock->type == SILC_SOCKET_TYPE_SERVER ?
2075                                  "server" : "router")));
2076       silc_server_disconnect_remote(server, sock, 
2077                                     SILC_STATUS_ERR_NOT_AUTHENTICATED, NULL);
2078       return NULL;
2079     }
2080     local = FALSE;
2081   }
2082
2083   /* Parse the incoming packet */
2084   ret = silc_buffer_unformat(buffer,
2085                              SILC_STR_UI16_NSTRING_ALLOC(&id_string, &id_len),
2086                              SILC_STR_UI16_NSTRING_ALLOC(&server_name, 
2087                                                          &name_len),
2088                              SILC_STR_END);
2089   if (ret == -1) {
2090     if (id_string)
2091       silc_free(id_string);
2092     if (server_name)
2093       silc_free(server_name);
2094     return NULL;
2095   }
2096
2097   if (id_len > buffer->len) {
2098     silc_free(id_string);
2099     silc_free(server_name);
2100     return NULL;
2101   }
2102
2103   if (name_len > 256)
2104     server_name[255] = '\0';
2105
2106   /* Get Server ID */
2107   server_id = silc_id_str2id(id_string, id_len, SILC_ID_SERVER);
2108   if (!server_id) {
2109     silc_free(id_string);
2110     silc_free(server_name);
2111     return NULL;
2112   }
2113   silc_free(id_string);
2114
2115   /* Check for valid server ID */
2116   if (!silc_id_is_valid_server_id(server, server_id, sock)) {
2117     SILC_LOG_INFO(("Invalid server ID sent by %s (%s)",
2118                    sock->ip, sock->hostname));
2119     silc_server_disconnect_remote(server, sock, 
2120                                   SILC_STATUS_ERR_BAD_SERVER_ID, NULL);
2121     silc_free(server_name);
2122     return NULL;
2123   }
2124
2125   /* Check that we do not have this ID already */
2126   server_entry = silc_idlist_find_server_by_id(server->local_list, 
2127                                                server_id, TRUE, NULL);
2128   if (server_entry) {
2129     silc_idcache_del_by_context(server->local_list->servers, server_entry);
2130   } else {
2131     server_entry = silc_idlist_find_server_by_id(server->global_list, 
2132                                                  server_id, TRUE, NULL);
2133     if (server_entry) 
2134       silc_idcache_del_by_context(server->global_list->servers, server_entry);
2135   }
2136
2137   /* Update server entry */
2138   idata->status |= SILC_IDLIST_STATUS_REGISTERED;
2139   new_server->server_name = server_name;
2140   new_server->id = server_id;
2141   
2142   SILC_LOG_DEBUG(("New server id(%s)",
2143                   silc_id_render(server_id, SILC_ID_SERVER)));
2144
2145   /* Add again the entry to the ID cache. */
2146   silc_idcache_add(local ? server->local_list->servers : 
2147                    server->global_list->servers, server_name, server_id, 
2148                    new_server, 0, NULL);
2149
2150   /* Distribute the information about new server in the SILC network
2151      to our router. If we are normal server we won't send anything
2152      since this connection must be our router connection. */
2153   if (server->server_type == SILC_ROUTER && !server->standalone &&
2154       server->router->connection != sock)
2155     silc_server_send_new_id(server, server->router->connection,
2156                             TRUE, new_server->id, SILC_ID_SERVER, 
2157                             silc_id_get_len(server_id, SILC_ID_SERVER));
2158
2159   if (server->server_type == SILC_ROUTER)
2160     server->stat.cell_servers++;
2161
2162   /* Check whether this router connection has been replaced by an
2163      backup router. If it has been then we'll disable the server and will
2164      ignore everything it will send until the backup router resuming
2165      protocol has been completed. */
2166   if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
2167       silc_server_backup_replaced_get(server, server_id, NULL)) {
2168     /* Send packet to the server indicating that it cannot use this
2169        connection as it has been replaced by backup router. */
2170     SilcBuffer packet = silc_buffer_alloc(2);
2171     silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
2172     silc_buffer_format(packet,
2173                        SILC_STR_UI_CHAR(SILC_SERVER_BACKUP_REPLACED),
2174                        SILC_STR_UI_CHAR(0),
2175                        SILC_STR_END);
2176     silc_server_packet_send(server, sock, 
2177                             SILC_PACKET_RESUME_ROUTER, 0, 
2178                             packet->data, packet->len, TRUE);
2179     silc_buffer_free(packet);
2180
2181     /* Mark the router disabled. The data sent earlier will go but nothing
2182        after this does not go to this connection. */
2183     idata->status |= SILC_IDLIST_STATUS_DISABLED;
2184   } else {
2185     /* If it is router announce our stuff to it. */
2186     if (sock->type == SILC_SOCKET_TYPE_ROUTER && 
2187         server->server_type == SILC_ROUTER) {
2188       silc_server_announce_servers(server, FALSE, 0, sock);
2189       silc_server_announce_clients(server, 0, sock);
2190       silc_server_announce_channels(server, 0, sock);
2191     }
2192   }
2193
2194   return new_server;
2195 }
2196
2197 /* Processes incoming New ID packet. New ID Payload is used to distribute
2198    information about newly registered clients and servers. */
2199
2200 static void silc_server_new_id_real(SilcServer server, 
2201                                     SilcSocketConnection sock,
2202                                     SilcPacketContext *packet,
2203                                     int broadcast)
2204 {
2205   SilcBuffer buffer = packet->buffer;
2206   SilcIDList id_list;
2207   SilcServerEntry router, server_entry;
2208   SilcSocketConnection router_sock;
2209   SilcIDPayload idp;
2210   SilcIdType id_type;
2211   void *id;
2212
2213   SILC_LOG_DEBUG(("Processing new ID"));
2214
2215   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
2216       server->server_type == SILC_SERVER ||
2217       packet->src_id_type != SILC_ID_SERVER)
2218     return;
2219
2220   idp = silc_id_payload_parse(buffer->data, buffer->len);
2221   if (!idp)
2222     return;
2223
2224   id_type = silc_id_payload_get_type(idp);
2225
2226   /* Normal server cannot have other normal server connections */
2227   server_entry = (SilcServerEntry)sock->user_data;
2228   if (id_type == SILC_ID_SERVER && sock->type == SILC_SOCKET_TYPE_SERVER &&
2229       server_entry->server_type == SILC_SERVER)
2230     goto out;
2231
2232   id = silc_id_payload_get_id(idp);
2233   if (!id)
2234     goto out;
2235
2236   /* If the packet is coming from server then use the sender as the
2237      origin of the the packet. If it came from router then check the real
2238      sender of the packet and use that as the origin. */
2239   if (sock->type == SILC_SOCKET_TYPE_SERVER) {
2240     id_list = server->local_list;
2241     router_sock = sock;
2242     router = sock->user_data;
2243
2244     /* If the sender is backup router and ID is server (and we are not
2245        backup router) then switch the entry to global list. */
2246     if (server_entry->server_type == SILC_BACKUP_ROUTER && 
2247         id_type == SILC_ID_SERVER && 
2248         server->id_entry->server_type != SILC_BACKUP_ROUTER) {
2249       id_list = server->global_list;
2250       router_sock = server->router ? server->router->connection : sock;
2251     }
2252   } else {
2253     void *sender_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2254                                      packet->src_id_type);
2255     router = silc_idlist_find_server_by_id(server->global_list,
2256                                            sender_id, TRUE, NULL);
2257     if (!router)
2258       router = silc_idlist_find_server_by_id(server->local_list,
2259                                              sender_id, TRUE, NULL);
2260     silc_free(sender_id);
2261     router_sock = sock;
2262     id_list = server->global_list;
2263   }
2264
2265   if (!router)
2266     goto out;
2267
2268   switch(id_type) {
2269   case SILC_ID_CLIENT:
2270     {
2271       SilcClientEntry entry;
2272
2273       /* Check that we do not have this client already */
2274       entry = silc_idlist_find_client_by_id(server->global_list, 
2275                                             id, server->server_type, 
2276                                             NULL);
2277       if (!entry)
2278         entry = silc_idlist_find_client_by_id(server->local_list, 
2279                                               id, server->server_type,
2280                                               NULL);
2281       if (entry) {
2282         SILC_LOG_DEBUG(("Ignoring client that we already have"));
2283         goto out;
2284       }
2285
2286       SILC_LOG_DEBUG(("New client id(%s) from [%s] %s",
2287                       silc_id_render(id, SILC_ID_CLIENT),
2288                       sock->type == SILC_SOCKET_TYPE_SERVER ?
2289                       "Server" : "Router", sock->hostname));
2290     
2291       /* As a router we keep information of all global information in our
2292          global list. Cell wide information however is kept in the local
2293          list. */
2294       entry = silc_idlist_add_client(id_list, NULL, NULL, NULL, 
2295                                      id, router, NULL, 0);
2296       if (!entry) {
2297         SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
2298
2299         /* Inform the sender that the ID is not usable */
2300         silc_server_send_notify_signoff(server, sock, FALSE, id, NULL);
2301         goto out;
2302       }
2303       entry->nickname = NULL;
2304       entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
2305
2306       if (sock->type == SILC_SOCKET_TYPE_SERVER)
2307         server->stat.cell_clients++;
2308       server->stat.clients++;
2309
2310       /* Check if anyone is watching this nickname */
2311       if (server->server_type == SILC_ROUTER && id_list == server->local_list)
2312         silc_server_check_watcher_list(server, entry, NULL, 0);
2313     }
2314     break;
2315
2316   case SILC_ID_SERVER:
2317     {
2318       SilcServerEntry entry;
2319
2320       /* If the ID is mine, ignore it. */
2321       if (SILC_ID_SERVER_COMPARE(id, server->id)) {
2322         SILC_LOG_DEBUG(("Ignoring my own ID as new ID"));
2323         break;
2324       }
2325
2326       /* If the ID is the sender's ID, ignore it (we have it already) */
2327       if (SILC_ID_SERVER_COMPARE(id, router->id)) {
2328         SILC_LOG_DEBUG(("Ignoring sender's own ID"));
2329         break;
2330       }
2331       
2332       /* Check that we do not have this server already */
2333       entry = silc_idlist_find_server_by_id(server->global_list, 
2334                                             id, server->server_type, 
2335                                             NULL);
2336       if (!entry)
2337         entry = silc_idlist_find_server_by_id(server->local_list, 
2338                                               id, server->server_type,
2339                                               NULL);
2340       if (entry) {
2341         SILC_LOG_DEBUG(("Ignoring server that we already have"));
2342         goto out;
2343       }
2344
2345       SILC_LOG_DEBUG(("New server id(%s) from [%s] %s",
2346                       silc_id_render(id, SILC_ID_SERVER),
2347                       sock->type == SILC_SOCKET_TYPE_SERVER ?
2348                       "Server" : "Router", sock->hostname));
2349       
2350       /* As a router we keep information of all global information in our 
2351          global list. Cell wide information however is kept in the local
2352          list. */
2353       entry = silc_idlist_add_server(id_list, NULL, 0, id, router, 
2354                                      router_sock);
2355       if (!entry) {
2356         SILC_LOG_ERROR(("Could not add new server to the ID Cache"));
2357         goto out;
2358       }
2359       entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
2360       
2361       if (sock->type == SILC_SOCKET_TYPE_SERVER)
2362         server->stat.cell_servers++;
2363       server->stat.servers++;
2364     }
2365     break;
2366
2367   case SILC_ID_CHANNEL:
2368     SILC_LOG_ERROR(("Channel cannot be registered with NEW_ID packet"));
2369     goto out;
2370     break;
2371
2372   default:
2373     goto out;
2374     break;
2375   }
2376
2377   /* If the sender of this packet is server and we are router we need to
2378      broadcast this packet to other routers in the network. */
2379   if (broadcast && !server->standalone && server->server_type == SILC_ROUTER &&
2380       sock->type == SILC_SOCKET_TYPE_SERVER &&
2381       !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
2382     SILC_LOG_DEBUG(("Broadcasting received New ID packet"));
2383     silc_server_packet_send(server, server->router->connection,
2384                             packet->type, 
2385                             packet->flags | SILC_PACKET_FLAG_BROADCAST,
2386                             buffer->data, buffer->len, FALSE);
2387     silc_server_backup_send(server, (SilcServerEntry)sock->user_data, 
2388                             packet->type, packet->flags,
2389                             packet->buffer->data, packet->buffer->len, 
2390                             FALSE, TRUE);
2391   }
2392
2393  out:
2394   silc_id_payload_free(idp);
2395 }
2396
2397
2398 /* Processes incoming New ID packet. New ID Payload is used to distribute
2399    information about newly registered clients and servers. */
2400
2401 void silc_server_new_id(SilcServer server, SilcSocketConnection sock,
2402                         SilcPacketContext *packet)
2403 {
2404   silc_server_new_id_real(server, sock, packet, TRUE);
2405 }
2406
2407 /* Receoved New Id List packet, list of New ID payloads inside one
2408    packet. Process the New ID payloads one by one. */
2409
2410 void silc_server_new_id_list(SilcServer server, SilcSocketConnection sock,
2411                              SilcPacketContext *packet)
2412 {
2413   SilcPacketContext *new_id;
2414   SilcBuffer idp;
2415   SilcUInt16 id_len;
2416
2417   SILC_LOG_DEBUG(("Processing New ID List"));
2418
2419   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
2420       packet->src_id_type != SILC_ID_SERVER)
2421     return;
2422
2423   /* If the sender of this packet is server and we are router we need to
2424      broadcast this packet to other routers in the network. Broadcast
2425      this list packet instead of multiple New ID packets. */
2426   if (!server->standalone && server->server_type == SILC_ROUTER &&
2427       sock->type == SILC_SOCKET_TYPE_SERVER &&
2428       !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
2429     SILC_LOG_DEBUG(("Broadcasting received New ID List packet"));
2430     silc_server_packet_send(server, server->router->connection,
2431                             packet->type, 
2432                             packet->flags | SILC_PACKET_FLAG_BROADCAST,
2433                             packet->buffer->data, packet->buffer->len, FALSE);
2434     silc_server_backup_send(server, (SilcServerEntry)sock->user_data, 
2435                             packet->type, packet->flags,
2436                             packet->buffer->data, packet->buffer->len, 
2437                             FALSE, TRUE);
2438   }
2439
2440   /* Make copy of the original packet context, except for the actual
2441      data buffer, which we will here now fetch from the original buffer. */
2442   new_id = silc_packet_context_alloc();
2443   new_id->type = SILC_PACKET_NEW_ID;
2444   new_id->flags = packet->flags;
2445   new_id->src_id = packet->src_id;
2446   new_id->src_id_len = packet->src_id_len;
2447   new_id->src_id_type = packet->src_id_type;
2448   new_id->dst_id = packet->dst_id;
2449   new_id->dst_id_len = packet->dst_id_len;
2450   new_id->dst_id_type = packet->dst_id_type;
2451
2452   idp = silc_buffer_alloc(256);
2453   new_id->buffer = idp;
2454
2455   while (packet->buffer->len) {
2456     SILC_GET16_MSB(id_len, packet->buffer->data + 2);
2457     if ((id_len > packet->buffer->len) ||
2458         (id_len > idp->truelen))
2459       break;
2460
2461     silc_buffer_pull_tail(idp, 4 + id_len);
2462     silc_buffer_put(idp, packet->buffer->data, 4 + id_len);
2463
2464     /* Process the New ID */
2465     silc_server_new_id_real(server, sock, new_id, FALSE);
2466
2467     silc_buffer_push_tail(idp, 4 + id_len);
2468     silc_buffer_pull(packet->buffer, 4 + id_len);
2469   }
2470
2471   silc_buffer_free(idp);
2472   silc_free(new_id);
2473 }
2474
2475 /* Received New Channel packet. Information about new channels in the 
2476    network are distributed using this packet. Save the information about
2477    the new channel. This usually comes from router but also normal server
2478    can send this to notify channels it has when it connects to us. */
2479
2480 void silc_server_new_channel(SilcServer server,
2481                              SilcSocketConnection sock,
2482                              SilcPacketContext *packet)
2483 {
2484   SilcChannelPayload payload;
2485   SilcChannelID *channel_id;
2486   char *channel_name;
2487   SilcUInt32 name_len;
2488   unsigned char *id;
2489   SilcUInt32 id_len;
2490   SilcUInt32 mode;
2491   SilcServerEntry server_entry;
2492   SilcChannelEntry channel;
2493
2494   SILC_LOG_DEBUG(("Processing New Channel"));
2495
2496   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
2497       packet->src_id_type != SILC_ID_SERVER ||
2498       server->server_type == SILC_SERVER)
2499     return;
2500
2501   /* Parse the channel payload */
2502   payload = silc_channel_payload_parse(packet->buffer->data,
2503                                        packet->buffer->len);
2504   if (!payload)
2505     return;
2506     
2507   /* Get the channel ID */
2508   channel_id = silc_channel_get_id_parse(payload);
2509   if (!channel_id) {
2510     silc_channel_payload_free(payload);
2511     return;
2512   }
2513
2514   channel_name = silc_channel_get_name(payload, &name_len);
2515   if (name_len > 256)
2516     channel_name[255] = '\0';
2517
2518   id = silc_channel_get_id(payload, &id_len);
2519
2520   server_entry = (SilcServerEntry)sock->user_data;
2521
2522   if (sock->type == SILC_SOCKET_TYPE_ROUTER) {
2523     /* Add the channel to global list as it is coming from router. It 
2524        cannot be our own channel as it is coming from router. */
2525
2526     /* Check that we don't already have this channel */
2527     channel = silc_idlist_find_channel_by_name(server->local_list, 
2528                                                channel_name, NULL);
2529     if (!channel)
2530       channel = silc_idlist_find_channel_by_name(server->global_list, 
2531                                                  channel_name, NULL);
2532     if (!channel) {
2533       SILC_LOG_DEBUG(("New channel id(%s) from [Router] %s",
2534                       silc_id_render(channel_id, SILC_ID_CHANNEL), 
2535                       sock->hostname));
2536     
2537       channel = 
2538         silc_idlist_add_channel(server->global_list, strdup(channel_name), 
2539                                 0, channel_id, sock->user_data, NULL, NULL, 0);
2540       if (!channel)
2541         return;
2542
2543       server->stat.channels++;
2544       if (server->server_type == SILC_ROUTER)
2545         channel->users_resolved = TRUE;
2546     }
2547   } else {
2548     /* The channel is coming from our server, thus it is in our cell
2549        we will add it to our local list. */
2550     SilcBuffer chk;
2551
2552     SILC_LOG_DEBUG(("Channel id(%s) from [Server] %s",
2553                     silc_id_render(channel_id, SILC_ID_CHANNEL), 
2554                     sock->hostname));
2555
2556     /* Check that we don't already have this channel */
2557     channel = silc_idlist_find_channel_by_name(server->local_list, 
2558                                                channel_name, NULL);
2559     if (!channel)
2560       channel = silc_idlist_find_channel_by_name(server->global_list, 
2561                                                  channel_name, NULL);
2562
2563     /* If the channel does not exist, then create it. This creates a new
2564        key to the channel as well that we will send to the server. */
2565     if (!channel) {
2566       /* The protocol says that the Channel ID's IP address must be based
2567          on the router's IP address.  Check whether the ID is based in our
2568          IP and if it is not then create a new ID and enforce the server
2569          to switch the ID. */
2570       if (server_entry->server_type != SILC_BACKUP_ROUTER &&
2571           !SILC_ID_COMPARE(channel_id, server->id, server->id->ip.data_len)) {
2572         SilcChannelID *tmp;
2573         SILC_LOG_DEBUG(("Forcing the server to change Channel ID"));
2574         
2575         if (silc_id_create_channel_id(server, server->id, server->rng, &tmp)) {
2576           silc_server_send_notify_channel_change(server, sock, FALSE, 
2577                                                  channel_id, tmp);
2578           silc_free(channel_id);
2579           channel_id = tmp;
2580         }
2581       }
2582
2583       /* Create the channel with the provided Channel ID */
2584       channel = silc_server_create_new_channel_with_id(server, NULL, NULL,
2585                                                        channel_name,
2586                                                        channel_id, FALSE);
2587       if (!channel) {
2588         silc_channel_payload_free(payload);
2589         silc_free(channel_id);
2590         return;
2591       }
2592
2593       /* Get the mode and set it to the channel */
2594       channel->mode = silc_channel_get_mode(payload);
2595
2596       /* Send the new channel key to the server */
2597       id = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
2598       id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
2599       chk = silc_channel_key_payload_encode(id_len, id,
2600                                             strlen(channel->channel_key->
2601                                                    cipher->name),
2602                                             channel->channel_key->cipher->name,
2603                                             channel->key_len / 8, 
2604                                             channel->key);
2605       silc_server_packet_send(server, sock, SILC_PACKET_CHANNEL_KEY, 0, 
2606                               chk->data, chk->len, FALSE);
2607       silc_buffer_free(chk);
2608
2609     } else {
2610       /* The channel exist by that name, check whether the ID's match.
2611          If they don't then we'll force the server to use the ID we have.
2612          We also create a new key for the channel. */
2613       SilcBuffer users = NULL, users_modes = NULL;
2614
2615       if (!SILC_ID_CHANNEL_COMPARE(channel_id, channel->id)) {
2616         /* They don't match, send CHANNEL_CHANGE notify to the server to
2617            force the ID change. */
2618         SILC_LOG_DEBUG(("Forcing the server to change Channel ID"));
2619         silc_server_send_notify_channel_change(server, sock, FALSE, 
2620                                                channel_id, channel->id);
2621       }
2622
2623       /* If the mode is different from what we have then enforce the
2624          mode change. */
2625       mode = silc_channel_get_mode(payload);
2626       if (channel->mode != mode) {
2627         SILC_LOG_DEBUG(("Forcing the server to change channel mode"));
2628         silc_server_send_notify_cmode(server, sock, FALSE, channel,
2629                                       channel->mode, server->id,
2630                                       SILC_ID_SERVER,
2631                                       channel->cipher, channel->hmac_name,
2632                                       channel->passphrase);
2633       }
2634
2635       /* Create new key for the channel and send it to the server and
2636          everybody else possibly on the channel. */
2637
2638       if (!(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
2639         if (!silc_server_create_channel_key(server, channel, 0))
2640           return;
2641         
2642         /* Send to the channel */
2643         silc_server_send_channel_key(server, sock, channel, FALSE);
2644         id = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
2645         id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
2646
2647         /* Send to the server */
2648         chk = silc_channel_key_payload_encode(id_len, id,
2649                                               strlen(channel->channel_key->
2650                                                      cipher->name),
2651                                               channel->channel_key->
2652                                               cipher->name,
2653                                               channel->key_len / 8, 
2654                                               channel->key);
2655         silc_server_packet_send(server, sock, SILC_PACKET_CHANNEL_KEY, 0, 
2656                                 chk->data, chk->len, FALSE);
2657         silc_buffer_free(chk);
2658         silc_free(id);
2659       }
2660
2661       silc_free(channel_id);
2662
2663       /* Since the channel is coming from server and we also know about it
2664          then send the JOIN notify to the server so that it see's our
2665          users on the channel "joining" the channel. */
2666       silc_server_announce_get_channel_users(server, channel, &users,
2667                                              &users_modes);
2668       if (users) {
2669         silc_buffer_push(users, users->data - users->head);
2670         silc_server_packet_send(server, sock,
2671                                 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
2672                                 users->data, users->len, FALSE);
2673         silc_buffer_free(users);
2674       }
2675       if (users_modes) {
2676         silc_buffer_push(users_modes, users_modes->data - users_modes->head);
2677         silc_server_packet_send_dest(server, sock,
2678                                      SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
2679                                      channel->id, SILC_ID_CHANNEL,
2680                                      users_modes->data, 
2681                                      users_modes->len, FALSE);
2682         silc_buffer_free(users_modes);
2683       }
2684     }
2685   }
2686
2687   silc_channel_payload_free(payload);
2688 }
2689
2690 /* Received New Channel List packet, list of New Channel List payloads inside
2691    one packet. Process the New Channel payloads one by one. */
2692
2693 void silc_server_new_channel_list(SilcServer server,
2694                                   SilcSocketConnection sock,
2695                                   SilcPacketContext *packet)
2696 {
2697   SilcPacketContext *new;
2698   SilcBuffer buffer;
2699   SilcUInt16 len1, len2;
2700
2701   SILC_LOG_DEBUG(("Processing New Channel List"));
2702
2703   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
2704       packet->src_id_type != SILC_ID_SERVER ||
2705       server->server_type == SILC_SERVER)
2706     return;
2707
2708   /* If the sender of this packet is server and we are router we need to
2709      broadcast this packet to other routers in the network. Broadcast
2710      this list packet instead of multiple New Channel packets. */
2711   if (!server->standalone && server->server_type == SILC_ROUTER &&
2712       sock->type == SILC_SOCKET_TYPE_SERVER &&
2713       !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
2714     SILC_LOG_DEBUG(("Broadcasting received New Channel List packet"));
2715     silc_server_packet_send(server, server->router->connection,
2716                             packet->type, 
2717                             packet->flags | SILC_PACKET_FLAG_BROADCAST,
2718                             packet->buffer->data, packet->buffer->len, FALSE);
2719     silc_server_backup_send(server, (SilcServerEntry)sock->user_data, 
2720                             packet->type, packet->flags,
2721                             packet->buffer->data, packet->buffer->len, 
2722                             FALSE, TRUE);
2723   }
2724
2725   /* Make copy of the original packet context, except for the actual
2726      data buffer, which we will here now fetch from the original buffer. */
2727   new = silc_packet_context_alloc();
2728   new->type = SILC_PACKET_NEW_CHANNEL;
2729   new->flags = packet->flags;
2730   new->src_id = packet->src_id;
2731   new->src_id_len = packet->src_id_len;
2732   new->src_id_type = packet->src_id_type;
2733   new->dst_id = packet->dst_id;
2734   new->dst_id_len = packet->dst_id_len;
2735   new->dst_id_type = packet->dst_id_type;
2736
2737   buffer = silc_buffer_alloc(512);
2738   new->buffer = buffer;
2739
2740   while (packet->buffer->len) {
2741     SILC_GET16_MSB(len1, packet->buffer->data);
2742     if ((len1 > packet->buffer->len) ||
2743         (len1 > buffer->truelen))
2744       break;
2745
2746     SILC_GET16_MSB(len2, packet->buffer->data + 2 + len1);
2747     if ((len2 > packet->buffer->len) ||
2748         (len2 > buffer->truelen))
2749       break;
2750
2751     silc_buffer_pull_tail(buffer, 8 + len1 + len2);
2752     silc_buffer_put(buffer, packet->buffer->data, 8 + len1 + len2);
2753
2754     /* Process the New Channel */
2755     silc_server_new_channel(server, sock, new);
2756
2757     silc_buffer_push_tail(buffer, 8 + len1 + len2);
2758     silc_buffer_pull(packet->buffer, 8 + len1 + len2);
2759   }
2760
2761   silc_buffer_free(buffer);
2762   silc_free(new);
2763 }
2764
2765 /* Received key agreement packet. This packet is never for us. It is to
2766    the client in the packet's destination ID. Sending of this sort of packet
2767    equals sending private message, ie. it is sent point to point from
2768    one client to another. */
2769
2770 void silc_server_key_agreement(SilcServer server,
2771                                SilcSocketConnection sock,
2772                                SilcPacketContext *packet)
2773 {
2774   SilcSocketConnection dst_sock;
2775   SilcIDListData idata;
2776
2777   SILC_LOG_DEBUG(("Start"));
2778
2779   if (packet->src_id_type != SILC_ID_CLIENT ||
2780       packet->dst_id_type != SILC_ID_CLIENT)
2781     return;
2782
2783   if (!packet->dst_id)
2784     return;
2785
2786   /* Get the route to the client */
2787   dst_sock = silc_server_get_client_route(server, packet->dst_id,
2788                                           packet->dst_id_len, NULL, 
2789                                           &idata, NULL);
2790   if (!dst_sock)
2791     return;
2792
2793   /* Relay the packet */
2794   silc_server_relay_packet(server, dst_sock, idata->send_key,
2795                            idata->hmac_send, idata->psn_send++,
2796                            packet, FALSE);
2797 }
2798
2799 /* Received connection auth request packet that is used during connection
2800    phase to resolve the mandatory authentication method.  This packet can
2801    actually be received at anytime but usually it is used only during
2802    the connection authentication phase. Now, protocol says that this packet
2803    can come from client or server, however, we support only this coming
2804    from client and expect that server always knows what authentication
2805    method to use. */
2806
2807 void silc_server_connection_auth_request(SilcServer server,
2808                                          SilcSocketConnection sock,
2809                                          SilcPacketContext *packet)
2810 {
2811   SilcServerConfigClient *client = NULL;
2812   SilcUInt16 conn_type;
2813   int ret;
2814   SilcAuthMethod auth_meth = SILC_AUTH_NONE;
2815
2816   SILC_LOG_DEBUG(("Start"));
2817
2818   if (packet->src_id_type && packet->src_id_type != SILC_ID_CLIENT)
2819     return;
2820
2821   /* Parse the payload */
2822   ret = silc_buffer_unformat(packet->buffer,
2823                              SILC_STR_UI_SHORT(&conn_type),
2824                              SILC_STR_UI_SHORT(NULL),
2825                              SILC_STR_END);
2826   if (ret == -1)
2827     return;
2828
2829   if (conn_type != SILC_SOCKET_TYPE_CLIENT)
2830     return;
2831
2832   /* Get the authentication method for the client */
2833   auth_meth = SILC_AUTH_NONE;
2834   client = silc_server_config_find_client(server, sock->ip);
2835   if (!client)
2836     client = silc_server_config_find_client(server, sock->hostname);
2837   if (client) {
2838     if (client->passphrase) {
2839       if (client->publickeys && !server->config->prefer_passphrase_auth)
2840         auth_meth = SILC_AUTH_PUBLIC_KEY;
2841       else
2842         auth_meth = SILC_AUTH_PASSWORD;
2843     } else if (client->publickeys)
2844       auth_meth = SILC_AUTH_PUBLIC_KEY;
2845   }
2846
2847   /* Send it back to the client */
2848   silc_server_send_connection_auth_request(server, sock, conn_type, auth_meth);
2849 }
2850
2851 /* Received REKEY packet. The sender of the packet wants to regenerate
2852    its session keys. This starts the REKEY protocol. */
2853
2854 void silc_server_rekey(SilcServer server,
2855                        SilcSocketConnection sock,
2856                        SilcPacketContext *packet)
2857 {
2858   SilcProtocol protocol;
2859   SilcServerRekeyInternalContext *proto_ctx;
2860   SilcIDListData idata = (SilcIDListData)sock->user_data;
2861
2862   SILC_LOG_DEBUG(("Start"));
2863
2864   /* Allocate internal protocol context. This is sent as context
2865      to the protocol. */
2866   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
2867   proto_ctx->server = (void *)server;
2868   proto_ctx->sock = sock;
2869   proto_ctx->responder = TRUE;
2870   proto_ctx->pfs = idata->rekey->pfs;
2871       
2872   /* Perform rekey protocol. Will call the final callback after the
2873      protocol is over. */
2874   silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY, 
2875                       &protocol, proto_ctx, silc_server_rekey_final);
2876   sock->protocol = protocol;
2877
2878   if (proto_ctx->pfs == FALSE)
2879     /* Run the protocol */
2880     silc_protocol_execute(protocol, server->schedule, 0, 0);
2881 }
2882
2883 /* Received file transger packet. This packet is never for us. It is to
2884    the client in the packet's destination ID. Sending of this sort of packet
2885    equals sending private message, ie. it is sent point to point from
2886    one client to another. */
2887
2888 void silc_server_ftp(SilcServer server,
2889                      SilcSocketConnection sock,
2890                      SilcPacketContext *packet)
2891 {
2892   SilcSocketConnection dst_sock;
2893   SilcIDListData idata;
2894
2895   SILC_LOG_DEBUG(("Start"));
2896
2897   if (packet->src_id_type != SILC_ID_CLIENT ||
2898       packet->dst_id_type != SILC_ID_CLIENT)
2899     return;
2900
2901   if (!packet->dst_id)
2902     return;
2903
2904   /* Get the route to the client */
2905   dst_sock = silc_server_get_client_route(server, packet->dst_id,
2906                                           packet->dst_id_len, NULL, 
2907                                           &idata, NULL);
2908   if (!dst_sock)
2909     return;
2910
2911   /* Relay the packet */
2912   silc_server_relay_packet(server, dst_sock, idata->send_key,
2913                            idata->hmac_send, idata->psn_send++,
2914                            packet, FALSE);
2915 }
2916
2917 typedef struct {
2918   SilcServer server;
2919   SilcSocketConnection sock;
2920   SilcPacketContext *packet;
2921   void *data;
2922 } *SilcServerResumeResolve;
2923
2924 SILC_SERVER_CMD_FUNC(resume_resolve)
2925 {
2926   SilcServerResumeResolve r = (SilcServerResumeResolve)context;
2927   SilcServer server = r->server;
2928   SilcSocketConnection sock = r->sock;
2929   SilcServerCommandReplyContext reply = context2;
2930   SilcClientEntry client;
2931
2932   SILC_LOG_DEBUG(("Start"));
2933
2934   if (!reply || !silc_command_get_status(reply->payload, NULL, NULL)) {
2935     SILC_LOG_ERROR(("Client %s (%s) tried to resume unknown client, "
2936                     "closing connection", sock->hostname, sock->ip));
2937     silc_server_disconnect_remote(server, sock,
2938                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2939                                   "Resuming not possible");
2940     goto out;
2941   }
2942
2943   if (reply && silc_command_get(reply->payload) == SILC_COMMAND_WHOIS) {
2944     /* Get entry to the client, and resolve it if we don't have it. */
2945     client = silc_idlist_find_client_by_id(server->local_list, 
2946                                            r->data, TRUE, NULL);
2947     if (!client) {
2948       client = silc_idlist_find_client_by_id(server->global_list,
2949                                              r->data, TRUE, NULL);
2950       if (!client) {
2951         SILC_LOG_ERROR(("Client %s (%s) tried to resume unknown client, "
2952                         "closing connection", sock->hostname, sock->ip));
2953         silc_server_disconnect_remote(server, sock,
2954                                       SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2955                                       "Resuming not possible");
2956         goto out;
2957       }
2958     }
2959
2960     if (!(client->mode & SILC_UMODE_DETACHED)) {
2961       SILC_LOG_ERROR(("Client %s (%s) tried to resume un-detached client, "
2962                       "closing connection", sock->hostname, sock->ip));
2963       silc_server_disconnect_remote(server, sock,
2964                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2965                                     "Resuming not possible");
2966       goto out;
2967     }
2968   }
2969
2970   /* Reprocess the packet */
2971   silc_server_resume_client(server, sock, r->packet);
2972
2973  out:
2974   silc_socket_free(r->sock);
2975   silc_packet_context_free(r->packet);
2976   silc_free(r->data);
2977   silc_free(r);
2978 }
2979
2980 /* Received client resuming packet.  This is used to resume detached
2981    client session.  It can be sent by the client who wishes to resume
2982    but this is also sent by servers and routers to notify other routers
2983    that the client is not detached anymore. */
2984
2985 void silc_server_resume_client(SilcServer server,
2986                                SilcSocketConnection sock,
2987                                SilcPacketContext *packet)
2988 {
2989   SilcBuffer buffer = packet->buffer, buf;
2990   SilcIDListData idata;
2991   SilcClientEntry detached_client;
2992   SilcClientID *client_id = NULL;
2993   unsigned char *id_string, *auth = NULL;
2994   SilcUInt16 id_len, auth_len = 0;
2995   int ret, nickfail = 0;
2996   bool resolved, local, nick_change = FALSE, resolve = FALSE;
2997   SilcChannelEntry channel;
2998   SilcHashTableList htl;
2999   SilcChannelClientEntry chl;
3000   SilcServerResumeResolve r;
3001
3002   SILC_LOG_DEBUG(("Start"));
3003
3004   ret = silc_buffer_unformat(buffer,
3005                              SILC_STR_UI16_NSTRING(&id_string, &id_len),
3006                              SILC_STR_END);
3007   if (ret != -1)
3008     client_id = silc_id_str2id(id_string, id_len, SILC_ID_CLIENT);
3009
3010   if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
3011     /* Client send this and is attempting to resume to old client session */
3012     SilcClientEntry client;
3013     SilcBuffer keyp;
3014
3015     if (ret != -1) {
3016       silc_buffer_pull(buffer, 2 + id_len);
3017       auth = buffer->data;
3018       auth_len = buffer->len;
3019       silc_buffer_push(buffer, 2 + id_len);
3020     }
3021
3022     if (!client_id || auth_len < 128) {
3023       SILC_LOG_ERROR(("Client %s (%s) sent incomplete resume information, "
3024                       "closing connection", sock->hostname, sock->ip));
3025       silc_server_disconnect_remote(server, sock,
3026                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3027                                     "Resuming not possible");
3028       return;
3029     }
3030
3031     /* Take client entry of this connection */
3032     client = (SilcClientEntry)sock->user_data;
3033     idata = (SilcIDListData)client;
3034
3035     /* Get entry to the client, and resolve it if we don't have it. */
3036     detached_client = silc_server_get_client_resolve(server, client_id, FALSE,
3037                                                      &resolved);
3038     if (!detached_client) {
3039       if (resolved) {
3040         /* The client info is being resolved. Reprocess this packet after
3041            receiving the reply to the query. */
3042         SILC_LOG_DEBUG(("Resolving client"));
3043         r = silc_calloc(1, sizeof(*r));
3044         if (!r)
3045           return;
3046         r->server = server;
3047         r->sock = silc_socket_dup(sock);
3048         r->packet = silc_packet_context_dup(packet);
3049         r->data = silc_id_dup(client_id, SILC_ID_CLIENT);
3050         silc_server_command_pending(server, SILC_COMMAND_WHOIS,
3051                                     server->cmd_ident,
3052                                     silc_server_command_resume_resolve, r);
3053       } else {
3054         SILC_LOG_ERROR(("Client %s (%s) tried to resume unknown client, "
3055                         "closing connection", sock->hostname, sock->ip));
3056         silc_server_disconnect_remote(server, sock,
3057                                       SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3058                                       "Resuming not possible");
3059       }
3060       return;
3061     }
3062
3063     if (!(detached_client->mode & SILC_UMODE_DETACHED))
3064       resolve = TRUE;
3065     if (!silc_hash_table_count(detached_client->channels) &&
3066         detached_client->router)
3067       resolve = TRUE;
3068     if (!detached_client->nickname)
3069       resolve = TRUE;
3070
3071     if (resolve) {
3072       if (server->server_type == SILC_SERVER && !server->standalone) {
3073         /* The client info is being resolved. Reprocess this packet after
3074            receiving the reply to the query. */
3075         SILC_LOG_DEBUG(("Resolving client info"));
3076         silc_server_get_client_resolve(server, client_id, TRUE, NULL);
3077         r = silc_calloc(1, sizeof(*r));
3078         if (!r)
3079           return;
3080         r->server = server;
3081         r->sock = silc_socket_dup(sock);
3082         r->packet = silc_packet_context_dup(packet);
3083         r->data = silc_id_dup(client_id, SILC_ID_CLIENT);
3084         silc_server_command_pending(server, SILC_COMMAND_WHOIS,
3085                                     server->cmd_ident,
3086                                     silc_server_command_resume_resolve, r);
3087         return;
3088       }
3089       if (server->server_type == SILC_SERVER) {
3090         SILC_LOG_ERROR(("Client %s (%s) tried to resume un-detached client, "
3091                         "closing connection", sock->hostname, sock->ip));
3092         silc_server_disconnect_remote(server, sock,
3093                                       SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3094                                       "Resuming not possible");
3095         return;
3096       }
3097     }
3098
3099     /* Check that we have the public key of the client, if not then we must
3100        resolve it first. */
3101     if (!detached_client->data.public_key) {
3102       if (server->server_type == SILC_SERVER && server->standalone) {
3103         silc_server_disconnect_remote(server, sock,
3104                                       SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3105                                       "Resuming not possible");
3106       } else {
3107         /* We must retrieve the detached client's public key by sending
3108            GETKEY command. Reprocess this packet after receiving the key */
3109         SilcBuffer idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
3110         SilcSocketConnection dest_sock = 
3111           silc_server_get_client_route(server, NULL, 0, client_id, NULL, NULL);
3112
3113         SILC_LOG_DEBUG(("Resolving client public key"));
3114
3115         silc_server_send_command(server, dest_sock ? dest_sock : 
3116                                  server->router->connection,
3117                                  SILC_COMMAND_GETKEY, ++server->cmd_ident,
3118                                  1, 1, idp->data, idp->len);
3119
3120         r = silc_calloc(1, sizeof(*r));
3121         if (!r)
3122           return;
3123
3124         r->server = server;
3125         r->sock = silc_socket_dup(sock);
3126         r->packet = silc_packet_context_dup(packet);
3127         silc_server_command_pending(server, SILC_COMMAND_GETKEY,
3128                                     server->cmd_ident,
3129                                     silc_server_command_resume_resolve, r);
3130
3131         silc_buffer_free(idp);
3132       }
3133       return;
3134     } else if (!silc_pkcs_public_key_compare(detached_client->data.public_key,
3135                                              idata->public_key)) {
3136       /* We require that the connection and resuming authentication data
3137          must be using same key pair. */
3138       silc_server_disconnect_remote(server, sock,
3139                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3140                                     "Resuming not possible");
3141       return;
3142     }
3143
3144     /* Verify the authentication payload.  This has to be successful in
3145        order to allow the resuming */
3146     if (!silc_auth_verify_data(auth, auth_len, SILC_AUTH_PUBLIC_KEY,
3147                                detached_client->data.public_key, 0,
3148                                idata->hash, detached_client->id, 
3149                                SILC_ID_CLIENT)) {
3150       SILC_LOG_ERROR(("Client %s (%s) resume authentication failed, "
3151                       "closing connection", sock->hostname, sock->ip));
3152       silc_server_disconnect_remote(server, sock,
3153                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3154                                     "Resuming not possible");
3155       return;
3156     }
3157
3158     /* Now resume the client to the network */
3159
3160     silc_schedule_task_del_by_context(server->schedule, detached_client);
3161     sock->user_data = detached_client;
3162     detached_client->connection = sock;
3163
3164     /* Take new keys and stuff into use in the old entry */
3165     silc_idlist_del_data(detached_client);
3166     silc_idlist_add_data(detached_client, idata);
3167     detached_client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
3168     detached_client->data.status |= SILC_IDLIST_STATUS_RESUMED;
3169     detached_client->mode &= ~SILC_UMODE_DETACHED;
3170
3171     /* Send the RESUME_CLIENT packet to our primary router so that others
3172        know this client isn't detached anymore. */
3173     buf = silc_buffer_alloc_size(2 + id_len);
3174     silc_buffer_format(buf,
3175                        SILC_STR_UI_SHORT(id_len),
3176                        SILC_STR_UI_XNSTRING(id_string, id_len),
3177                        SILC_STR_END);
3178
3179     /* Send to primary router */
3180     if (!server->standalone)
3181       silc_server_packet_send(server, server->router->connection,
3182                               SILC_PACKET_RESUME_CLIENT, 0, 
3183                               buf->data, buf->len, TRUE);
3184
3185     /* As router we must deliver this packet directly to the original
3186        server whom this client was earlier. */
3187     if (server->server_type == SILC_ROUTER && detached_client->router &&
3188         detached_client->router->server_type != SILC_ROUTER)
3189       silc_server_packet_send(server, detached_client->router->connection,
3190                               SILC_PACKET_RESUME_CLIENT, 0, 
3191                               buf->data, buf->len, TRUE);
3192     silc_buffer_free(buf);
3193
3194     detached_client->router = NULL;
3195
3196     /* Delete this client entry since we're resuming to old one. */
3197     server->stat.my_clients--;
3198     server->stat.clients--;
3199     if (server->stat.cell_clients)
3200       server->stat.cell_clients--;
3201     silc_idlist_del_client(server->local_list, client);
3202     client = detached_client;
3203
3204     /* If the ID is not based in our ID then change it */
3205     if (!SILC_ID_COMPARE(client->id, server->id, server->id->ip.data_len)) {
3206       while (!silc_id_create_client_id(server, server->id, server->rng, 
3207                                        server->md5hash, client->nickname, 
3208                                        &client_id)) {
3209         nickfail++;
3210         if (nickfail > 9) {
3211           silc_server_disconnect_remote(server, sock, 
3212                                         SILC_STATUS_ERR_BAD_NICKNAME, NULL);
3213           return;
3214         }
3215         snprintf(&client->nickname[strlen(client->nickname) - 1], 1, 
3216                  "%d", nickfail);
3217       }
3218       nick_change = TRUE;
3219     }
3220
3221     if (nick_change) {
3222       /* Notify about Client ID change, nickname doesn't actually change. */
3223       if (!server->standalone)
3224         silc_server_send_notify_nick_change(server, server->router->connection,
3225                                             FALSE, client->id, client_id,
3226                                             client->nickname);
3227     }
3228
3229     /* Resolve users on those channels that client has joined but we
3230        haven't resolved user list yet. */
3231     if (server->server_type == SILC_SERVER && !server->standalone) {
3232       silc_hash_table_list(client->channels, &htl);
3233       while (silc_hash_table_get(&htl, NULL, (void **)&chl)) {
3234         channel = chl->channel;
3235         SILC_LOG_DEBUG(("Resolving users for %s channel", 
3236                         channel->channel_name));
3237         if (channel->disabled || !channel->users_resolved) {
3238           silc_server_send_command(server, server->router->connection,
3239                                    SILC_COMMAND_USERS, ++server->cmd_ident,
3240                                    1, 2, channel->channel_name,
3241                                    strlen(channel->channel_name));
3242         }
3243       }
3244       silc_hash_table_list_reset(&htl);
3245     }
3246
3247     /* Send the new client ID to the client. After this client may start
3248        receiving other packets, and may start sending packets too. */
3249     silc_server_send_new_id(server, sock, FALSE, client_id, SILC_ID_CLIENT,
3250                             silc_id_get_len(client_id, SILC_ID_CLIENT));
3251
3252     if (nick_change) {
3253       /* Send NICK change notify to channels as well. */
3254       SilcBuffer oidp, nidp;
3255       oidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3256       nidp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
3257       silc_server_send_notify_on_channels(server, NULL, client, 
3258                                           SILC_NOTIFY_TYPE_NICK_CHANGE, 3,
3259                                           oidp->data, oidp->len, 
3260                                           nidp->data, nidp->len,
3261                                           client->nickname, 
3262                                           strlen(client->nickname));
3263       silc_buffer_free(oidp);
3264       silc_buffer_free(nidp);
3265     }
3266
3267     /* Add the client again to the ID cache to get it to correct list */
3268     if (!silc_idcache_del_by_context(server->local_list->clients, client))
3269       silc_idcache_del_by_context(server->global_list->clients, client);
3270     silc_free(client->id);
3271     client->id = client_id;
3272     client_id = NULL;
3273     silc_idcache_add(server->local_list->clients, client->nickname,
3274                      client->id, client, 0, NULL);
3275
3276     /* Send some nice info to the client */
3277     silc_server_send_connect_notifys(server, sock, client);
3278
3279     /* Send all channel keys of channels the client has joined */
3280     silc_hash_table_list(client->channels, &htl);
3281     while (silc_hash_table_get(&htl, NULL, (void **)&chl)) {
3282       bool created = FALSE;
3283       channel = chl->channel;
3284
3285       if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY)
3286         continue;
3287
3288       /* If we don't have channel key, then create one */
3289       if (!channel->channel_key) {
3290         if (!silc_server_create_channel_key(server, channel, 0))
3291           continue;
3292         created = TRUE;
3293       }
3294
3295       id_string = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3296       keyp = 
3297         silc_channel_key_payload_encode(silc_id_get_len(channel->id,
3298                                                         SILC_ID_CHANNEL), 
3299                                         id_string,
3300                                         strlen(channel->channel_key->
3301                                                cipher->name),
3302                                         channel->channel_key->cipher->name,
3303                                         channel->key_len / 8, channel->key);
3304       silc_free(id_string);
3305
3306       /* Send the key packet to client */
3307       silc_server_packet_send(server, sock, SILC_PACKET_CHANNEL_KEY, 0, 
3308                               keyp->data, keyp->len, FALSE);
3309
3310       if (created && server->server_type == SILC_SERVER && 
3311           !server->standalone)
3312         silc_server_packet_send(server, server->router->connection, 
3313                                 SILC_PACKET_CHANNEL_KEY, 0, 
3314                                 keyp->data, keyp->len, FALSE);
3315
3316       silc_buffer_free(keyp);
3317     }
3318     silc_hash_table_list_reset(&htl);
3319
3320   } else if (sock->type != SILC_SOCKET_TYPE_CLIENT) {
3321     /* Server or router sent this to us to notify that that a client has
3322        been resumed. */
3323     SilcServerEntry server_entry;
3324     SilcServerID *server_id;
3325
3326     if (!client_id)
3327       return;
3328
3329     /* Get entry to the client, and resolve it if we don't have it. */
3330     detached_client = silc_idlist_find_client_by_id(server->local_list, 
3331                                                     client_id, TRUE, NULL);
3332     if (!detached_client) {
3333       detached_client = silc_idlist_find_client_by_id(server->global_list,
3334                                                       client_id, TRUE, NULL);
3335       if (!detached_client)
3336         return;
3337     }
3338
3339     /* Check that the client has not been resumed already because it is
3340        protocol error to attempt to resume more than once.  The client
3341        will be killed if this protocol error occurs. */
3342     if (detached_client->data.status & SILC_IDLIST_STATUS_RESUMED &&
3343         !(detached_client->mode & SILC_UMODE_DETACHED)) {
3344       /* The client is clearly attempting to resume more than once and
3345          perhaps playing around by resuming from several different places
3346          at the same time. */
3347       silc_server_kill_client(server, detached_client, NULL,
3348                               server->id, SILC_ID_SERVER);
3349       return;
3350     }
3351
3352     /* Check whether client is detached at all */
3353     if (!(detached_client->mode & SILC_UMODE_DETACHED))
3354       return;
3355
3356     /* Client is detached, and now it is resumed.  Remove the detached
3357        mode and mark that it is resumed. */
3358     detached_client->mode &= ~SILC_UMODE_DETACHED;
3359     detached_client->data.status |= SILC_IDLIST_STATUS_RESUMED;
3360
3361     /* Get the new owner of the resumed client */
3362     server_id = silc_id_str2id(packet->src_id, packet->src_id_len,
3363                                packet->src_id_type);
3364     if (!server_id)
3365       return;
3366
3367     /* Get server entry */
3368     server_entry = silc_idlist_find_server_by_id(server->global_list, 
3369                                                  server_id, TRUE, NULL);
3370     local = TRUE;
3371     if (!server_entry) {
3372       server_entry = silc_idlist_find_server_by_id(server->local_list, 
3373                                                    server_id, TRUE, NULL);
3374       local = FALSE;
3375       if (!server_entry) {
3376         silc_free(server_id);
3377         return;
3378       }
3379     }
3380
3381     if (server->server_type == SILC_ROUTER &&
3382         sock->type == SILC_SOCKET_TYPE_ROUTER && 
3383         server_entry->server_type == SILC_ROUTER)
3384       local = FALSE;
3385
3386     SILC_LOG_DEBUG(("Resuming detached client"));
3387
3388     /* Change the client to correct list. */
3389     if (!silc_idcache_del_by_context(server->local_list->clients,
3390                                      detached_client))
3391       silc_idcache_del_by_context(server->global_list->clients,
3392                                   detached_client);
3393     silc_idcache_add(local && server->server_type == SILC_ROUTER ? 
3394                      server->local_list->clients : 
3395                      server->global_list->clients, 
3396                      detached_client->nickname,
3397                      detached_client->id, detached_client, FALSE, NULL);
3398
3399     /* Change the owner of the client if needed */
3400     if (detached_client->router != server_entry)
3401       detached_client->router = server_entry;
3402
3403     /* Update channel information regarding global clients on channel. */
3404     if (server->server_type == SILC_SERVER) {
3405       silc_hash_table_list(detached_client->channels, &htl);
3406       while (silc_hash_table_get(&htl, NULL, (void **)&chl))
3407         chl->channel->global_users = 
3408           silc_server_channel_has_global(chl->channel);
3409       silc_hash_table_list_reset(&htl);
3410     }
3411
3412     silc_schedule_task_del_by_context(server->schedule, detached_client);
3413
3414     /* If the sender of this packet is server and we are router we need to
3415        broadcast this packet to other routers in the network. */
3416     if (!server->standalone && server->server_type == SILC_ROUTER &&
3417         sock->type == SILC_SOCKET_TYPE_SERVER &&
3418         !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
3419       SILC_LOG_DEBUG(("Broadcasting received Resume Client packet"));
3420       silc_server_packet_send(server, server->router->connection,
3421                               packet->type, 
3422                               packet->flags | SILC_PACKET_FLAG_BROADCAST,
3423                               buffer->data, buffer->len, FALSE);
3424       silc_server_backup_send(server, (SilcServerEntry)sock->user_data, 
3425                               packet->type, packet->flags,
3426                               packet->buffer->data, packet->buffer->len, 
3427                               FALSE, TRUE);
3428     }
3429
3430     silc_free(server_id);
3431   }
3432
3433   silc_free(client_id);
3434 }