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