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