Fixed invite and ban list handling in command reply.
[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     /* Sending SERVER_SIGNOFF is not right way to signoff local connection */
1310     if (SILC_IS_LOCAL(server_entry))
1311       break;
1312
1313     /* Remove all servers that are originated from this server, and
1314        remove the clients of those servers too. */
1315     silc_server_remove_servers_by_server(server, server_entry, TRUE);
1316
1317     /* Remove the clients that this server owns as they will become
1318        invalid now too. */
1319     silc_server_remove_clients_by_server(server, server_entry->router,
1320                                          server_entry, TRUE);
1321     silc_server_backup_del(server, server_entry);
1322
1323     /* Remove the server entry */
1324     silc_idlist_del_server(local ? server->local_list :
1325                            server->global_list, server_entry);
1326
1327     /* Update statistics */
1328     if (server->server_type == SILC_ROUTER)
1329       server->stat.servers--;
1330
1331     break;
1332
1333   case SILC_NOTIFY_TYPE_KICKED:
1334     /* 
1335      * Distribute the notify to local clients on the channel
1336      */
1337     
1338     SILC_LOG_DEBUG(("KICKED notify"));
1339       
1340     if (!channel_id) {
1341       channel_id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
1342                                   packet->dst_id_type);
1343       if (!channel_id)
1344         goto out;
1345     }
1346
1347     /* Get channel entry */
1348     channel = silc_idlist_find_channel_by_id(server->global_list, 
1349                                              channel_id, NULL);
1350     if (!channel) {
1351       channel = silc_idlist_find_channel_by_id(server->local_list, 
1352                                                channel_id, NULL);
1353       if (!channel) {
1354         SILC_LOG_DEBUG(("Notify for unknown channel"));
1355         silc_free(channel_id);
1356         goto out;
1357       }
1358     }
1359     silc_free(channel_id);
1360
1361     /* Get client ID */
1362     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
1363     if (!tmp)
1364       goto out;
1365     client_id = silc_id_payload_parse_id(tmp, tmp_len, NULL);
1366     if (!client_id)
1367       goto out;
1368
1369     /* If the the client is not in local list we check global list */
1370     client = silc_idlist_find_client_by_id(server->global_list, 
1371                                            client_id, TRUE, NULL);
1372     if (!client) {
1373       client = silc_idlist_find_client_by_id(server->local_list, 
1374                                              client_id, TRUE, NULL);
1375       if (!client) {
1376         silc_free(client_id);
1377         goto out;
1378       }
1379     }
1380     silc_free(client_id);
1381
1382     /* If target is founder they cannot be kicked */
1383     if (!silc_server_client_on_channel(client, channel, &chl))
1384       goto out;
1385     if (chl->mode & SILC_CHANNEL_UMODE_CHANFO)
1386       goto out;
1387     
1388     /* Get the kicker's Client ID */
1389     tmp = silc_argument_get_arg_type(args, 3, &tmp_len);
1390     if (!tmp)
1391       goto out;
1392     client_id = silc_id_payload_parse_id(tmp, tmp_len, NULL);
1393     if (!client_id)
1394       goto out;
1395
1396     /* If the the client is not in local list we check global list */
1397     client2 = silc_idlist_find_client_by_id(server->global_list, 
1398                                             client_id, TRUE, NULL);
1399     if (!client2) {
1400       client2 = silc_idlist_find_client_by_id(server->local_list, 
1401                                               client_id, TRUE, NULL);
1402       if (!client2) {
1403         silc_free(client_id);
1404         goto out;
1405       }
1406     }
1407     silc_free(client_id);
1408
1409     /* Kicker must be operator on channel */
1410     if (!silc_server_client_on_channel(client2, channel, &chl))
1411       goto out;
1412     if (!(chl->mode & SILC_CHANNEL_UMODE_CHANOP) &&
1413         !(chl->mode & SILC_CHANNEL_UMODE_CHANFO)) {
1414       SILC_LOG_DEBUG(("Kicking is not allowed"));
1415       goto out;
1416     }
1417
1418     /* Send to channel */
1419     silc_server_packet_send_to_channel(server, sock, channel, packet->type, 
1420                                        FALSE, packet->buffer->data, 
1421                                        packet->buffer->len, FALSE);
1422
1423     /* Remove the client from channel's invite list */
1424     if (channel->invite_list && silc_hash_table_count(channel->invite_list)) {
1425       SilcBuffer ab;
1426       SilcArgumentPayload iargs;
1427       tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
1428       ab = silc_argument_payload_encode_one(NULL, tmp, tmp_len, 3);
1429       iargs = silc_argument_payload_parse(ab->data, ab->len, 1);
1430       silc_server_inviteban_process(server, channel->invite_list, 1, iargs);
1431       silc_buffer_free(ab);
1432       silc_argument_payload_free(iargs);
1433     }
1434
1435     /* Remove the client from channel */
1436     silc_server_remove_from_one_channel(server, sock, channel, client, FALSE);
1437
1438     break;
1439
1440   case SILC_NOTIFY_TYPE_KILLED:
1441     {
1442       /* 
1443        * Distribute the notify to local clients on channels
1444        */
1445       unsigned char *id, *comment;
1446       SilcUInt32 id_len, comment_len;
1447     
1448       SILC_LOG_DEBUG(("KILLED notify"));
1449       
1450       /* Get client ID */
1451       id = silc_argument_get_arg_type(args, 1, &id_len);
1452       if (!id)
1453         goto out;
1454       client_id = silc_id_payload_parse_id(id, id_len, NULL);
1455       if (!client_id)
1456         goto out;
1457
1458       /* If the the client is not in local list we check global list */
1459       client = silc_idlist_find_client_by_id(server->global_list, 
1460                                              client_id, TRUE, &cache);
1461       if (!client) {
1462         client = silc_idlist_find_client_by_id(server->local_list, 
1463                                                client_id, TRUE, &cache);
1464         if (!client) {
1465           silc_free(client_id);
1466           goto out;
1467         }
1468       }
1469       silc_free(client_id);
1470
1471       /* If the client is one of ours, then close the connection to the
1472          client now. This removes the client from all channels as well. */
1473       if (packet->dst_id_type == SILC_ID_CLIENT && client->connection) {
1474         sock = client->connection;
1475         silc_server_free_client_data(server, NULL, client, FALSE, NULL);
1476         silc_server_close_connection(server, sock);
1477         break;
1478       }
1479
1480       /* Get comment */
1481       comment = silc_argument_get_arg_type(args, 2, &comment_len);
1482       if (comment_len > 128)
1483         comment_len = 127;
1484
1485       /* Get the killer's Client ID */
1486       tmp = silc_argument_get_arg_type(args, 3, &tmp_len);
1487       if (!tmp)
1488         goto out;
1489       client_id = silc_id_payload_parse_id(tmp, tmp_len, &id_type);
1490       if (!client_id)
1491         goto out;
1492
1493       if (id_type == SILC_ID_CLIENT) {
1494         /* If the the client is not in local list we check global list */
1495         client2 = silc_idlist_find_client_by_id(server->global_list, 
1496                                                 client_id, TRUE, NULL);
1497         if (!client2) {
1498           client2 = silc_idlist_find_client_by_id(server->local_list, 
1499                                                   client_id, TRUE, NULL);
1500           if (!client2) {
1501             silc_free(client_id);
1502             goto out;
1503           }
1504         }
1505         silc_free(client_id);
1506
1507         /* Killer must be router operator */
1508         if (server->server_type != SILC_SERVER &&
1509             !(client2->mode & SILC_UMODE_ROUTER_OPERATOR)) {
1510           SILC_LOG_DEBUG(("Killing is not allowed"));
1511           goto out;
1512         }
1513       }
1514
1515       /* Send the notify to local clients on the channels except to the
1516          client who is killed. */
1517       silc_server_send_notify_on_channels(server, client, client,
1518                                           SILC_NOTIFY_TYPE_KILLED, 3,
1519                                           id, id_len, comment, comment_len,
1520                                           tmp, tmp_len);
1521
1522       /* Remove the client from all channels */
1523       silc_server_remove_from_channels(server, NULL, client, FALSE, NULL, 
1524                                        FALSE, TRUE);
1525
1526       /* Check if anyone is watching this nickname */
1527       silc_server_check_watcher_list(server, client, NULL,
1528                                      SILC_NOTIFY_TYPE_KILLED);
1529
1530       /* Update statistics */
1531       server->stat.clients--;
1532       if (server->stat.cell_clients)
1533         server->stat.cell_clients--;
1534       SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
1535       SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
1536
1537       if (SILC_IS_LOCAL(client)) {
1538         server->stat.my_clients--;
1539         silc_schedule_task_del_by_context(server->schedule, client);
1540         silc_idlist_del_data(client);
1541         client->mode = 0;
1542       }
1543
1544       client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
1545       cache->expire = SILC_ID_CACHE_EXPIRE_DEF;
1546       break;
1547     }
1548
1549   case SILC_NOTIFY_TYPE_UMODE_CHANGE:
1550     /*
1551      * Save the mode of the client.
1552      */
1553
1554     SILC_LOG_DEBUG(("UMODE_CHANGE notify"));
1555
1556     /* Get client ID */
1557     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
1558     if (!tmp)
1559       goto out;
1560     client_id = silc_id_payload_parse_id(tmp, tmp_len, NULL);
1561     if (!client_id)
1562       goto out;
1563
1564     /* Get client entry */
1565     client = silc_idlist_find_client_by_id(server->global_list, 
1566                                            client_id, TRUE, NULL);
1567     if (!client) {
1568       client = silc_idlist_find_client_by_id(server->local_list, 
1569                                              client_id, TRUE, NULL);
1570       if (!client) {
1571         silc_free(client_id);
1572         goto out;
1573       }
1574     }
1575     silc_free(client_id);
1576
1577     /* Get the mode */
1578     tmp = silc_argument_get_arg_type(args, 2, &tmp_len);
1579     if (!tmp)
1580       goto out;
1581     SILC_GET32_MSB(mode, tmp);
1582
1583     /* Remove internal resumed flag if client is marked detached now */
1584     if (mode & SILC_UMODE_DETACHED)
1585       client->data.status &= ~SILC_IDLIST_STATUS_RESUMED;
1586
1587     /* Update statistics */
1588     if (server->server_type == SILC_ROUTER) {
1589       if (mode & SILC_UMODE_GONE) {
1590         if (!(client->mode & SILC_UMODE_GONE))
1591           server->stat.aways++;
1592       } else {
1593         if (client->mode & SILC_UMODE_GONE)
1594           server->stat.aways--;
1595       }
1596       if (mode & SILC_UMODE_DETACHED) {
1597         if (!(client->mode & SILC_UMODE_DETACHED))
1598           server->stat.detached++;
1599       } else {
1600         if (client->mode & SILC_UMODE_DETACHED)
1601           server->stat.detached--;
1602       }
1603     }
1604     SILC_UMODE_STATS_UPDATE(server, SILC_UMODE_SERVER_OPERATOR);
1605     SILC_UMODE_STATS_UPDATE(router, SILC_UMODE_ROUTER_OPERATOR);
1606
1607     /* Change the mode */
1608     client->mode = mode;
1609
1610     /* Check if anyone is watching this nickname */
1611     if (server->server_type == SILC_ROUTER)
1612       silc_server_check_watcher_list(server, client, NULL,
1613                                      SILC_NOTIFY_TYPE_UMODE_CHANGE);
1614
1615     break;
1616
1617   case SILC_NOTIFY_TYPE_BAN:
1618     /*
1619      * Save the ban
1620      */
1621
1622     SILC_LOG_DEBUG(("BAN notify"));
1623     
1624     /* Get Channel ID */
1625     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
1626     if (!tmp)
1627       goto out;
1628     channel_id = silc_id_payload_parse_id(tmp, tmp_len, NULL);
1629     if (!channel_id)
1630       goto out;
1631     
1632     /* Get channel entry */
1633     channel = silc_idlist_find_channel_by_id(server->global_list, 
1634                                              channel_id, NULL);
1635     if (!channel) {
1636       channel = silc_idlist_find_channel_by_id(server->local_list, 
1637                                                channel_id, NULL);
1638       if (!channel) {
1639         SILC_LOG_DEBUG(("Notify for unknown channel"));
1640         silc_free(channel_id);
1641         goto out;
1642       }
1643     }
1644     silc_free(channel_id);
1645
1646     /* Get the ban action */
1647     tmp = silc_argument_get_arg_type(args, 2, &tmp_len);
1648     if (tmp && tmp_len == 1) {
1649       SilcUInt8 action = (SilcUInt8)tmp[0];
1650       SilcUInt16 iargc = 0;
1651       SilcArgumentPayload iargs;
1652
1653       /* Get ban list */
1654       tmp = silc_argument_get_arg_type(args, 3, &tmp_len);
1655       if (!tmp || tmp_len < 2)
1656         goto out;
1657
1658       /* Parse the arguments to see they are constructed correctly */
1659       SILC_GET16_MSB(iargc, tmp);
1660       iargs = silc_argument_payload_parse(tmp + 2, tmp_len - 2, iargc);
1661       if (!iargs)
1662         goto out;
1663
1664       if (action == 0 && !channel->ban_list)
1665         channel->ban_list =
1666           silc_hash_table_alloc(0, silc_hash_ptr,
1667                                 NULL, NULL, NULL,
1668                                 silc_server_inviteban_destruct, channel, TRUE);
1669
1670       /* Proces the ban action */
1671       silc_server_inviteban_process(server, channel->ban_list, action,
1672                                     iargs);
1673       silc_argument_payload_free(iargs);
1674     }
1675     break;
1676
1677   case SILC_NOTIFY_TYPE_ERROR:
1678     {
1679       /*
1680        * Error notify
1681        */
1682       SilcStatus error;
1683
1684       tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
1685       if (!tmp && tmp_len != 1)
1686         goto out;
1687       error = (SilcStatus)tmp[0];
1688
1689       SILC_LOG_DEBUG(("ERROR notify (%d)", error));
1690
1691       if (error == SILC_STATUS_ERR_NO_SUCH_CLIENT_ID &&
1692           sock->type == SILC_SOCKET_TYPE_ROUTER) {
1693         tmp = silc_argument_get_arg_type(args, 2, &tmp_len);
1694         if (tmp) {
1695           SILC_LOG_DEBUG(("Received invalid client ID notification, deleting "
1696                           "the entry from cache"));
1697           client_id = silc_id_payload_parse_id(tmp, tmp_len, NULL);
1698           if (!client_id)
1699             goto out;
1700           client = silc_idlist_find_client_by_id(server->global_list, 
1701                                                  client_id, FALSE, NULL);
1702           if (client) {
1703             silc_server_remove_from_channels(server, NULL, client, TRUE, 
1704                                              NULL, TRUE, FALSE);
1705             silc_idlist_del_data(client);
1706             silc_idlist_del_client(server->global_list, client);
1707           }
1708           silc_free(client_id);
1709         }
1710       }
1711     }
1712     break;
1713
1714     /* Ignore rest of the notify types for now */
1715   case SILC_NOTIFY_TYPE_NONE:
1716   case SILC_NOTIFY_TYPE_MOTD:
1717     break;
1718   default:
1719     break;
1720   }
1721
1722  out:
1723   silc_notify_payload_free(payload);
1724 }
1725
1726 void silc_server_notify_list(SilcServer server,
1727                              SilcSocketConnection sock,
1728                              SilcPacketContext *packet)
1729 {
1730   SilcPacketContext *new;
1731   SilcBuffer buffer;
1732   SilcUInt16 len;
1733
1734   SILC_LOG_DEBUG(("Processing Notify List"));
1735
1736   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
1737       packet->src_id_type != SILC_ID_SERVER)
1738     return;
1739
1740   /* Make copy of the original packet context, except for the actual
1741      data buffer, which we will here now fetch from the original buffer. */
1742   new = silc_packet_context_alloc();
1743   new->type = SILC_PACKET_NOTIFY;
1744   new->flags = packet->flags;
1745   new->src_id = packet->src_id;
1746   new->src_id_len = packet->src_id_len;
1747   new->src_id_type = packet->src_id_type;
1748   new->dst_id = packet->dst_id;
1749   new->dst_id_len = packet->dst_id_len;
1750   new->dst_id_type = packet->dst_id_type;
1751
1752   buffer = silc_buffer_alloc(1024);
1753   new->buffer = buffer;
1754
1755   while (packet->buffer->len) {
1756     SILC_GET16_MSB(len, packet->buffer->data + 2);
1757     if (len > packet->buffer->len)
1758       break;
1759
1760     if (len > buffer->truelen) {
1761       silc_buffer_free(buffer);
1762       buffer = silc_buffer_alloc(1024 + len);
1763     }
1764
1765     silc_buffer_pull_tail(buffer, len);
1766     silc_buffer_put(buffer, packet->buffer->data, len);
1767
1768     /* Process the Notify */
1769     silc_server_notify(server, sock, new);
1770
1771     silc_buffer_push_tail(buffer, len);
1772     silc_buffer_pull(packet->buffer, len);
1773   }
1774
1775   silc_buffer_free(buffer);
1776   silc_free(new);
1777 }
1778
1779 /* Received private message. This resolves the destination of the message 
1780    and sends the packet. This is used by both server and router.  If the
1781    destination is our locally connected client this sends the packet to
1782    the client. This may also send the message for further routing if
1783    the destination is not in our server (or router). */
1784
1785 void silc_server_private_message(SilcServer server,
1786                                  SilcSocketConnection sock,
1787                                  SilcPacketContext *packet)
1788 {
1789   SilcSocketConnection dst_sock;
1790   SilcIDListData idata;
1791   SilcClientEntry client;
1792
1793   SILC_LOG_DEBUG(("Start"));
1794
1795   if (packet->src_id_type != SILC_ID_CLIENT ||
1796       packet->dst_id_type != SILC_ID_CLIENT || !packet->dst_id)
1797     return;
1798
1799   /* Get the route to the client */
1800   dst_sock = silc_server_get_client_route(server, packet->dst_id,
1801                                           packet->dst_id_len, NULL, 
1802                                           &idata, &client);
1803   if (!dst_sock) {
1804     SilcBuffer idp;
1805     unsigned char error;
1806
1807     if (client && client->mode & SILC_UMODE_DETACHED) {
1808       SILC_LOG_DEBUG(("Client is detached, discarding packet"));
1809       return;
1810     }
1811
1812     /* Send SILC_NOTIFY_TYPE_ERROR to indicate that such destination ID
1813        does not exist or is invalid. */
1814     idp = silc_id_payload_encode_data(packet->dst_id,
1815                                       packet->dst_id_len,
1816                                       packet->dst_id_type);
1817     if (!idp)
1818       return;
1819
1820     error = SILC_STATUS_ERR_NO_SUCH_CLIENT_ID;
1821     if (packet->src_id_type == SILC_ID_CLIENT) {
1822       SilcClientID *client_id = silc_id_str2id(packet->src_id,
1823                                                packet->src_id_len,
1824                                                packet->src_id_type);
1825       silc_server_send_notify_dest(server, sock, FALSE,
1826                                    client_id, SILC_ID_CLIENT,
1827                                    SILC_NOTIFY_TYPE_ERROR, 2,
1828                                    &error, 1,
1829                                    idp->data, idp->len);
1830       silc_free(client_id);
1831     } else {
1832       silc_server_send_notify(server, sock, FALSE,
1833                               SILC_NOTIFY_TYPE_ERROR, 2,
1834                               &error, 1,
1835                               idp->data, idp->len);
1836     }
1837
1838     silc_buffer_free(idp);
1839     return;
1840   }
1841
1842   /* Check whether destination client wishes to receive private messages */
1843   if (client && !(packet->flags & SILC_PACKET_FLAG_PRIVMSG_KEY) &&
1844       client->mode & SILC_UMODE_BLOCK_PRIVMSG) {
1845     SILC_LOG_DEBUG(("Client blocks private messages, discarding packet"));
1846     return;
1847   }
1848
1849   /* Send the private message */
1850   silc_server_send_private_message(server, dst_sock, idata->send_key,
1851                                    idata->hmac_send, idata->psn_send++,
1852                                    packet);
1853 }
1854
1855 /* Received private message key packet.. This packet is never for us. It is to
1856    the client in the packet's destination ID. Sending of this sort of packet
1857    equals sending private message, ie. it is sent point to point from
1858    one client to another. */
1859
1860 void silc_server_private_message_key(SilcServer server,
1861                                      SilcSocketConnection sock,
1862                                      SilcPacketContext *packet)
1863 {
1864   SilcSocketConnection dst_sock;
1865   SilcIDListData idata;
1866
1867   SILC_LOG_DEBUG(("Start"));
1868
1869   if (packet->src_id_type != SILC_ID_CLIENT ||
1870       packet->dst_id_type != SILC_ID_CLIENT)
1871     return;
1872
1873   if (!packet->dst_id)
1874     return;
1875
1876   /* Get the route to the client */
1877   dst_sock = silc_server_get_client_route(server, packet->dst_id,
1878                                           packet->dst_id_len, NULL, 
1879                                           &idata, NULL);
1880   if (!dst_sock)
1881     return;
1882
1883   /* Relay the packet */
1884   silc_server_relay_packet(server, dst_sock, idata->send_key,
1885                            idata->hmac_send, idata->psn_send++, packet, FALSE);
1886 }
1887
1888 /* Processes incoming command reply packet. The command reply packet may
1889    be destined to one of our clients or it may directly for us. We will 
1890    call the command reply routine after processing the packet. */
1891
1892 void silc_server_command_reply(SilcServer server,
1893                                SilcSocketConnection sock,
1894                                SilcPacketContext *packet)
1895 {
1896   SilcBuffer buffer = packet->buffer;
1897   SilcClientEntry client = NULL;
1898   SilcSocketConnection dst_sock;
1899   SilcIDListData idata;
1900   SilcClientID *id = NULL;
1901
1902   SILC_LOG_DEBUG(("Start"));
1903
1904   if (packet->dst_id_type == SILC_ID_CHANNEL)
1905     return;
1906
1907   if (packet->dst_id_type == SILC_ID_CLIENT) {
1908     /* Destination must be one of ours */
1909     id = silc_id_str2id(packet->dst_id, packet->dst_id_len, SILC_ID_CLIENT);
1910     if (!id)
1911       return;
1912     client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
1913     if (!client) {
1914       SILC_LOG_ERROR(("Cannot process command reply to unknown client"));
1915       silc_free(id);
1916       return;
1917     }
1918   }
1919
1920   if (packet->dst_id_type == SILC_ID_SERVER) {
1921     /* For now this must be for us */
1922     if (memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
1923       SILC_LOG_ERROR(("Cannot process command reply to unknown server"));
1924       return;
1925     }
1926   }
1927
1928   /* Execute command reply locally for the command */
1929   silc_server_command_reply_process(server, sock, buffer);
1930
1931   if (packet->dst_id_type == SILC_ID_CLIENT && client && id) {
1932     /* Relay the packet to the client */
1933     const SilcBufferStruct p;
1934     
1935     dst_sock = (SilcSocketConnection)client->connection;
1936     idata = (SilcIDListData)client;
1937     
1938     silc_buffer_push(buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len 
1939                      + packet->dst_id_len + packet->padlen);
1940     if (!silc_packet_send_prepare(dst_sock, 0, 0, buffer->len,
1941                                   idata->hmac_send, (const SilcBuffer)&p)) {
1942       SILC_LOG_ERROR(("Cannot send packet"));
1943       return;
1944     }
1945     silc_buffer_put((SilcBuffer)&p, buffer->data, buffer->len);
1946     
1947     /* Encrypt packet */
1948     silc_packet_encrypt(idata->send_key, idata->hmac_send, idata->psn_send++,
1949                         (SilcBuffer)&p, buffer->len);
1950     
1951     /* Send the packet */
1952     silc_server_packet_send_real(server, dst_sock, TRUE);
1953
1954     silc_free(id);
1955   }
1956 }
1957
1958 /* Process received channel message. The message can be originated from
1959    client or server. */
1960
1961 void silc_server_channel_message(SilcServer server,
1962                                  SilcSocketConnection sock,
1963                                  SilcPacketContext *packet)
1964 {
1965   SilcChannelEntry channel = NULL;
1966   SilcChannelID *id = NULL;
1967   void *sender_id = NULL;
1968   SilcClientEntry sender_entry = NULL;
1969   SilcChannelClientEntry chl;
1970   bool local = TRUE;
1971
1972   SILC_LOG_DEBUG(("Processing channel message"));
1973
1974   /* Sanity checks */
1975   if (packet->dst_id_type != SILC_ID_CHANNEL) {
1976     SILC_LOG_DEBUG(("Received bad message for channel, dropped"));
1977     goto out;
1978   }
1979
1980   /* Find channel entry */
1981   id = silc_id_str2id(packet->dst_id, packet->dst_id_len, SILC_ID_CHANNEL);
1982   if (!id)
1983     goto out;
1984   channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
1985   if (!channel) {
1986     channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
1987     if (!channel) {
1988       SilcBuffer idp;
1989       unsigned char error;
1990
1991       /* Send SILC_NOTIFY_TYPE_ERROR to indicate that such destination ID
1992          does not exist or is invalid. */
1993       idp = silc_id_payload_encode_data(packet->dst_id,
1994                                         packet->dst_id_len,
1995                                         packet->dst_id_type);
1996       if (!idp)
1997         goto out;
1998
1999       error = SILC_STATUS_ERR_NO_SUCH_CHANNEL_ID;
2000       if (packet->src_id_type == SILC_ID_CLIENT) {
2001         SilcClientID *client_id = silc_id_str2id(packet->src_id,
2002                                                  packet->src_id_len,
2003                                                  packet->src_id_type);
2004         silc_server_send_notify_dest(server, sock, FALSE,
2005                                      client_id, SILC_ID_CLIENT,
2006                                      SILC_NOTIFY_TYPE_ERROR, 2,
2007                                      &error, 1, idp->data, idp->len);
2008         silc_free(client_id);
2009       } else {
2010         silc_server_send_notify(server, sock, FALSE,
2011                                 SILC_NOTIFY_TYPE_ERROR, 2,
2012                                 &error, 1, idp->data, idp->len);
2013       }
2014       
2015       silc_buffer_free(idp);
2016       goto out;
2017     }
2018   }
2019
2020   /* See that this client is on the channel. If the original sender is
2021      not client (as it can be server as well) we don't do the check. */
2022   sender_id = silc_id_str2id(packet->src_id, packet->src_id_len, 
2023                              packet->src_id_type);
2024   if (!sender_id)
2025     goto out;
2026   if (packet->src_id_type == SILC_ID_CLIENT) {
2027     sender_entry = silc_idlist_find_client_by_id(server->local_list, 
2028                                                  sender_id, TRUE, NULL);
2029     if (!sender_entry) {
2030       local = FALSE;
2031       sender_entry = silc_idlist_find_client_by_id(server->global_list, 
2032                                                    sender_id, TRUE, NULL);
2033     }
2034     if (!sender_entry || !silc_server_client_on_channel(sender_entry, 
2035                                                         channel, &chl)) {
2036       SILC_LOG_DEBUG(("Client not on channel"));
2037       goto out;
2038     }
2039
2040     /* If channel is moderated check that client is allowed to send
2041        messages. */
2042     if (channel->mode & SILC_CHANNEL_MODE_SILENCE_USERS && 
2043         !(chl->mode & SILC_CHANNEL_UMODE_CHANOP) &&
2044         !(chl->mode & SILC_CHANNEL_UMODE_CHANFO)) {
2045       SILC_LOG_DEBUG(("Channel is silenced from normal users"));
2046       goto out;
2047     }
2048     if (channel->mode & SILC_CHANNEL_MODE_SILENCE_OPERS && 
2049         chl->mode & SILC_CHANNEL_UMODE_CHANOP &&
2050         !(chl->mode & SILC_CHANNEL_UMODE_CHANFO)) {
2051       SILC_LOG_DEBUG(("Channel is silenced from operators"));
2052       goto out;
2053     }
2054     if (chl->mode & SILC_CHANNEL_UMODE_QUIET) {
2055       SILC_LOG_DEBUG(("Sender is quieted on the channel"));
2056       goto out;
2057     }
2058
2059     /* If the packet is coming from router, but the client entry is local 
2060        entry to us then some router is rerouting this to us and it is not 
2061        allowed. When the client is local to us it means that we've routed
2062        this packet to network, and now someone is routing it back to us. */
2063     if (server->server_type == SILC_ROUTER &&
2064         sock->type == SILC_SOCKET_TYPE_ROUTER && local) {
2065       SILC_LOG_DEBUG(("Channel message rerouted to the sender, drop it"));
2066       goto out;
2067     }
2068   }
2069
2070   /* Distribute the packet to our local clients. This will send the
2071      packet for further routing as well, if needed. */
2072   silc_server_packet_relay_to_channel(server, sock, channel, sender_id,
2073                                       packet->src_id_type, sender_entry,
2074                                       packet->buffer->data,
2075                                       packet->buffer->len, FALSE);
2076
2077  out:
2078   silc_free(sender_id);
2079   silc_free(id);
2080 }
2081
2082 /* Received channel key packet. We distribute the key to all of our locally
2083    connected clients on the channel. */
2084
2085 void silc_server_channel_key(SilcServer server,
2086                              SilcSocketConnection sock,
2087                              SilcPacketContext *packet)
2088 {
2089   SilcBuffer buffer = packet->buffer;
2090   SilcChannelEntry channel;
2091
2092   if (packet->src_id_type != SILC_ID_SERVER ||
2093       (server->server_type == SILC_ROUTER && !server->backup_router &&
2094        sock->type == SILC_SOCKET_TYPE_ROUTER))
2095     return;
2096
2097   /* Save the channel key */
2098   channel = silc_server_save_channel_key(server, buffer, NULL);
2099   if (!channel) {
2100     SILC_LOG_ERROR(("Bad channel key from %s (%s)",
2101                     sock->hostname, sock->ip));
2102     return;
2103   }
2104     
2105   /* Distribute the key to everybody who is on the channel. If we are router
2106      we will also send it to locally connected servers. */
2107   silc_server_send_channel_key(server, sock, channel, FALSE);
2108   
2109   if (server->server_type != SILC_BACKUP_ROUTER) {
2110     /* Distribute to local cell backup routers. */
2111     silc_server_backup_send(server, sock->user_data, 
2112                             SILC_PACKET_CHANNEL_KEY, 0,
2113                             buffer->data, buffer->len, FALSE, TRUE);
2114   }
2115 }
2116
2117 /* Received New Client packet and processes it.  Creates Client ID for the
2118    client. Client becomes registered after calling this functions. */
2119
2120 SilcClientEntry silc_server_new_client(SilcServer server,
2121                                        SilcSocketConnection sock,
2122                                        SilcPacketContext *packet)
2123 {
2124   SilcBuffer buffer = packet->buffer;
2125   SilcClientEntry client;
2126   SilcClientID *client_id;
2127   SilcIDListData idata;
2128   char *username = NULL, *realname = NULL;
2129   SilcUInt16 username_len;
2130   SilcUInt32 id_len;
2131   int ret;
2132   char *hostname, *nickname;
2133   int nickfail = 0;
2134
2135   SILC_LOG_DEBUG(("Creating new client"));
2136
2137   if (sock->type != SILC_SOCKET_TYPE_CLIENT)
2138     return NULL;
2139
2140   /* Take client entry */
2141   client = (SilcClientEntry)sock->user_data;
2142   idata = (SilcIDListData)client;
2143
2144   /* Remove the old cache entry. */
2145   if (!silc_idcache_del_by_context(server->local_list->clients, client)) {
2146     SILC_LOG_INFO(("Unauthenticated client attempted to register to network"));
2147     silc_server_disconnect_remote(server, sock, 
2148                                   SILC_STATUS_ERR_NOT_AUTHENTICATED, NULL);
2149     if (sock->user_data)
2150       silc_server_free_sock_user_data(server, sock, NULL);
2151     return NULL;
2152   }
2153
2154   /* Parse incoming packet */
2155   ret = silc_buffer_unformat(buffer,
2156                              SILC_STR_UI16_NSTRING_ALLOC(&username, 
2157                                                          &username_len),
2158                              SILC_STR_UI16_STRING_ALLOC(&realname),
2159                              SILC_STR_END);
2160   if (ret == -1) {
2161     silc_free(username);
2162     silc_free(realname);
2163     SILC_LOG_ERROR(("Client %s (%s) sent incomplete information, closing "
2164                     "connection", sock->hostname, sock->ip));
2165     silc_server_disconnect_remote(server, sock, 
2166                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION, 
2167                                   NULL);
2168     if (sock->user_data)
2169       silc_server_free_sock_user_data(server, sock, NULL);
2170     return NULL;
2171   }
2172
2173   if (!username) {
2174     silc_free(username);
2175     silc_free(realname);
2176     SILC_LOG_ERROR(("Client %s (%s) did not send its username, closing "
2177                     "connection", sock->hostname, sock->ip));
2178     silc_server_disconnect_remote(server, sock, 
2179                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2180                                   NULL);
2181     if (sock->user_data)
2182       silc_server_free_sock_user_data(server, sock, NULL);
2183     return NULL;
2184   }
2185
2186   if (username_len > 128)
2187     username[128] = '\0';
2188
2189   /* Check for bad characters for nickname, and modify the nickname if
2190      it includes those. */
2191   if (silc_server_name_bad_chars(username, username_len)) {
2192     nickname = silc_server_name_modify_bad(username, username_len);
2193   } else {
2194     nickname = strdup(username);
2195   }
2196
2197   /* Make sanity checks for the hostname of the client. If the hostname
2198      is provided in the `username' check that it is the same than the
2199      resolved hostname, or if not resolved the hostname that appears in
2200      the client's public key. If the hostname is not present then put
2201      it from the resolved name or from the public key. */
2202   if (strchr(username, '@')) {
2203     SilcPublicKeyIdentifier pident;
2204     int tlen = strcspn(username, "@");
2205     char *phostname = NULL;
2206
2207     hostname = silc_memdup(username + tlen + 1, strlen(username) - tlen - 1);
2208
2209     if (strcmp(sock->hostname, sock->ip) && 
2210         strcmp(sock->hostname, hostname)) {
2211       silc_free(username);
2212       silc_free(hostname);
2213       silc_free(realname);
2214       SILC_LOG_ERROR(("Client %s (%s) sent incomplete information, closing "
2215                       "connection", sock->hostname, sock->ip));
2216       silc_server_disconnect_remote(server, sock, 
2217                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2218                                     NULL);
2219       if (sock->user_data)
2220         silc_server_free_sock_user_data(server, sock, NULL);
2221       return NULL;
2222     }
2223     
2224     pident = silc_pkcs_decode_identifier(client->data.public_key->identifier);
2225     if (pident) {
2226       phostname = strdup(pident->host);
2227       silc_pkcs_free_identifier(pident);
2228     }
2229
2230     if (!strcmp(sock->hostname, sock->ip) && 
2231         phostname && strcmp(phostname, hostname)) {
2232       silc_free(username);
2233       silc_free(hostname);
2234       silc_free(phostname);
2235       silc_free(realname);
2236       SILC_LOG_ERROR(("Client %s (%s) sent incomplete information, closing "
2237                       "connection", sock->hostname, sock->ip));
2238       silc_server_disconnect_remote(server, sock, 
2239                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2240                                     NULL);
2241       if (sock->user_data)
2242         silc_server_free_sock_user_data(server, sock, NULL);
2243       return NULL;
2244     }
2245     
2246     silc_free(phostname);
2247   } else {
2248     /* The hostname is not present, add it. */
2249     char *newusername;
2250     /* XXX For now we cannot take the host name from the public key since
2251        they are not trusted or we cannot verify them as trusted. Just take
2252        what the resolved name or address is. */
2253 #if 0
2254     if (strcmp(sock->hostname, sock->ip)) {
2255 #endif
2256       newusername = silc_calloc(strlen(username) + 
2257                                 strlen(sock->hostname) + 2,
2258                                 sizeof(*newusername));
2259       strncat(newusername, username, strlen(username));
2260       strncat(newusername, "@", 1);
2261       strncat(newusername, sock->hostname, strlen(sock->hostname));
2262       silc_free(username);
2263       username = newusername;
2264 #if 0
2265     } else {
2266       SilcPublicKeyIdentifier pident = 
2267         silc_pkcs_decode_identifier(client->data.public_key->identifier);
2268       
2269       if (pident) {
2270         newusername = silc_calloc(strlen(username) + 
2271                                   strlen(pident->host) + 2,
2272                                   sizeof(*newusername));
2273         strncat(newusername, username, strlen(username));
2274         strncat(newusername, "@", 1);
2275         strncat(newusername, pident->host, strlen(pident->host));
2276         silc_free(username);
2277         username = newusername;
2278         silc_pkcs_free_identifier(pident);
2279       }
2280     }
2281 #endif
2282   }
2283
2284   /* Create Client ID */
2285   while (!silc_id_create_client_id(server, server->id, server->rng, 
2286                                    server->md5hash, nickname, &client_id)) {
2287     nickfail++;
2288     if (nickfail > 9) {
2289       silc_server_disconnect_remote(server, sock, 
2290                                     SILC_STATUS_ERR_BAD_NICKNAME, NULL);
2291       if (sock->user_data)
2292         silc_server_free_sock_user_data(server, sock, NULL);
2293       return NULL;
2294     }
2295     snprintf(&nickname[strlen(nickname) - 1], 1, "%d", nickfail);
2296   }
2297
2298   /* If client marked as anonymous, scramble the username and hostname */
2299   if (client->mode & SILC_UMODE_ANONYMOUS) {
2300     char *scramble;
2301
2302     if (strlen(username) >= 2) {
2303       username[0] = silc_rng_get_byte_fast(server->rng);
2304       username[1] = silc_rng_get_byte_fast(server->rng);
2305     }
2306
2307     scramble = silc_hash_babbleprint(server->sha1hash, username,
2308                                      strlen(username));
2309     scramble[5] = '@';
2310     scramble[11] = '.';
2311     memcpy(&scramble[16], ".silc", 5);
2312     scramble[21] = '\0';
2313     silc_free(username);
2314     username = scramble;
2315   }
2316
2317   /* Update client entry */
2318   idata->status |= SILC_IDLIST_STATUS_REGISTERED;
2319   client->nickname = nickname;
2320   client->username = username;
2321   client->userinfo = realname ? realname : strdup(username);
2322   client->id = client_id;
2323   id_len = silc_id_get_len(client_id, SILC_ID_CLIENT);
2324
2325   /* Add the client again to the ID cache */
2326   silc_idcache_add(server->local_list->clients, client->nickname,
2327                    client_id, client, 0, NULL);
2328
2329   /* Notify our router about new client on the SILC network */
2330   silc_server_send_new_id(server, SILC_PRIMARY_ROUTE(server),
2331                           SILC_BROADCAST(server), client->id,
2332                           SILC_ID_CLIENT, id_len);
2333
2334   /* Distribute to backup routers */
2335   if (server->server_type == SILC_ROUTER) {
2336     SilcBuffer idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2337     silc_server_backup_send(server, sock->user_data, SILC_PACKET_NEW_ID, 0,
2338                             idp->data, idp->len, FALSE, TRUE);
2339     silc_buffer_free(idp);
2340   }
2341
2342   /* Send the new client ID to the client. */
2343   silc_server_send_new_id(server, sock, FALSE, client->id, SILC_ID_CLIENT,
2344                           silc_id_get_len(client->id, SILC_ID_CLIENT));
2345
2346   /* Send some nice info to the client */
2347   silc_server_send_connect_notifys(server, sock, client);
2348
2349   /* Check if anyone is watching this nickname */
2350   if (server->server_type == SILC_ROUTER)
2351     silc_server_check_watcher_list(server, client, NULL, 0);
2352
2353   return client;
2354 }
2355
2356 /* Create new server. This processes received New Server packet and
2357    saves the received Server ID. The server is our locally connected
2358    server thus we save all the information and save it to local list. 
2359    This funtion can be used by both normal server and router server.
2360    If normal server uses this it means that its router has connected
2361    to the server. If router uses this it means that one of the cell's
2362    servers is connected to the router. */
2363
2364 SilcServerEntry silc_server_new_server(SilcServer server,
2365                                        SilcSocketConnection sock,
2366                                        SilcPacketContext *packet)
2367 {
2368   SilcBuffer buffer = packet->buffer;
2369   SilcServerEntry new_server, server_entry;
2370   SilcServerID *server_id;
2371   SilcIDListData idata;
2372   unsigned char *server_name, *id_string;
2373   SilcUInt16 id_len, name_len;
2374   int ret;
2375   bool local = TRUE;
2376
2377   SILC_LOG_DEBUG(("Creating new server"));
2378
2379   if (sock->type != SILC_SOCKET_TYPE_SERVER &&
2380       sock->type != SILC_SOCKET_TYPE_ROUTER)
2381     return NULL;
2382
2383   /* Take server entry */
2384   new_server = (SilcServerEntry)sock->user_data;
2385   idata = (SilcIDListData)new_server;
2386
2387   /* Remove the old cache entry */
2388   if (!silc_idcache_del_by_context(server->local_list->servers, new_server)) {
2389     if (!silc_idcache_del_by_context(server->global_list->servers, 
2390                                      new_server)) {
2391       SILC_LOG_INFO(("Unauthenticated %s attempted to register to "
2392                      "network", (sock->type == SILC_SOCKET_TYPE_SERVER ?
2393                                  "server" : "router")));
2394       silc_server_disconnect_remote(server, sock, 
2395                                     SILC_STATUS_ERR_NOT_AUTHENTICATED, NULL);
2396       if (sock->user_data)
2397         silc_server_free_sock_user_data(server, sock, NULL);
2398       return NULL;
2399     }
2400     local = FALSE;
2401   }
2402
2403   /* Parse the incoming packet */
2404   ret = silc_buffer_unformat(buffer,
2405                              SILC_STR_UI16_NSTRING_ALLOC(&id_string, &id_len),
2406                              SILC_STR_UI16_NSTRING_ALLOC(&server_name, 
2407                                                          &name_len),
2408                              SILC_STR_END);
2409   if (ret == -1) {
2410     silc_free(id_string);
2411     silc_free(server_name);
2412     silc_server_disconnect_remote(server, sock, 
2413                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2414                                   NULL);
2415     if (sock->user_data)
2416       silc_server_free_sock_user_data(server, sock, NULL);
2417     return NULL;
2418   }
2419
2420   if (id_len > buffer->len) {
2421     silc_free(id_string);
2422     silc_free(server_name);
2423     silc_server_disconnect_remote(server, sock, 
2424                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2425                                   NULL);
2426     if (sock->user_data)
2427       silc_server_free_sock_user_data(server, sock, NULL);
2428     return NULL;
2429   }
2430
2431   if (name_len > 256)
2432     server_name[255] = '\0';
2433
2434   /* Get Server ID */
2435   server_id = silc_id_str2id(id_string, id_len, SILC_ID_SERVER);
2436   if (!server_id) {
2437     silc_free(id_string);
2438     silc_free(server_name);
2439     silc_server_disconnect_remote(server, sock, 
2440                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2441                                   NULL);
2442     if (sock->user_data)
2443       silc_server_free_sock_user_data(server, sock, NULL);
2444     return NULL;
2445   }
2446   silc_free(id_string);
2447
2448   /* Check for valid server ID */
2449   if (!silc_id_is_valid_server_id(server, server_id, sock)) {
2450     SILC_LOG_INFO(("Invalid server ID sent by %s (%s)",
2451                    sock->ip, sock->hostname));
2452     silc_server_disconnect_remote(server, sock, 
2453                                   SILC_STATUS_ERR_BAD_SERVER_ID, NULL);
2454     if (sock->user_data)
2455       silc_server_free_sock_user_data(server, sock, NULL);
2456     silc_free(server_name);
2457     return NULL;
2458   }
2459
2460   /* Check that we do not have this ID already */
2461   server_entry = silc_idlist_find_server_by_id(server->local_list, 
2462                                                server_id, TRUE, NULL);
2463   if (server_entry) {
2464     silc_idcache_del_by_context(server->local_list->servers, server_entry);
2465   } else {
2466     server_entry = silc_idlist_find_server_by_id(server->global_list, 
2467                                                  server_id, TRUE, NULL);
2468     if (server_entry) 
2469       silc_idcache_del_by_context(server->global_list->servers, server_entry);
2470   }
2471
2472   /* Update server entry */
2473   idata->status |= SILC_IDLIST_STATUS_REGISTERED;
2474   new_server->server_name = server_name;
2475   new_server->id = server_id;
2476   
2477   SILC_LOG_DEBUG(("New server id(%s)",
2478                   silc_id_render(server_id, SILC_ID_SERVER)));
2479
2480   /* Add again the entry to the ID cache. */
2481   silc_idcache_add(local ? server->local_list->servers : 
2482                    server->global_list->servers, server_name, server_id, 
2483                    new_server, 0, NULL);
2484
2485   /* Distribute the information about new server in the SILC network
2486      to our router. If we are normal server we won't send anything
2487      since this connection must be our router connection. */
2488   if (server->server_type == SILC_ROUTER && !server->standalone &&
2489       SILC_PRIMARY_ROUTE(server) != sock)
2490     silc_server_send_new_id(server, SILC_PRIMARY_ROUTE(server),
2491                             TRUE, new_server->id, SILC_ID_SERVER, 
2492                             silc_id_get_len(server_id, SILC_ID_SERVER));
2493
2494   if (server->server_type == SILC_ROUTER) {
2495     /* Distribute to backup routers */
2496     SilcBuffer idp = silc_id_payload_encode(new_server->id, SILC_ID_SERVER);
2497     silc_server_backup_send(server, sock->user_data, SILC_PACKET_NEW_ID, 0,
2498                             idp->data, idp->len, FALSE, TRUE);
2499     silc_buffer_free(idp);
2500
2501     /* Statistics */
2502     server->stat.cell_servers++;
2503   }
2504
2505   /* Check whether this router connection has been replaced by an
2506      backup router. If it has been then we'll disable the server and will
2507      ignore everything it will send until the backup router resuming
2508      protocol has been completed. */
2509   if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
2510       silc_server_backup_replaced_get(server, server_id, NULL)) {
2511     /* Send packet to the server indicating that it cannot use this
2512        connection as it has been replaced by backup router. */
2513     SilcBuffer packet = silc_buffer_alloc(2);
2514     silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
2515     silc_buffer_format(packet,
2516                        SILC_STR_UI_CHAR(SILC_SERVER_BACKUP_REPLACED),
2517                        SILC_STR_UI_CHAR(0),
2518                        SILC_STR_END);
2519     silc_server_packet_send(server, sock, 
2520                             SILC_PACKET_RESUME_ROUTER, 0, 
2521                             packet->data, packet->len, TRUE);
2522     silc_buffer_free(packet);
2523
2524     /* Mark the router disabled. The data sent earlier will go but nothing
2525        after this does not go to this connection. */
2526     idata->status |= SILC_IDLIST_STATUS_DISABLED;
2527   } else {
2528     /* If it is router announce our stuff to it. */
2529     if (sock->type == SILC_SOCKET_TYPE_ROUTER && 
2530         server->server_type == SILC_ROUTER) {
2531       silc_server_announce_servers(server, FALSE, 0, sock);
2532       silc_server_announce_clients(server, 0, sock);
2533       silc_server_announce_channels(server, 0, sock);
2534     }
2535
2536     /* Announce our information to backup router */
2537     if (new_server->server_type == SILC_BACKUP_ROUTER &&
2538         sock->type == SILC_SOCKET_TYPE_SERVER &&
2539         server->server_type == SILC_ROUTER) {
2540       silc_server_announce_servers(server, TRUE, 0, sock);
2541       silc_server_announce_clients(server, 0, sock);
2542       silc_server_announce_channels(server, 0, sock);
2543     }
2544
2545     /* If backup router, mark it as one of ours.  This server is considered
2546        to be backup router after this setting. */
2547     if (new_server->server_type == SILC_BACKUP_ROUTER) {
2548       SilcServerConfigRouter *backup;
2549       backup = silc_server_config_find_backup_conn(server, sock->ip);
2550       if (!backup)
2551         backup = silc_server_config_find_backup_conn(server, sock->hostname);
2552       if (backup) {
2553         /* Add as our backup router */
2554         silc_server_backup_add(server, new_server, backup->backup_replace_ip,
2555                                backup->backup_replace_port,
2556                                backup->backup_local);
2557       }
2558     }
2559
2560     /* By default the servers connected to backup router are disabled
2561        until backup router has become the primary */
2562     if (server->server_type == SILC_BACKUP_ROUTER &&
2563         sock->type == SILC_SOCKET_TYPE_SERVER)
2564       idata->status |= SILC_IDLIST_STATUS_DISABLED;
2565   }
2566
2567   return new_server;
2568 }
2569
2570 /* Processes incoming New ID packet. New ID Payload is used to distribute
2571    information about newly registered clients and servers. */
2572
2573 static void silc_server_new_id_real(SilcServer server, 
2574                                     SilcSocketConnection sock,
2575                                     SilcPacketContext *packet,
2576                                     int broadcast)
2577 {
2578   SilcBuffer buffer = packet->buffer;
2579   SilcIDList id_list;
2580   SilcServerEntry router, server_entry;
2581   SilcSocketConnection router_sock;
2582   SilcIDPayload idp;
2583   SilcIdType id_type;
2584   void *id;
2585
2586   SILC_LOG_DEBUG(("Processing new ID"));
2587
2588   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
2589       server->server_type == SILC_SERVER ||
2590       packet->src_id_type != SILC_ID_SERVER)
2591     return;
2592
2593   idp = silc_id_payload_parse(buffer->data, buffer->len);
2594   if (!idp)
2595     return;
2596
2597   id_type = silc_id_payload_get_type(idp);
2598
2599   /* Normal server cannot have other normal server connections */
2600   server_entry = (SilcServerEntry)sock->user_data;
2601   if (id_type == SILC_ID_SERVER && sock->type == SILC_SOCKET_TYPE_SERVER &&
2602       server_entry->server_type == SILC_SERVER)
2603     goto out;
2604
2605   id = silc_id_payload_get_id(idp);
2606   if (!id)
2607     goto out;
2608
2609   /* If the packet is coming from server then use the sender as the
2610      origin of the the packet. If it came from router then check the real
2611      sender of the packet and use that as the origin. */
2612   if (sock->type == SILC_SOCKET_TYPE_SERVER) {
2613     id_list = server->local_list;
2614     router_sock = sock;
2615     router = sock->user_data;
2616
2617     /* If the sender is backup router and ID is server (and we are not
2618        backup router) then switch the entry to global list. */
2619     if (server_entry->server_type == SILC_BACKUP_ROUTER && 
2620         id_type == SILC_ID_SERVER && 
2621         server->id_entry->server_type != SILC_BACKUP_ROUTER) {
2622       id_list = server->global_list;
2623       router_sock = server->router ? SILC_PRIMARY_ROUTE(server) : sock;
2624     }
2625   } else {
2626     void *sender_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2627                                      packet->src_id_type);
2628     router = silc_idlist_find_server_by_id(server->global_list,
2629                                            sender_id, TRUE, NULL);
2630     if (!router)
2631       router = silc_idlist_find_server_by_id(server->local_list,
2632                                              sender_id, TRUE, NULL);
2633     silc_free(sender_id);
2634     router_sock = sock;
2635     id_list = server->global_list;
2636   }
2637
2638   if (!router)
2639     goto out;
2640
2641   switch(id_type) {
2642   case SILC_ID_CLIENT:
2643     {
2644       SilcClientEntry entry;
2645
2646       /* Check that we do not have this client already */
2647       entry = silc_idlist_find_client_by_id(server->global_list, 
2648                                             id, server->server_type, 
2649                                             NULL);
2650       if (!entry)
2651         entry = silc_idlist_find_client_by_id(server->local_list, 
2652                                               id, server->server_type,
2653                                               NULL);
2654       if (entry) {
2655         SILC_LOG_DEBUG(("Ignoring client that we already have"));
2656         goto out;
2657       }
2658
2659       SILC_LOG_DEBUG(("New client id(%s) from [%s] %s",
2660                       silc_id_render(id, SILC_ID_CLIENT),
2661                       sock->type == SILC_SOCKET_TYPE_SERVER ?
2662                       "Server" : "Router", sock->hostname));
2663     
2664       /* As a router we keep information of all global information in our
2665          global list. Cell wide information however is kept in the local
2666          list. */
2667       entry = silc_idlist_add_client(id_list, NULL, NULL, NULL, 
2668                                      id, router, NULL, 0);
2669       if (!entry) {
2670         SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
2671
2672         /* Inform the sender that the ID is not usable */
2673         silc_server_send_notify_signoff(server, sock, FALSE, id, NULL);
2674         goto out;
2675       }
2676       entry->nickname = NULL;
2677       entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
2678
2679       if (sock->type == SILC_SOCKET_TYPE_SERVER)
2680         server->stat.cell_clients++;
2681       server->stat.clients++;
2682
2683       /* Check if anyone is watching this nickname */
2684       if (server->server_type == SILC_ROUTER && id_list == server->local_list)
2685         silc_server_check_watcher_list(server, entry, NULL, 0);
2686     }
2687     break;
2688
2689   case SILC_ID_SERVER:
2690     {
2691       SilcServerEntry entry;
2692
2693       /* If the ID is mine, ignore it. */
2694       if (SILC_ID_SERVER_COMPARE(id, server->id)) {
2695         SILC_LOG_DEBUG(("Ignoring my own ID as new ID"));
2696         break;
2697       }
2698
2699       /* If the ID is the sender's ID, ignore it (we have it already) */
2700       if (SILC_ID_SERVER_COMPARE(id, router->id)) {
2701         SILC_LOG_DEBUG(("Ignoring sender's own ID"));
2702         break;
2703       }
2704       
2705       /* Check that we do not have this server already */
2706       entry = silc_idlist_find_server_by_id(server->global_list, 
2707                                             id, server->server_type, 
2708                                             NULL);
2709       if (!entry)
2710         entry = silc_idlist_find_server_by_id(server->local_list, 
2711                                               id, server->server_type,
2712                                               NULL);
2713       if (entry) {
2714         SILC_LOG_DEBUG(("Ignoring server that we already have"));
2715         goto out;
2716       }
2717
2718       SILC_LOG_DEBUG(("New server id(%s) from [%s] %s",
2719                       silc_id_render(id, SILC_ID_SERVER),
2720                       sock->type == SILC_SOCKET_TYPE_SERVER ?
2721                       "Server" : "Router", sock->hostname));
2722       
2723       /* As a router we keep information of all global information in our 
2724          global list. Cell wide information however is kept in the local
2725          list. */
2726       entry = silc_idlist_add_server(id_list, NULL, 0, id, router, 
2727                                      router_sock);
2728       if (!entry) {
2729         SILC_LOG_ERROR(("Could not add new server to the ID Cache"));
2730         goto out;
2731       }
2732       entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
2733       
2734       if (sock->type == SILC_SOCKET_TYPE_SERVER)
2735         server->stat.cell_servers++;
2736       server->stat.servers++;
2737     }
2738     break;
2739
2740   case SILC_ID_CHANNEL:
2741     SILC_LOG_ERROR(("Channel cannot be registered with NEW_ID packet"));
2742     goto out;
2743     break;
2744
2745   default:
2746     goto out;
2747     break;
2748   }
2749
2750   /* If the sender of this packet is server and we are router we need to
2751      broadcast this packet to other routers in the network. */
2752   if (broadcast && server->server_type == SILC_ROUTER &&
2753       sock->type == SILC_SOCKET_TYPE_SERVER &&
2754       !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
2755     SILC_LOG_DEBUG(("Broadcasting received New ID packet"));
2756     silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
2757                             packet->type, 
2758                             packet->flags | SILC_PACKET_FLAG_BROADCAST,
2759                             buffer->data, buffer->len, FALSE);
2760     silc_server_backup_send(server, sock->user_data, 
2761                             packet->type, packet->flags,
2762                             packet->buffer->data, packet->buffer->len, 
2763                             FALSE, TRUE);
2764   }
2765
2766  out:
2767   silc_id_payload_free(idp);
2768 }
2769
2770
2771 /* Processes incoming New ID packet. New ID Payload is used to distribute
2772    information about newly registered clients and servers. */
2773
2774 void silc_server_new_id(SilcServer server, SilcSocketConnection sock,
2775                         SilcPacketContext *packet)
2776 {
2777   silc_server_new_id_real(server, sock, packet, TRUE);
2778 }
2779
2780 /* Receoved New Id List packet, list of New ID payloads inside one
2781    packet. Process the New ID payloads one by one. */
2782
2783 void silc_server_new_id_list(SilcServer server, SilcSocketConnection sock,
2784                              SilcPacketContext *packet)
2785 {
2786   SilcPacketContext *new_id;
2787   SilcBuffer idp;
2788   SilcUInt16 id_len;
2789
2790   SILC_LOG_DEBUG(("Processing New ID List"));
2791
2792   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
2793       packet->src_id_type != SILC_ID_SERVER)
2794     return;
2795
2796   /* If the sender of this packet is server and we are router we need to
2797      broadcast this packet to other routers in the network. Broadcast
2798      this list packet instead of multiple New ID packets. */
2799   if (server->server_type == SILC_ROUTER &&
2800       sock->type == SILC_SOCKET_TYPE_SERVER &&
2801       !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
2802     SILC_LOG_DEBUG(("Broadcasting received New ID List packet"));
2803     silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
2804                             packet->type, 
2805                             packet->flags | SILC_PACKET_FLAG_BROADCAST,
2806                             packet->buffer->data, 
2807                             packet->buffer->len, FALSE);
2808     silc_server_backup_send(server, sock->user_data, 
2809                             packet->type, packet->flags,
2810                             packet->buffer->data, packet->buffer->len, 
2811                             FALSE, TRUE);
2812   }
2813
2814   /* Make copy of the original packet context, except for the actual
2815      data buffer, which we will here now fetch from the original buffer. */
2816   new_id = silc_packet_context_alloc();
2817   new_id->type = SILC_PACKET_NEW_ID;
2818   new_id->flags = packet->flags & (~SILC_PACKET_FLAG_LIST);
2819   new_id->src_id = packet->src_id;
2820   new_id->src_id_len = packet->src_id_len;
2821   new_id->src_id_type = packet->src_id_type;
2822   new_id->dst_id = packet->dst_id;
2823   new_id->dst_id_len = packet->dst_id_len;
2824   new_id->dst_id_type = packet->dst_id_type;
2825
2826   idp = silc_buffer_alloc(256);
2827   new_id->buffer = idp;
2828
2829   while (packet->buffer->len) {
2830     SILC_GET16_MSB(id_len, packet->buffer->data + 2);
2831     if ((id_len > packet->buffer->len) ||
2832         (id_len > idp->truelen))
2833       break;
2834
2835     silc_buffer_pull_tail(idp, 4 + id_len);
2836     silc_buffer_put(idp, packet->buffer->data, 4 + id_len);
2837
2838     /* Process the New ID */
2839     silc_server_new_id_real(server, sock, new_id, FALSE);
2840
2841     silc_buffer_push_tail(idp, 4 + id_len);
2842     silc_buffer_pull(packet->buffer, 4 + id_len);
2843   }
2844
2845   silc_buffer_free(idp);
2846   silc_free(new_id);
2847 }
2848
2849 /* Received New Channel packet. Information about new channels in the 
2850    network are distributed using this packet. Save the information about
2851    the new channel. This usually comes from router but also normal server
2852    can send this to notify channels it has when it connects to us. */
2853
2854 void silc_server_new_channel(SilcServer server,
2855                              SilcSocketConnection sock,
2856                              SilcPacketContext *packet)
2857 {
2858   SilcChannelPayload payload;
2859   SilcChannelID *channel_id;
2860   char *channel_name;
2861   SilcUInt32 name_len;
2862   unsigned char *id;
2863   SilcUInt32 id_len, cipher_len;
2864   SilcServerEntry server_entry;
2865   SilcChannelEntry channel;
2866   const char *cipher;
2867
2868   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
2869       packet->src_id_type != SILC_ID_SERVER ||
2870       server->server_type == SILC_SERVER)
2871     return;
2872
2873   /* Parse the channel payload */
2874   payload = silc_channel_payload_parse(packet->buffer->data,
2875                                        packet->buffer->len);
2876   if (!payload)
2877     return;
2878     
2879   /* Get the channel ID */
2880   channel_id = silc_channel_get_id_parse(payload);
2881   if (!channel_id) {
2882     silc_channel_payload_free(payload);
2883     return;
2884   }
2885
2886   channel_name = silc_channel_get_name(payload, &name_len);
2887   if (name_len > 256)
2888     channel_name[255] = '\0';
2889
2890   id = silc_channel_get_id(payload, &id_len);
2891
2892   server_entry = (SilcServerEntry)sock->user_data;
2893
2894   if (sock->type == SILC_SOCKET_TYPE_ROUTER) {
2895     /* Add the channel to global list as it is coming from router. It 
2896        cannot be our own channel as it is coming from router. */
2897
2898     /* Check that we don't already have this channel */
2899     channel = silc_idlist_find_channel_by_name(server->local_list, 
2900                                                channel_name, NULL);
2901     if (!channel)
2902       channel = silc_idlist_find_channel_by_name(server->global_list, 
2903                                                  channel_name, NULL);
2904     if (!channel) {
2905       SILC_LOG_DEBUG(("New channel id(%s) from [Router] %s",
2906                       silc_id_render(channel_id, SILC_ID_CHANNEL), 
2907                       sock->hostname));
2908     
2909       channel = 
2910         silc_idlist_add_channel(server->global_list, strdup(channel_name), 
2911                                 0, channel_id, sock->user_data, NULL, NULL, 0);
2912       if (!channel) {
2913         silc_channel_payload_free(payload);
2914         silc_free(channel_id);
2915         return;
2916       }
2917       channel->disabled = TRUE;    /* Disabled until someone JOINs */
2918
2919       server->stat.channels++;
2920       if (server->server_type == SILC_ROUTER)
2921         channel->users_resolved = TRUE;
2922     }
2923   } else {
2924     /* The channel is coming from our server, thus it is in our cell
2925        we will add it to our local list. */
2926     SilcBuffer chk;
2927
2928     SILC_LOG_DEBUG(("Channel id(%s) from [Server] %s",
2929                     silc_id_render(channel_id, SILC_ID_CHANNEL), 
2930                     sock->hostname));
2931
2932     /* Check that we don't already have this channel */
2933     channel = silc_idlist_find_channel_by_name(server->local_list, 
2934                                                channel_name, NULL);
2935     if (!channel)
2936       channel = silc_idlist_find_channel_by_name(server->global_list, 
2937                                                  channel_name, NULL);
2938
2939     /* If the channel does not exist, then create it. This creates a new
2940        key to the channel as well that we will send to the server. */
2941     if (!channel) {
2942       SILC_LOG_DEBUG(("Channel is new to us"));
2943
2944       /* The protocol says that the Channel ID's IP address must be based
2945          on the router's IP address.  Check whether the ID is based in our
2946          IP and if it is not then create a new ID and enforce the server
2947          to switch the ID. */
2948       if (server_entry->server_type != SILC_BACKUP_ROUTER &&
2949           !SILC_ID_COMPARE(channel_id, server->id, server->id->ip.data_len)) {
2950         SilcChannelID *tmp;
2951         SILC_LOG_DEBUG(("Forcing the server to change Channel ID"));
2952         if (silc_id_create_channel_id(server, server->id, server->rng, &tmp)) {
2953           silc_server_send_notify_channel_change(server, sock, FALSE, 
2954                                                  channel_id, tmp);
2955           silc_channel_payload_free(payload);
2956           silc_free(channel_id);
2957           silc_free(tmp);
2958         }
2959
2960         /* Wait that server re-announces this channel */
2961         return;
2962       }
2963
2964       /* Create the channel with the provided Channel ID */
2965       channel = silc_server_create_new_channel_with_id(server, NULL, NULL,
2966                                                        channel_name,
2967                                                        channel_id, FALSE);
2968       if (!channel) {
2969         silc_channel_payload_free(payload);
2970         silc_free(channel_id);
2971         return;
2972       }
2973       channel->disabled = TRUE;    /* Disabled until someone JOINs */
2974
2975 #if 0 /* We assume that CMODE_CHANGE notify is sent to us after this. */
2976
2977       /* XXX Dunno if this is supposed to be set in any server type.  If set
2978          here the CMODE_CHANGE that may follow sets mode that we already
2979          have, and we may loose data from the CMODE_CHANGE notify. */
2980       if (server_entry->server_type != SILC_BACKUP_ROUTER)
2981         channel->mode = silc_channel_get_mode(payload);
2982 #endif
2983
2984       /* Send the new channel key to the server */
2985       id = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
2986       id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
2987       cipher = silc_cipher_get_name(channel->channel_key);
2988       cipher_len = strlen(cipher);
2989       chk = silc_channel_key_payload_encode(id_len, id,
2990                                             cipher_len, cipher,
2991                                             channel->key_len / 8, 
2992                                             channel->key);
2993       silc_server_packet_send(server, sock, SILC_PACKET_CHANNEL_KEY, 0, 
2994                               chk->data, chk->len, FALSE);
2995       silc_buffer_free(chk);
2996       silc_free(id);
2997     } else {
2998       /* The channel exist by that name, check whether the ID's match.
2999          If they don't then we'll force the server to use the ID we have.
3000          We also create a new key for the channel. */
3001       SilcBuffer modes = NULL, users = NULL, users_modes = NULL;
3002
3003       SILC_LOG_DEBUG(("Channel already exists"));
3004
3005       if (!SILC_ID_CHANNEL_COMPARE(channel_id, channel->id)) {
3006         /* They don't match, send CHANNEL_CHANGE notify to the server to
3007            force the ID change. */
3008         SILC_LOG_DEBUG(("Forcing the server to change Channel ID"));
3009         silc_server_send_notify_channel_change(server, sock, FALSE, 
3010                                                channel_id, channel->id);
3011         silc_channel_payload_free(payload);
3012         silc_free(channel_id);
3013
3014         /* Wait that server re-announces this channel */
3015         return;
3016       }
3017
3018 #if 0 /* We will announce our CMODE anyway for this channel, so no need
3019          to check it (implicit enforce). */
3020
3021       /* If the mode is different from what we have then enforce the
3022          mode change. */
3023       mode = silc_channel_get_mode(payload);
3024       if (channel->mode != mode) {
3025         SILC_LOG_DEBUG(("Forcing the server to change channel mode"));
3026         silc_server_send_notify_cmode(server, sock, FALSE, channel,
3027                                       channel->mode, server->id,
3028                                       SILC_ID_SERVER, channel->cipher,
3029                                       channel->hmac_name,
3030                                       channel->passphrase,
3031                                       channel->founder_key);
3032       }
3033 #endif
3034
3035       /* Create new key for the channel and send it to the server and
3036          everybody else possibly on the channel. */
3037       if (!(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
3038
3039         if (silc_hash_table_count(channel->user_list)) {
3040           if (!silc_server_create_channel_key(server, channel, 0)) {
3041             silc_channel_payload_free(payload);
3042             silc_free(channel_id);
3043             return;
3044           }
3045
3046           /* Send to the channel */
3047           silc_server_send_channel_key(server, sock, channel, FALSE);
3048         }
3049
3050         /* Send to the server */
3051         id = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3052         id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3053         cipher = silc_cipher_get_name(channel->channel_key);
3054         cipher_len = strlen(cipher);
3055         chk = silc_channel_key_payload_encode(id_len, id,
3056                                               cipher_len, cipher,
3057                                               channel->key_len / 8, 
3058                                               channel->key);
3059         silc_server_packet_send(server, sock, SILC_PACKET_CHANNEL_KEY, 0, 
3060                                 chk->data, chk->len, FALSE);
3061         silc_buffer_free(chk);
3062         silc_free(id);
3063       }
3064
3065       silc_free(channel_id);
3066
3067       /* Since the channel is coming from server and we also know about it
3068          then send the JOIN notify to the server so that it see's our
3069          users on the channel "joining" the channel. */
3070       silc_server_announce_get_channel_users(server, channel, &modes, &users,
3071                                              &users_modes);
3072       if (users) {
3073         silc_buffer_push(users, users->data - users->head);
3074         silc_server_packet_send(server, sock,
3075                                 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3076                                 users->data, users->len, FALSE);
3077         silc_buffer_free(users);
3078       }
3079       if (modes) {
3080         silc_buffer_push(modes, modes->data - modes->head);
3081         silc_server_packet_send_dest(server, sock,
3082                                      SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3083                                      channel->id, SILC_ID_CHANNEL,
3084                                      modes->data, modes->len, FALSE);
3085         silc_buffer_free(modes);
3086       }
3087       if (users_modes) {
3088         silc_buffer_push(users_modes, users_modes->data - users_modes->head);
3089         silc_server_packet_send_dest(server, sock,
3090                                      SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3091                                      channel->id, SILC_ID_CHANNEL,
3092                                      users_modes->data, 
3093                                      users_modes->len, FALSE);
3094         silc_buffer_free(users_modes);
3095       }
3096       if (channel->topic) {
3097         silc_server_send_notify_topic_set(server, sock,
3098                                           server->server_type == SILC_ROUTER ?
3099                                           TRUE : FALSE, channel, 
3100                                           server->id, SILC_ID_SERVER,
3101                                           channel->topic);
3102       }
3103     }
3104   }
3105
3106   /* If the sender of this packet is server and we are router we need to
3107      broadcast this packet to other routers in the network. Broadcast
3108      this list packet instead of multiple New Channel packets. */
3109   if (server->server_type == SILC_ROUTER &&
3110       sock->type == SILC_SOCKET_TYPE_SERVER &&
3111       !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
3112     SILC_LOG_DEBUG(("Broadcasting received New Channel packet"));
3113     silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
3114                             packet->type, 
3115                             packet->flags | SILC_PACKET_FLAG_BROADCAST,
3116                             packet->buffer->data, 
3117                             packet->buffer->len, FALSE);
3118     silc_server_backup_send(server, sock->user_data, 
3119                             packet->type, packet->flags,
3120                             packet->buffer->data, packet->buffer->len, 
3121                             FALSE, TRUE);
3122   }
3123
3124   silc_channel_payload_free(payload);
3125 }
3126
3127 /* Received New Channel List packet, list of New Channel List payloads inside
3128    one packet. Process the New Channel payloads one by one. */
3129
3130 void silc_server_new_channel_list(SilcServer server,
3131                                   SilcSocketConnection sock,
3132                                   SilcPacketContext *packet)
3133 {
3134   SilcPacketContext *new;
3135   SilcBuffer buffer;
3136   SilcUInt16 len1, len2;
3137
3138   SILC_LOG_DEBUG(("Processing New Channel List"));
3139
3140   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
3141       packet->src_id_type != SILC_ID_SERVER ||
3142       server->server_type == SILC_SERVER)
3143     return;
3144
3145   /* Make copy of the original packet context, except for the actual
3146      data buffer, which we will here now fetch from the original buffer. */
3147   new = silc_packet_context_alloc();
3148   new->type = SILC_PACKET_NEW_CHANNEL;
3149   new->flags = packet->flags & (~SILC_PACKET_FLAG_LIST);
3150   new->src_id = packet->src_id;
3151   new->src_id_len = packet->src_id_len;
3152   new->src_id_type = packet->src_id_type;
3153   new->dst_id = packet->dst_id;
3154   new->dst_id_len = packet->dst_id_len;
3155   new->dst_id_type = packet->dst_id_type;
3156
3157   buffer = silc_buffer_alloc(512);
3158   new->buffer = buffer;
3159
3160   while (packet->buffer->len) {
3161     SILC_GET16_MSB(len1, packet->buffer->data);
3162     if ((len1 > packet->buffer->len) ||
3163         (len1 > buffer->truelen))
3164       break;
3165
3166     SILC_GET16_MSB(len2, packet->buffer->data + 2 + len1);
3167     if ((len2 > packet->buffer->len) ||
3168         (len2 > buffer->truelen))
3169       break;
3170
3171     silc_buffer_pull_tail(buffer, 8 + len1 + len2);
3172     silc_buffer_put(buffer, packet->buffer->data, 8 + len1 + len2);
3173
3174     /* Process the New Channel */
3175     silc_server_new_channel(server, sock, new);
3176
3177     silc_buffer_push_tail(buffer, 8 + len1 + len2);
3178     silc_buffer_pull(packet->buffer, 8 + len1 + len2);
3179   }
3180
3181   silc_buffer_free(buffer);
3182   silc_free(new);
3183 }
3184
3185 /* Received key agreement packet. This packet is never for us. It is to
3186    the client in the packet's destination ID. Sending of this sort of packet
3187    equals sending private message, ie. it is sent point to point from
3188    one client to another. */
3189
3190 void silc_server_key_agreement(SilcServer server,
3191                                SilcSocketConnection sock,
3192                                SilcPacketContext *packet)
3193 {
3194   SilcSocketConnection dst_sock;
3195   SilcIDListData idata;
3196
3197   SILC_LOG_DEBUG(("Start"));
3198
3199   if (packet->src_id_type != SILC_ID_CLIENT ||
3200       packet->dst_id_type != SILC_ID_CLIENT)
3201     return;
3202
3203   if (!packet->dst_id)
3204     return;
3205
3206   /* Get the route to the client */
3207   dst_sock = silc_server_get_client_route(server, packet->dst_id,
3208                                           packet->dst_id_len, NULL, 
3209                                           &idata, NULL);
3210   if (!dst_sock)
3211     return;
3212
3213   /* Relay the packet */
3214   silc_server_relay_packet(server, dst_sock, idata->send_key,
3215                            idata->hmac_send, idata->psn_send++,
3216                            packet, FALSE);
3217 }
3218
3219 /* Received connection auth request packet that is used during connection
3220    phase to resolve the mandatory authentication method.  This packet can
3221    actually be received at anytime but usually it is used only during
3222    the connection authentication phase. Now, protocol says that this packet
3223    can come from client or server, however, we support only this coming
3224    from client and expect that server always knows what authentication
3225    method to use. */
3226
3227 void silc_server_connection_auth_request(SilcServer server,
3228                                          SilcSocketConnection sock,
3229                                          SilcPacketContext *packet)
3230 {
3231   SilcServerConfigClient *client = NULL;
3232   SilcUInt16 conn_type;
3233   int ret;
3234   SilcAuthMethod auth_meth = SILC_AUTH_NONE;
3235
3236   if (packet->src_id_type && packet->src_id_type != SILC_ID_CLIENT) {
3237     SILC_LOG_DEBUG(("Request not from client"));
3238     return;
3239   }
3240
3241   /* Parse the payload */
3242   ret = silc_buffer_unformat(packet->buffer,
3243                              SILC_STR_UI_SHORT(&conn_type),
3244                              SILC_STR_UI_SHORT(NULL),
3245                              SILC_STR_END);
3246   if (ret == -1)
3247     return;
3248
3249   if (conn_type != SILC_SOCKET_TYPE_CLIENT)
3250     return;
3251
3252   /* Get the authentication method for the client */
3253   auth_meth = SILC_AUTH_NONE;
3254   client = silc_server_config_find_client(server, sock->ip);
3255   if (!client)
3256     client = silc_server_config_find_client(server, sock->hostname);
3257   if (client) {
3258     if (client->passphrase) {
3259       if (client->publickeys && !server->config->prefer_passphrase_auth)
3260         auth_meth = SILC_AUTH_PUBLIC_KEY;
3261       else
3262         auth_meth = SILC_AUTH_PASSWORD;
3263     } else if (client->publickeys)
3264       auth_meth = SILC_AUTH_PUBLIC_KEY;
3265   }
3266
3267   SILC_LOG_DEBUG(("Authentication method is [%s]",
3268                   (auth_meth == SILC_AUTH_NONE ? "None" :
3269                    auth_meth == SILC_AUTH_PASSWORD ? "Passphrase" :
3270                    "Digital signatures")));
3271
3272   /* Send it back to the client */
3273   silc_server_send_connection_auth_request(server, sock, conn_type, auth_meth);
3274 }
3275
3276 /* Received REKEY packet. The sender of the packet wants to regenerate
3277    its session keys. This starts the REKEY protocol. */
3278
3279 void silc_server_rekey(SilcServer server,
3280                        SilcSocketConnection sock,
3281                        SilcPacketContext *packet)
3282 {
3283   SilcProtocol protocol;
3284   SilcServerRekeyInternalContext *proto_ctx;
3285   SilcIDListData idata = (SilcIDListData)sock->user_data;
3286
3287   SILC_LOG_DEBUG(("Start"));
3288
3289   /* Allocate internal protocol context. This is sent as context
3290      to the protocol. */
3291   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
3292   proto_ctx->server = (void *)server;
3293   proto_ctx->sock = sock;
3294   proto_ctx->responder = TRUE;
3295   proto_ctx->pfs = idata->rekey->pfs;
3296       
3297   /* Perform rekey protocol. Will call the final callback after the
3298      protocol is over. */
3299   silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY, 
3300                       &protocol, proto_ctx, silc_server_rekey_final);
3301   sock->protocol = protocol;
3302
3303   if (proto_ctx->pfs == FALSE)
3304     /* Run the protocol */
3305     silc_protocol_execute(protocol, server->schedule, 0, 0);
3306 }
3307
3308 /* Received file transger packet. This packet is never for us. It is to
3309    the client in the packet's destination ID. Sending of this sort of packet
3310    equals sending private message, ie. it is sent point to point from
3311    one client to another. */
3312
3313 void silc_server_ftp(SilcServer server,
3314                      SilcSocketConnection sock,
3315                      SilcPacketContext *packet)
3316 {
3317   SilcSocketConnection dst_sock;
3318   SilcIDListData idata;
3319
3320   SILC_LOG_DEBUG(("Start"));
3321
3322   if (packet->src_id_type != SILC_ID_CLIENT ||
3323       packet->dst_id_type != SILC_ID_CLIENT)
3324     return;
3325
3326   if (!packet->dst_id)
3327     return;
3328
3329   /* Get the route to the client */
3330   dst_sock = silc_server_get_client_route(server, packet->dst_id,
3331                                           packet->dst_id_len, NULL, 
3332                                           &idata, NULL);
3333   if (!dst_sock)
3334     return;
3335
3336   /* Relay the packet */
3337   silc_server_relay_packet(server, dst_sock, idata->send_key,
3338                            idata->hmac_send, idata->psn_send++,
3339                            packet, FALSE);
3340 }
3341
3342 typedef struct {
3343   SilcServer server;
3344   SilcSocketConnection sock;
3345   SilcPacketContext *packet;
3346   void *data;
3347 } *SilcServerResumeResolve;
3348
3349 SILC_SERVER_CMD_FUNC(resume_resolve)
3350 {
3351   SilcServerResumeResolve r = (SilcServerResumeResolve)context;
3352   SilcServer server = r->server;
3353   SilcSocketConnection sock = r->sock;
3354   SilcServerCommandReplyContext reply = context2;
3355   SilcClientEntry client;
3356
3357   SILC_LOG_DEBUG(("Start"));
3358
3359   if (!reply || !silc_command_get_status(reply->payload, NULL, NULL)) {
3360     SILC_LOG_ERROR(("Client %s (%s) tried to resume unknown client, "
3361                     "closing connection", sock->hostname, sock->ip));
3362     silc_server_disconnect_remote(server, sock,
3363                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3364                                   "Resuming not possible");
3365     if (sock->user_data)
3366       silc_server_free_sock_user_data(server, sock, NULL);
3367     goto out;
3368   }
3369
3370   if (reply && silc_command_get(reply->payload) == SILC_COMMAND_WHOIS) {
3371     /* Get entry to the client, and resolve it if we don't have it. */
3372     client = silc_idlist_find_client_by_id(server->local_list, 
3373                                            r->data, TRUE, NULL);
3374     if (!client) {
3375       client = silc_idlist_find_client_by_id(server->global_list,
3376                                              r->data, TRUE, NULL);
3377       if (!client) {
3378         SILC_LOG_ERROR(("Client %s (%s) tried to resume unknown client, "
3379                         "closing connection", sock->hostname, sock->ip));
3380         silc_server_disconnect_remote(server, sock,
3381                                       SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3382                                       "Resuming not possible");
3383         if (sock->user_data)
3384           silc_server_free_sock_user_data(server, sock, NULL);
3385         goto out;
3386       }
3387     }
3388
3389     if (!(client->mode & SILC_UMODE_DETACHED)) {
3390       SILC_LOG_ERROR(("Client %s (%s) tried to resume un-detached client, "
3391                       "closing connection", sock->hostname, sock->ip));
3392       silc_server_disconnect_remote(server, sock,
3393                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3394                                     "Resuming not possible");
3395       if (sock->user_data)
3396         silc_server_free_sock_user_data(server, sock, NULL);
3397       goto out;
3398     }
3399
3400     client->data.status |= SILC_IDLIST_STATUS_RESUME_RES;
3401   }
3402
3403   /* Reprocess the packet */
3404   silc_server_resume_client(server, sock, r->packet);
3405
3406  out:
3407   silc_socket_free(r->sock);
3408   silc_packet_context_free(r->packet);
3409   silc_free(r->data);
3410   silc_free(r);
3411 }
3412
3413 /* Received client resuming packet.  This is used to resume detached
3414    client session.  It can be sent by the client who wishes to resume
3415    but this is also sent by servers and routers to notify other routers
3416    that the client is not detached anymore. */
3417
3418 void silc_server_resume_client(SilcServer server,
3419                                SilcSocketConnection sock,
3420                                SilcPacketContext *packet)
3421 {
3422   SilcBuffer buffer = packet->buffer, buf;
3423   SilcIDListData idata;
3424   SilcIDCacheEntry id_cache = NULL;
3425   SilcClientEntry detached_client;
3426   SilcClientID *client_id = NULL;
3427   unsigned char *id_string, *auth = NULL;
3428   SilcUInt16 id_len, auth_len = 0;
3429   int ret, nickfail = 0;
3430   bool resolved, local, nick_change = FALSE, resolve = FALSE;
3431   SilcChannelEntry channel;
3432   SilcHashTableList htl;
3433   SilcChannelClientEntry chl;
3434   SilcServerResumeResolve r;
3435   const char *cipher;
3436
3437   ret = silc_buffer_unformat(buffer,
3438                              SILC_STR_UI16_NSTRING(&id_string, &id_len),
3439                              SILC_STR_END);
3440   if (ret != -1)
3441     client_id = silc_id_str2id(id_string, id_len, SILC_ID_CLIENT);
3442
3443   if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
3444     /* Client send this and is attempting to resume to old client session */
3445     SilcClientEntry client;
3446     SilcBuffer keyp;
3447
3448     if (ret != -1) {
3449       silc_buffer_pull(buffer, 2 + id_len);
3450       auth = buffer->data;
3451       auth_len = buffer->len;
3452       silc_buffer_push(buffer, 2 + id_len);
3453     }
3454
3455     if (!client_id || auth_len < 128) {
3456       SILC_LOG_ERROR(("Client %s (%s) sent incomplete resume information, "
3457                       "closing connection", sock->hostname, sock->ip));
3458       silc_server_disconnect_remote(server, sock,
3459                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3460                                     "Resuming not possible");
3461       if (sock->user_data)
3462         silc_server_free_sock_user_data(server, sock, NULL);
3463       silc_free(client_id);
3464       return;
3465     }
3466
3467     /* Take client entry of this connection */
3468     client = (SilcClientEntry)sock->user_data;
3469     idata = (SilcIDListData)client;
3470
3471     /* Get entry to the client, and resolve it if we don't have it. */
3472     detached_client = silc_server_query_client(server, client_id, FALSE,
3473                                                &resolved);
3474     if (!detached_client) {
3475       if (resolved) {
3476         /* The client info is being resolved. Reprocess this packet after
3477            receiving the reply to the query. */
3478         SILC_LOG_DEBUG(("Resolving client"));
3479         r = silc_calloc(1, sizeof(*r));
3480         if (!r)
3481           return;
3482         r->server = server;
3483         r->sock = silc_socket_dup(sock);
3484         r->packet = silc_packet_context_dup(packet);
3485         r->data = client_id;
3486         silc_server_command_pending(server, SILC_COMMAND_WHOIS,
3487                                     server->cmd_ident,
3488                                     silc_server_command_resume_resolve, r);
3489       } else {
3490         SILC_LOG_ERROR(("Client %s (%s) tried to resume unknown client, "
3491                         "closing connection", sock->hostname, sock->ip));
3492         silc_server_disconnect_remote(server, sock,
3493                                       SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3494                                       "Resuming not possible");
3495         if (sock->user_data)
3496           silc_server_free_sock_user_data(server, sock, NULL);
3497         silc_free(client_id);
3498       }
3499       return;
3500     }
3501
3502     if (!(detached_client->mode & SILC_UMODE_DETACHED))
3503       resolve = TRUE;
3504     if (!silc_hash_table_count(detached_client->channels) &&
3505         detached_client->router)
3506       resolve = TRUE;
3507     if (!detached_client->nickname)
3508       resolve = TRUE;
3509     if (detached_client->data.status & SILC_IDLIST_STATUS_RESUME_RES)
3510       resolve = FALSE;
3511
3512     if (resolve) {
3513       if (server->server_type == SILC_SERVER && !server->standalone) {
3514         /* The client info is being resolved. Reprocess this packet after
3515            receiving the reply to the query. */
3516         SILC_LOG_DEBUG(("Resolving client info"));
3517         silc_server_query_client(server, client_id, TRUE, NULL);
3518         r = silc_calloc(1, sizeof(*r));
3519         if (!r)
3520           return;
3521         r->server = server;
3522         r->sock = silc_socket_dup(sock);
3523         r->packet = silc_packet_context_dup(packet);
3524         r->data = client_id;
3525         silc_server_command_pending(server, SILC_COMMAND_WHOIS,
3526                                     server->cmd_ident,
3527                                     silc_server_command_resume_resolve, r);
3528         return;
3529       }
3530       if (server->server_type == SILC_SERVER) {
3531         SILC_LOG_ERROR(("Client %s (%s) tried to resume un-detached client, "
3532                         "closing connection", sock->hostname, sock->ip));
3533         silc_server_disconnect_remote(server, sock,
3534                                       SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3535                                       "Resuming not possible");
3536         if (sock->user_data)
3537           silc_server_free_sock_user_data(server, sock, NULL);
3538         silc_free(client_id);
3539         return;
3540       }
3541     }
3542
3543     /* Check that we have the public key of the client, if not then we must
3544        resolve it first. */
3545     if (!detached_client->data.public_key) {
3546       if (server->server_type == SILC_SERVER && server->standalone) {
3547         SILC_LOG_ERROR(("Detached client's public key not present, "
3548                         "closing connection"));
3549         silc_server_disconnect_remote(server, sock,
3550                                       SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3551                                       "Resuming not possible");
3552         if (sock->user_data)
3553           silc_server_free_sock_user_data(server, sock, NULL);
3554         silc_free(client_id);
3555       } else {
3556         /* We must retrieve the detached client's public key by sending
3557            GETKEY command. Reprocess this packet after receiving the key */
3558         SilcBuffer idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
3559         SilcSocketConnection dest_sock = 
3560           silc_server_get_client_route(server, NULL, 0, client_id, NULL, NULL);
3561
3562         SILC_LOG_DEBUG(("Resolving client public key"));
3563
3564         silc_server_send_command(server, dest_sock ? dest_sock : 
3565                                  SILC_PRIMARY_ROUTE(server),
3566                                  SILC_COMMAND_GETKEY, ++server->cmd_ident,
3567                                  1, 1, idp->data, idp->len);
3568
3569         r = silc_calloc(1, sizeof(*r));
3570         if (!r) {
3571           silc_free(client_id);
3572           return;
3573         }
3574
3575         r->server = server;
3576         r->sock = silc_socket_dup(sock);
3577         r->packet = silc_packet_context_dup(packet);
3578         silc_server_command_pending(server, SILC_COMMAND_GETKEY,
3579                                     server->cmd_ident,
3580                                     silc_server_command_resume_resolve, r);
3581
3582         silc_buffer_free(idp);
3583       }
3584       silc_free(client_id);
3585       return;
3586     } else if (!silc_pkcs_public_key_compare(detached_client->data.public_key,
3587                                              idata->public_key)) {
3588       /* We require that the connection and resuming authentication data
3589          must be using same key pair. */
3590       SILC_LOG_ERROR(("Resuming attempted with wrong public key, "
3591                       "closing connection"));
3592       silc_server_disconnect_remote(server, sock,
3593                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3594                                     "Resuming not possible");
3595       if (sock->user_data)
3596         silc_server_free_sock_user_data(server, sock, NULL);
3597       silc_free(client_id);
3598       return;
3599     }
3600
3601     /* Verify the authentication payload.  This has to be successful in
3602        order to allow the resuming */
3603     if (!idata->hash ||
3604         !silc_auth_verify_data(auth, auth_len, SILC_AUTH_PUBLIC_KEY,
3605                                detached_client->data.public_key, 0,
3606                                idata->hash, detached_client->id, 
3607                                SILC_ID_CLIENT)) {
3608       SILC_LOG_ERROR(("Client %s (%s) resume authentication failed, "
3609                       "closing connection", sock->hostname, sock->ip));
3610       silc_server_disconnect_remote(server, sock,
3611                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3612                                     "Resuming not possible");
3613       if (sock->user_data)
3614         silc_server_free_sock_user_data(server, sock, NULL);
3615       silc_free(client_id);
3616       return;
3617     }
3618
3619     /* Now resume the client to the network */
3620
3621     silc_schedule_task_del_by_context(server->schedule, detached_client);
3622     sock->user_data = detached_client;
3623     detached_client->connection = sock;
3624
3625     /* Take new keys and stuff into use in the old entry */
3626     silc_idlist_del_data(detached_client);
3627     silc_idlist_add_data(detached_client, idata);
3628     detached_client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
3629     detached_client->data.status |= SILC_IDLIST_STATUS_RESUMED;
3630     detached_client->data.status |= SILC_IDLIST_STATUS_LOCAL;
3631     detached_client->data.status &= ~SILC_IDLIST_STATUS_RESUME_RES;
3632     detached_client->mode &= ~SILC_UMODE_DETACHED;
3633     server->stat.my_detached--;
3634
3635     /* Send the RESUME_CLIENT packet to our primary router so that others
3636        know this client isn't detached anymore. */
3637     buf = silc_buffer_alloc_size(2 + id_len);
3638     silc_buffer_format(buf,
3639                        SILC_STR_UI_SHORT(id_len),
3640                        SILC_STR_UI_XNSTRING(id_string, id_len),
3641                        SILC_STR_END);
3642
3643     /* Send to primary router */
3644     silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
3645                             SILC_PACKET_RESUME_CLIENT, 0, 
3646                             buf->data, buf->len, TRUE);
3647     silc_server_backup_send(server, detached_client->router,
3648                             SILC_PACKET_RESUME_CLIENT, 0,
3649                             buf->data, buf->len, TRUE, TRUE);
3650
3651     /* As router we must deliver this packet directly to the original
3652        server whom this client was earlier. */
3653     if (server->server_type == SILC_ROUTER && detached_client->router &&
3654         detached_client->router->server_type != SILC_ROUTER)
3655       silc_server_packet_send(server, detached_client->router->connection,
3656                               SILC_PACKET_RESUME_CLIENT, 0, 
3657                               buf->data, buf->len, TRUE);
3658     silc_buffer_free(buf);
3659
3660     detached_client->router = NULL;
3661
3662     /* Delete this client entry since we're resuming to old one. */
3663     server->stat.my_clients--;
3664     server->stat.clients--;
3665     if (server->stat.cell_clients)
3666       server->stat.cell_clients--;
3667     silc_server_remove_from_channels(server, NULL, client, FALSE,
3668                                      NULL, FALSE, FALSE);
3669     silc_server_del_from_watcher_list(server, client);
3670     if (!silc_idlist_del_client(server->local_list, client))
3671       silc_idlist_del_client(server->global_list, client);
3672     client = detached_client;
3673     silc_free(client->servername);
3674     client->servername = strdup(server->server_name);
3675
3676     /* If the ID is not based in our ID then change it */
3677     if (!SILC_ID_COMPARE(client->id, server->id, server->id->ip.data_len)) {
3678       silc_free(client_id);
3679       while (!silc_id_create_client_id(server, server->id, server->rng, 
3680                                        server->md5hash, client->nickname, 
3681                                        &client_id)) {
3682         nickfail++;
3683         if (nickfail > 9) {
3684           silc_server_disconnect_remote(server, sock, 
3685                                         SILC_STATUS_ERR_BAD_NICKNAME, NULL);
3686           if (sock->user_data)
3687             silc_server_free_sock_user_data(server, sock, NULL);
3688           return;
3689         }
3690         snprintf(&client->nickname[strlen(client->nickname) - 1], 1, 
3691                  "%d", nickfail);
3692       }
3693       nick_change = TRUE;
3694     }
3695
3696     if (nick_change) {
3697       /* Notify about Client ID change, nickname doesn't actually change. */
3698       silc_server_send_notify_nick_change(server, SILC_PRIMARY_ROUTE(server),
3699                                           SILC_BROADCAST(server),
3700                                           client->id, client_id,
3701                                           client->nickname);
3702     }
3703
3704     /* Resolve users on those channels that client has joined but we
3705        haven't resolved user list yet. */
3706     if (server->server_type == SILC_SERVER && !server->standalone) {
3707       silc_hash_table_list(client->channels, &htl);
3708       while (silc_hash_table_get(&htl, NULL, (void **)&chl)) {
3709         channel = chl->channel;
3710         SILC_LOG_DEBUG(("Resolving users for %s channel", 
3711                         channel->channel_name));
3712         if (channel->disabled || !channel->users_resolved) {
3713           silc_server_send_command(server, SILC_PRIMARY_ROUTE(server),
3714                                    SILC_COMMAND_USERS, ++server->cmd_ident,
3715                                    1, 2, channel->channel_name,
3716                                    strlen(channel->channel_name));
3717         }
3718       }
3719       silc_hash_table_list_reset(&htl);
3720     }
3721
3722     /* Send the new client ID to the client. After this client may start
3723        receiving other packets, and may start sending packets too. */
3724     silc_server_send_new_id(server, sock, FALSE, client_id, SILC_ID_CLIENT,
3725                             silc_id_get_len(client_id, SILC_ID_CLIENT));
3726
3727     if (nick_change) {
3728       /* Send NICK change notify to channels as well. */
3729       SilcBuffer oidp, nidp;
3730       oidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3731       nidp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
3732       silc_server_send_notify_on_channels(server, NULL, client, 
3733                                           SILC_NOTIFY_TYPE_NICK_CHANGE, 3,
3734                                           oidp->data, oidp->len, 
3735                                           nidp->data, nidp->len,
3736                                           client->nickname, 
3737                                           strlen(client->nickname));
3738       silc_buffer_free(oidp);
3739       silc_buffer_free(nidp);
3740     }
3741
3742     /* Add the client again to the ID cache to get it to correct list */
3743     if (!silc_idcache_del_by_context(server->local_list->clients, client))
3744       silc_idcache_del_by_context(server->global_list->clients, client);
3745     silc_free(client->id);
3746     client->id = client_id;
3747     client_id = NULL;
3748     silc_idcache_add(server->local_list->clients, client->nickname,
3749                      client->id, client, 0, NULL);
3750
3751     /* Send some nice info to the client */
3752     silc_server_send_connect_notifys(server, sock, client);
3753
3754     /* Send all channel keys of channels the client has joined */
3755     silc_hash_table_list(client->channels, &htl);
3756     while (silc_hash_table_get(&htl, NULL, (void **)&chl)) {
3757       bool created = FALSE;
3758       channel = chl->channel;
3759
3760       if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY)
3761         continue;
3762
3763       /* If we don't have channel key, then create one */
3764       if (!channel->channel_key) {
3765         if (!silc_server_create_channel_key(server, channel, 0))
3766           continue;
3767         created = TRUE;
3768       }
3769
3770       id_string = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3771       cipher = silc_cipher_get_name(channel->channel_key);
3772       keyp = 
3773         silc_channel_key_payload_encode(silc_id_get_len(channel->id,
3774                                                         SILC_ID_CHANNEL), 
3775                                         id_string,
3776                                         strlen(cipher), cipher,
3777                                         channel->key_len / 8, channel->key);
3778       silc_free(id_string);
3779
3780       /* Send the channel key to the client */
3781       silc_server_packet_send(server, sock, SILC_PACKET_CHANNEL_KEY, 0, 
3782                               keyp->data, keyp->len, FALSE);
3783
3784       /* Distribute the channel key to channel */
3785       if (created) {
3786         silc_server_send_channel_key(server, NULL, channel,
3787                                      server->server_type == SILC_ROUTER ? 
3788                                      FALSE : !server->standalone);
3789         silc_server_backup_send(server, NULL, SILC_PACKET_CHANNEL_KEY, 0,
3790                                 keyp->data, keyp->len, FALSE, TRUE);
3791       }
3792
3793       silc_buffer_free(keyp);
3794     }
3795     silc_hash_table_list_reset(&htl);
3796
3797   } else if (sock->type != SILC_SOCKET_TYPE_CLIENT) {
3798     /* Server or router sent this to us to notify that that a client has
3799        been resumed. */
3800     SilcServerEntry server_entry;
3801     SilcServerID *server_id;
3802
3803     if (!client_id) {
3804       SILC_LOG_DEBUG(("Malformed resuming packet"));
3805       return;
3806     }
3807
3808     /* Get entry to the client, and resolve it if we don't have it. */
3809     detached_client = silc_idlist_find_client_by_id(server->local_list, 
3810                                                     client_id, TRUE,
3811                                                     &id_cache);
3812     if (!detached_client) {
3813       detached_client = silc_idlist_find_client_by_id(server->global_list,
3814                                                       client_id, TRUE,
3815                                                       &id_cache);
3816       if (!detached_client) {
3817         SILC_LOG_DEBUG(("Resuming client is unknown"));
3818         silc_free(client_id);
3819         return;
3820       }
3821     }
3822
3823     /* Check that the client has not been resumed already because it is
3824        protocol error to attempt to resume more than once.  The client
3825        will be killed if this protocol error occurs. */
3826     if (detached_client->data.status & SILC_IDLIST_STATUS_RESUMED &&
3827         !(detached_client->mode & SILC_UMODE_DETACHED)) {
3828       /* The client is clearly attempting to resume more than once and
3829          perhaps playing around by resuming from several different places
3830          at the same time. */
3831       SILC_LOG_DEBUG(("Attempting to re-resume client, killing both"));
3832       silc_server_kill_client(server, detached_client, NULL,
3833                               server->id, SILC_ID_SERVER);
3834       silc_free(client_id);
3835       return;
3836     }
3837
3838     /* Check whether client is detached at all */
3839     if (!(detached_client->mode & SILC_UMODE_DETACHED)) {
3840       SILC_LOG_DEBUG(("Client is not detached"));
3841       silc_free(client_id);
3842       return;
3843     }
3844
3845     SILC_LOG_DEBUG(("Resuming detached client"));
3846
3847     /* If the sender of this packet is server and we are router we need to
3848        broadcast this packet to other routers in the network. */
3849     if (server->server_type == SILC_ROUTER &&
3850         sock->type == SILC_SOCKET_TYPE_SERVER &&
3851         !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
3852       SILC_LOG_DEBUG(("Broadcasting received Resume Client packet"));
3853       silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
3854                               packet->type, 
3855                               packet->flags | SILC_PACKET_FLAG_BROADCAST,
3856                               buffer->data, buffer->len, FALSE);
3857       silc_server_backup_send(server, sock->user_data, 
3858                               packet->type, packet->flags,
3859                               packet->buffer->data, packet->buffer->len, 
3860                               FALSE, TRUE);
3861     }
3862
3863     /* Client is detached, and now it is resumed.  Remove the detached
3864        mode and mark that it is resumed. */
3865     silc_idlist_del_data(detached_client);
3866     detached_client->mode &= ~SILC_UMODE_DETACHED;
3867     detached_client->data.status |= SILC_IDLIST_STATUS_RESUMED;
3868     detached_client->data.status &= ~SILC_IDLIST_STATUS_LOCAL;
3869     id_cache->expire = 0;
3870
3871     silc_schedule_task_del_by_context(server->schedule, detached_client);
3872
3873     /* Get the new owner of the resumed client */
3874     server_id = silc_id_str2id(packet->src_id, packet->src_id_len,
3875                                packet->src_id_type);
3876     if (!server_id) {
3877       silc_free(client_id);
3878       return;
3879     }
3880
3881     /* Get server entry */
3882     server_entry = silc_idlist_find_server_by_id(server->global_list, 
3883                                                  server_id, TRUE, NULL);
3884     local = FALSE;
3885     if (!server_entry) {
3886       server_entry = silc_idlist_find_server_by_id(server->local_list, 
3887                                                    server_id, TRUE, NULL);
3888       local = TRUE;
3889       if (!server_entry) {
3890         silc_free(server_id);
3891         silc_free(client_id);
3892         return;
3893       }
3894     }
3895
3896     if (server->server_type == SILC_ROUTER &&
3897         sock->type == SILC_SOCKET_TYPE_ROUTER &&
3898         server_entry->server_type == SILC_ROUTER)
3899       local = FALSE;
3900
3901     /* Change the client to correct list. */
3902     if (!silc_idcache_del_by_context(server->local_list->clients,
3903                                      detached_client))
3904       silc_idcache_del_by_context(server->global_list->clients,
3905                                   detached_client);
3906     silc_idcache_add(local && server->server_type == SILC_ROUTER ?
3907                      server->local_list->clients :
3908                      server->global_list->clients,
3909                      detached_client->nickname,
3910                      detached_client->id, detached_client, FALSE, NULL);
3911
3912     /* Change the owner of the client */
3913     detached_client->router = server_entry;
3914
3915     /* Update channel information regarding global clients on channel. */
3916     if (server->server_type != SILC_ROUTER) {
3917       silc_hash_table_list(detached_client->channels, &htl);
3918       while (silc_hash_table_get(&htl, NULL, (void **)&chl))
3919         chl->channel->global_users = 
3920           silc_server_channel_has_global(chl->channel);
3921       silc_hash_table_list_reset(&htl);
3922     }
3923
3924     silc_free(server_id);
3925   }
3926
3927   silc_free(client_id);
3928 }