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