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