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