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