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