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