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