Fixed the INVITE and BAN notify handling in router end.
[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       if (mode & SILC_CHANNEL_UMODE_CHANFO &&
952           !(chl->mode & SILC_CHANNEL_UMODE_CHANFO) &&
953           server->server_type == SILC_ROUTER &&
954           sock != SILC_PRIMARY_ROUTE(server)) {
955         SilcPublicKey founder_key = NULL;
956
957         /* If channel doesn't have founder auth mode then it's impossible
958            that someone would be getting founder rights with CUMODE command.
959            In that case there already either is founder or there isn't
960            founder at all on the channel. */
961         if (client && !(channel->mode & SILC_CHANNEL_MODE_FOUNDER_AUTH)) {
962           /* Force the mode to not have founder mode */
963           chl->mode = mode &= ~SILC_CHANNEL_UMODE_CHANFO;
964           silc_server_force_cumode_change(server, sock, channel, chl, mode);
965           notify_sent = TRUE;
966           break;
967         }
968
969         /* Get the founder of the channel and if found then this client
970            cannot be the founder since there already is one. */
971         silc_hash_table_list(channel->user_list, &htl);
972         while (silc_hash_table_get(&htl, NULL, (void *)&chl2))
973           if (chl2->mode & SILC_CHANNEL_UMODE_CHANFO) {
974             /* XXX this is not correct anymore in 1.2 -Pekka */
975
976             /* If the founder on the channel is not the one whom has set
977                the founder mode, then it's possible that this CUMODE_CHANGE
978                is correct.  Due to netsplits it's possible that this
979                situation happens. */
980             if (!(channel->mode & SILC_CHANNEL_MODE_FOUNDER_AUTH) ||
981                 (channel->founder_key && chl2->client->data.public_key &&
982                  silc_pkcs_public_key_compare(
983                                         channel->founder_key,
984                                         chl2->client->data.public_key))) {
985               chl->mode = mode &= ~SILC_CHANNEL_UMODE_CHANFO;
986               silc_server_force_cumode_change(server, sock, channel,
987                                               chl, mode);
988               notify_sent = TRUE;
989             }
990             break;
991           }
992         silc_hash_table_list_reset(&htl);
993         if (!(mode & SILC_CHANNEL_UMODE_CHANFO))
994           break;
995
996         /* Founder not found of the channel.  Since the founder auth mode
997            is set on the channel now check whether this is the client that
998            originally set the mode. */
999
1000         if (channel->founder_key) {
1001           /* Get public key that must be present in notify */
1002           tmp = silc_argument_get_arg_type(args, 4, &tmp_len);
1003           if (!tmp || !silc_pkcs_public_key_payload_decode(tmp, tmp_len,
1004                                                            &founder_key)) {
1005             chl->mode = mode &= ~SILC_CHANNEL_UMODE_CHANFO;
1006             silc_server_force_cumode_change(server, sock, channel, chl, mode);
1007             notify_sent = TRUE;
1008             break;
1009           }
1010
1011           /* Now match the public key we have cached and public key sent.
1012              They must match. */
1013 #if 0 /* The key may be other than the client's in 1.2 */
1014           if (client && client->data.public_key &&
1015               !silc_pkcs_public_key_compare(channel->founder_key,
1016                                             client->data.public_key)) {
1017             chl->mode = mode &= ~SILC_CHANNEL_UMODE_CHANFO;
1018             silc_server_force_cumode_change(server, sock, channel, chl, mode);
1019             notify_sent = TRUE;
1020             break;
1021           }
1022 #endif
1023           if (!silc_pkcs_public_key_compare(channel->founder_key,
1024                                             founder_key)) {
1025             chl->mode = mode &= ~SILC_CHANNEL_UMODE_CHANFO;
1026             silc_server_force_cumode_change(server, sock, channel, chl, mode);
1027             notify_sent = TRUE;
1028             break;
1029           }
1030         }
1031
1032         /* There cannot be anyone else as founder on the channel now.  This
1033            client is definitely the founder due to this authentication */
1034         silc_hash_table_list(channel->user_list, &htl);
1035         while (silc_hash_table_get(&htl, NULL, (void *)&chl2))
1036           if (chl2->mode & SILC_CHANNEL_UMODE_CHANFO) {
1037             chl2->mode &= ~SILC_CHANNEL_UMODE_CHANFO;
1038             silc_server_force_cumode_change(server, NULL, channel, chl2,
1039                                             chl2->mode);
1040             break;
1041           }
1042         silc_hash_table_list_reset(&htl);
1043
1044         if (founder_key)
1045           silc_pkcs_public_key_free(founder_key);
1046       }
1047
1048       if (server->server_type != SILC_SERVER && chl->mode == mode) {
1049         SILC_LOG_DEBUG(("Mode is changed already"));
1050         break;
1051       }
1052
1053       SILC_LOG_DEBUG(("Changing %s channel user mode",
1054                       chl->client->nickname ? chl->client->nickname :
1055                       (unsigned char *)""));
1056
1057       /* Change the mode */
1058       chl->mode = mode;
1059
1060       /* Send the same notify to the channel */
1061       if (!notify_sent)
1062         silc_server_packet_send_to_channel(server, NULL, channel,
1063                                            packet->type,
1064                                            FALSE, TRUE, packet->buffer->data,
1065                                            packet->buffer->len, FALSE);
1066
1067       silc_free(channel_id);
1068       break;
1069     }
1070
1071   case SILC_NOTIFY_TYPE_INVITE:
1072
1073     if (packet->dst_id_type == SILC_ID_CLIENT)
1074       goto out;
1075
1076     SILC_LOG_DEBUG(("INVITE notify"));
1077
1078     /* Get Channel ID */
1079     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
1080     if (!tmp)
1081       goto out;
1082     channel_id = silc_id_payload_parse_id(tmp, tmp_len, NULL);
1083     if (!channel_id)
1084       goto out;
1085
1086     /* Get channel entry */
1087     channel = silc_idlist_find_channel_by_id(server->global_list,
1088                                              channel_id, NULL);
1089     if (!channel) {
1090       channel = silc_idlist_find_channel_by_id(server->local_list,
1091                                                channel_id, NULL);
1092       if (!channel) {
1093         SILC_LOG_DEBUG(("Notify for unknown channel"));
1094         silc_free(channel_id);
1095         goto out;
1096       }
1097     }
1098     silc_free(channel_id);
1099
1100 #if 0 /* These aren't actually used anywhere or needed, since this
1101          notify is for handling the invite list (direct invite
1102          goes to client and is not handled here at all). */
1103
1104     /* Get client ID */
1105     tmp = silc_argument_get_arg_type(args, 3, &tmp_len);
1106     if (!tmp)
1107       goto out;
1108     client_id = silc_id_payload_parse_id(tmp, tmp_len, NULL);
1109     if (!client_id)
1110       goto out;
1111
1112     /* Get client entry */
1113     client = silc_idlist_find_client_by_id(server->global_list,
1114                                            client_id, TRUE, &cache);
1115     if (!client) {
1116       client = silc_idlist_find_client_by_id(server->local_list,
1117                                              client_id, TRUE, &cache);
1118       if (!client) {
1119         silc_free(client_id);
1120         goto out;
1121       }
1122     }
1123     silc_free(client_id);
1124
1125     /* Get user's channel entry and check that inviting is allowed. */
1126     if (server->server_type == SILC_ROUTER) {
1127       if (!silc_server_client_on_channel(client, channel, &chl))
1128         goto out;
1129       if (channel->mode & SILC_CHANNEL_MODE_INVITE &&
1130           !(chl->mode & SILC_CHANNEL_UMODE_CHANOP) &&
1131           !(chl->mode & SILC_CHANNEL_UMODE_CHANFO)) {
1132         SILC_LOG_DEBUG(("Inviting is not allowed"));
1133         goto out;
1134       }
1135     }
1136 #endif
1137
1138     /* Get the invite action */
1139     tmp = silc_argument_get_arg_type(args, 4, &tmp_len);
1140     if (tmp && tmp_len == 1) {
1141       SilcUInt8 action = (SilcUInt8)tmp[0];
1142       SilcUInt16 iargc = 0;
1143       SilcArgumentPayload iargs;
1144
1145       /* Get invite list */
1146       tmp = silc_argument_get_arg_type(args, 5, &tmp_len);
1147       if (!tmp || tmp_len < 2)
1148         goto out;
1149
1150       /* Parse the arguments to see they are constructed correctly */
1151       SILC_GET16_MSB(iargc, tmp);
1152       iargs = silc_argument_payload_parse(tmp + 2, tmp_len - 2, iargc);
1153       if (!iargs)
1154         goto out;
1155
1156       if (action != 0x01 && !channel->invite_list)
1157         channel->invite_list =
1158           silc_hash_table_alloc(0, silc_hash_ptr,
1159                                 NULL, NULL, NULL,
1160                                 silc_server_inviteban_destruct, channel, TRUE);
1161
1162       /* Proces the invite action */
1163       silc_server_inviteban_process(server, channel->invite_list, action,
1164                                     iargs);
1165       silc_argument_payload_free(iargs);
1166
1167       /* If we are router we must send this notify to our local servers on
1168          the channel.  Normal server does nothing.  The notify is not
1169          sent to clients. */
1170       if (server->server_type == SILC_ROUTER)
1171         silc_server_packet_send_to_channel(server, sock, channel,
1172                                            packet->type, FALSE, FALSE,
1173                                            packet->buffer->data,
1174                                            packet->buffer->len, FALSE);
1175     }
1176
1177     break;
1178
1179   case SILC_NOTIFY_TYPE_CHANNEL_CHANGE:
1180     /*
1181      * Distribute to the local clients on the channel and change the
1182      * channel ID.
1183      */
1184
1185     SILC_LOG_DEBUG(("CHANNEL CHANGE"));
1186
1187     if (sock->type != SILC_SOCKET_TYPE_ROUTER)
1188       break;
1189
1190     /* Get the old Channel ID */
1191     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
1192     if (!tmp)
1193       goto out;
1194     channel_id = silc_id_payload_parse_id(tmp, tmp_len, NULL);
1195     if (!channel_id)
1196       goto out;
1197
1198     /* Get the channel entry */
1199     channel = silc_idlist_find_channel_by_id(server->local_list,
1200                                              channel_id, NULL);
1201     if (!channel) {
1202       channel = silc_idlist_find_channel_by_id(server->global_list,
1203                                                channel_id, NULL);
1204       if (!channel) {
1205         SILC_LOG_DEBUG(("Notify for unknown channel"));
1206         silc_free(channel_id);
1207         goto out;
1208       }
1209     }
1210
1211     /* Send the notify to the channel */
1212     silc_server_packet_send_to_channel(server, sock, channel, packet->type,
1213                                        FALSE, TRUE, packet->buffer->data,
1214                                        packet->buffer->len, FALSE);
1215
1216     /* Get the new Channel ID */
1217     tmp = silc_argument_get_arg_type(args, 2, &tmp_len);
1218     if (!tmp)
1219       goto out;
1220     channel_id2 = silc_id_payload_parse_id(tmp, tmp_len, NULL);
1221     if (!channel_id2)
1222       goto out;
1223
1224     SILC_LOG_DEBUG(("Old Channel ID id(%s)",
1225                     silc_id_render(channel_id, SILC_ID_CHANNEL)));
1226     SILC_LOG_DEBUG(("New Channel ID id(%s)",
1227                     silc_id_render(channel_id2, SILC_ID_CHANNEL)));
1228
1229     /* Replace the Channel ID */
1230     if (!silc_idlist_replace_channel_id(server->local_list, channel_id,
1231                                         channel_id2))
1232       if (!silc_idlist_replace_channel_id(server->global_list, channel_id,
1233                                           channel_id2)) {
1234         silc_free(channel_id2);
1235         channel_id2 = NULL;
1236       }
1237
1238     if (channel_id2) {
1239       SilcBuffer modes = NULL, users = NULL, users_modes = NULL;
1240
1241       /* Re-announce this channel which ID was changed. */
1242       silc_server_send_new_channel(server, sock, FALSE, channel->channel_name,
1243                                    channel->id,
1244                                    silc_id_get_len(channel->id,
1245                                                    SILC_ID_CHANNEL),
1246                                    channel->mode);
1247
1248       /* Re-announce our clients on the channel as the ID has changed now */
1249       silc_server_announce_get_channel_users(server, channel, &modes, &users,
1250                                              &users_modes);
1251       if (users) {
1252         silc_buffer_push(users, users->data - users->head);
1253         silc_server_packet_send(server, sock,
1254                                 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
1255                                 users->data, users->len, FALSE);
1256         silc_buffer_free(users);
1257       }
1258       if (modes) {
1259         silc_buffer_push(modes, modes->data - modes->head);
1260         silc_server_packet_send_dest(server, sock,
1261                                      SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
1262                                      channel->id, SILC_ID_CHANNEL,
1263                                      modes->data, modes->len, FALSE);
1264         silc_buffer_free(modes);
1265       }
1266       if (users_modes) {
1267         silc_buffer_push(users_modes, users_modes->data - users_modes->head);
1268         silc_server_packet_send_dest(server, sock,
1269                                      SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
1270                                      channel->id, SILC_ID_CHANNEL,
1271                                      users_modes->data,
1272                                      users_modes->len, FALSE);
1273         silc_buffer_free(users_modes);
1274       }
1275
1276       /* Re-announce channel's topic */
1277       if (channel->topic) {
1278         silc_server_send_notify_topic_set(server, sock,
1279                                           server->server_type == SILC_ROUTER ?
1280                                           TRUE : FALSE, channel,
1281                                           server->id, SILC_ID_SERVER,
1282                                           channel->topic);
1283       }
1284     }
1285
1286     silc_free(channel_id);
1287
1288     break;
1289
1290   case SILC_NOTIFY_TYPE_SERVER_SIGNOFF:
1291     /*
1292      * Remove the server entry and all clients that this server owns.
1293      */
1294
1295     SILC_LOG_DEBUG(("SERVER SIGNOFF notify"));
1296
1297     /* Get Server ID */
1298     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
1299     if (!tmp)
1300       goto out;
1301     server_id = silc_id_payload_parse_id(tmp, tmp_len, NULL);
1302     if (!server_id)
1303       goto out;
1304
1305     /* If the ID is mine, this notify is not allowed. */
1306     if (SILC_ID_SERVER_COMPARE(server_id, server->id)) {
1307       SILC_LOG_DEBUG(("Ignoring my own ID for SERVER_SIGNOFF"));
1308       break;
1309     }
1310
1311     /* Get server entry */
1312     server_entry = silc_idlist_find_server_by_id(server->global_list,
1313                                                  server_id, TRUE, NULL);
1314     local = FALSE;
1315     if (!server_entry) {
1316       server_entry = silc_idlist_find_server_by_id(server->local_list,
1317                                                    server_id, TRUE, NULL);
1318       local = TRUE;
1319       if (!server_entry) {
1320         /* If we are normal server then we might not have the server. Check
1321            whether router was kind enough to send the list of all clients
1322            that actually was to be removed. Remove them if the list is
1323            available. */
1324         if (server->server_type != SILC_ROUTER &&
1325             silc_argument_get_arg_num(args) > 1) {
1326           int i;
1327
1328           for (i = 1; i < silc_argument_get_arg_num(args); i++) {
1329             /* Get Client ID */
1330             tmp = silc_argument_get_arg_type(args, i + 1, &tmp_len);
1331             if (!tmp)
1332               continue;
1333             client_id = silc_id_payload_parse_id(tmp, tmp_len, NULL);
1334             if (!client_id)
1335               continue;
1336
1337             /* Get client entry */
1338             client = silc_idlist_find_client_by_id(server->global_list,
1339                                                    client_id, TRUE, &cache);
1340             local = TRUE;
1341             if (!client) {
1342               client = silc_idlist_find_client_by_id(server->local_list,
1343                                                      client_id, TRUE, &cache);
1344               local = FALSE;
1345               if (!client) {
1346                 silc_free(client_id);
1347                 continue;
1348               }
1349             }
1350             silc_free(client_id);
1351
1352             /* Update statistics */
1353             server->stat.clients--;
1354             if (server->stat.cell_clients)
1355               server->stat.cell_clients--;
1356             SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
1357             SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
1358
1359             /* Remove the client from all channels. */
1360             silc_server_remove_from_channels(server, NULL, client,
1361                                              TRUE, NULL, FALSE, FALSE);
1362
1363             /* Check if anyone is watching this nickname */
1364             if (server->server_type == SILC_ROUTER)
1365               silc_server_check_watcher_list(server, client, NULL,
1366                                              SILC_NOTIFY_TYPE_SERVER_SIGNOFF);
1367
1368             /* Remove this client from watcher list if it is */
1369             if (local)
1370               silc_server_del_from_watcher_list(server, client);
1371
1372             /* Remove the client */
1373             silc_idlist_del_data(client);
1374             silc_idlist_del_client(local ? server->local_list :
1375                                    server->global_list, client);
1376           }
1377         }
1378
1379         silc_free(server_id);
1380         goto out;
1381       }
1382     }
1383     silc_free(server_id);
1384
1385     /* For local entrys SERVER_SIGNOFF is processed only on backup router.
1386        It is possible that router sends server signoff for a server.  If
1387        backup router has it as local connection it will be closed. */
1388     if (SILC_IS_LOCAL(server_entry)) {
1389       if (server->server_type == SILC_BACKUP_ROUTER) {
1390         sock = server_entry->connection;
1391         SILC_LOG_DEBUG(("Closing connection %s after SERVER_SIGNOFF",
1392                        sock->hostname));
1393         if (sock->user_data)
1394           silc_server_free_sock_user_data(server, sock, NULL);
1395         SILC_SET_DISCONNECTING(sock);
1396         silc_server_close_connection(server, sock);
1397       }
1398
1399       break;
1400     }
1401
1402     /* Remove all servers that are originated from this server, and
1403        remove the clients of those servers too. */
1404     silc_server_remove_servers_by_server(server, server_entry, TRUE);
1405
1406     /* Remove the clients that this server owns as they will become
1407        invalid now too. */
1408     silc_server_remove_clients_by_server(server, server_entry->router,
1409                                          server_entry, TRUE);
1410     silc_server_backup_del(server, server_entry);
1411
1412     /* Remove the server entry */
1413     silc_idlist_del_server(local ? server->local_list :
1414                            server->global_list, server_entry);
1415
1416     /* Update statistics */
1417     if (server->server_type == SILC_ROUTER)
1418       server->stat.servers--;
1419
1420     break;
1421
1422   case SILC_NOTIFY_TYPE_KICKED:
1423     /*
1424      * Distribute the notify to local clients on the channel
1425      */
1426
1427     SILC_LOG_DEBUG(("KICKED notify"));
1428
1429     if (!channel_id) {
1430       channel_id = silc_id_str2id(packet->dst_id, packet->dst_id_len,
1431                                   packet->dst_id_type);
1432       if (!channel_id)
1433         goto out;
1434     }
1435
1436     /* Get channel entry */
1437     channel = silc_idlist_find_channel_by_id(server->global_list,
1438                                              channel_id, NULL);
1439     if (!channel) {
1440       channel = silc_idlist_find_channel_by_id(server->local_list,
1441                                                channel_id, NULL);
1442       if (!channel) {
1443         SILC_LOG_DEBUG(("Notify for unknown channel"));
1444         silc_free(channel_id);
1445         goto out;
1446       }
1447     }
1448     silc_free(channel_id);
1449
1450     /* Get client ID */
1451     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
1452     if (!tmp)
1453       goto out;
1454     client_id = silc_id_payload_parse_id(tmp, tmp_len, NULL);
1455     if (!client_id)
1456       goto out;
1457
1458     /* If the the client is not in local list we check global list */
1459     client = silc_idlist_find_client_by_id(server->global_list,
1460                                            client_id, TRUE, NULL);
1461     if (!client) {
1462       client = silc_idlist_find_client_by_id(server->local_list,
1463                                              client_id, TRUE, NULL);
1464       if (!client) {
1465         silc_free(client_id);
1466         goto out;
1467       }
1468     }
1469     silc_free(client_id);
1470
1471     /* If target is founder they cannot be kicked */
1472     if (!silc_server_client_on_channel(client, channel, &chl))
1473       goto out;
1474     if (chl->mode & SILC_CHANNEL_UMODE_CHANFO)
1475       goto out;
1476
1477     /* Get the kicker's Client ID */
1478     tmp = silc_argument_get_arg_type(args, 3, &tmp_len);
1479     if (!tmp)
1480       goto out;
1481     client_id = silc_id_payload_parse_id(tmp, tmp_len, NULL);
1482     if (!client_id)
1483       goto out;
1484
1485     /* If the the client is not in local list we check global list */
1486     client2 = silc_idlist_find_client_by_id(server->global_list,
1487                                             client_id, TRUE, NULL);
1488     if (!client2) {
1489       client2 = silc_idlist_find_client_by_id(server->local_list,
1490                                               client_id, TRUE, NULL);
1491       if (!client2) {
1492         silc_free(client_id);
1493         goto out;
1494       }
1495     }
1496     silc_free(client_id);
1497
1498     /* Kicker must be operator on channel */
1499     if (!silc_server_client_on_channel(client2, channel, &chl))
1500       goto out;
1501     if (!(chl->mode & SILC_CHANNEL_UMODE_CHANOP) &&
1502         !(chl->mode & SILC_CHANNEL_UMODE_CHANFO)) {
1503       SILC_LOG_DEBUG(("Kicking is not allowed"));
1504       goto out;
1505     }
1506
1507     /* Send to channel */
1508     silc_server_packet_send_to_channel(server, sock, channel, packet->type,
1509                                        FALSE, TRUE, packet->buffer->data,
1510                                        packet->buffer->len, FALSE);
1511
1512     /* Remove the client from channel's invite list */
1513     if (channel->invite_list && silc_hash_table_count(channel->invite_list)) {
1514       SilcBuffer ab;
1515       SilcArgumentPayload iargs;
1516       tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
1517       ab = silc_argument_payload_encode_one(NULL, tmp, tmp_len, 3);
1518       iargs = silc_argument_payload_parse(ab->data, ab->len, 1);
1519       silc_server_inviteban_process(server, channel->invite_list, 1, iargs);
1520       silc_buffer_free(ab);
1521       silc_argument_payload_free(iargs);
1522     }
1523
1524     /* Remove the client from channel */
1525     silc_server_remove_from_one_channel(server, sock, channel, client, FALSE);
1526
1527     break;
1528
1529   case SILC_NOTIFY_TYPE_KILLED:
1530     {
1531       /*
1532        * Distribute the notify to local clients on channels
1533        */
1534       unsigned char *id, *comment;
1535       SilcUInt32 id_len, comment_len;
1536
1537       SILC_LOG_DEBUG(("KILLED notify"));
1538
1539       /* Get client ID */
1540       id = silc_argument_get_arg_type(args, 1, &id_len);
1541       if (!id)
1542         goto out;
1543       client_id = silc_id_payload_parse_id(id, id_len, NULL);
1544       if (!client_id)
1545         goto out;
1546
1547       /* If the the client is not in local list we check global list */
1548       client = silc_idlist_find_client_by_id(server->global_list,
1549                                              client_id, TRUE, &cache);
1550       if (!client) {
1551         client = silc_idlist_find_client_by_id(server->local_list,
1552                                                client_id, TRUE, &cache);
1553         if (!client) {
1554           silc_free(client_id);
1555           goto out;
1556         }
1557       }
1558       silc_free(client_id);
1559
1560       /* If the client is one of ours, then close the connection to the
1561          client now. This removes the client from all channels as well. */
1562       if (packet->dst_id_type == SILC_ID_CLIENT && client->connection) {
1563         sock = client->connection;
1564         silc_server_free_client_data(server, NULL, client, FALSE, NULL);
1565         silc_server_close_connection(server, sock);
1566         break;
1567       }
1568
1569       /* Get comment */
1570       comment = silc_argument_get_arg_type(args, 2, &comment_len);
1571       if (comment_len > 128)
1572         comment_len = 127;
1573
1574       /* Get the killer's Client ID */
1575       tmp = silc_argument_get_arg_type(args, 3, &tmp_len);
1576       if (!tmp)
1577         goto out;
1578       client_id = silc_id_payload_parse_id(tmp, tmp_len, &id_type);
1579       if (!client_id)
1580         goto out;
1581
1582       if (id_type == SILC_ID_CLIENT) {
1583         /* If the the client is not in local list we check global list */
1584         client2 = silc_idlist_find_client_by_id(server->global_list,
1585                                                 client_id, TRUE, NULL);
1586         if (!client2) {
1587           client2 = silc_idlist_find_client_by_id(server->local_list,
1588                                                   client_id, TRUE, NULL);
1589           if (!client2) {
1590             silc_free(client_id);
1591             goto out;
1592           }
1593         }
1594         silc_free(client_id);
1595
1596         /* Killer must be router operator */
1597         if (server->server_type != SILC_SERVER &&
1598             !(client2->mode & SILC_UMODE_ROUTER_OPERATOR)) {
1599           SILC_LOG_DEBUG(("Killing is not allowed"));
1600           goto out;
1601         }
1602       }
1603
1604       /* Send the notify to local clients on the channels except to the
1605          client who is killed. */
1606       silc_server_send_notify_on_channels(server, client, client,
1607                                           SILC_NOTIFY_TYPE_KILLED, 3,
1608                                           id, id_len, comment, comment_len,
1609                                           tmp, tmp_len);
1610
1611       /* Remove the client from all channels */
1612       silc_server_remove_from_channels(server, NULL, client, FALSE, NULL,
1613                                        FALSE, TRUE);
1614
1615       /* Check if anyone is watching this nickname */
1616       silc_server_check_watcher_list(server, client, NULL,
1617                                      SILC_NOTIFY_TYPE_KILLED);
1618
1619       /* Update statistics */
1620       server->stat.clients--;
1621       if (server->stat.cell_clients)
1622         server->stat.cell_clients--;
1623       SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
1624       SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
1625
1626       if (SILC_IS_LOCAL(client)) {
1627         server->stat.my_clients--;
1628         silc_schedule_task_del_by_context(server->schedule, client);
1629         silc_idlist_del_data(client);
1630         client->mode = 0;
1631       }
1632
1633       client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
1634       cache->expire = SILC_ID_CACHE_EXPIRE_DEF;
1635       break;
1636     }
1637
1638   case SILC_NOTIFY_TYPE_UMODE_CHANGE:
1639     /*
1640      * Save the mode of the client.
1641      */
1642
1643     SILC_LOG_DEBUG(("UMODE_CHANGE notify"));
1644
1645     /* Get client ID */
1646     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
1647     if (!tmp)
1648       goto out;
1649     client_id = silc_id_payload_parse_id(tmp, tmp_len, NULL);
1650     if (!client_id)
1651       goto out;
1652
1653     /* Get client entry */
1654     client = silc_idlist_find_client_by_id(server->global_list,
1655                                            client_id, TRUE, NULL);
1656     if (!client) {
1657       client = silc_idlist_find_client_by_id(server->local_list,
1658                                              client_id, TRUE, NULL);
1659       if (!client) {
1660         silc_free(client_id);
1661         goto out;
1662       }
1663     }
1664     silc_free(client_id);
1665
1666     /* Get the mode */
1667     tmp = silc_argument_get_arg_type(args, 2, &tmp_len);
1668     if (!tmp)
1669       goto out;
1670     SILC_GET32_MSB(mode, tmp);
1671
1672     /* Remove internal resumed flag if client is marked detached now */
1673     if (mode & SILC_UMODE_DETACHED)
1674       client->data.status &= ~SILC_IDLIST_STATUS_RESUMED;
1675
1676     /* Update statistics */
1677     if (server->server_type == SILC_ROUTER) {
1678       if (mode & SILC_UMODE_GONE) {
1679         if (!(client->mode & SILC_UMODE_GONE))
1680           server->stat.aways++;
1681       } else {
1682         if (client->mode & SILC_UMODE_GONE)
1683           server->stat.aways--;
1684       }
1685       if (mode & SILC_UMODE_DETACHED) {
1686         if (!(client->mode & SILC_UMODE_DETACHED))
1687           server->stat.detached++;
1688       } else {
1689         if (client->mode & SILC_UMODE_DETACHED)
1690           server->stat.detached--;
1691       }
1692     }
1693     SILC_UMODE_STATS_UPDATE(server, SILC_UMODE_SERVER_OPERATOR);
1694     SILC_UMODE_STATS_UPDATE(router, SILC_UMODE_ROUTER_OPERATOR);
1695
1696     /* Change the mode */
1697     client->mode = mode;
1698
1699     /* Check if anyone is watching this nickname */
1700     if (server->server_type == SILC_ROUTER)
1701       silc_server_check_watcher_list(server, client, NULL,
1702                                      SILC_NOTIFY_TYPE_UMODE_CHANGE);
1703
1704     break;
1705
1706   case SILC_NOTIFY_TYPE_BAN:
1707     /*
1708      * Save the ban
1709      */
1710
1711     SILC_LOG_DEBUG(("BAN notify"));
1712
1713     /* Get Channel ID */
1714     tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
1715     if (!tmp)
1716       goto out;
1717     channel_id = silc_id_payload_parse_id(tmp, tmp_len, NULL);
1718     if (!channel_id)
1719       goto out;
1720
1721     /* Get channel entry */
1722     channel = silc_idlist_find_channel_by_id(server->global_list,
1723                                              channel_id, NULL);
1724     if (!channel) {
1725       channel = silc_idlist_find_channel_by_id(server->local_list,
1726                                                channel_id, NULL);
1727       if (!channel) {
1728         SILC_LOG_DEBUG(("Notify for unknown channel"));
1729         silc_free(channel_id);
1730         goto out;
1731       }
1732     }
1733     silc_free(channel_id);
1734
1735     /* Get the ban action */
1736     tmp = silc_argument_get_arg_type(args, 2, &tmp_len);
1737     if (tmp && tmp_len == 1) {
1738       SilcUInt8 action = (SilcUInt8)tmp[0];
1739       SilcUInt16 iargc = 0;
1740       SilcArgumentPayload iargs;
1741
1742       /* Get ban list */
1743       tmp = silc_argument_get_arg_type(args, 3, &tmp_len);
1744       if (!tmp || tmp_len < 2)
1745         goto out;
1746
1747       /* Parse the arguments to see they are constructed correctly */
1748       SILC_GET16_MSB(iargc, tmp);
1749       iargs = silc_argument_payload_parse(tmp + 2, tmp_len - 2, iargc);
1750       if (!iargs)
1751         goto out;
1752
1753       if (action != 0x01 && !channel->ban_list)
1754         channel->ban_list =
1755           silc_hash_table_alloc(0, silc_hash_ptr,
1756                                 NULL, NULL, NULL,
1757                                 silc_server_inviteban_destruct, channel, TRUE);
1758
1759       /* Proces the ban action */
1760       silc_server_inviteban_process(server, channel->ban_list, action,
1761                                     iargs);
1762       silc_argument_payload_free(iargs);
1763
1764       /* If we are router we must send this notify to our local servers on
1765          the channel.  Normal server does nothing.  The notify is not
1766          sent to clients. */
1767       if (server->server_type == SILC_ROUTER)
1768         silc_server_packet_send_to_channel(server, sock, channel,
1769                                            packet->type, FALSE, FALSE,
1770                                            packet->buffer->data,
1771                                            packet->buffer->len, FALSE);
1772     }
1773     break;
1774
1775   case SILC_NOTIFY_TYPE_ERROR:
1776     {
1777       /*
1778        * Error notify
1779        */
1780       SilcStatus error;
1781
1782       tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
1783       if (!tmp && tmp_len != 1)
1784         goto out;
1785       error = (SilcStatus)tmp[0];
1786
1787       SILC_LOG_DEBUG(("ERROR notify (%d)", error));
1788
1789       if (error == SILC_STATUS_ERR_NO_SUCH_CLIENT_ID &&
1790           sock->type == SILC_SOCKET_TYPE_ROUTER) {
1791         tmp = silc_argument_get_arg_type(args, 2, &tmp_len);
1792         if (tmp) {
1793           SILC_LOG_DEBUG(("Received invalid client ID notification, deleting "
1794                           "the entry from cache"));
1795           client_id = silc_id_payload_parse_id(tmp, tmp_len, NULL);
1796           if (!client_id)
1797             goto out;
1798           client = silc_idlist_find_client_by_id(server->global_list,
1799                                                  client_id, FALSE, NULL);
1800           if (client) {
1801             silc_server_remove_from_channels(server, NULL, client, TRUE,
1802                                              NULL, TRUE, FALSE);
1803             silc_idlist_del_data(client);
1804             silc_idlist_del_client(server->global_list, client);
1805           }
1806           silc_free(client_id);
1807         }
1808       }
1809     }
1810     break;
1811
1812     /* Ignore rest of the notify types for now */
1813   case SILC_NOTIFY_TYPE_NONE:
1814   case SILC_NOTIFY_TYPE_MOTD:
1815     break;
1816   default:
1817     break;
1818   }
1819
1820  out:
1821   silc_notify_payload_free(payload);
1822 }
1823
1824 void silc_server_notify_list(SilcServer server,
1825                              SilcSocketConnection sock,
1826                              SilcPacketContext *packet)
1827 {
1828   SilcPacketContext *new;
1829   SilcBuffer buffer;
1830   SilcUInt16 len;
1831
1832   SILC_LOG_DEBUG(("Processing Notify List"));
1833
1834   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
1835       packet->src_id_type != SILC_ID_SERVER)
1836     return;
1837
1838   /* Make copy of the original packet context, except for the actual
1839      data buffer, which we will here now fetch from the original buffer. */
1840   new = silc_packet_context_alloc();
1841   new->type = SILC_PACKET_NOTIFY;
1842   new->flags = packet->flags;
1843   new->src_id = packet->src_id;
1844   new->src_id_len = packet->src_id_len;
1845   new->src_id_type = packet->src_id_type;
1846   new->dst_id = packet->dst_id;
1847   new->dst_id_len = packet->dst_id_len;
1848   new->dst_id_type = packet->dst_id_type;
1849
1850   buffer = silc_buffer_alloc(1024);
1851   new->buffer = buffer;
1852
1853   while (packet->buffer->len) {
1854     SILC_GET16_MSB(len, packet->buffer->data + 2);
1855     if (len > packet->buffer->len)
1856       break;
1857
1858     if (len > buffer->truelen) {
1859       silc_buffer_free(buffer);
1860       buffer = silc_buffer_alloc(1024 + len);
1861     }
1862
1863     silc_buffer_pull_tail(buffer, len);
1864     silc_buffer_put(buffer, packet->buffer->data, len);
1865
1866     /* Process the Notify */
1867     silc_server_notify(server, sock, new);
1868
1869     silc_buffer_push_tail(buffer, len);
1870     silc_buffer_pull(packet->buffer, len);
1871   }
1872
1873   silc_buffer_free(buffer);
1874   silc_free(new);
1875 }
1876
1877 /* Received private message. This resolves the destination of the message
1878    and sends the packet. This is used by both server and router.  If the
1879    destination is our locally connected client this sends the packet to
1880    the client. This may also send the message for further routing if
1881    the destination is not in our server (or router). */
1882
1883 void silc_server_private_message(SilcServer server,
1884                                  SilcSocketConnection sock,
1885                                  SilcPacketContext *packet)
1886 {
1887   SilcSocketConnection dst_sock;
1888   SilcIDListData idata;
1889   SilcClientEntry client;
1890
1891   SILC_LOG_DEBUG(("Start"));
1892
1893   if (packet->src_id_type != SILC_ID_CLIENT ||
1894       packet->dst_id_type != SILC_ID_CLIENT || !packet->dst_id)
1895     return;
1896
1897   /* Get the route to the client */
1898   dst_sock = silc_server_get_client_route(server, packet->dst_id,
1899                                           packet->dst_id_len, NULL,
1900                                           &idata, &client);
1901   if (!dst_sock) {
1902     SilcBuffer idp;
1903     unsigned char error;
1904
1905     if (client && client->mode & SILC_UMODE_DETACHED) {
1906       SILC_LOG_DEBUG(("Client is detached, discarding packet"));
1907       return;
1908     }
1909
1910     /* Send SILC_NOTIFY_TYPE_ERROR to indicate that such destination ID
1911        does not exist or is invalid. */
1912     idp = silc_id_payload_encode_data(packet->dst_id,
1913                                       packet->dst_id_len,
1914                                       packet->dst_id_type);
1915     if (!idp)
1916       return;
1917
1918     error = SILC_STATUS_ERR_NO_SUCH_CLIENT_ID;
1919     if (packet->src_id_type == SILC_ID_CLIENT) {
1920       SilcClientID *client_id = silc_id_str2id(packet->src_id,
1921                                                packet->src_id_len,
1922                                                packet->src_id_type);
1923       silc_server_send_notify_dest(server, sock, FALSE,
1924                                    client_id, SILC_ID_CLIENT,
1925                                    SILC_NOTIFY_TYPE_ERROR, 2,
1926                                    &error, 1,
1927                                    idp->data, idp->len);
1928       silc_free(client_id);
1929     } else {
1930       silc_server_send_notify(server, sock, FALSE,
1931                               SILC_NOTIFY_TYPE_ERROR, 2,
1932                               &error, 1,
1933                               idp->data, idp->len);
1934     }
1935
1936     silc_buffer_free(idp);
1937     return;
1938   }
1939
1940   /* Check whether destination client wishes to receive private messages */
1941   if (client && !(packet->flags & SILC_PACKET_FLAG_PRIVMSG_KEY) &&
1942       client->mode & SILC_UMODE_BLOCK_PRIVMSG) {
1943     SILC_LOG_DEBUG(("Client blocks private messages, discarding packet"));
1944     return;
1945   }
1946
1947   /* Send the private message */
1948   silc_server_send_private_message(server, dst_sock, idata->send_key,
1949                                    idata->hmac_send, idata->psn_send++,
1950                                    packet);
1951 }
1952
1953 /* Received private message key packet.. This packet is never for us. It is to
1954    the client in the packet's destination ID. Sending of this sort of packet
1955    equals sending private message, ie. it is sent point to point from
1956    one client to another. */
1957
1958 void silc_server_private_message_key(SilcServer server,
1959                                      SilcSocketConnection sock,
1960                                      SilcPacketContext *packet)
1961 {
1962   SilcSocketConnection dst_sock;
1963   SilcIDListData idata;
1964
1965   SILC_LOG_DEBUG(("Start"));
1966
1967   if (packet->src_id_type != SILC_ID_CLIENT ||
1968       packet->dst_id_type != SILC_ID_CLIENT)
1969     return;
1970
1971   if (!packet->dst_id)
1972     return;
1973
1974   /* Get the route to the client */
1975   dst_sock = silc_server_get_client_route(server, packet->dst_id,
1976                                           packet->dst_id_len, NULL,
1977                                           &idata, NULL);
1978   if (!dst_sock)
1979     return;
1980
1981   /* Relay the packet */
1982   silc_server_relay_packet(server, dst_sock, idata->send_key,
1983                            idata->hmac_send, idata->psn_send++, packet, FALSE);
1984 }
1985
1986 /* Processes incoming command reply packet. The command reply packet may
1987    be destined to one of our clients or it may directly for us. We will
1988    call the command reply routine after processing the packet. */
1989
1990 void silc_server_command_reply(SilcServer server,
1991                                SilcSocketConnection sock,
1992                                SilcPacketContext *packet)
1993 {
1994   SilcBuffer buffer = packet->buffer;
1995   SilcClientEntry client = NULL;
1996   SilcSocketConnection dst_sock;
1997   SilcIDListData idata;
1998   SilcClientID *id = NULL;
1999
2000   SILC_LOG_DEBUG(("Start"));
2001
2002   if (packet->dst_id_type == SILC_ID_CHANNEL)
2003     return;
2004
2005   if (packet->dst_id_type == SILC_ID_CLIENT) {
2006     /* Destination must be one of ours */
2007     id = silc_id_str2id(packet->dst_id, packet->dst_id_len, SILC_ID_CLIENT);
2008     if (!id)
2009       return;
2010     client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
2011     if (!client) {
2012       SILC_LOG_ERROR(("Cannot process command reply to unknown client"));
2013       silc_free(id);
2014       return;
2015     }
2016   }
2017
2018   if (packet->dst_id_type == SILC_ID_SERVER) {
2019     /* For now this must be for us */
2020     if (memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
2021       SILC_LOG_ERROR(("Cannot process command reply to unknown server"));
2022       return;
2023     }
2024   }
2025
2026   /* Execute command reply locally for the command */
2027   silc_server_command_reply_process(server, sock, buffer);
2028
2029   if (packet->dst_id_type == SILC_ID_CLIENT && client && id) {
2030     /* Relay the packet to the client */
2031     const SilcBufferStruct p;
2032
2033     dst_sock = (SilcSocketConnection)client->connection;
2034     idata = (SilcIDListData)client;
2035
2036     silc_buffer_push(buffer, SILC_PACKET_HEADER_LEN + packet->src_id_len
2037                      + packet->dst_id_len + packet->padlen);
2038     if (!silc_packet_send_prepare(dst_sock, 0, 0, buffer->len,
2039                                   idata->hmac_send, (const SilcBuffer)&p)) {
2040       SILC_LOG_ERROR(("Cannot send packet"));
2041       return;
2042     }
2043     silc_buffer_put((SilcBuffer)&p, buffer->data, buffer->len);
2044
2045     /* Encrypt packet */
2046     silc_packet_encrypt(idata->send_key, idata->hmac_send, idata->psn_send++,
2047                         (SilcBuffer)&p, buffer->len);
2048
2049     /* Send the packet */
2050     silc_server_packet_send_real(server, dst_sock, TRUE);
2051
2052     silc_free(id);
2053   }
2054 }
2055
2056 /* Process received channel message. The message can be originated from
2057    client or server. */
2058
2059 void silc_server_channel_message(SilcServer server,
2060                                  SilcSocketConnection sock,
2061                                  SilcPacketContext *packet)
2062 {
2063   SilcChannelEntry channel = NULL;
2064   SilcChannelID *id = NULL;
2065   void *sender_id = NULL;
2066   SilcClientEntry sender_entry = NULL;
2067   SilcChannelClientEntry chl;
2068   bool local = TRUE;
2069
2070   SILC_LOG_DEBUG(("Processing channel message"));
2071
2072   /* Sanity checks */
2073   if (packet->dst_id_type != SILC_ID_CHANNEL) {
2074     SILC_LOG_DEBUG(("Received bad message for channel, dropped"));
2075     goto out;
2076   }
2077
2078   /* Find channel entry */
2079   id = silc_id_str2id(packet->dst_id, packet->dst_id_len, SILC_ID_CHANNEL);
2080   if (!id)
2081     goto out;
2082   channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
2083   if (!channel) {
2084     channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
2085     if (!channel) {
2086       SilcBuffer idp;
2087       unsigned char error;
2088
2089       /* Send SILC_NOTIFY_TYPE_ERROR to indicate that such destination ID
2090          does not exist or is invalid. */
2091       idp = silc_id_payload_encode_data(packet->dst_id,
2092                                         packet->dst_id_len,
2093                                         packet->dst_id_type);
2094       if (!idp)
2095         goto out;
2096
2097       error = SILC_STATUS_ERR_NO_SUCH_CHANNEL_ID;
2098       if (packet->src_id_type == SILC_ID_CLIENT) {
2099         SilcClientID *client_id = silc_id_str2id(packet->src_id,
2100                                                  packet->src_id_len,
2101                                                  packet->src_id_type);
2102         silc_server_send_notify_dest(server, sock, FALSE,
2103                                      client_id, SILC_ID_CLIENT,
2104                                      SILC_NOTIFY_TYPE_ERROR, 2,
2105                                      &error, 1, idp->data, idp->len);
2106         silc_free(client_id);
2107       } else {
2108         silc_server_send_notify(server, sock, FALSE,
2109                                 SILC_NOTIFY_TYPE_ERROR, 2,
2110                                 &error, 1, idp->data, idp->len);
2111       }
2112
2113       silc_buffer_free(idp);
2114       goto out;
2115     }
2116   }
2117
2118   /* See that this client is on the channel. If the original sender is
2119      not client (as it can be server as well) we don't do the check. */
2120   sender_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2121                              packet->src_id_type);
2122   if (!sender_id)
2123     goto out;
2124   if (packet->src_id_type == SILC_ID_CLIENT) {
2125     sender_entry = silc_idlist_find_client_by_id(server->local_list,
2126                                                  sender_id, TRUE, NULL);
2127     if (!sender_entry) {
2128       local = FALSE;
2129       sender_entry = silc_idlist_find_client_by_id(server->global_list,
2130                                                    sender_id, TRUE, NULL);
2131     }
2132     if (!sender_entry || !silc_server_client_on_channel(sender_entry,
2133                                                         channel, &chl)) {
2134       SILC_LOG_DEBUG(("Client not on channel"));
2135       goto out;
2136     }
2137
2138     /* If channel is moderated check that client is allowed to send
2139        messages. */
2140     if (channel->mode & SILC_CHANNEL_MODE_SILENCE_USERS &&
2141         !(chl->mode & SILC_CHANNEL_UMODE_CHANOP) &&
2142         !(chl->mode & SILC_CHANNEL_UMODE_CHANFO)) {
2143       SILC_LOG_DEBUG(("Channel is silenced from normal users"));
2144       goto out;
2145     }
2146     if (channel->mode & SILC_CHANNEL_MODE_SILENCE_OPERS &&
2147         chl->mode & SILC_CHANNEL_UMODE_CHANOP &&
2148         !(chl->mode & SILC_CHANNEL_UMODE_CHANFO)) {
2149       SILC_LOG_DEBUG(("Channel is silenced from operators"));
2150       goto out;
2151     }
2152     if (chl->mode & SILC_CHANNEL_UMODE_QUIET) {
2153       SILC_LOG_DEBUG(("Sender is quieted on the channel"));
2154       goto out;
2155     }
2156
2157     /* If the packet is coming from router, but the client entry is local
2158        entry to us then some router is rerouting this to us and it is not
2159        allowed. When the client is local to us it means that we've routed
2160        this packet to network, and now someone is routing it back to us. */
2161     if (server->server_type == SILC_ROUTER &&
2162         sock->type == SILC_SOCKET_TYPE_ROUTER && local) {
2163       SILC_LOG_DEBUG(("Channel message rerouted to the sender, drop it"));
2164       goto out;
2165     }
2166   }
2167
2168   /* Distribute the packet to our local clients. This will send the
2169      packet for further routing as well, if needed. */
2170   silc_server_packet_relay_to_channel(server, sock, channel, sender_id,
2171                                       packet->src_id_type, sender_entry,
2172                                       packet->buffer->data,
2173                                       packet->buffer->len, FALSE);
2174
2175  out:
2176   silc_free(sender_id);
2177   silc_free(id);
2178 }
2179
2180 /* Received channel key packet. We distribute the key to all of our locally
2181    connected clients on the channel. */
2182
2183 void silc_server_channel_key(SilcServer server,
2184                              SilcSocketConnection sock,
2185                              SilcPacketContext *packet)
2186 {
2187   SilcBuffer buffer = packet->buffer;
2188   SilcChannelEntry channel;
2189
2190   if (packet->src_id_type != SILC_ID_SERVER ||
2191       (server->server_type == SILC_ROUTER && !server->backup_router &&
2192        sock->type == SILC_SOCKET_TYPE_ROUTER))
2193     return;
2194
2195   /* Save the channel key */
2196   channel = silc_server_save_channel_key(server, buffer, NULL);
2197   if (!channel) {
2198     SILC_LOG_ERROR(("Bad channel key from %s (%s)",
2199                     sock->hostname, sock->ip));
2200     return;
2201   }
2202
2203   /* Distribute the key to everybody who is on the channel. If we are router
2204      we will also send it to locally connected servers. */
2205   silc_server_send_channel_key(server, sock, channel, FALSE);
2206
2207   if (server->server_type != SILC_BACKUP_ROUTER) {
2208     /* Distribute to local cell backup routers. */
2209     silc_server_backup_send(server, sock->user_data,
2210                             SILC_PACKET_CHANNEL_KEY, 0,
2211                             buffer->data, buffer->len, FALSE, TRUE);
2212   }
2213 }
2214
2215 /* Received New Client packet and processes it.  Creates Client ID for the
2216    client. Client becomes registered after calling this functions. */
2217
2218 SilcClientEntry silc_server_new_client(SilcServer server,
2219                                        SilcSocketConnection sock,
2220                                        SilcPacketContext *packet)
2221 {
2222   SilcBuffer buffer = packet->buffer;
2223   SilcClientEntry client;
2224   SilcClientID *client_id;
2225   SilcIDListData idata;
2226   char *username = NULL, *realname = NULL;
2227   SilcUInt16 username_len;
2228   SilcUInt32 id_len;
2229   int ret;
2230   char *hostname, *nickname;
2231   int nickfail = 0;
2232
2233   SILC_LOG_DEBUG(("Creating new client"));
2234
2235   if (sock->type != SILC_SOCKET_TYPE_CLIENT)
2236     return NULL;
2237
2238   /* Take client entry */
2239   client = (SilcClientEntry)sock->user_data;
2240   idata = (SilcIDListData)client;
2241
2242   /* Remove the old cache entry. */
2243   if (!silc_idcache_del_by_context(server->local_list->clients, client)) {
2244     SILC_LOG_INFO(("Unauthenticated client attempted to register to network"));
2245     silc_server_disconnect_remote(server, sock,
2246                                   SILC_STATUS_ERR_NOT_AUTHENTICATED, NULL);
2247     if (sock->user_data)
2248       silc_server_free_sock_user_data(server, sock, NULL);
2249     return NULL;
2250   }
2251
2252   /* Make sure this client hasn't registered already */
2253   if (idata->status & SILC_IDLIST_STATUS_REGISTERED) {
2254     silc_server_disconnect_remote(server, sock,
2255                                   SILC_STATUS_ERR_OPERATION_ALLOWED,
2256                                   "Too many registrations");
2257     if (sock->user_data)
2258       silc_server_free_sock_user_data(server, sock, NULL);
2259     return NULL;
2260   }
2261
2262   /* Parse incoming packet */
2263   ret = silc_buffer_unformat(buffer,
2264                              SILC_STR_UI16_NSTRING_ALLOC(&username,
2265                                                          &username_len),
2266                              SILC_STR_UI16_STRING_ALLOC(&realname),
2267                              SILC_STR_END);
2268   if (ret == -1) {
2269     silc_free(username);
2270     silc_free(realname);
2271     SILC_LOG_ERROR(("Client %s (%s) sent incomplete information, closing "
2272                     "connection", sock->hostname, sock->ip));
2273     silc_server_disconnect_remote(server, sock,
2274                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2275                                   NULL);
2276     if (sock->user_data)
2277       silc_server_free_sock_user_data(server, sock, NULL);
2278     return NULL;
2279   }
2280
2281   if (!username) {
2282     silc_free(username);
2283     silc_free(realname);
2284     SILC_LOG_ERROR(("Client %s (%s) did not send its username, closing "
2285                     "connection", sock->hostname, sock->ip));
2286     silc_server_disconnect_remote(server, sock,
2287                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2288                                   NULL);
2289     if (sock->user_data)
2290       silc_server_free_sock_user_data(server, sock, NULL);
2291     return NULL;
2292   }
2293
2294   if (username_len > 128)
2295     username[128] = '\0';
2296
2297   /* Check for bad characters for nickname, and modify the nickname if
2298      it includes those. */
2299   if (silc_server_name_bad_chars(username, username_len)) {
2300     nickname = silc_server_name_modify_bad(username, username_len);
2301   } else {
2302     nickname = strdup(username);
2303   }
2304
2305   /* Make sanity checks for the hostname of the client. If the hostname
2306      is provided in the `username' check that it is the same than the
2307      resolved hostname, or if not resolved the hostname that appears in
2308      the client's public key. If the hostname is not present then put
2309      it from the resolved name or from the public key. */
2310   if (strchr(username, '@')) {
2311     SilcPublicKeyIdentifier pident;
2312     int tlen = strcspn(username, "@");
2313     char *phostname = NULL;
2314
2315     hostname = silc_memdup(username + tlen + 1, strlen(username) - tlen - 1);
2316
2317     if (strcmp(sock->hostname, sock->ip) &&
2318         strcmp(sock->hostname, hostname)) {
2319       silc_free(username);
2320       silc_free(hostname);
2321       silc_free(realname);
2322       SILC_LOG_ERROR(("Client %s (%s) sent incomplete information, closing "
2323                       "connection", sock->hostname, sock->ip));
2324       silc_server_disconnect_remote(server, sock,
2325                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2326                                     NULL);
2327       if (sock->user_data)
2328         silc_server_free_sock_user_data(server, sock, NULL);
2329       return NULL;
2330     }
2331
2332     pident = silc_pkcs_decode_identifier(client->data.public_key->identifier);
2333     if (pident) {
2334       phostname = strdup(pident->host);
2335       silc_pkcs_free_identifier(pident);
2336     }
2337
2338     if (!strcmp(sock->hostname, sock->ip) &&
2339         phostname && strcmp(phostname, hostname)) {
2340       silc_free(username);
2341       silc_free(hostname);
2342       silc_free(phostname);
2343       silc_free(realname);
2344       SILC_LOG_ERROR(("Client %s (%s) sent incomplete information, closing "
2345                       "connection", sock->hostname, sock->ip));
2346       silc_server_disconnect_remote(server, sock,
2347                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2348                                     NULL);
2349       if (sock->user_data)
2350         silc_server_free_sock_user_data(server, sock, NULL);
2351       return NULL;
2352     }
2353
2354     silc_free(phostname);
2355   } else {
2356     /* The hostname is not present, add it. */
2357     char *newusername;
2358     /* XXX For now we cannot take the host name from the public key since
2359        they are not trusted or we cannot verify them as trusted. Just take
2360        what the resolved name or address is. */
2361 #if 0
2362     if (strcmp(sock->hostname, sock->ip)) {
2363 #endif
2364       newusername = silc_calloc(strlen(username) +
2365                                 strlen(sock->hostname) + 2,
2366                                 sizeof(*newusername));
2367       strncat(newusername, username, strlen(username));
2368       strncat(newusername, "@", 1);
2369       strncat(newusername, sock->hostname, strlen(sock->hostname));
2370       silc_free(username);
2371       username = newusername;
2372 #if 0
2373     } else {
2374       SilcPublicKeyIdentifier pident =
2375         silc_pkcs_decode_identifier(client->data.public_key->identifier);
2376
2377       if (pident) {
2378         newusername = silc_calloc(strlen(username) +
2379                                   strlen(pident->host) + 2,
2380                                   sizeof(*newusername));
2381         strncat(newusername, username, strlen(username));
2382         strncat(newusername, "@", 1);
2383         strncat(newusername, pident->host, strlen(pident->host));
2384         silc_free(username);
2385         username = newusername;
2386         silc_pkcs_free_identifier(pident);
2387       }
2388     }
2389 #endif
2390   }
2391
2392   /* Create Client ID */
2393   while (!silc_id_create_client_id(server, server->id, server->rng,
2394                                    server->md5hash, nickname, &client_id)) {
2395     nickfail++;
2396     if (nickfail > 9) {
2397       silc_server_disconnect_remote(server, sock,
2398                                     SILC_STATUS_ERR_BAD_NICKNAME, NULL);
2399       if (sock->user_data)
2400         silc_server_free_sock_user_data(server, sock, NULL);
2401       return NULL;
2402     }
2403     snprintf(&nickname[strlen(nickname) - 1], 1, "%d", nickfail);
2404   }
2405
2406   /* If client marked as anonymous, scramble the username and hostname */
2407   if (client->mode & SILC_UMODE_ANONYMOUS) {
2408     char *scramble;
2409
2410     if (strlen(username) >= 2) {
2411       username[0] = silc_rng_get_byte_fast(server->rng);
2412       username[1] = silc_rng_get_byte_fast(server->rng);
2413     }
2414
2415     scramble = silc_hash_babbleprint(server->sha1hash, username,
2416                                      strlen(username));
2417     scramble[5] = '@';
2418     scramble[11] = '.';
2419     memcpy(&scramble[16], ".silc", 5);
2420     scramble[21] = '\0';
2421     silc_free(username);
2422     username = scramble;
2423   }
2424
2425   /* Update client entry */
2426   idata->status |= SILC_IDLIST_STATUS_REGISTERED;
2427   client->nickname = nickname;
2428   client->username = username;
2429   client->userinfo = realname ? realname : strdup(username);
2430   client->id = client_id;
2431   id_len = silc_id_get_len(client_id, SILC_ID_CLIENT);
2432
2433   /* Add the client again to the ID cache */
2434   silc_idcache_add(server->local_list->clients, client->nickname,
2435                    client_id, client, 0, NULL);
2436
2437   /* Notify our router about new client on the SILC network */
2438   silc_server_send_new_id(server, SILC_PRIMARY_ROUTE(server),
2439                           SILC_BROADCAST(server), client->id,
2440                           SILC_ID_CLIENT, id_len);
2441
2442   /* Distribute to backup routers */
2443   if (server->server_type == SILC_ROUTER) {
2444     SilcBuffer idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2445     silc_server_backup_send(server, sock->user_data, SILC_PACKET_NEW_ID, 0,
2446                             idp->data, idp->len, FALSE, TRUE);
2447     silc_buffer_free(idp);
2448   }
2449
2450   /* Send the new client ID to the client. */
2451   silc_server_send_new_id(server, sock, FALSE, client->id, SILC_ID_CLIENT,
2452                           silc_id_get_len(client->id, SILC_ID_CLIENT));
2453
2454   /* Send some nice info to the client */
2455   silc_server_send_connect_notifys(server, sock, client);
2456
2457   /* Check if anyone is watching this nickname */
2458   if (server->server_type == SILC_ROUTER)
2459     silc_server_check_watcher_list(server, client, NULL, 0);
2460
2461   return client;
2462 }
2463
2464 /* Create new server. This processes received New Server packet and
2465    saves the received Server ID. The server is our locally connected
2466    server thus we save all the information and save it to local list.
2467    This funtion can be used by both normal server and router server.
2468    If normal server uses this it means that its router has connected
2469    to the server. If router uses this it means that one of the cell's
2470    servers is connected to the router. */
2471
2472 SilcServerEntry silc_server_new_server(SilcServer server,
2473                                        SilcSocketConnection sock,
2474                                        SilcPacketContext *packet)
2475 {
2476   SilcBuffer buffer = packet->buffer;
2477   SilcServerEntry new_server, server_entry;
2478   SilcServerID *server_id;
2479   SilcIDListData idata;
2480   unsigned char *server_name, *id_string;
2481   SilcUInt16 id_len, name_len;
2482   int ret;
2483   bool local = TRUE;
2484
2485   SILC_LOG_DEBUG(("Creating new server"));
2486
2487   if (sock->type != SILC_SOCKET_TYPE_SERVER &&
2488       sock->type != SILC_SOCKET_TYPE_ROUTER)
2489     return NULL;
2490
2491   /* Take server entry */
2492   new_server = (SilcServerEntry)sock->user_data;
2493   idata = (SilcIDListData)new_server;
2494
2495   /* Remove the old cache entry */
2496   if (!silc_idcache_del_by_context(server->local_list->servers, new_server)) {
2497     if (!silc_idcache_del_by_context(server->global_list->servers,
2498                                      new_server)) {
2499       SILC_LOG_INFO(("Unauthenticated %s attempted to register to "
2500                      "network", (sock->type == SILC_SOCKET_TYPE_SERVER ?
2501                                  "server" : "router")));
2502       silc_server_disconnect_remote(server, sock,
2503                                     SILC_STATUS_ERR_NOT_AUTHENTICATED, NULL);
2504       if (sock->user_data)
2505         silc_server_free_sock_user_data(server, sock, NULL);
2506       return NULL;
2507     }
2508     local = FALSE;
2509   }
2510
2511   /* Make sure this server hasn't registered already */
2512   if (idata->status & SILC_IDLIST_STATUS_REGISTERED) {
2513     silc_server_disconnect_remote(server, sock,
2514                                   SILC_STATUS_ERR_OPERATION_ALLOWED,
2515                                   "Too many registrations");
2516     if (sock->user_data)
2517       silc_server_free_sock_user_data(server, sock, NULL);
2518     return NULL;
2519   }
2520
2521   /* Parse the incoming packet */
2522   ret = silc_buffer_unformat(buffer,
2523                              SILC_STR_UI16_NSTRING_ALLOC(&id_string, &id_len),
2524                              SILC_STR_UI16_NSTRING_ALLOC(&server_name,
2525                                                          &name_len),
2526                              SILC_STR_END);
2527   if (ret == -1) {
2528     silc_free(id_string);
2529     silc_free(server_name);
2530     silc_server_disconnect_remote(server, sock,
2531                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2532                                   NULL);
2533     if (sock->user_data)
2534       silc_server_free_sock_user_data(server, sock, NULL);
2535     return NULL;
2536   }
2537
2538   if (id_len > buffer->len) {
2539     silc_free(id_string);
2540     silc_free(server_name);
2541     silc_server_disconnect_remote(server, sock,
2542                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2543                                   NULL);
2544     if (sock->user_data)
2545       silc_server_free_sock_user_data(server, sock, NULL);
2546     return NULL;
2547   }
2548
2549   if (name_len > 256)
2550     server_name[255] = '\0';
2551
2552   /* Get Server ID */
2553   server_id = silc_id_str2id(id_string, id_len, SILC_ID_SERVER);
2554   if (!server_id) {
2555     silc_free(id_string);
2556     silc_free(server_name);
2557     silc_server_disconnect_remote(server, sock,
2558                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2559                                   NULL);
2560     if (sock->user_data)
2561       silc_server_free_sock_user_data(server, sock, NULL);
2562     return NULL;
2563   }
2564   silc_free(id_string);
2565
2566   /* Check for valid server ID */
2567   if (!silc_id_is_valid_server_id(server, server_id, sock)) {
2568     SILC_LOG_INFO(("Invalid server ID sent by %s (%s)",
2569                    sock->ip, sock->hostname));
2570     silc_server_disconnect_remote(server, sock,
2571                                   SILC_STATUS_ERR_BAD_SERVER_ID, NULL);
2572     if (sock->user_data)
2573       silc_server_free_sock_user_data(server, sock, NULL);
2574     silc_free(server_name);
2575     return NULL;
2576   }
2577
2578   /* Check that we do not have this ID already */
2579   server_entry = silc_idlist_find_server_by_id(server->local_list,
2580                                                server_id, TRUE, NULL);
2581   if (server_entry) {
2582     if (SILC_IS_LOCAL(server_entry)) {
2583       silc_server_disconnect_remote(server, server_entry->connection,
2584                                     SILC_STATUS_ERR_OPERATION_ALLOWED,
2585                                     "Too many registrations");
2586       if (((SilcSocketConnection)server_entry->connection)->user_data)
2587         silc_server_free_sock_user_data(server, sock, NULL);
2588     } else {
2589       silc_idcache_del_by_context(server->local_list->servers, server_entry);
2590     }
2591   } else {
2592     server_entry = silc_idlist_find_server_by_id(server->global_list,
2593                                                  server_id, TRUE, NULL);
2594     if (server_entry) {
2595       if (SILC_IS_LOCAL(server_entry)) {
2596         silc_server_disconnect_remote(server, server_entry->connection,
2597                                       SILC_STATUS_ERR_OPERATION_ALLOWED,
2598                                       "Too many registrations");
2599         if (((SilcSocketConnection)server_entry->connection)->user_data)
2600           silc_server_free_sock_user_data(server, server_entry->connection,
2601                                           NULL);
2602       } else {
2603         silc_idcache_del_by_context(server->global_list->servers,
2604                                     server_entry);
2605       }
2606     }
2607   }
2608
2609   /* Update server entry */
2610   idata->status |= SILC_IDLIST_STATUS_REGISTERED;
2611   new_server->server_name = server_name;
2612   new_server->id = server_id;
2613
2614   SILC_LOG_DEBUG(("New server id(%s)",
2615                   silc_id_render(server_id, SILC_ID_SERVER)));
2616
2617   /* Add again the entry to the ID cache. */
2618   silc_idcache_add(local ? server->local_list->servers :
2619                    server->global_list->servers, server_name, server_id,
2620                    new_server, 0, NULL);
2621
2622   /* Distribute the information about new server in the SILC network
2623      to our router. If we are normal server we won't send anything
2624      since this connection must be our router connection. */
2625   if (server->server_type == SILC_ROUTER && !server->standalone &&
2626       SILC_PRIMARY_ROUTE(server) != sock)
2627     silc_server_send_new_id(server, SILC_PRIMARY_ROUTE(server),
2628                             TRUE, new_server->id, SILC_ID_SERVER,
2629                             silc_id_get_len(server_id, SILC_ID_SERVER));
2630
2631   if (server->server_type == SILC_ROUTER) {
2632     /* Distribute to backup routers */
2633     SilcBuffer idp = silc_id_payload_encode(new_server->id, SILC_ID_SERVER);
2634     silc_server_backup_send(server, sock->user_data, SILC_PACKET_NEW_ID, 0,
2635                             idp->data, idp->len, FALSE, TRUE);
2636     silc_buffer_free(idp);
2637
2638     /* Statistics */
2639     server->stat.cell_servers++;
2640   }
2641
2642   /* Check whether this router connection has been replaced by an
2643      backup router. If it has been then we'll disable the server and will
2644      ignore everything it will send until the backup router resuming
2645      protocol has been completed. */
2646   if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
2647       silc_server_backup_replaced_get(server, server_id, NULL)) {
2648     /* Send packet to the router indicating that it cannot use this
2649        connection as it has been replaced by backup router. */
2650     SILC_LOG_DEBUG(("Remote router has been replaced by backup router, "
2651                     "disabling its connection"));
2652
2653     silc_server_backup_send_replaced(server, sock);
2654
2655     /* Mark the router disabled. The data sent earlier will go but nothing
2656        after this goes to this connection. */
2657     idata->status |= SILC_IDLIST_STATUS_DISABLED;
2658   } else {
2659     /* If it is router announce our stuff to it. */
2660     if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
2661         server->server_type == SILC_ROUTER) {
2662       silc_server_announce_servers(server, FALSE, 0, sock);
2663       silc_server_announce_clients(server, 0, sock);
2664       silc_server_announce_channels(server, 0, sock);
2665     }
2666
2667     /* Announce our information to backup router */
2668     if (new_server->server_type == SILC_BACKUP_ROUTER &&
2669         sock->type == SILC_SOCKET_TYPE_SERVER &&
2670         server->server_type == SILC_ROUTER) {
2671       silc_server_announce_servers(server, TRUE, 0, sock);
2672       silc_server_announce_clients(server, 0, sock);
2673       silc_server_announce_channels(server, 0, sock);
2674     }
2675
2676     /* If backup router, mark it as one of ours.  This server is considered
2677        to be backup router after this setting. */
2678     if (new_server->server_type == SILC_BACKUP_ROUTER) {
2679       SilcServerConfigRouter *backup;
2680       backup = silc_server_config_find_backup_conn(server, sock->ip);
2681       if (!backup)
2682         backup = silc_server_config_find_backup_conn(server, sock->hostname);
2683       if (backup) {
2684         /* Add as our backup router */
2685         silc_server_backup_add(server, new_server, backup->backup_replace_ip,
2686                                backup->backup_replace_port,
2687                                backup->backup_local);
2688       }
2689     }
2690
2691     /* By default the servers connected to backup router are disabled
2692        until backup router has become the primary */
2693     if (server->server_type == SILC_BACKUP_ROUTER &&
2694         sock->type == SILC_SOCKET_TYPE_SERVER)
2695       idata->status |= SILC_IDLIST_STATUS_DISABLED;
2696   }
2697
2698   return new_server;
2699 }
2700
2701 /* Processes incoming New ID packet. New ID Payload is used to distribute
2702    information about newly registered clients and servers. */
2703
2704 static void silc_server_new_id_real(SilcServer server,
2705                                     SilcSocketConnection sock,
2706                                     SilcPacketContext *packet,
2707                                     int broadcast)
2708 {
2709   SilcBuffer buffer = packet->buffer;
2710   SilcIDList id_list;
2711   SilcServerEntry router, server_entry;
2712   SilcSocketConnection router_sock;
2713   SilcIDPayload idp;
2714   SilcIdType id_type;
2715   void *id;
2716
2717   SILC_LOG_DEBUG(("Processing new ID"));
2718
2719   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
2720       server->server_type == SILC_SERVER ||
2721       packet->src_id_type != SILC_ID_SERVER)
2722     return;
2723
2724   idp = silc_id_payload_parse(buffer->data, buffer->len);
2725   if (!idp)
2726     return;
2727
2728   id_type = silc_id_payload_get_type(idp);
2729
2730   /* Normal server cannot have other normal server connections */
2731   server_entry = (SilcServerEntry)sock->user_data;
2732   if (id_type == SILC_ID_SERVER && sock->type == SILC_SOCKET_TYPE_SERVER &&
2733       server_entry->server_type == SILC_SERVER)
2734     goto out;
2735
2736   id = silc_id_payload_get_id(idp);
2737   if (!id)
2738     goto out;
2739
2740   /* If the packet is coming from server then use the sender as the
2741      origin of the the packet. If it came from router then check the real
2742      sender of the packet and use that as the origin. */
2743   if (sock->type == SILC_SOCKET_TYPE_SERVER) {
2744     id_list = server->local_list;
2745     router_sock = sock;
2746     router = sock->user_data;
2747
2748     /* If the sender is backup router and ID is server (and we are not
2749        backup router) then switch the entry to global list. */
2750     if (server_entry->server_type == SILC_BACKUP_ROUTER &&
2751         id_type == SILC_ID_SERVER &&
2752         server->id_entry->server_type != SILC_BACKUP_ROUTER) {
2753       id_list = server->global_list;
2754       router_sock = server->router ? SILC_PRIMARY_ROUTE(server) : sock;
2755     }
2756   } else {
2757     void *sender_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2758                                      packet->src_id_type);
2759     router = silc_idlist_find_server_by_id(server->global_list,
2760                                            sender_id, TRUE, NULL);
2761     if (!router)
2762       router = silc_idlist_find_server_by_id(server->local_list,
2763                                              sender_id, TRUE, NULL);
2764     silc_free(sender_id);
2765     router_sock = sock;
2766     id_list = server->global_list;
2767   }
2768
2769   if (!router)
2770     goto out;
2771
2772   switch(id_type) {
2773   case SILC_ID_CLIENT:
2774     {
2775       SilcClientEntry entry;
2776
2777       /* Check that we do not have this client already */
2778       entry = silc_idlist_find_client_by_id(server->global_list,
2779                                             id, server->server_type,
2780                                             NULL);
2781       if (!entry)
2782         entry = silc_idlist_find_client_by_id(server->local_list,
2783                                               id, server->server_type,
2784                                               NULL);
2785       if (entry) {
2786         SILC_LOG_DEBUG(("Ignoring client that we already have"));
2787         goto out;
2788       }
2789
2790       SILC_LOG_DEBUG(("New client id(%s) from [%s] %s",
2791                       silc_id_render(id, SILC_ID_CLIENT),
2792                       sock->type == SILC_SOCKET_TYPE_SERVER ?
2793                       "Server" : "Router", sock->hostname));
2794
2795       /* As a router we keep information of all global information in our
2796          global list. Cell wide information however is kept in the local
2797          list. */
2798       entry = silc_idlist_add_client(id_list, NULL, NULL, NULL,
2799                                      id, router, NULL, 0);
2800       if (!entry) {
2801         SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
2802
2803         /* Inform the sender that the ID is not usable */
2804         silc_server_send_notify_signoff(server, sock, FALSE, id, NULL);
2805         goto out;
2806       }
2807       entry->nickname = NULL;
2808       entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
2809
2810       if (sock->type == SILC_SOCKET_TYPE_SERVER)
2811         server->stat.cell_clients++;
2812       server->stat.clients++;
2813
2814       /* Check if anyone is watching this nickname */
2815       if (server->server_type == SILC_ROUTER && id_list == server->local_list)
2816         silc_server_check_watcher_list(server, entry, NULL, 0);
2817     }
2818     break;
2819
2820   case SILC_ID_SERVER:
2821     {
2822       SilcServerEntry entry;
2823
2824       /* If the ID is mine, ignore it. */
2825       if (SILC_ID_SERVER_COMPARE(id, server->id)) {
2826         SILC_LOG_DEBUG(("Ignoring my own ID as new ID"));
2827         break;
2828       }
2829
2830       /* If the ID is the sender's ID, ignore it (we have it already) */
2831       if (SILC_ID_SERVER_COMPARE(id, router->id)) {
2832         SILC_LOG_DEBUG(("Ignoring sender's own ID"));
2833         break;
2834       }
2835
2836       /* Check that we do not have this server already */
2837       entry = silc_idlist_find_server_by_id(server->global_list,
2838                                             id, server->server_type,
2839                                             NULL);
2840       if (!entry)
2841         entry = silc_idlist_find_server_by_id(server->local_list,
2842                                               id, server->server_type,
2843                                               NULL);
2844       if (entry) {
2845         SILC_LOG_DEBUG(("Ignoring server that we already have"));
2846         goto out;
2847       }
2848
2849       SILC_LOG_DEBUG(("New server id(%s) from [%s] %s",
2850                       silc_id_render(id, SILC_ID_SERVER),
2851                       sock->type == SILC_SOCKET_TYPE_SERVER ?
2852                       "Server" : "Router", sock->hostname));
2853
2854       /* As a router we keep information of all global information in our
2855          global list. Cell wide information however is kept in the local
2856          list. */
2857       entry = silc_idlist_add_server(id_list, NULL, 0, id, router,
2858                                      router_sock);
2859       if (!entry) {
2860         SILC_LOG_ERROR(("Could not add new server to the ID Cache"));
2861         goto out;
2862       }
2863       entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
2864
2865       if (sock->type == SILC_SOCKET_TYPE_SERVER)
2866         server->stat.cell_servers++;
2867       server->stat.servers++;
2868     }
2869     break;
2870
2871   case SILC_ID_CHANNEL:
2872     SILC_LOG_ERROR(("Channel cannot be registered with NEW_ID packet"));
2873     goto out;
2874     break;
2875
2876   default:
2877     goto out;
2878     break;
2879   }
2880
2881   /* If the sender of this packet is server and we are router we need to
2882      broadcast this packet to other routers in the network. */
2883   if (broadcast && server->server_type == SILC_ROUTER &&
2884       sock->type == SILC_SOCKET_TYPE_SERVER &&
2885       !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
2886     SILC_LOG_DEBUG(("Broadcasting received New ID packet"));
2887     silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
2888                             packet->type,
2889                             packet->flags | SILC_PACKET_FLAG_BROADCAST,
2890                             buffer->data, buffer->len, FALSE);
2891     silc_server_backup_send(server, sock->user_data,
2892                             packet->type, packet->flags,
2893                             packet->buffer->data, packet->buffer->len,
2894                             FALSE, TRUE);
2895   }
2896
2897  out:
2898   silc_id_payload_free(idp);
2899 }
2900
2901
2902 /* Processes incoming New ID packet. New ID Payload is used to distribute
2903    information about newly registered clients and servers. */
2904
2905 void silc_server_new_id(SilcServer server, SilcSocketConnection sock,
2906                         SilcPacketContext *packet)
2907 {
2908   silc_server_new_id_real(server, sock, packet, TRUE);
2909 }
2910
2911 /* Receoved New Id List packet, list of New ID payloads inside one
2912    packet. Process the New ID payloads one by one. */
2913
2914 void silc_server_new_id_list(SilcServer server, SilcSocketConnection sock,
2915                              SilcPacketContext *packet)
2916 {
2917   SilcPacketContext *new_id;
2918   SilcBuffer idp;
2919   SilcUInt16 id_len;
2920
2921   SILC_LOG_DEBUG(("Processing New ID List"));
2922
2923   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
2924       packet->src_id_type != SILC_ID_SERVER)
2925     return;
2926
2927   /* If the sender of this packet is server and we are router we need to
2928      broadcast this packet to other routers in the network. Broadcast
2929      this list packet instead of multiple New ID packets. */
2930   if (server->server_type == SILC_ROUTER &&
2931       sock->type == SILC_SOCKET_TYPE_SERVER &&
2932       !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
2933     SILC_LOG_DEBUG(("Broadcasting received New ID List packet"));
2934     silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
2935                             packet->type,
2936                             packet->flags | SILC_PACKET_FLAG_BROADCAST,
2937                             packet->buffer->data,
2938                             packet->buffer->len, FALSE);
2939     silc_server_backup_send(server, sock->user_data,
2940                             packet->type, packet->flags,
2941                             packet->buffer->data, packet->buffer->len,
2942                             FALSE, TRUE);
2943   }
2944
2945   /* Make copy of the original packet context, except for the actual
2946      data buffer, which we will here now fetch from the original buffer. */
2947   new_id = silc_packet_context_alloc();
2948   new_id->type = SILC_PACKET_NEW_ID;
2949   new_id->flags = packet->flags & (~SILC_PACKET_FLAG_LIST);
2950   new_id->src_id = packet->src_id;
2951   new_id->src_id_len = packet->src_id_len;
2952   new_id->src_id_type = packet->src_id_type;
2953   new_id->dst_id = packet->dst_id;
2954   new_id->dst_id_len = packet->dst_id_len;
2955   new_id->dst_id_type = packet->dst_id_type;
2956
2957   idp = silc_buffer_alloc(256);
2958   new_id->buffer = idp;
2959
2960   while (packet->buffer->len) {
2961     SILC_GET16_MSB(id_len, packet->buffer->data + 2);
2962     if ((id_len > packet->buffer->len) ||
2963         (id_len > idp->truelen))
2964       break;
2965
2966     silc_buffer_pull_tail(idp, 4 + id_len);
2967     silc_buffer_put(idp, packet->buffer->data, 4 + id_len);
2968
2969     /* Process the New ID */
2970     silc_server_new_id_real(server, sock, new_id, FALSE);
2971
2972     silc_buffer_push_tail(idp, 4 + id_len);
2973     silc_buffer_pull(packet->buffer, 4 + id_len);
2974   }
2975
2976   silc_buffer_free(idp);
2977   silc_free(new_id);
2978 }
2979
2980 /* Received New Channel packet. Information about new channels in the
2981    network are distributed using this packet. Save the information about
2982    the new channel. This usually comes from router but also normal server
2983    can send this to notify channels it has when it connects to us. */
2984
2985 void silc_server_new_channel(SilcServer server,
2986                              SilcSocketConnection sock,
2987                              SilcPacketContext *packet)
2988 {
2989   SilcChannelPayload payload;
2990   SilcChannelID *channel_id;
2991   char *channel_name;
2992   SilcUInt32 name_len;
2993   unsigned char *id;
2994   SilcUInt32 id_len, cipher_len;
2995   SilcServerEntry server_entry;
2996   SilcChannelEntry channel;
2997   const char *cipher;
2998
2999   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
3000       packet->src_id_type != SILC_ID_SERVER ||
3001       server->server_type == SILC_SERVER)
3002     return;
3003
3004   /* Parse the channel payload */
3005   payload = silc_channel_payload_parse(packet->buffer->data,
3006                                        packet->buffer->len);
3007   if (!payload)
3008     return;
3009
3010   /* Get the channel ID */
3011   channel_id = silc_channel_get_id_parse(payload);
3012   if (!channel_id) {
3013     silc_channel_payload_free(payload);
3014     return;
3015   }
3016
3017   channel_name = silc_channel_get_name(payload, &name_len);
3018   if (name_len > 256)
3019     channel_name[255] = '\0';
3020
3021   id = silc_channel_get_id(payload, &id_len);
3022
3023   server_entry = (SilcServerEntry)sock->user_data;
3024
3025   if (sock->type == SILC_SOCKET_TYPE_ROUTER) {
3026     /* Add the channel to global list as it is coming from router. It
3027        cannot be our own channel as it is coming from router. */
3028
3029     /* Check that we don't already have this channel */
3030     channel = silc_idlist_find_channel_by_name(server->local_list,
3031                                                channel_name, NULL);
3032     if (!channel)
3033       channel = silc_idlist_find_channel_by_name(server->global_list,
3034                                                  channel_name, NULL);
3035     if (!channel) {
3036       SILC_LOG_DEBUG(("New channel id(%s) from [Router] %s",
3037                       silc_id_render(channel_id, SILC_ID_CHANNEL),
3038                       sock->hostname));
3039
3040       channel =
3041         silc_idlist_add_channel(server->global_list, strdup(channel_name),
3042                                 0, channel_id, sock->user_data, NULL, NULL, 0);
3043       if (!channel) {
3044         silc_channel_payload_free(payload);
3045         silc_free(channel_id);
3046         return;
3047       }
3048       channel->disabled = TRUE;    /* Disabled until someone JOINs */
3049
3050       server->stat.channels++;
3051       if (server->server_type == SILC_ROUTER)
3052         channel->users_resolved = TRUE;
3053     }
3054   } else {
3055     /* The channel is coming from our server, thus it is in our cell
3056        we will add it to our local list. */
3057     SilcBuffer chk;
3058
3059     SILC_LOG_DEBUG(("Channel id(%s) from [Server] %s",
3060                     silc_id_render(channel_id, SILC_ID_CHANNEL),
3061                     sock->hostname));
3062
3063     /* Check that we don't already have this channel */
3064     channel = silc_idlist_find_channel_by_name(server->local_list,
3065                                                channel_name, NULL);
3066     if (!channel)
3067       channel = silc_idlist_find_channel_by_name(server->global_list,
3068                                                  channel_name, NULL);
3069
3070     /* If the channel does not exist, then create it. This creates a new
3071        key to the channel as well that we will send to the server. */
3072     if (!channel) {
3073       SILC_LOG_DEBUG(("Channel is new to us"));
3074
3075       /* The protocol says that the Channel ID's IP address must be based
3076          on the router's IP address.  Check whether the ID is based in our
3077          IP and if it is not then create a new ID and enforce the server
3078          to switch the ID. */
3079       if (server_entry->server_type != SILC_BACKUP_ROUTER &&
3080           !SILC_ID_COMPARE(channel_id, server->id, server->id->ip.data_len)) {
3081         SilcChannelID *tmp;
3082         SILC_LOG_DEBUG(("Forcing the server to change Channel ID"));
3083         if (silc_id_create_channel_id(server, server->id, server->rng, &tmp)) {
3084           silc_server_send_notify_channel_change(server, sock, FALSE,
3085                                                  channel_id, tmp);
3086           silc_channel_payload_free(payload);
3087           silc_free(channel_id);
3088           silc_free(tmp);
3089         }
3090
3091         /* Wait that server re-announces this channel */
3092         return;
3093       }
3094
3095       /* Create the channel with the provided Channel ID */
3096       channel = silc_server_create_new_channel_with_id(server, NULL, NULL,
3097                                                        channel_name,
3098                                                        channel_id, FALSE);
3099       if (!channel) {
3100         silc_channel_payload_free(payload);
3101         silc_free(channel_id);
3102         return;
3103       }
3104       channel->disabled = TRUE;    /* Disabled until someone JOINs */
3105
3106 #if 0 /* We assume that CMODE_CHANGE notify is sent to us after this. */
3107
3108       /* XXX Dunno if this is supposed to be set in any server type.  If set
3109          here the CMODE_CHANGE that may follow sets mode that we already
3110          have, and we may loose data from the CMODE_CHANGE notify. */
3111       if (server_entry->server_type != SILC_BACKUP_ROUTER)
3112         channel->mode = silc_channel_get_mode(payload);
3113 #endif
3114
3115       /* Send the new channel key to the server */
3116       id = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3117       id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3118       cipher = silc_cipher_get_name(channel->channel_key);
3119       cipher_len = strlen(cipher);
3120       chk = silc_channel_key_payload_encode(id_len, id,
3121                                             cipher_len, cipher,
3122                                             channel->key_len / 8,
3123                                             channel->key);
3124       silc_server_packet_send(server, sock, SILC_PACKET_CHANNEL_KEY, 0,
3125                               chk->data, chk->len, FALSE);
3126       silc_buffer_free(chk);
3127       silc_free(id);
3128     } else {
3129       /* The channel exist by that name, check whether the ID's match.
3130          If they don't then we'll force the server to use the ID we have.
3131          We also create a new key for the channel. */
3132       SilcBuffer modes = NULL, users = NULL, users_modes = NULL;
3133
3134       SILC_LOG_DEBUG(("Channel already exists"));
3135
3136       if (!SILC_ID_CHANNEL_COMPARE(channel_id, channel->id)) {
3137         /* They don't match, send CHANNEL_CHANGE notify to the server to
3138            force the ID change. */
3139         SILC_LOG_DEBUG(("Forcing the server to change Channel ID"));
3140         silc_server_send_notify_channel_change(server, sock, FALSE,
3141                                                channel_id, channel->id);
3142         silc_channel_payload_free(payload);
3143         silc_free(channel_id);
3144
3145         /* Wait that server re-announces this channel */
3146         return;
3147       }
3148
3149 #if 0 /* We will announce our CMODE anyway for this channel, so no need
3150          to check it (implicit enforce). */
3151
3152       /* If the mode is different from what we have then enforce the
3153          mode change. */
3154       mode = silc_channel_get_mode(payload);
3155       if (channel->mode != mode) {
3156         SILC_LOG_DEBUG(("Forcing the server to change channel mode"));
3157         silc_server_send_notify_cmode(server, sock, FALSE, channel,
3158                                       channel->mode, server->id,
3159                                       SILC_ID_SERVER, channel->cipher,
3160                                       channel->hmac_name,
3161                                       channel->passphrase,
3162                                       channel->founder_key);
3163       }
3164 #endif
3165
3166       /* Create new key for the channel and send it to the server and
3167          everybody else possibly on the channel. */
3168       if (!(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
3169
3170         if (silc_hash_table_count(channel->user_list)) {
3171           if (!silc_server_create_channel_key(server, channel, 0)) {
3172             silc_channel_payload_free(payload);
3173             silc_free(channel_id);
3174             return;
3175           }
3176
3177           /* Send to the channel */
3178           silc_server_send_channel_key(server, sock, channel, FALSE);
3179         }
3180
3181         /* Send to the server */
3182         id = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3183         id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3184         cipher = silc_cipher_get_name(channel->channel_key);
3185         cipher_len = strlen(cipher);
3186         chk = silc_channel_key_payload_encode(id_len, id,
3187                                               cipher_len, cipher,
3188                                               channel->key_len / 8,
3189                                               channel->key);
3190         silc_server_packet_send(server, sock, SILC_PACKET_CHANNEL_KEY, 0,
3191                                 chk->data, chk->len, FALSE);
3192         silc_buffer_free(chk);
3193         silc_free(id);
3194       }
3195
3196       silc_free(channel_id);
3197
3198       /* Since the channel is coming from server and we also know about it
3199          then send the JOIN notify to the server so that it see's our
3200          users on the channel "joining" the channel. */
3201       silc_server_announce_get_channel_users(server, channel, &modes, &users,
3202                                              &users_modes);
3203       if (users) {
3204         silc_buffer_push(users, users->data - users->head);
3205         silc_server_packet_send(server, sock,
3206                                 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3207                                 users->data, users->len, FALSE);
3208         silc_buffer_free(users);
3209       }
3210       if (modes) {
3211         silc_buffer_push(modes, modes->data - 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                                      modes->data, modes->len, FALSE);
3216         silc_buffer_free(modes);
3217       }
3218       if (users_modes) {
3219         silc_buffer_push(users_modes, users_modes->data - users_modes->head);
3220         silc_server_packet_send_dest(server, sock,
3221                                      SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3222                                      channel->id, SILC_ID_CHANNEL,
3223                                      users_modes->data,
3224                                      users_modes->len, FALSE);
3225         silc_buffer_free(users_modes);
3226       }
3227       if (channel->topic) {
3228         silc_server_send_notify_topic_set(server, sock,
3229                                           server->server_type == SILC_ROUTER ?
3230                                           TRUE : FALSE, channel,
3231                                           server->id, SILC_ID_SERVER,
3232                                           channel->topic);
3233       }
3234     }
3235   }
3236
3237   /* If the sender of this packet is server and we are router we need to
3238      broadcast this packet to other routers in the network. Broadcast
3239      this list packet instead of multiple New Channel packets. */
3240   if (server->server_type == SILC_ROUTER &&
3241       sock->type == SILC_SOCKET_TYPE_SERVER &&
3242       !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
3243     SILC_LOG_DEBUG(("Broadcasting received New Channel packet"));
3244     silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
3245                             packet->type,
3246                             packet->flags | SILC_PACKET_FLAG_BROADCAST,
3247                             packet->buffer->data,
3248                             packet->buffer->len, FALSE);
3249     silc_server_backup_send(server, sock->user_data,
3250                             packet->type, packet->flags,
3251                             packet->buffer->data, packet->buffer->len,
3252                             FALSE, TRUE);
3253   }
3254
3255   silc_channel_payload_free(payload);
3256 }
3257
3258 /* Received New Channel List packet, list of New Channel List payloads inside
3259    one packet. Process the New Channel payloads one by one. */
3260
3261 void silc_server_new_channel_list(SilcServer server,
3262                                   SilcSocketConnection sock,
3263                                   SilcPacketContext *packet)
3264 {
3265   SilcPacketContext *new;
3266   SilcBuffer buffer;
3267   SilcUInt16 len1, len2;
3268
3269   SILC_LOG_DEBUG(("Processing New Channel List"));
3270
3271   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
3272       packet->src_id_type != SILC_ID_SERVER ||
3273       server->server_type == SILC_SERVER)
3274     return;
3275
3276   /* Make copy of the original packet context, except for the actual
3277      data buffer, which we will here now fetch from the original buffer. */
3278   new = silc_packet_context_alloc();
3279   new->type = SILC_PACKET_NEW_CHANNEL;
3280   new->flags = packet->flags & (~SILC_PACKET_FLAG_LIST);
3281   new->src_id = packet->src_id;
3282   new->src_id_len = packet->src_id_len;
3283   new->src_id_type = packet->src_id_type;
3284   new->dst_id = packet->dst_id;
3285   new->dst_id_len = packet->dst_id_len;
3286   new->dst_id_type = packet->dst_id_type;
3287
3288   buffer = silc_buffer_alloc(512);
3289   new->buffer = buffer;
3290
3291   while (packet->buffer->len) {
3292     SILC_GET16_MSB(len1, packet->buffer->data);
3293     if ((len1 > packet->buffer->len) ||
3294         (len1 > buffer->truelen))
3295       break;
3296
3297     SILC_GET16_MSB(len2, packet->buffer->data + 2 + len1);
3298     if ((len2 > packet->buffer->len) ||
3299         (len2 > buffer->truelen))
3300       break;
3301
3302     silc_buffer_pull_tail(buffer, 8 + len1 + len2);
3303     silc_buffer_put(buffer, packet->buffer->data, 8 + len1 + len2);
3304
3305     /* Process the New Channel */
3306     silc_server_new_channel(server, sock, new);
3307
3308     silc_buffer_push_tail(buffer, 8 + len1 + len2);
3309     silc_buffer_pull(packet->buffer, 8 + len1 + len2);
3310   }
3311
3312   silc_buffer_free(buffer);
3313   silc_free(new);
3314 }
3315
3316 /* Received key agreement packet. This packet is never for us. It is to
3317    the client in the packet's destination ID. Sending of this sort of packet
3318    equals sending private message, ie. it is sent point to point from
3319    one client to another. */
3320
3321 void silc_server_key_agreement(SilcServer server,
3322                                SilcSocketConnection sock,
3323                                SilcPacketContext *packet)
3324 {
3325   SilcSocketConnection dst_sock;
3326   SilcIDListData idata;
3327
3328   SILC_LOG_DEBUG(("Start"));
3329
3330   if (packet->src_id_type != SILC_ID_CLIENT ||
3331       packet->dst_id_type != SILC_ID_CLIENT)
3332     return;
3333
3334   if (!packet->dst_id)
3335     return;
3336
3337   /* Get the route to the client */
3338   dst_sock = silc_server_get_client_route(server, packet->dst_id,
3339                                           packet->dst_id_len, NULL,
3340                                           &idata, NULL);
3341   if (!dst_sock)
3342     return;
3343
3344   /* Relay the packet */
3345   silc_server_relay_packet(server, dst_sock, idata->send_key,
3346                            idata->hmac_send, idata->psn_send++,
3347                            packet, FALSE);
3348 }
3349
3350 /* Received connection auth request packet that is used during connection
3351    phase to resolve the mandatory authentication method.  This packet can
3352    actually be received at anytime but usually it is used only during
3353    the connection authentication phase. Now, protocol says that this packet
3354    can come from client or server, however, we support only this coming
3355    from client and expect that server always knows what authentication
3356    method to use. */
3357
3358 void silc_server_connection_auth_request(SilcServer server,
3359                                          SilcSocketConnection sock,
3360                                          SilcPacketContext *packet)
3361 {
3362   SilcServerConfigClient *client = NULL;
3363   SilcUInt16 conn_type;
3364   int ret;
3365   SilcAuthMethod auth_meth = SILC_AUTH_NONE;
3366
3367   if (packet->src_id_type && packet->src_id_type != SILC_ID_CLIENT) {
3368     SILC_LOG_DEBUG(("Request not from client"));
3369     return;
3370   }
3371
3372   /* Parse the payload */
3373   ret = silc_buffer_unformat(packet->buffer,
3374                              SILC_STR_UI_SHORT(&conn_type),
3375                              SILC_STR_UI_SHORT(NULL),
3376                              SILC_STR_END);
3377   if (ret == -1)
3378     return;
3379
3380   if (conn_type != SILC_SOCKET_TYPE_CLIENT)
3381     return;
3382
3383   /* Get the authentication method for the client */
3384   auth_meth = SILC_AUTH_NONE;
3385   client = silc_server_config_find_client(server, sock->ip);
3386   if (!client)
3387     client = silc_server_config_find_client(server, sock->hostname);
3388   if (client) {
3389     if (client->passphrase) {
3390       if (client->publickeys && !server->config->prefer_passphrase_auth)
3391         auth_meth = SILC_AUTH_PUBLIC_KEY;
3392       else
3393         auth_meth = SILC_AUTH_PASSWORD;
3394     } else if (client->publickeys)
3395       auth_meth = SILC_AUTH_PUBLIC_KEY;
3396   }
3397
3398   SILC_LOG_DEBUG(("Authentication method is [%s]",
3399                   (auth_meth == SILC_AUTH_NONE ? "None" :
3400                    auth_meth == SILC_AUTH_PASSWORD ? "Passphrase" :
3401                    "Digital signatures")));
3402
3403   /* Send it back to the client */
3404   silc_server_send_connection_auth_request(server, sock, conn_type, auth_meth);
3405 }
3406
3407 /* Received REKEY packet. The sender of the packet wants to regenerate
3408    its session keys. This starts the REKEY protocol. */
3409
3410 void silc_server_rekey(SilcServer server,
3411                        SilcSocketConnection sock,
3412                        SilcPacketContext *packet)
3413 {
3414   SilcProtocol protocol;
3415   SilcServerRekeyInternalContext *proto_ctx;
3416   SilcIDListData idata = (SilcIDListData)sock->user_data;
3417
3418   SILC_LOG_DEBUG(("Start"));
3419
3420   /* Allocate internal protocol context. This is sent as context
3421      to the protocol. */
3422   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
3423   proto_ctx->server = (void *)server;
3424   proto_ctx->sock = sock;
3425   proto_ctx->responder = TRUE;
3426   proto_ctx->pfs = idata->rekey->pfs;
3427
3428   /* Perform rekey protocol. Will call the final callback after the
3429      protocol is over. */
3430   silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
3431                       &protocol, proto_ctx, silc_server_rekey_final);
3432   sock->protocol = protocol;
3433
3434   if (proto_ctx->pfs == FALSE)
3435     /* Run the protocol */
3436     silc_protocol_execute(protocol, server->schedule, 0, 0);
3437 }
3438
3439 /* Received file transger packet. This packet is never for us. It is to
3440    the client in the packet's destination ID. Sending of this sort of packet
3441    equals sending private message, ie. it is sent point to point from
3442    one client to another. */
3443
3444 void silc_server_ftp(SilcServer server,
3445                      SilcSocketConnection sock,
3446                      SilcPacketContext *packet)
3447 {
3448   SilcSocketConnection dst_sock;
3449   SilcIDListData idata;
3450
3451   SILC_LOG_DEBUG(("Start"));
3452
3453   if (packet->src_id_type != SILC_ID_CLIENT ||
3454       packet->dst_id_type != SILC_ID_CLIENT)
3455     return;
3456
3457   if (!packet->dst_id)
3458     return;
3459
3460   /* Get the route to the client */
3461   dst_sock = silc_server_get_client_route(server, packet->dst_id,
3462                                           packet->dst_id_len, NULL,
3463                                           &idata, NULL);
3464   if (!dst_sock)
3465     return;
3466
3467   /* Relay the packet */
3468   silc_server_relay_packet(server, dst_sock, idata->send_key,
3469                            idata->hmac_send, idata->psn_send++,
3470                            packet, FALSE);
3471 }
3472
3473 typedef struct {
3474   SilcServer server;
3475   SilcSocketConnection sock;
3476   SilcPacketContext *packet;
3477   void *data;
3478 } *SilcServerResumeResolve;
3479
3480 SILC_SERVER_CMD_FUNC(resume_resolve)
3481 {
3482   SilcServerResumeResolve r = (SilcServerResumeResolve)context;
3483   SilcServer server = r->server;
3484   SilcSocketConnection sock = r->sock;
3485   SilcServerCommandReplyContext reply = context2;
3486   SilcClientEntry client;
3487
3488   SILC_LOG_DEBUG(("Start"));
3489
3490   if (!reply || !silc_command_get_status(reply->payload, NULL, NULL)) {
3491     SILC_LOG_ERROR(("Client %s (%s) tried to resume unknown client, "
3492                     "closing connection", sock->hostname, sock->ip));
3493     silc_server_disconnect_remote(server, sock,
3494                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3495                                   "Resuming not possible");
3496     if (sock->user_data)
3497       silc_server_free_sock_user_data(server, sock, NULL);
3498     goto out;
3499   }
3500
3501   if (reply && silc_command_get(reply->payload) == SILC_COMMAND_WHOIS) {
3502     /* Get entry to the client, and resolve it if we don't have it. */
3503     client = silc_idlist_find_client_by_id(server->local_list,
3504                                            r->data, TRUE, NULL);
3505     if (!client) {
3506       client = silc_idlist_find_client_by_id(server->global_list,
3507                                              r->data, TRUE, NULL);
3508       if (!client) {
3509         SILC_LOG_ERROR(("Client %s (%s) tried to resume unknown client, "
3510                         "closing connection", sock->hostname, sock->ip));
3511         silc_server_disconnect_remote(server, sock,
3512                                       SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3513                                       "Resuming not possible");
3514         if (sock->user_data)
3515           silc_server_free_sock_user_data(server, sock, NULL);
3516         goto out;
3517       }
3518     }
3519
3520     if (!(client->mode & SILC_UMODE_DETACHED)) {
3521       SILC_LOG_ERROR(("Client %s (%s) tried to resume un-detached client, "
3522                       "closing connection", sock->hostname, sock->ip));
3523       silc_server_disconnect_remote(server, sock,
3524                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3525                                     "Resuming not possible");
3526       if (sock->user_data)
3527         silc_server_free_sock_user_data(server, sock, NULL);
3528       goto out;
3529     }
3530
3531     client->data.status |= SILC_IDLIST_STATUS_RESUME_RES;
3532   }
3533
3534   /* Reprocess the packet */
3535   silc_server_resume_client(server, sock, r->packet);
3536
3537  out:
3538   silc_socket_free(r->sock);
3539   silc_packet_context_free(r->packet);
3540   silc_free(r->data);
3541   silc_free(r);
3542 }
3543
3544 /* Received client resuming packet.  This is used to resume detached
3545    client session.  It can be sent by the client who wishes to resume
3546    but this is also sent by servers and routers to notify other routers
3547    that the client is not detached anymore. */
3548
3549 void silc_server_resume_client(SilcServer server,
3550                                SilcSocketConnection sock,
3551                                SilcPacketContext *packet)
3552 {
3553   SilcBuffer buffer = packet->buffer, buf;
3554   SilcIDListData idata;
3555   SilcIDCacheEntry id_cache = NULL;
3556   SilcClientEntry detached_client;
3557   SilcClientID *client_id = NULL;
3558   unsigned char *id_string, *auth = NULL;
3559   SilcUInt16 id_len, auth_len = 0;
3560   int ret, nickfail = 0;
3561   bool resolved, local, nick_change = FALSE, resolve = FALSE;
3562   SilcChannelEntry channel;
3563   SilcHashTableList htl;
3564   SilcChannelClientEntry chl;
3565   SilcServerResumeResolve r;
3566   const char *cipher;
3567
3568   ret = silc_buffer_unformat(buffer,
3569                              SILC_STR_UI16_NSTRING(&id_string, &id_len),
3570                              SILC_STR_END);
3571   if (ret != -1)
3572     client_id = silc_id_str2id(id_string, id_len, SILC_ID_CLIENT);
3573
3574   if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
3575     /* Client send this and is attempting to resume to old client session */
3576     SilcClientEntry client;
3577     SilcBuffer keyp;
3578
3579     if (ret != -1) {
3580       silc_buffer_pull(buffer, 2 + id_len);
3581       auth = buffer->data;
3582       auth_len = buffer->len;
3583       silc_buffer_push(buffer, 2 + id_len);
3584     }
3585
3586     if (!client_id || auth_len < 128) {
3587       SILC_LOG_ERROR(("Client %s (%s) sent incomplete resume information, "
3588                       "closing connection", sock->hostname, sock->ip));
3589       silc_server_disconnect_remote(server, sock,
3590                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3591                                     "Resuming not possible");
3592       if (sock->user_data)
3593         silc_server_free_sock_user_data(server, sock, NULL);
3594       silc_free(client_id);
3595       return;
3596     }
3597
3598     /* Take client entry of this connection */
3599     client = (SilcClientEntry)sock->user_data;
3600     idata = (SilcIDListData)client;
3601
3602     /* Get entry to the client, and resolve it if we don't have it. */
3603     detached_client = silc_server_query_client(server, client_id, FALSE,
3604                                                &resolved);
3605     if (!detached_client) {
3606       if (resolved) {
3607         /* The client info is being resolved. Reprocess this packet after
3608            receiving the reply to the query. */
3609         SILC_LOG_DEBUG(("Resolving client"));
3610         r = silc_calloc(1, sizeof(*r));
3611         if (!r)
3612           return;
3613         r->server = server;
3614         r->sock = silc_socket_dup(sock);
3615         r->packet = silc_packet_context_dup(packet);
3616         r->data = client_id;
3617         silc_server_command_pending(server, SILC_COMMAND_WHOIS,
3618                                     server->cmd_ident,
3619                                     silc_server_command_resume_resolve, r);
3620       } else {
3621         SILC_LOG_ERROR(("Client %s (%s) tried to resume unknown client, "
3622                         "closing connection", sock->hostname, sock->ip));
3623         silc_server_disconnect_remote(server, sock,
3624                                       SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3625                                       "Resuming not possible");
3626         if (sock->user_data)
3627           silc_server_free_sock_user_data(server, sock, NULL);
3628         silc_free(client_id);
3629       }
3630       return;
3631     }
3632
3633     if (!(detached_client->mode & SILC_UMODE_DETACHED))
3634       resolve = TRUE;
3635     if (!silc_hash_table_count(detached_client->channels) &&
3636         detached_client->router)
3637       resolve = TRUE;
3638     if (!detached_client->nickname)
3639       resolve = TRUE;
3640     if (detached_client->data.status & SILC_IDLIST_STATUS_RESUME_RES)
3641       resolve = FALSE;
3642
3643     if (resolve) {
3644       if (server->server_type == SILC_SERVER && !server->standalone) {
3645         /* The client info is being resolved. Reprocess this packet after
3646            receiving the reply to the query. */
3647         SILC_LOG_DEBUG(("Resolving client info"));
3648         silc_server_query_client(server, client_id, TRUE, NULL);
3649         r = silc_calloc(1, sizeof(*r));
3650         if (!r)
3651           return;
3652         r->server = server;
3653         r->sock = silc_socket_dup(sock);
3654         r->packet = silc_packet_context_dup(packet);
3655         r->data = client_id;
3656         silc_server_command_pending(server, SILC_COMMAND_WHOIS,
3657                                     server->cmd_ident,
3658                                     silc_server_command_resume_resolve, r);
3659         return;
3660       }
3661       if (server->server_type == SILC_SERVER) {
3662         SILC_LOG_ERROR(("Client %s (%s) tried to resume un-detached client, "
3663                         "closing connection", sock->hostname, sock->ip));
3664         silc_server_disconnect_remote(server, sock,
3665                                       SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3666                                       "Resuming not possible");
3667         if (sock->user_data)
3668           silc_server_free_sock_user_data(server, sock, NULL);
3669         silc_free(client_id);
3670         return;
3671       }
3672     }
3673
3674     /* Check that we have the public key of the client, if not then we must
3675        resolve it first. */
3676     if (!detached_client->data.public_key) {
3677       if (server->server_type == SILC_SERVER && server->standalone) {
3678         SILC_LOG_ERROR(("Detached client's public key not present, "
3679                         "closing connection"));
3680         silc_server_disconnect_remote(server, sock,
3681                                       SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3682                                       "Resuming not possible");
3683         if (sock->user_data)
3684           silc_server_free_sock_user_data(server, sock, NULL);
3685         silc_free(client_id);
3686       } else {
3687         /* We must retrieve the detached client's public key by sending
3688            GETKEY command. Reprocess this packet after receiving the key */
3689         SilcBuffer idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
3690         SilcSocketConnection dest_sock =
3691           silc_server_get_client_route(server, NULL, 0, client_id, NULL, NULL);
3692
3693         SILC_LOG_DEBUG(("Resolving client public key"));
3694
3695         silc_server_send_command(server, dest_sock ? dest_sock :
3696                                  SILC_PRIMARY_ROUTE(server),
3697                                  SILC_COMMAND_GETKEY, ++server->cmd_ident,
3698                                  1, 1, idp->data, idp->len);
3699
3700         r = silc_calloc(1, sizeof(*r));
3701         if (!r) {
3702           silc_free(client_id);
3703           return;
3704         }
3705
3706         r->server = server;
3707         r->sock = silc_socket_dup(sock);
3708         r->packet = silc_packet_context_dup(packet);
3709         silc_server_command_pending(server, SILC_COMMAND_GETKEY,
3710                                     server->cmd_ident,
3711                                     silc_server_command_resume_resolve, r);
3712
3713         silc_buffer_free(idp);
3714       }
3715       silc_free(client_id);
3716       return;
3717     } else if (!silc_pkcs_public_key_compare(detached_client->data.public_key,
3718                                              idata->public_key)) {
3719       /* We require that the connection and resuming authentication data
3720          must be using same key pair. */
3721       SILC_LOG_ERROR(("Resuming attempted with wrong public key, "
3722                       "closing connection"));
3723       silc_server_disconnect_remote(server, sock,
3724                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3725                                     "Resuming not possible");
3726       if (sock->user_data)
3727         silc_server_free_sock_user_data(server, sock, NULL);
3728       silc_free(client_id);
3729       return;
3730     }
3731
3732     /* Verify the authentication payload.  This has to be successful in
3733        order to allow the resuming */
3734     if (!idata->hash ||
3735         !silc_auth_verify_data(auth, auth_len, SILC_AUTH_PUBLIC_KEY,
3736                                detached_client->data.public_key, 0,
3737                                idata->hash, detached_client->id,
3738                                SILC_ID_CLIENT)) {
3739       SILC_LOG_ERROR(("Client %s (%s) resume authentication failed, "
3740                       "closing connection", sock->hostname, sock->ip));
3741       silc_server_disconnect_remote(server, sock,
3742                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3743                                     "Resuming not possible");
3744       if (sock->user_data)
3745         silc_server_free_sock_user_data(server, sock, NULL);
3746       silc_free(client_id);
3747       return;
3748     }
3749
3750     /* Now resume the client to the network */
3751
3752     silc_schedule_task_del_by_context(server->schedule, detached_client);
3753     sock->user_data = detached_client;
3754     detached_client->connection = sock;
3755
3756     /* Take new keys and stuff into use in the old entry */
3757     silc_idlist_del_data(detached_client);
3758     silc_idlist_add_data(detached_client, idata);
3759     detached_client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
3760     detached_client->data.status |= SILC_IDLIST_STATUS_RESUMED;
3761     detached_client->data.status |= SILC_IDLIST_STATUS_LOCAL;
3762     detached_client->data.status &= ~SILC_IDLIST_STATUS_RESUME_RES;
3763     detached_client->mode &= ~SILC_UMODE_DETACHED;
3764     server->stat.my_detached--;
3765
3766     /* Send the RESUME_CLIENT packet to our primary router so that others
3767        know this client isn't detached anymore. */
3768     buf = silc_buffer_alloc_size(2 + id_len);
3769     silc_buffer_format(buf,
3770                        SILC_STR_UI_SHORT(id_len),
3771                        SILC_STR_UI_XNSTRING(id_string, id_len),
3772                        SILC_STR_END);
3773
3774     /* Send to primary router */
3775     silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
3776                             SILC_PACKET_RESUME_CLIENT, 0,
3777                             buf->data, buf->len, TRUE);
3778     silc_server_backup_send(server, detached_client->router,
3779                             SILC_PACKET_RESUME_CLIENT, 0,
3780                             buf->data, buf->len, TRUE, TRUE);
3781
3782     /* As router we must deliver this packet directly to the original
3783        server whom this client was earlier. */
3784     if (server->server_type == SILC_ROUTER && detached_client->router &&
3785         detached_client->router->server_type != SILC_ROUTER)
3786       silc_server_packet_send(server, detached_client->router->connection,
3787                               SILC_PACKET_RESUME_CLIENT, 0,
3788                               buf->data, buf->len, TRUE);
3789     silc_buffer_free(buf);
3790
3791     detached_client->router = NULL;
3792
3793     /* Delete this client entry since we're resuming to old one. */
3794     server->stat.my_clients--;
3795     server->stat.clients--;
3796     if (server->stat.cell_clients)
3797       server->stat.cell_clients--;
3798     silc_server_remove_from_channels(server, NULL, client, FALSE,
3799                                      NULL, FALSE, FALSE);
3800     silc_server_del_from_watcher_list(server, client);
3801     if (!silc_idlist_del_client(server->local_list, client))
3802       silc_idlist_del_client(server->global_list, client);
3803     client = detached_client;
3804     silc_free(client->servername);
3805     client->servername = strdup(server->server_name);
3806
3807     /* If the ID is not based in our ID then change it */
3808     if (!SILC_ID_COMPARE(client->id, server->id, server->id->ip.data_len)) {
3809       silc_free(client_id);
3810       while (!silc_id_create_client_id(server, server->id, server->rng,
3811                                        server->md5hash, client->nickname,
3812                                        &client_id)) {
3813         nickfail++;
3814         if (nickfail > 9) {
3815           silc_server_disconnect_remote(server, sock,
3816                                         SILC_STATUS_ERR_BAD_NICKNAME, NULL);
3817           if (sock->user_data)
3818             silc_server_free_sock_user_data(server, sock, NULL);
3819           return;
3820         }
3821         snprintf(&client->nickname[strlen(client->nickname) - 1], 1,
3822                  "%d", nickfail);
3823       }
3824       nick_change = TRUE;
3825     }
3826
3827     if (nick_change) {
3828       /* Notify about Client ID change, nickname doesn't actually change. */
3829       silc_server_send_notify_nick_change(server, SILC_PRIMARY_ROUTE(server),
3830                                           SILC_BROADCAST(server),
3831                                           client->id, client_id,
3832                                           client->nickname);
3833     }
3834
3835     /* Resolve users on those channels that client has joined but we
3836        haven't resolved user list yet. */
3837     if (server->server_type == SILC_SERVER && !server->standalone) {
3838       silc_hash_table_list(client->channels, &htl);
3839       while (silc_hash_table_get(&htl, NULL, (void **)&chl)) {
3840         channel = chl->channel;
3841         SILC_LOG_DEBUG(("Resolving users for %s channel",
3842                         channel->channel_name));
3843         if (channel->disabled || !channel->users_resolved) {
3844           silc_server_send_command(server, SILC_PRIMARY_ROUTE(server),
3845                                    SILC_COMMAND_USERS, ++server->cmd_ident,
3846                                    1, 2, channel->channel_name,
3847                                    strlen(channel->channel_name));
3848         }
3849       }
3850       silc_hash_table_list_reset(&htl);
3851     }
3852
3853     /* Send the new client ID to the client. After this client may start
3854        receiving other packets, and may start sending packets too. */
3855     silc_server_send_new_id(server, sock, FALSE, client_id, SILC_ID_CLIENT,
3856                             silc_id_get_len(client_id, SILC_ID_CLIENT));
3857
3858     if (nick_change) {
3859       /* Send NICK change notify to channels as well. */
3860       SilcBuffer oidp, nidp;
3861       oidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3862       nidp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
3863       silc_server_send_notify_on_channels(server, NULL, client,
3864                                           SILC_NOTIFY_TYPE_NICK_CHANGE, 3,
3865                                           oidp->data, oidp->len,
3866                                           nidp->data, nidp->len,
3867                                           client->nickname,
3868                                           strlen(client->nickname));
3869       silc_buffer_free(oidp);
3870       silc_buffer_free(nidp);
3871     }
3872
3873     /* Add the client again to the ID cache to get it to correct list */
3874     if (!silc_idcache_del_by_context(server->local_list->clients, client))
3875       silc_idcache_del_by_context(server->global_list->clients, client);
3876     silc_free(client->id);
3877     client->id = client_id;
3878     client_id = NULL;
3879     silc_idcache_add(server->local_list->clients, client->nickname,
3880                      client->id, client, 0, NULL);
3881
3882     /* Send some nice info to the client */
3883     silc_server_send_connect_notifys(server, sock, client);
3884
3885     /* Send all channel keys of channels the client has joined */
3886     silc_hash_table_list(client->channels, &htl);
3887     while (silc_hash_table_get(&htl, NULL, (void **)&chl)) {
3888       bool created = FALSE;
3889       channel = chl->channel;
3890
3891       if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY)
3892         continue;
3893
3894       /* If we don't have channel key, then create one */
3895       if (!channel->channel_key) {
3896         if (!silc_server_create_channel_key(server, channel, 0))
3897           continue;
3898         created = TRUE;
3899       }
3900
3901       id_string = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3902       cipher = silc_cipher_get_name(channel->channel_key);
3903       keyp =
3904         silc_channel_key_payload_encode(silc_id_get_len(channel->id,
3905                                                         SILC_ID_CHANNEL),
3906                                         id_string,
3907                                         strlen(cipher), cipher,
3908                                         channel->key_len / 8, channel->key);
3909       silc_free(id_string);
3910
3911       /* Send the channel key to the client */
3912       silc_server_packet_send(server, sock, SILC_PACKET_CHANNEL_KEY, 0,
3913                               keyp->data, keyp->len, FALSE);
3914
3915       /* Distribute the channel key to channel */
3916       if (created) {
3917         silc_server_send_channel_key(server, NULL, channel,
3918                                      server->server_type == SILC_ROUTER ?
3919                                      FALSE : !server->standalone);
3920         silc_server_backup_send(server, NULL, SILC_PACKET_CHANNEL_KEY, 0,
3921                                 keyp->data, keyp->len, FALSE, TRUE);
3922       }
3923
3924       silc_buffer_free(keyp);
3925     }
3926     silc_hash_table_list_reset(&htl);
3927
3928   } else if (sock->type != SILC_SOCKET_TYPE_CLIENT) {
3929     /* Server or router sent this to us to notify that that a client has
3930        been resumed. */
3931     SilcServerEntry server_entry;
3932     SilcServerID *server_id;
3933
3934     if (!client_id) {
3935       SILC_LOG_DEBUG(("Malformed resuming packet"));
3936       return;
3937     }
3938
3939     /* Get entry to the client, and resolve it if we don't have it. */
3940     detached_client = silc_idlist_find_client_by_id(server->local_list,
3941                                                     client_id, TRUE,
3942                                                     &id_cache);
3943     if (!detached_client) {
3944       detached_client = silc_idlist_find_client_by_id(server->global_list,
3945                                                       client_id, TRUE,
3946                                                       &id_cache);
3947       if (!detached_client) {
3948         SILC_LOG_DEBUG(("Resuming client is unknown"));
3949         silc_free(client_id);
3950         return;
3951       }
3952     }
3953
3954     /* Check that the client has not been resumed already because it is
3955        protocol error to attempt to resume more than once.  The client
3956        will be killed if this protocol error occurs. */
3957     if (detached_client->data.status & SILC_IDLIST_STATUS_RESUMED &&
3958         !(detached_client->mode & SILC_UMODE_DETACHED)) {
3959       /* The client is clearly attempting to resume more than once and
3960          perhaps playing around by resuming from several different places
3961          at the same time. */
3962       SILC_LOG_DEBUG(("Attempting to re-resume client, killing both"));
3963       silc_server_kill_client(server, detached_client, NULL,
3964                               server->id, SILC_ID_SERVER);
3965       silc_free(client_id);
3966       return;
3967     }
3968
3969     /* Check whether client is detached at all */
3970     if (!(detached_client->mode & SILC_UMODE_DETACHED)) {
3971       SILC_LOG_DEBUG(("Client is not detached"));
3972       silc_free(client_id);
3973       return;
3974     }
3975
3976     SILC_LOG_DEBUG(("Resuming detached client"));
3977
3978     /* If the sender of this packet is server and we are router we need to
3979        broadcast this packet to other routers in the network. */
3980     if (server->server_type == SILC_ROUTER &&
3981         sock->type == SILC_SOCKET_TYPE_SERVER &&
3982         !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
3983       SILC_LOG_DEBUG(("Broadcasting received Resume Client packet"));
3984       silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
3985                               packet->type,
3986                               packet->flags | SILC_PACKET_FLAG_BROADCAST,
3987                               buffer->data, buffer->len, FALSE);
3988       silc_server_backup_send(server, sock->user_data,
3989                               packet->type, packet->flags,
3990                               packet->buffer->data, packet->buffer->len,
3991                               FALSE, TRUE);
3992     }
3993
3994     /* Client is detached, and now it is resumed.  Remove the detached
3995        mode and mark that it is resumed. */
3996     silc_idlist_del_data(detached_client);
3997     detached_client->mode &= ~SILC_UMODE_DETACHED;
3998     detached_client->data.status |= SILC_IDLIST_STATUS_RESUMED;
3999     detached_client->data.status &= ~SILC_IDLIST_STATUS_LOCAL;
4000     id_cache->expire = 0;
4001
4002     silc_schedule_task_del_by_context(server->schedule, detached_client);
4003
4004     /* Get the new owner of the resumed client */
4005     server_id = silc_id_str2id(packet->src_id, packet->src_id_len,
4006                                packet->src_id_type);
4007     if (!server_id) {
4008       silc_free(client_id);
4009       return;
4010     }
4011
4012     /* Get server entry */
4013     server_entry = silc_idlist_find_server_by_id(server->global_list,
4014                                                  server_id, TRUE, NULL);
4015     local = FALSE;
4016     if (!server_entry) {
4017       server_entry = silc_idlist_find_server_by_id(server->local_list,
4018                                                    server_id, TRUE, NULL);
4019       local = TRUE;
4020       if (!server_entry) {
4021         silc_free(server_id);
4022         silc_free(client_id);
4023         return;
4024       }
4025     }
4026
4027     if (server->server_type == SILC_ROUTER &&
4028         sock->type == SILC_SOCKET_TYPE_ROUTER &&
4029         server_entry->server_type == SILC_ROUTER)
4030       local = FALSE;
4031
4032     /* Change the client to correct list. */
4033     if (!silc_idcache_del_by_context(server->local_list->clients,
4034                                      detached_client))
4035       silc_idcache_del_by_context(server->global_list->clients,
4036                                   detached_client);
4037     silc_idcache_add(local && server->server_type == SILC_ROUTER ?
4038                      server->local_list->clients :
4039                      server->global_list->clients,
4040                      detached_client->nickname,
4041                      detached_client->id, detached_client, FALSE, NULL);
4042
4043     /* Change the owner of the client */
4044     detached_client->router = server_entry;
4045
4046     /* Update channel information regarding global clients on channel. */
4047     if (server->server_type != SILC_ROUTER) {
4048       silc_hash_table_list(detached_client->channels, &htl);
4049       while (silc_hash_table_get(&htl, NULL, (void **)&chl))
4050         chl->channel->global_users =
4051           silc_server_channel_has_global(chl->channel);
4052       silc_hash_table_list_reset(&htl);
4053     }
4054
4055     silc_free(server_id);
4056   }
4057
4058   silc_free(client_id);
4059 }