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