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