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