05928b5116be393ea4a9c80d62e9c329e66c3c76
[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   /* Statistics */
2509   if (server->server_type == SILC_ROUTER)
2510     server->stat.cell_servers++;
2511
2512   /* Remove the old cache entry */
2513   if (!silc_idcache_del_by_context(server->local_list->servers, new_server)) {
2514     if (!silc_idcache_del_by_context(server->global_list->servers,
2515                                      new_server)) {
2516       SILC_LOG_INFO(("Unauthenticated %s attempted to register to "
2517                      "network", (sock->type == SILC_SOCKET_TYPE_SERVER ?
2518                                  "server" : "router")));
2519       silc_server_disconnect_remote(server, sock,
2520                                     SILC_STATUS_ERR_NOT_AUTHENTICATED, NULL);
2521       if (sock->user_data)
2522         silc_server_free_sock_user_data(server, sock, NULL);
2523       return NULL;
2524     }
2525     local = FALSE;
2526   }
2527
2528   /* Make sure this server hasn't registered already */
2529   if (idata->status & SILC_IDLIST_STATUS_REGISTERED) {
2530     silc_server_disconnect_remote(server, sock,
2531                                   SILC_STATUS_ERR_OPERATION_ALLOWED,
2532                                   "Too many registrations");
2533     if (sock->user_data)
2534       silc_server_free_sock_user_data(server, sock, NULL);
2535     return NULL;
2536   }
2537
2538   /* Parse the incoming packet */
2539   ret = silc_buffer_unformat(buffer,
2540                              SILC_STR_UI16_NSTRING_ALLOC(&id_string, &id_len),
2541                              SILC_STR_UI16_NSTRING_ALLOC(&server_name,
2542                                                          &name_len),
2543                              SILC_STR_END);
2544   if (ret == -1) {
2545     silc_free(id_string);
2546     silc_free(server_name);
2547     silc_server_disconnect_remote(server, sock,
2548                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2549                                   NULL);
2550     if (sock->user_data)
2551       silc_server_free_sock_user_data(server, sock, NULL);
2552     return NULL;
2553   }
2554
2555   if (id_len > buffer->len) {
2556     silc_free(id_string);
2557     silc_free(server_name);
2558     silc_server_disconnect_remote(server, sock,
2559                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2560                                   NULL);
2561     if (sock->user_data)
2562       silc_server_free_sock_user_data(server, sock, NULL);
2563     return NULL;
2564   }
2565
2566   if (name_len > 256)
2567     server_name[255] = '\0';
2568
2569   /* Get Server ID */
2570   server_id = silc_id_str2id(id_string, id_len, SILC_ID_SERVER);
2571   if (!server_id) {
2572     silc_free(id_string);
2573     silc_free(server_name);
2574     silc_server_disconnect_remote(server, sock,
2575                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2576                                   NULL);
2577     if (sock->user_data)
2578       silc_server_free_sock_user_data(server, sock, NULL);
2579     return NULL;
2580   }
2581   silc_free(id_string);
2582
2583   /* Check for valid server ID */
2584   if (!silc_id_is_valid_server_id(server, server_id, sock)) {
2585     SILC_LOG_INFO(("Invalid server ID sent by %s (%s)",
2586                    sock->ip, sock->hostname));
2587     silc_server_disconnect_remote(server, sock,
2588                                   SILC_STATUS_ERR_BAD_SERVER_ID, NULL);
2589     if (sock->user_data)
2590       silc_server_free_sock_user_data(server, sock, NULL);
2591     silc_free(server_name);
2592     return NULL;
2593   }
2594
2595   /* Check that we do not have this ID already */
2596   server_entry = silc_idlist_find_server_by_id(server->local_list,
2597                                                server_id, TRUE, NULL);
2598   if (server_entry) {
2599     if (SILC_IS_LOCAL(server_entry)) {
2600       silc_server_disconnect_remote(server, sock,
2601                                     SILC_STATUS_ERR_OPERATION_ALLOWED,
2602                                     "Too many registrations");
2603       if (sock->user_data)
2604         silc_server_free_sock_user_data(server, sock, NULL);
2605       return NULL;
2606     } else {
2607       silc_idcache_del_by_context(server->local_list->servers, server_entry);
2608     }
2609   } else {
2610     server_entry = silc_idlist_find_server_by_id(server->global_list,
2611                                                  server_id, TRUE, NULL);
2612     if (server_entry) {
2613       if (SILC_IS_LOCAL(server_entry)) {
2614         silc_server_disconnect_remote(server, sock,
2615                                       SILC_STATUS_ERR_OPERATION_ALLOWED,
2616                                       "Too many registrations");
2617         if (sock->user_data)
2618           silc_server_free_sock_user_data(server, sock, NULL);
2619         return NULL;
2620       } else {
2621         silc_idcache_del_by_context(server->global_list->servers,
2622                                     server_entry);
2623       }
2624     }
2625   }
2626
2627   /* Update server entry */
2628   idata->status |= SILC_IDLIST_STATUS_REGISTERED;
2629   new_server->server_name = server_name;
2630   new_server->id = server_id;
2631
2632   SILC_LOG_DEBUG(("New server id(%s)",
2633                   silc_id_render(server_id, SILC_ID_SERVER)));
2634
2635   /* Add again the entry to the ID cache. */
2636   silc_idcache_add(local ? server->local_list->servers :
2637                    server->global_list->servers, server_name, server_id,
2638                    new_server, 0, NULL);
2639
2640   /* Distribute the information about new server in the SILC network
2641      to our router. If we are normal server we won't send anything
2642      since this connection must be our router connection. */
2643   if (server->server_type == SILC_ROUTER && !server->standalone &&
2644       SILC_PRIMARY_ROUTE(server) != sock)
2645     silc_server_send_new_id(server, SILC_PRIMARY_ROUTE(server),
2646                             TRUE, new_server->id, SILC_ID_SERVER,
2647                             silc_id_get_len(server_id, SILC_ID_SERVER));
2648
2649   if (server->server_type == SILC_ROUTER) {
2650     /* Distribute to backup routers */
2651     SilcBuffer idp = silc_id_payload_encode(new_server->id, SILC_ID_SERVER);
2652     silc_server_backup_send(server, sock->user_data, SILC_PACKET_NEW_ID, 0,
2653                             idp->data, idp->len, FALSE, TRUE);
2654     silc_buffer_free(idp);
2655   }
2656
2657   /* Check whether this router connection has been replaced by an
2658      backup router. If it has been then we'll disable the server and will
2659      ignore everything it will send until the backup router resuming
2660      protocol has been completed. */
2661   if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
2662       silc_server_backup_replaced_get(server, server_id, NULL)) {
2663     /* Send packet to the router indicating that it cannot use this
2664        connection as it has been replaced by backup router. */
2665     SILC_LOG_DEBUG(("Remote router has been replaced by backup router, "
2666                     "disabling its connection"));
2667
2668     silc_server_backup_send_replaced(server, sock);
2669
2670     /* Mark the router disabled. The data sent earlier will go but nothing
2671        after this goes to this connection. */
2672     idata->status |= SILC_IDLIST_STATUS_DISABLED;
2673   } else {
2674     /* If it is router announce our stuff to it. */
2675     if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
2676         server->server_type == SILC_ROUTER) {
2677       silc_server_announce_servers(server, FALSE, 0, sock);
2678       silc_server_announce_clients(server, 0, sock);
2679       silc_server_announce_channels(server, 0, sock);
2680     }
2681
2682     /* Announce our information to backup router */
2683     if (new_server->server_type == SILC_BACKUP_ROUTER &&
2684         sock->type == SILC_SOCKET_TYPE_SERVER &&
2685         server->server_type == SILC_ROUTER) {
2686       silc_server_announce_servers(server, TRUE, 0, sock);
2687       silc_server_announce_clients(server, 0, sock);
2688       silc_server_announce_channels(server, 0, sock);
2689     }
2690
2691     /* If backup router, mark it as one of ours.  This server is considered
2692        to be backup router after this setting. */
2693     if (new_server->server_type == SILC_BACKUP_ROUTER) {
2694       SilcServerConfigRouter *backup;
2695       backup = silc_server_config_find_backup_conn(server, sock->ip);
2696       if (!backup)
2697         backup = silc_server_config_find_backup_conn(server, sock->hostname);
2698       if (backup) {
2699         /* Add as our backup router */
2700         silc_server_backup_add(server, new_server, backup->backup_replace_ip,
2701                                backup->backup_replace_port,
2702                                backup->backup_local);
2703       }
2704     }
2705
2706     /* By default the servers connected to backup router are disabled
2707        until backup router has become the primary */
2708     if (server->server_type == SILC_BACKUP_ROUTER &&
2709         sock->type == SILC_SOCKET_TYPE_SERVER)
2710       idata->status |= SILC_IDLIST_STATUS_DISABLED;
2711   }
2712
2713   return new_server;
2714 }
2715
2716 /* Processes incoming New ID packet. New ID Payload is used to distribute
2717    information about newly registered clients and servers. */
2718
2719 static void silc_server_new_id_real(SilcServer server,
2720                                     SilcSocketConnection sock,
2721                                     SilcPacketContext *packet,
2722                                     int broadcast)
2723 {
2724   SilcBuffer buffer = packet->buffer;
2725   SilcIDList id_list;
2726   SilcServerEntry router, server_entry;
2727   SilcSocketConnection router_sock;
2728   SilcIDPayload idp;
2729   SilcIdType id_type;
2730   void *id;
2731
2732   SILC_LOG_DEBUG(("Processing new ID"));
2733
2734   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
2735       server->server_type == SILC_SERVER ||
2736       packet->src_id_type != SILC_ID_SERVER)
2737     return;
2738
2739   idp = silc_id_payload_parse(buffer->data, buffer->len);
2740   if (!idp)
2741     return;
2742
2743   id_type = silc_id_payload_get_type(idp);
2744
2745   /* Normal server cannot have other normal server connections */
2746   server_entry = (SilcServerEntry)sock->user_data;
2747   if (id_type == SILC_ID_SERVER && sock->type == SILC_SOCKET_TYPE_SERVER &&
2748       server_entry->server_type == SILC_SERVER)
2749     goto out;
2750
2751   id = silc_id_payload_get_id(idp);
2752   if (!id)
2753     goto out;
2754
2755   /* If the packet is coming from server then use the sender as the
2756      origin of the the packet. If it came from router then check the real
2757      sender of the packet and use that as the origin. */
2758   if (sock->type == SILC_SOCKET_TYPE_SERVER) {
2759     id_list = server->local_list;
2760     router_sock = sock;
2761     router = sock->user_data;
2762
2763     /* If the sender is backup router and ID is server (and we are not
2764        backup router) then switch the entry to global list. */
2765     if (server_entry->server_type == SILC_BACKUP_ROUTER &&
2766         id_type == SILC_ID_SERVER &&
2767         server->id_entry->server_type != SILC_BACKUP_ROUTER) {
2768       id_list = server->global_list;
2769       router_sock = server->router ? SILC_PRIMARY_ROUTE(server) : sock;
2770     }
2771   } else {
2772     void *sender_id = silc_id_str2id(packet->src_id, packet->src_id_len,
2773                                      packet->src_id_type);
2774     router = silc_idlist_find_server_by_id(server->global_list,
2775                                            sender_id, TRUE, NULL);
2776     if (!router)
2777       router = silc_idlist_find_server_by_id(server->local_list,
2778                                              sender_id, TRUE, NULL);
2779     silc_free(sender_id);
2780     router_sock = sock;
2781     id_list = server->global_list;
2782   }
2783
2784   if (!router)
2785     goto out;
2786
2787   switch(id_type) {
2788   case SILC_ID_CLIENT:
2789     {
2790       SilcClientEntry entry;
2791
2792       /* Check that we do not have this client already */
2793       entry = silc_idlist_find_client_by_id(server->global_list,
2794                                             id, server->server_type,
2795                                             NULL);
2796       if (!entry)
2797         entry = silc_idlist_find_client_by_id(server->local_list,
2798                                               id, server->server_type,
2799                                               NULL);
2800       if (entry) {
2801         SILC_LOG_DEBUG(("Ignoring client that we already have"));
2802         goto out;
2803       }
2804
2805       SILC_LOG_DEBUG(("New client id(%s) from [%s] %s",
2806                       silc_id_render(id, SILC_ID_CLIENT),
2807                       sock->type == SILC_SOCKET_TYPE_SERVER ?
2808                       "Server" : "Router", sock->hostname));
2809
2810       /* As a router we keep information of all global information in our
2811          global list. Cell wide information however is kept in the local
2812          list. */
2813       entry = silc_idlist_add_client(id_list, NULL, NULL, NULL,
2814                                      id, router, NULL, 0);
2815       if (!entry) {
2816         SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
2817
2818         /* Inform the sender that the ID is not usable */
2819         silc_server_send_notify_signoff(server, sock, FALSE, id, NULL);
2820         goto out;
2821       }
2822       entry->nickname = NULL;
2823       entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
2824
2825       if (sock->type == SILC_SOCKET_TYPE_SERVER)
2826         server->stat.cell_clients++;
2827       server->stat.clients++;
2828
2829       /* Check if anyone is watching this nickname */
2830       if (server->server_type == SILC_ROUTER && id_list == server->local_list)
2831         silc_server_check_watcher_list(server, entry, NULL, 0);
2832
2833       if (server->server_type == SILC_ROUTER) {
2834         /* Add the client's public key to hash table or get the key with
2835            GETKEY command. */
2836         if (entry->data.public_key)
2837           silc_hash_table_add(server->pk_hash, entry->data.public_key, entry);
2838         else
2839           silc_server_send_command(server, router_sock,
2840                                    SILC_COMMAND_GETKEY, ++server->cmd_ident,
2841                                    1, 1, buffer->data, buffer->len);
2842       }
2843     }
2844     break;
2845
2846   case SILC_ID_SERVER:
2847     {
2848       SilcServerEntry entry;
2849
2850       /* If the ID is mine, ignore it. */
2851       if (SILC_ID_SERVER_COMPARE(id, server->id)) {
2852         SILC_LOG_DEBUG(("Ignoring my own ID as new ID"));
2853         break;
2854       }
2855
2856       /* If the ID is the sender's ID, ignore it (we have it already) */
2857       if (SILC_ID_SERVER_COMPARE(id, router->id)) {
2858         SILC_LOG_DEBUG(("Ignoring sender's own ID"));
2859         break;
2860       }
2861
2862       /* Check that we do not have this server already */
2863       entry = silc_idlist_find_server_by_id(server->global_list,
2864                                             id, server->server_type,
2865                                             NULL);
2866       if (!entry)
2867         entry = silc_idlist_find_server_by_id(server->local_list,
2868                                               id, server->server_type,
2869                                               NULL);
2870       if (entry) {
2871         SILC_LOG_DEBUG(("Ignoring server that we already have"));
2872         goto out;
2873       }
2874
2875       SILC_LOG_DEBUG(("New server id(%s) from [%s] %s",
2876                       silc_id_render(id, SILC_ID_SERVER),
2877                       sock->type == SILC_SOCKET_TYPE_SERVER ?
2878                       "Server" : "Router", sock->hostname));
2879
2880       /* As a router we keep information of all global information in our
2881          global list. Cell wide information however is kept in the local
2882          list. */
2883       entry = silc_idlist_add_server(id_list, NULL, 0, id, router,
2884                                      router_sock);
2885       if (!entry) {
2886         SILC_LOG_ERROR(("Could not add new server to the ID Cache"));
2887         goto out;
2888       }
2889       entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
2890
2891       if (sock->type == SILC_SOCKET_TYPE_SERVER)
2892         server->stat.cell_servers++;
2893       server->stat.servers++;
2894     }
2895     break;
2896
2897   case SILC_ID_CHANNEL:
2898     SILC_LOG_ERROR(("Channel cannot be registered with NEW_ID packet"));
2899     goto out;
2900     break;
2901
2902   default:
2903     goto out;
2904     break;
2905   }
2906
2907   /* If the sender of this packet is server and we are router we need to
2908      broadcast this packet to other routers in the network. */
2909   if (broadcast && server->server_type == SILC_ROUTER &&
2910       sock->type == SILC_SOCKET_TYPE_SERVER &&
2911       !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
2912     SILC_LOG_DEBUG(("Broadcasting received New ID packet"));
2913     silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
2914                             packet->type,
2915                             packet->flags | SILC_PACKET_FLAG_BROADCAST,
2916                             buffer->data, buffer->len, FALSE);
2917     silc_server_backup_send(server, sock->user_data,
2918                             packet->type, packet->flags,
2919                             packet->buffer->data, packet->buffer->len,
2920                             FALSE, TRUE);
2921   }
2922
2923  out:
2924   silc_id_payload_free(idp);
2925 }
2926
2927
2928 /* Processes incoming New ID packet. New ID Payload is used to distribute
2929    information about newly registered clients and servers. */
2930
2931 void silc_server_new_id(SilcServer server, SilcSocketConnection sock,
2932                         SilcPacketContext *packet)
2933 {
2934   silc_server_new_id_real(server, sock, packet, TRUE);
2935 }
2936
2937 /* Receoved New Id List packet, list of New ID payloads inside one
2938    packet. Process the New ID payloads one by one. */
2939
2940 void silc_server_new_id_list(SilcServer server, SilcSocketConnection sock,
2941                              SilcPacketContext *packet)
2942 {
2943   SilcPacketContext *new_id;
2944   SilcBuffer idp;
2945   SilcUInt16 id_len;
2946
2947   SILC_LOG_DEBUG(("Processing New ID List"));
2948
2949   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
2950       packet->src_id_type != SILC_ID_SERVER)
2951     return;
2952
2953   /* If the sender of this packet is server and we are router we need to
2954      broadcast this packet to other routers in the network. Broadcast
2955      this list packet instead of multiple New ID packets. */
2956   if (server->server_type == SILC_ROUTER &&
2957       sock->type == SILC_SOCKET_TYPE_SERVER &&
2958       !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
2959     SILC_LOG_DEBUG(("Broadcasting received New ID List packet"));
2960     silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
2961                             packet->type,
2962                             packet->flags | SILC_PACKET_FLAG_BROADCAST,
2963                             packet->buffer->data,
2964                             packet->buffer->len, FALSE);
2965     silc_server_backup_send(server, sock->user_data,
2966                             packet->type, packet->flags,
2967                             packet->buffer->data, packet->buffer->len,
2968                             FALSE, TRUE);
2969   }
2970
2971   /* Make copy of the original packet context, except for the actual
2972      data buffer, which we will here now fetch from the original buffer. */
2973   new_id = silc_packet_context_alloc();
2974   new_id->type = SILC_PACKET_NEW_ID;
2975   new_id->flags = packet->flags & (~SILC_PACKET_FLAG_LIST);
2976   new_id->src_id = packet->src_id;
2977   new_id->src_id_len = packet->src_id_len;
2978   new_id->src_id_type = packet->src_id_type;
2979   new_id->dst_id = packet->dst_id;
2980   new_id->dst_id_len = packet->dst_id_len;
2981   new_id->dst_id_type = packet->dst_id_type;
2982
2983   idp = silc_buffer_alloc(256);
2984   new_id->buffer = idp;
2985
2986   while (packet->buffer->len) {
2987     SILC_GET16_MSB(id_len, packet->buffer->data + 2);
2988     if ((id_len > packet->buffer->len) ||
2989         (id_len > idp->truelen))
2990       break;
2991
2992     silc_buffer_pull_tail(idp, 4 + id_len);
2993     silc_buffer_put(idp, packet->buffer->data, 4 + id_len);
2994
2995     /* Process the New ID */
2996     silc_server_new_id_real(server, sock, new_id, FALSE);
2997
2998     silc_buffer_push_tail(idp, 4 + id_len);
2999     silc_buffer_pull(packet->buffer, 4 + id_len);
3000   }
3001
3002   silc_buffer_free(idp);
3003   silc_free(new_id);
3004 }
3005
3006 /* Received New Channel packet. Information about new channels in the
3007    network are distributed using this packet. Save the information about
3008    the new channel. This usually comes from router but also normal server
3009    can send this to notify channels it has when it connects to us. */
3010
3011 void silc_server_new_channel(SilcServer server,
3012                              SilcSocketConnection sock,
3013                              SilcPacketContext *packet)
3014 {
3015   SilcChannelPayload payload;
3016   SilcChannelID *channel_id;
3017   char *channel_name;
3018   SilcUInt32 name_len;
3019   unsigned char *id;
3020   SilcUInt32 id_len, cipher_len;
3021   SilcServerEntry server_entry;
3022   SilcChannelEntry channel;
3023   const char *cipher;
3024
3025   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
3026       packet->src_id_type != SILC_ID_SERVER ||
3027       server->server_type == SILC_SERVER)
3028     return;
3029
3030   /* Parse the channel payload */
3031   payload = silc_channel_payload_parse(packet->buffer->data,
3032                                        packet->buffer->len);
3033   if (!payload)
3034     return;
3035
3036   /* Get the channel ID */
3037   channel_id = silc_channel_get_id_parse(payload);
3038   if (!channel_id) {
3039     silc_channel_payload_free(payload);
3040     return;
3041   }
3042
3043   channel_name = silc_channel_get_name(payload, &name_len);
3044   if (name_len > 256)
3045     channel_name[255] = '\0';
3046
3047   id = silc_channel_get_id(payload, &id_len);
3048
3049   server_entry = (SilcServerEntry)sock->user_data;
3050
3051   if (sock->type == SILC_SOCKET_TYPE_ROUTER) {
3052     /* Add the channel to global list as it is coming from router. It
3053        cannot be our own channel as it is coming from router. */
3054
3055     /* Check that we don't already have this channel */
3056     channel = silc_idlist_find_channel_by_name(server->local_list,
3057                                                channel_name, NULL);
3058     if (!channel)
3059       channel = silc_idlist_find_channel_by_name(server->global_list,
3060                                                  channel_name, NULL);
3061     if (!channel) {
3062       SILC_LOG_DEBUG(("New channel id(%s) from [Router] %s",
3063                       silc_id_render(channel_id, SILC_ID_CHANNEL),
3064                       sock->hostname));
3065
3066       channel =
3067         silc_idlist_add_channel(server->global_list, strdup(channel_name),
3068                                 0, channel_id, sock->user_data, NULL, NULL, 0);
3069       if (!channel) {
3070         silc_channel_payload_free(payload);
3071         silc_free(channel_id);
3072         return;
3073       }
3074       channel->disabled = TRUE;    /* Disabled until someone JOINs */
3075
3076       server->stat.channels++;
3077       if (server->server_type == SILC_ROUTER)
3078         channel->users_resolved = TRUE;
3079     }
3080   } else {
3081     /* The channel is coming from our server, thus it is in our cell
3082        we will add it to our local list. */
3083     SilcBuffer chk;
3084
3085     SILC_LOG_DEBUG(("Channel id(%s) from [Server] %s",
3086                     silc_id_render(channel_id, SILC_ID_CHANNEL),
3087                     sock->hostname));
3088
3089     /* Check that we don't already have this channel */
3090     channel = silc_idlist_find_channel_by_name(server->local_list,
3091                                                channel_name, NULL);
3092     if (!channel)
3093       channel = silc_idlist_find_channel_by_name(server->global_list,
3094                                                  channel_name, NULL);
3095
3096     /* If the channel does not exist, then create it. This creates a new
3097        key to the channel as well that we will send to the server. */
3098     if (!channel) {
3099       SILC_LOG_DEBUG(("Channel is new to us"));
3100
3101       /* The protocol says that the Channel ID's IP address must be based
3102          on the router's IP address.  Check whether the ID is based in our
3103          IP and if it is not then create a new ID and enforce the server
3104          to switch the ID. */
3105       if (server_entry->server_type != SILC_BACKUP_ROUTER &&
3106           !SILC_ID_COMPARE(channel_id, server->id, server->id->ip.data_len)) {
3107         SilcChannelID *tmp;
3108         SILC_LOG_DEBUG(("Forcing the server to change Channel ID"));
3109         if (silc_id_create_channel_id(server, server->id, server->rng, &tmp)) {
3110           silc_server_send_notify_channel_change(server, sock, FALSE,
3111                                                  channel_id, tmp);
3112           silc_channel_payload_free(payload);
3113           silc_free(channel_id);
3114           silc_free(tmp);
3115         }
3116
3117         /* Wait that server re-announces this channel */
3118         return;
3119       }
3120
3121       /* Create the channel with the provided Channel ID */
3122       channel = silc_server_create_new_channel_with_id(server, NULL, NULL,
3123                                                        channel_name,
3124                                                        channel_id, FALSE);
3125       if (!channel) {
3126         silc_channel_payload_free(payload);
3127         silc_free(channel_id);
3128         return;
3129       }
3130       channel->disabled = TRUE;    /* Disabled until someone JOINs */
3131
3132 #if 0 /* We assume that CMODE_CHANGE notify is sent to us after this. */
3133
3134       /* XXX Dunno if this is supposed to be set in any server type.  If set
3135          here the CMODE_CHANGE that may follow sets mode that we already
3136          have, and we may loose data from the CMODE_CHANGE notify. */
3137       if (server_entry->server_type != SILC_BACKUP_ROUTER)
3138         channel->mode = silc_channel_get_mode(payload);
3139 #endif
3140
3141       /* Send the new channel key to the server */
3142       id = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3143       id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3144       cipher = silc_cipher_get_name(channel->channel_key);
3145       cipher_len = strlen(cipher);
3146       chk = silc_channel_key_payload_encode(id_len, id,
3147                                             cipher_len, cipher,
3148                                             channel->key_len / 8,
3149                                             channel->key);
3150       silc_server_packet_send(server, sock, SILC_PACKET_CHANNEL_KEY, 0,
3151                               chk->data, chk->len, FALSE);
3152       silc_buffer_free(chk);
3153       silc_free(id);
3154     } else {
3155       /* The channel exist by that name, check whether the ID's match.
3156          If they don't then we'll force the server to use the ID we have.
3157          We also create a new key for the channel. */
3158       SilcBuffer modes = NULL, users = NULL, users_modes = NULL;
3159
3160       SILC_LOG_DEBUG(("Channel already exists"));
3161
3162       if (!SILC_ID_CHANNEL_COMPARE(channel_id, channel->id)) {
3163         /* They don't match, send CHANNEL_CHANGE notify to the server to
3164            force the ID change. */
3165         SILC_LOG_DEBUG(("Forcing the server to change Channel ID"));
3166         silc_server_send_notify_channel_change(server, sock, FALSE,
3167                                                channel_id, channel->id);
3168         silc_channel_payload_free(payload);
3169         silc_free(channel_id);
3170
3171         /* Wait that server re-announces this channel */
3172         return;
3173       }
3174
3175 #if 0 /* We will announce our CMODE anyway for this channel, so no need
3176          to check it (implicit enforce). */
3177
3178       /* If the mode is different from what we have then enforce the
3179          mode change. */
3180       mode = silc_channel_get_mode(payload);
3181       if (channel->mode != mode) {
3182         SILC_LOG_DEBUG(("Forcing the server to change channel mode"));
3183         silc_server_send_notify_cmode(server, sock, FALSE, channel,
3184                                       channel->mode, server->id,
3185                                       SILC_ID_SERVER, channel->cipher,
3186                                       channel->hmac_name,
3187                                       channel->passphrase,
3188                                       channel->founder_key);
3189       }
3190 #endif
3191
3192       /* Create new key for the channel and send it to the server and
3193          everybody else possibly on the channel. */
3194       if (!(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
3195
3196         if (silc_hash_table_count(channel->user_list)) {
3197           if (!silc_server_create_channel_key(server, channel, 0)) {
3198             silc_channel_payload_free(payload);
3199             silc_free(channel_id);
3200             return;
3201           }
3202
3203           /* Send to the channel */
3204           silc_server_send_channel_key(server, sock, channel, FALSE);
3205         }
3206
3207         /* Send to the server */
3208         id = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3209         id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3210         cipher = silc_cipher_get_name(channel->channel_key);
3211         cipher_len = strlen(cipher);
3212         chk = silc_channel_key_payload_encode(id_len, id,
3213                                               cipher_len, cipher,
3214                                               channel->key_len / 8,
3215                                               channel->key);
3216         silc_server_packet_send(server, sock, SILC_PACKET_CHANNEL_KEY, 0,
3217                                 chk->data, chk->len, FALSE);
3218         silc_buffer_free(chk);
3219         silc_free(id);
3220       }
3221
3222       silc_free(channel_id);
3223
3224       /* Since the channel is coming from server and we also know about it
3225          then send the JOIN notify to the server so that it see's our
3226          users on the channel "joining" the channel. */
3227       silc_server_announce_get_channel_users(server, channel, &modes, &users,
3228                                              &users_modes);
3229       if (users) {
3230         silc_buffer_push(users, users->data - users->head);
3231         silc_server_packet_send(server, sock,
3232                                 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3233                                 users->data, users->len, FALSE);
3234         silc_buffer_free(users);
3235       }
3236       if (modes) {
3237         silc_buffer_push(modes, modes->data - modes->head);
3238         silc_server_packet_send_dest(server, sock,
3239                                      SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3240                                      channel->id, SILC_ID_CHANNEL,
3241                                      modes->data, modes->len, FALSE);
3242         silc_buffer_free(modes);
3243       }
3244       if (users_modes) {
3245         silc_buffer_push(users_modes, users_modes->data - users_modes->head);
3246         silc_server_packet_send_dest(server, sock,
3247                                      SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3248                                      channel->id, SILC_ID_CHANNEL,
3249                                      users_modes->data,
3250                                      users_modes->len, FALSE);
3251         silc_buffer_free(users_modes);
3252       }
3253       if (channel->topic) {
3254         silc_server_send_notify_topic_set(server, sock,
3255                                           server->server_type == SILC_ROUTER ?
3256                                           TRUE : FALSE, channel,
3257                                           server->id, SILC_ID_SERVER,
3258                                           channel->topic);
3259       }
3260     }
3261   }
3262
3263   /* If the sender of this packet is server and we are router we need to
3264      broadcast this packet to other routers in the network. Broadcast
3265      this list packet instead of multiple New Channel packets. */
3266   if (server->server_type == SILC_ROUTER &&
3267       sock->type == SILC_SOCKET_TYPE_SERVER &&
3268       !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
3269     SILC_LOG_DEBUG(("Broadcasting received New Channel packet"));
3270     silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
3271                             packet->type,
3272                             packet->flags | SILC_PACKET_FLAG_BROADCAST,
3273                             packet->buffer->data,
3274                             packet->buffer->len, FALSE);
3275     silc_server_backup_send(server, sock->user_data,
3276                             packet->type, packet->flags,
3277                             packet->buffer->data, packet->buffer->len,
3278                             FALSE, TRUE);
3279   }
3280
3281   silc_channel_payload_free(payload);
3282 }
3283
3284 /* Received New Channel List packet, list of New Channel List payloads inside
3285    one packet. Process the New Channel payloads one by one. */
3286
3287 void silc_server_new_channel_list(SilcServer server,
3288                                   SilcSocketConnection sock,
3289                                   SilcPacketContext *packet)
3290 {
3291   SilcPacketContext *new;
3292   SilcBuffer buffer;
3293   SilcUInt16 len1, len2;
3294
3295   SILC_LOG_DEBUG(("Processing New Channel List"));
3296
3297   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
3298       packet->src_id_type != SILC_ID_SERVER ||
3299       server->server_type == SILC_SERVER)
3300     return;
3301
3302   /* Make copy of the original packet context, except for the actual
3303      data buffer, which we will here now fetch from the original buffer. */
3304   new = silc_packet_context_alloc();
3305   new->type = SILC_PACKET_NEW_CHANNEL;
3306   new->flags = packet->flags & (~SILC_PACKET_FLAG_LIST);
3307   new->src_id = packet->src_id;
3308   new->src_id_len = packet->src_id_len;
3309   new->src_id_type = packet->src_id_type;
3310   new->dst_id = packet->dst_id;
3311   new->dst_id_len = packet->dst_id_len;
3312   new->dst_id_type = packet->dst_id_type;
3313
3314   buffer = silc_buffer_alloc(512);
3315   new->buffer = buffer;
3316
3317   while (packet->buffer->len) {
3318     SILC_GET16_MSB(len1, packet->buffer->data);
3319     if ((len1 > packet->buffer->len) ||
3320         (len1 > buffer->truelen))
3321       break;
3322
3323     SILC_GET16_MSB(len2, packet->buffer->data + 2 + len1);
3324     if ((len2 > packet->buffer->len) ||
3325         (len2 > buffer->truelen))
3326       break;
3327
3328     silc_buffer_pull_tail(buffer, 8 + len1 + len2);
3329     silc_buffer_put(buffer, packet->buffer->data, 8 + len1 + len2);
3330
3331     /* Process the New Channel */
3332     silc_server_new_channel(server, sock, new);
3333
3334     silc_buffer_push_tail(buffer, 8 + len1 + len2);
3335     silc_buffer_pull(packet->buffer, 8 + len1 + len2);
3336   }
3337
3338   silc_buffer_free(buffer);
3339   silc_free(new);
3340 }
3341
3342 /* Received key agreement packet. This packet is never for us. It is to
3343    the client in the packet's destination ID. Sending of this sort of packet
3344    equals sending private message, ie. it is sent point to point from
3345    one client to another. */
3346
3347 void silc_server_key_agreement(SilcServer server,
3348                                SilcSocketConnection sock,
3349                                SilcPacketContext *packet)
3350 {
3351   SilcSocketConnection dst_sock;
3352   SilcIDListData idata;
3353
3354   SILC_LOG_DEBUG(("Start"));
3355
3356   if (packet->src_id_type != SILC_ID_CLIENT ||
3357       packet->dst_id_type != SILC_ID_CLIENT)
3358     return;
3359
3360   if (!packet->dst_id)
3361     return;
3362
3363   /* Get the route to the client */
3364   dst_sock = silc_server_get_client_route(server, packet->dst_id,
3365                                           packet->dst_id_len, NULL,
3366                                           &idata, NULL);
3367   if (!dst_sock)
3368     return;
3369
3370   /* Relay the packet */
3371   silc_server_relay_packet(server, dst_sock, idata->send_key,
3372                            idata->hmac_send, idata->psn_send++,
3373                            packet, FALSE);
3374 }
3375
3376 /* Received connection auth request packet that is used during connection
3377    phase to resolve the mandatory authentication method.  This packet can
3378    actually be received at anytime but usually it is used only during
3379    the connection authentication phase. Now, protocol says that this packet
3380    can come from client or server, however, we support only this coming
3381    from client and expect that server always knows what authentication
3382    method to use. */
3383
3384 void silc_server_connection_auth_request(SilcServer server,
3385                                          SilcSocketConnection sock,
3386                                          SilcPacketContext *packet)
3387 {
3388   SilcServerConfigClient *client = NULL;
3389   SilcUInt16 conn_type;
3390   int ret;
3391   SilcAuthMethod auth_meth = SILC_AUTH_NONE;
3392
3393   if (packet->src_id_type && packet->src_id_type != SILC_ID_CLIENT) {
3394     SILC_LOG_DEBUG(("Request not from client"));
3395     return;
3396   }
3397
3398   /* Parse the payload */
3399   ret = silc_buffer_unformat(packet->buffer,
3400                              SILC_STR_UI_SHORT(&conn_type),
3401                              SILC_STR_UI_SHORT(NULL),
3402                              SILC_STR_END);
3403   if (ret == -1)
3404     return;
3405
3406   if (conn_type != SILC_SOCKET_TYPE_CLIENT)
3407     return;
3408
3409   /* Get the authentication method for the client */
3410   auth_meth = SILC_AUTH_NONE;
3411   client = silc_server_config_find_client(server, sock->ip);
3412   if (!client)
3413     client = silc_server_config_find_client(server, sock->hostname);
3414   if (client) {
3415     if (client->passphrase) {
3416       if (client->publickeys && !server->config->prefer_passphrase_auth)
3417         auth_meth = SILC_AUTH_PUBLIC_KEY;
3418       else
3419         auth_meth = SILC_AUTH_PASSWORD;
3420     } else if (client->publickeys)
3421       auth_meth = SILC_AUTH_PUBLIC_KEY;
3422   }
3423
3424   SILC_LOG_DEBUG(("Authentication method is [%s]",
3425                   (auth_meth == SILC_AUTH_NONE ? "None" :
3426                    auth_meth == SILC_AUTH_PASSWORD ? "Passphrase" :
3427                    "Digital signatures")));
3428
3429   /* Send it back to the client */
3430   silc_server_send_connection_auth_request(server, sock, conn_type, auth_meth);
3431 }
3432
3433 /* Received REKEY packet. The sender of the packet wants to regenerate
3434    its session keys. This starts the REKEY protocol. */
3435
3436 void silc_server_rekey(SilcServer server,
3437                        SilcSocketConnection sock,
3438                        SilcPacketContext *packet)
3439 {
3440   SilcProtocol protocol;
3441   SilcServerRekeyInternalContext *proto_ctx;
3442   SilcIDListData idata = (SilcIDListData)sock->user_data;
3443
3444   SILC_LOG_DEBUG(("Received rekey request"));
3445
3446   /* If we have other protocol executing we have no other choice but to
3447      not execute rekey. XXX This is very bad thing.  Let's hope this
3448      doesn't happen often. */
3449   if (sock->protocol) {
3450     SILC_LOG_WARNING(("Cannot execute REKEY protocol because other protocol "
3451                       "is executing at the same time"));
3452     return;
3453   }
3454
3455   /* Allocate internal protocol context. This is sent as context
3456      to the protocol. */
3457   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
3458   proto_ctx->server = (void *)server;
3459   proto_ctx->sock = silc_socket_dup(sock);
3460   proto_ctx->responder = TRUE;
3461   proto_ctx->pfs = idata->rekey->pfs;
3462
3463   /* Perform rekey protocol. Will call the final callback after the
3464      protocol is over. */
3465   silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
3466                       &protocol, proto_ctx, silc_server_rekey_final);
3467   sock->protocol = protocol;
3468
3469   if (proto_ctx->pfs == FALSE)
3470     /* Run the protocol */
3471     silc_protocol_execute(protocol, server->schedule, 0, 0);
3472 }
3473
3474 /* Received file transger packet. This packet is never for us. It is to
3475    the client in the packet's destination ID. Sending of this sort of packet
3476    equals sending private message, ie. it is sent point to point from
3477    one client to another. */
3478
3479 void silc_server_ftp(SilcServer server,
3480                      SilcSocketConnection sock,
3481                      SilcPacketContext *packet)
3482 {
3483   SilcSocketConnection dst_sock;
3484   SilcIDListData idata;
3485
3486   SILC_LOG_DEBUG(("Start"));
3487
3488   if (packet->src_id_type != SILC_ID_CLIENT ||
3489       packet->dst_id_type != SILC_ID_CLIENT)
3490     return;
3491
3492   if (!packet->dst_id)
3493     return;
3494
3495   /* Get the route to the client */
3496   dst_sock = silc_server_get_client_route(server, packet->dst_id,
3497                                           packet->dst_id_len, NULL,
3498                                           &idata, NULL);
3499   if (!dst_sock)
3500     return;
3501
3502   /* Relay the packet */
3503   silc_server_relay_packet(server, dst_sock, idata->send_key,
3504                            idata->hmac_send, idata->psn_send++,
3505                            packet, FALSE);
3506 }
3507
3508 typedef struct {
3509   SilcServer server;
3510   SilcSocketConnection sock;
3511   SilcPacketContext *packet;
3512   void *data;
3513 } *SilcServerResumeResolve;
3514
3515 SILC_SERVER_CMD_FUNC(resume_resolve)
3516 {
3517   SilcServerResumeResolve r = (SilcServerResumeResolve)context;
3518   SilcServer server = r->server;
3519   SilcSocketConnection sock = r->sock;
3520   SilcServerCommandReplyContext reply = context2;
3521   SilcClientEntry client;
3522
3523   SILC_LOG_DEBUG(("Start"));
3524
3525   if (!reply || !silc_command_get_status(reply->payload, NULL, NULL)) {
3526     SILC_LOG_ERROR(("Client %s (%s) tried to resume unknown client, "
3527                     "closing connection", sock->hostname, sock->ip));
3528     silc_server_disconnect_remote(server, sock,
3529                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3530                                   "Resuming not possible");
3531     if (sock->user_data)
3532       silc_server_free_sock_user_data(server, sock, NULL);
3533     goto out;
3534   }
3535
3536   if (reply && silc_command_get(reply->payload) == SILC_COMMAND_WHOIS) {
3537     /* Get entry to the client, and resolve it if we don't have it. */
3538     client = silc_idlist_find_client_by_id(server->local_list,
3539                                            r->data, TRUE, NULL);
3540     if (!client) {
3541       client = silc_idlist_find_client_by_id(server->global_list,
3542                                              r->data, TRUE, NULL);
3543       if (!client) {
3544         SILC_LOG_ERROR(("Client %s (%s) tried to resume unknown client, "
3545                         "closing connection", sock->hostname, sock->ip));
3546         silc_server_disconnect_remote(server, sock,
3547                                       SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3548                                       "Resuming not possible");
3549         if (sock->user_data)
3550           silc_server_free_sock_user_data(server, sock, NULL);
3551         goto out;
3552       }
3553     }
3554
3555     if (!(client->mode & SILC_UMODE_DETACHED)) {
3556       SILC_LOG_ERROR(("Client %s (%s) tried to resume un-detached client, "
3557                       "closing connection", sock->hostname, sock->ip));
3558       silc_server_disconnect_remote(server, sock,
3559                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3560                                     "Resuming not possible");
3561       if (sock->user_data)
3562         silc_server_free_sock_user_data(server, sock, NULL);
3563       goto out;
3564     }
3565
3566     client->data.status |= SILC_IDLIST_STATUS_RESUME_RES;
3567   }
3568
3569   /* Reprocess the packet */
3570   silc_server_resume_client(server, sock, r->packet);
3571
3572  out:
3573   silc_socket_free(r->sock);
3574   silc_packet_context_free(r->packet);
3575   silc_free(r->data);
3576   silc_free(r);
3577 }
3578
3579 /* Received client resuming packet.  This is used to resume detached
3580    client session.  It can be sent by the client who wishes to resume
3581    but this is also sent by servers and routers to notify other routers
3582    that the client is not detached anymore. */
3583
3584 void silc_server_resume_client(SilcServer server,
3585                                SilcSocketConnection sock,
3586                                SilcPacketContext *packet)
3587 {
3588   SilcBuffer buffer = packet->buffer, buf;
3589   SilcIDListData idata;
3590   SilcIDCacheEntry id_cache = NULL;
3591   SilcClientEntry detached_client;
3592   SilcClientID *client_id = NULL;
3593   unsigned char *id_string, *auth = NULL;
3594   SilcUInt16 id_len, auth_len = 0;
3595   int ret, nickfail = 0;
3596   bool resolved, local, nick_change = FALSE, resolve = FALSE;
3597   SilcChannelEntry channel;
3598   SilcHashTableList htl;
3599   SilcChannelClientEntry chl;
3600   SilcServerResumeResolve r;
3601   const char *cipher;
3602
3603   ret = silc_buffer_unformat(buffer,
3604                              SILC_STR_UI16_NSTRING(&id_string, &id_len),
3605                              SILC_STR_END);
3606   if (ret != -1)
3607     client_id = silc_id_str2id(id_string, id_len, SILC_ID_CLIENT);
3608
3609   if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
3610     /* Client send this and is attempting to resume to old client session */
3611     SilcClientEntry client;
3612     SilcBuffer keyp;
3613
3614     if (ret != -1) {
3615       silc_buffer_pull(buffer, 2 + id_len);
3616       auth = buffer->data;
3617       auth_len = buffer->len;
3618       silc_buffer_push(buffer, 2 + id_len);
3619     }
3620
3621     if (!client_id || auth_len < 128) {
3622       SILC_LOG_ERROR(("Client %s (%s) sent incomplete resume information, "
3623                       "closing connection", sock->hostname, sock->ip));
3624       silc_server_disconnect_remote(server, sock,
3625                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3626                                     "Resuming not possible");
3627       if (sock->user_data)
3628         silc_server_free_sock_user_data(server, sock, NULL);
3629       silc_free(client_id);
3630       return;
3631     }
3632
3633     /* Take client entry of this connection */
3634     client = (SilcClientEntry)sock->user_data;
3635     idata = (SilcIDListData)client;
3636
3637     /* Get entry to the client, and resolve it if we don't have it. */
3638     detached_client = silc_server_query_client(server, client_id, FALSE,
3639                                                &resolved);
3640     if (!detached_client) {
3641       if (resolved) {
3642         /* The client info is being resolved. Reprocess this packet after
3643            receiving the reply to the query. */
3644         SILC_LOG_DEBUG(("Resolving client"));
3645         r = silc_calloc(1, sizeof(*r));
3646         if (!r)
3647           return;
3648         r->server = server;
3649         r->sock = silc_socket_dup(sock);
3650         r->packet = silc_packet_context_dup(packet);
3651         r->data = client_id;
3652         silc_server_command_pending(server, SILC_COMMAND_WHOIS,
3653                                     server->cmd_ident,
3654                                     silc_server_command_resume_resolve, r);
3655       } else {
3656         SILC_LOG_ERROR(("Client %s (%s) tried to resume unknown client, "
3657                         "closing connection", sock->hostname, sock->ip));
3658         silc_server_disconnect_remote(server, sock,
3659                                       SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3660                                       "Resuming not possible");
3661         if (sock->user_data)
3662           silc_server_free_sock_user_data(server, sock, NULL);
3663         silc_free(client_id);
3664       }
3665       return;
3666     }
3667
3668     if (!(detached_client->mode & SILC_UMODE_DETACHED))
3669       resolve = TRUE;
3670     if (!silc_hash_table_count(detached_client->channels) &&
3671         detached_client->router)
3672       resolve = TRUE;
3673     if (!detached_client->nickname)
3674       resolve = TRUE;
3675     if (detached_client->data.status & SILC_IDLIST_STATUS_RESUME_RES)
3676       resolve = FALSE;
3677
3678     if (resolve) {
3679       if (server->server_type == SILC_SERVER && !server->standalone) {
3680         /* The client info is being resolved. Reprocess this packet after
3681            receiving the reply to the query. */
3682         SILC_LOG_DEBUG(("Resolving client info"));
3683         silc_server_query_client(server, client_id, TRUE, NULL);
3684         r = silc_calloc(1, sizeof(*r));
3685         if (!r)
3686           return;
3687         r->server = server;
3688         r->sock = silc_socket_dup(sock);
3689         r->packet = silc_packet_context_dup(packet);
3690         r->data = client_id;
3691         silc_server_command_pending(server, SILC_COMMAND_WHOIS,
3692                                     server->cmd_ident,
3693                                     silc_server_command_resume_resolve, r);
3694         return;
3695       }
3696       if (server->server_type == SILC_SERVER) {
3697         SILC_LOG_ERROR(("Client %s (%s) tried to resume un-detached client, "
3698                         "closing connection", sock->hostname, sock->ip));
3699         silc_server_disconnect_remote(server, sock,
3700                                       SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3701                                       "Resuming not possible");
3702         if (sock->user_data)
3703           silc_server_free_sock_user_data(server, sock, NULL);
3704         silc_free(client_id);
3705         return;
3706       }
3707     }
3708
3709     /* Check that we have the public key of the client, if not then we must
3710        resolve it first. */
3711     if (!detached_client->data.public_key) {
3712       if (server->server_type == SILC_SERVER && server->standalone) {
3713         SILC_LOG_ERROR(("Detached client's public key not present, "
3714                         "closing connection"));
3715         silc_server_disconnect_remote(server, sock,
3716                                       SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3717                                       "Resuming not possible");
3718         if (sock->user_data)
3719           silc_server_free_sock_user_data(server, sock, NULL);
3720         silc_free(client_id);
3721       } else {
3722         /* We must retrieve the detached client's public key by sending
3723            GETKEY command. Reprocess this packet after receiving the key */
3724         SilcBuffer idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
3725         SilcSocketConnection dest_sock =
3726           silc_server_get_client_route(server, NULL, 0, client_id, NULL, NULL);
3727
3728         SILC_LOG_DEBUG(("Resolving client public key"));
3729
3730         silc_server_send_command(server, dest_sock ? dest_sock :
3731                                  SILC_PRIMARY_ROUTE(server),
3732                                  SILC_COMMAND_GETKEY, ++server->cmd_ident,
3733                                  1, 1, idp->data, idp->len);
3734
3735         r = silc_calloc(1, sizeof(*r));
3736         if (!r) {
3737           silc_free(client_id);
3738           return;
3739         }
3740
3741         r->server = server;
3742         r->sock = silc_socket_dup(sock);
3743         r->packet = silc_packet_context_dup(packet);
3744         silc_server_command_pending(server, SILC_COMMAND_GETKEY,
3745                                     server->cmd_ident,
3746                                     silc_server_command_resume_resolve, r);
3747
3748         silc_buffer_free(idp);
3749       }
3750       silc_free(client_id);
3751       return;
3752     } else if (!silc_pkcs_public_key_compare(detached_client->data.public_key,
3753                                              idata->public_key)) {
3754       /* We require that the connection and resuming authentication data
3755          must be using same key pair. */
3756       SILC_LOG_ERROR(("Resuming attempted with wrong public key, "
3757                       "closing connection"));
3758       silc_server_disconnect_remote(server, sock,
3759                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3760                                     "Resuming not possible");
3761       if (sock->user_data)
3762         silc_server_free_sock_user_data(server, sock, NULL);
3763       silc_free(client_id);
3764       return;
3765     }
3766
3767     /* Verify the authentication payload.  This has to be successful in
3768        order to allow the resuming */
3769     if (!idata->hash ||
3770         !silc_auth_verify_data(auth, auth_len, SILC_AUTH_PUBLIC_KEY,
3771                                detached_client->data.public_key, 0,
3772                                idata->hash, detached_client->id,
3773                                SILC_ID_CLIENT)) {
3774       SILC_LOG_ERROR(("Client %s (%s) resume authentication failed, "
3775                       "closing connection", sock->hostname, sock->ip));
3776       silc_server_disconnect_remote(server, sock,
3777                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3778                                     "Resuming not possible");
3779       if (sock->user_data)
3780         silc_server_free_sock_user_data(server, sock, NULL);
3781       silc_free(client_id);
3782       return;
3783     }
3784
3785     /* Now resume the client to the network */
3786
3787     silc_schedule_task_del_by_context(server->schedule, detached_client);
3788     sock->user_data = detached_client;
3789     detached_client->connection = sock;
3790
3791     if (client->data.public_key)
3792       silc_hash_table_del_by_context(server->pk_hash,
3793                                      detached_client->data.public_key,
3794                                      client);
3795
3796     /* Take new keys and stuff into use in the old entry */
3797     silc_idlist_del_data(detached_client);
3798     silc_idlist_add_data(detached_client, idata);
3799
3800     if (detached_client->data.public_key)
3801       silc_hash_table_add(server->pk_hash,
3802                           detached_client->data.public_key, client);
3803
3804     detached_client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
3805     detached_client->data.status |= SILC_IDLIST_STATUS_RESUMED;
3806     detached_client->data.status |= SILC_IDLIST_STATUS_LOCAL;
3807     detached_client->data.status &= ~SILC_IDLIST_STATUS_RESUME_RES;
3808     detached_client->mode &= ~SILC_UMODE_DETACHED;
3809     server->stat.my_detached--;
3810
3811     /* Send the RESUME_CLIENT packet to our primary router so that others
3812        know this client isn't detached anymore. */
3813     buf = silc_buffer_alloc_size(2 + id_len);
3814     silc_buffer_format(buf,
3815                        SILC_STR_UI_SHORT(id_len),
3816                        SILC_STR_UI_XNSTRING(id_string, id_len),
3817                        SILC_STR_END);
3818
3819     /* Send to primary router */
3820     silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
3821                             SILC_PACKET_RESUME_CLIENT, 0,
3822                             buf->data, buf->len, TRUE);
3823     silc_server_backup_send(server, detached_client->router,
3824                             SILC_PACKET_RESUME_CLIENT, 0,
3825                             buf->data, buf->len, TRUE, TRUE);
3826
3827     /* As router we must deliver this packet directly to the original
3828        server whom this client was earlier. */
3829     if (server->server_type == SILC_ROUTER && detached_client->router &&
3830         detached_client->router->server_type != SILC_ROUTER)
3831       silc_server_packet_send(server, detached_client->router->connection,
3832                               SILC_PACKET_RESUME_CLIENT, 0,
3833                               buf->data, buf->len, TRUE);
3834     silc_buffer_free(buf);
3835
3836     detached_client->router = NULL;
3837
3838     /* Delete this client entry since we're resuming to old one. */
3839     server->stat.my_clients--;
3840     server->stat.clients--;
3841     if (server->stat.cell_clients)
3842       server->stat.cell_clients--;
3843     silc_server_remove_from_channels(server, NULL, client, FALSE,
3844                                      NULL, FALSE, FALSE);
3845
3846     /* Remove from public key hash table. */
3847     if (client->data.public_key)
3848       silc_hash_table_del_by_context(server->pk_hash,
3849                                      client->data.public_key,
3850                                      client);
3851
3852     silc_server_del_from_watcher_list(server, client);
3853     if (!silc_idlist_del_client(server->local_list, client))
3854       silc_idlist_del_client(server->global_list, client);
3855     client = detached_client;
3856     silc_free(client->servername);
3857     client->servername = strdup(server->server_name);
3858
3859     /* If the ID is not based in our ID then change it */
3860     if (!SILC_ID_COMPARE(client->id, server->id, server->id->ip.data_len)) {
3861       silc_free(client_id);
3862       while (!silc_id_create_client_id(server, server->id, server->rng,
3863                                        server->md5hash, client->nickname,
3864                                        &client_id)) {
3865         nickfail++;
3866         if (nickfail > 9) {
3867           silc_server_disconnect_remote(server, sock,
3868                                         SILC_STATUS_ERR_BAD_NICKNAME, NULL);
3869           if (sock->user_data)
3870             silc_server_free_sock_user_data(server, sock, NULL);
3871           return;
3872         }
3873         snprintf(&client->nickname[strlen(client->nickname) - 1], 1,
3874                  "%d", nickfail);
3875       }
3876       nick_change = TRUE;
3877     }
3878
3879     if (nick_change) {
3880       /* Notify about Client ID change, nickname doesn't actually change. */
3881       silc_server_send_notify_nick_change(server, SILC_PRIMARY_ROUTE(server),
3882                                           SILC_BROADCAST(server),
3883                                           client->id, client_id,
3884                                           client->nickname);
3885     }
3886
3887     /* Resolve users on those channels that client has joined but we
3888        haven't resolved user list yet. */
3889     if (server->server_type == SILC_SERVER && !server->standalone) {
3890       silc_hash_table_list(client->channels, &htl);
3891       while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3892         channel = chl->channel;
3893         SILC_LOG_DEBUG(("Resolving users for %s channel",
3894                         channel->channel_name));
3895         if (channel->disabled || !channel->users_resolved) {
3896           silc_server_send_command(server, SILC_PRIMARY_ROUTE(server),
3897                                    SILC_COMMAND_USERS, ++server->cmd_ident,
3898                                    1, 2, channel->channel_name,
3899                                    strlen(channel->channel_name));
3900         }
3901       }
3902       silc_hash_table_list_reset(&htl);
3903     }
3904
3905     /* Send the new client ID to the client. After this client may start
3906        receiving other packets, and may start sending packets too. */
3907     silc_server_send_new_id(server, sock, FALSE, client_id, SILC_ID_CLIENT,
3908                             silc_id_get_len(client_id, SILC_ID_CLIENT));
3909
3910     if (nick_change) {
3911       /* Send NICK change notify to channels as well. */
3912       SilcBuffer oidp, nidp;
3913       oidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3914       nidp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
3915       silc_server_send_notify_on_channels(server, NULL, client,
3916                                           SILC_NOTIFY_TYPE_NICK_CHANGE, 3,
3917                                           oidp->data, oidp->len,
3918                                           nidp->data, nidp->len,
3919                                           client->nickname,
3920                                           strlen(client->nickname));
3921       silc_buffer_free(oidp);
3922       silc_buffer_free(nidp);
3923     }
3924
3925     /* Add the client again to the ID cache to get it to correct list */
3926     if (!silc_idcache_del_by_context(server->local_list->clients, client))
3927       silc_idcache_del_by_context(server->global_list->clients, client);
3928     silc_free(client->id);
3929     client->id = client_id;
3930     client_id = NULL;
3931     silc_idcache_add(server->local_list->clients, client->nickname,
3932                      client->id, client, 0, NULL);
3933
3934     /* Send some nice info to the client */
3935     silc_server_send_connect_notifys(server, sock, client);
3936
3937     /* Send all channel keys of channels the client has joined */
3938     silc_hash_table_list(client->channels, &htl);
3939     while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3940       bool created = FALSE;
3941       channel = chl->channel;
3942
3943       if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY)
3944         continue;
3945
3946       /* If we don't have channel key, then create one */
3947       if (!channel->channel_key) {
3948         if (!silc_server_create_channel_key(server, channel, 0))
3949           continue;
3950         created = TRUE;
3951       }
3952
3953       id_string = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3954       cipher = silc_cipher_get_name(channel->channel_key);
3955       keyp =
3956         silc_channel_key_payload_encode(silc_id_get_len(channel->id,
3957                                                         SILC_ID_CHANNEL),
3958                                         id_string,
3959                                         strlen(cipher), cipher,
3960                                         channel->key_len / 8, channel->key);
3961       silc_free(id_string);
3962
3963       /* Send the channel key to the client */
3964       silc_server_packet_send(server, sock, SILC_PACKET_CHANNEL_KEY, 0,
3965                               keyp->data, keyp->len, FALSE);
3966
3967       /* Distribute the channel key to channel */
3968       if (created) {
3969         silc_server_send_channel_key(server, NULL, channel,
3970                                      server->server_type == SILC_ROUTER ?
3971                                      FALSE : !server->standalone);
3972         silc_server_backup_send(server, NULL, SILC_PACKET_CHANNEL_KEY, 0,
3973                                 keyp->data, keyp->len, FALSE, TRUE);
3974       }
3975
3976       silc_buffer_free(keyp);
3977     }
3978     silc_hash_table_list_reset(&htl);
3979
3980   } else if (sock->type != SILC_SOCKET_TYPE_CLIENT) {
3981     /* Server or router sent this to us to notify that that a client has
3982        been resumed. */
3983     SilcServerEntry server_entry;
3984     SilcServerID *server_id;
3985
3986     if (!client_id) {
3987       SILC_LOG_DEBUG(("Malformed resuming packet"));
3988       return;
3989     }
3990
3991     /* Get entry to the client, and resolve it if we don't have it. */
3992     detached_client = silc_idlist_find_client_by_id(server->local_list,
3993                                                     client_id, TRUE,
3994                                                     &id_cache);
3995     if (!detached_client) {
3996       detached_client = silc_idlist_find_client_by_id(server->global_list,
3997                                                       client_id, TRUE,
3998                                                       &id_cache);
3999       if (!detached_client) {
4000         SILC_LOG_DEBUG(("Resuming client is unknown"));
4001         silc_free(client_id);
4002         return;
4003       }
4004     }
4005
4006     /* Check that the client has not been resumed already because it is
4007        protocol error to attempt to resume more than once.  The client
4008        will be killed if this protocol error occurs. */
4009     if (detached_client->data.status & SILC_IDLIST_STATUS_RESUMED &&
4010         !(detached_client->mode & SILC_UMODE_DETACHED)) {
4011       /* The client is clearly attempting to resume more than once and
4012          perhaps playing around by resuming from several different places
4013          at the same time. */
4014       SILC_LOG_DEBUG(("Attempting to re-resume client, killing both"));
4015       silc_server_kill_client(server, detached_client, NULL,
4016                               server->id, SILC_ID_SERVER);
4017       silc_free(client_id);
4018       return;
4019     }
4020
4021     /* Check whether client is detached at all */
4022     if (!(detached_client->mode & SILC_UMODE_DETACHED)) {
4023       SILC_LOG_DEBUG(("Client is not detached"));
4024       silc_free(client_id);
4025       return;
4026     }
4027
4028     SILC_LOG_DEBUG(("Resuming detached client"));
4029
4030     /* If the sender of this packet is server and we are router we need to
4031        broadcast this packet to other routers in the network. */
4032     if (server->server_type == SILC_ROUTER &&
4033         sock->type == SILC_SOCKET_TYPE_SERVER &&
4034         !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
4035       SILC_LOG_DEBUG(("Broadcasting received Resume Client packet"));
4036       silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
4037                               packet->type,
4038                               packet->flags | SILC_PACKET_FLAG_BROADCAST,
4039                               buffer->data, buffer->len, FALSE);
4040       silc_server_backup_send(server, sock->user_data,
4041                               packet->type, packet->flags,
4042                               packet->buffer->data, packet->buffer->len,
4043                               FALSE, TRUE);
4044     }
4045
4046     /* Client is detached, and now it is resumed.  Remove the detached
4047        mode and mark that it is resumed. */
4048
4049     /* we need to delete the public key from the has .. but do we need to
4050      * get the key again? */
4051     if (detached_client->data.public_key)
4052       silc_hash_table_del_by_context(server->pk_hash,
4053                                      detached_client->data.public_key,
4054                                      detached_client);
4055
4056     silc_idlist_del_data(detached_client);
4057     detached_client->mode &= ~SILC_UMODE_DETACHED;
4058     detached_client->data.status |= SILC_IDLIST_STATUS_RESUMED;
4059     detached_client->data.status &= ~SILC_IDLIST_STATUS_LOCAL;
4060     id_cache->expire = 0;
4061
4062     silc_schedule_task_del_by_context(server->schedule, detached_client);
4063
4064     /* Get the new owner of the resumed client */
4065     server_id = silc_id_str2id(packet->src_id, packet->src_id_len,
4066                                packet->src_id_type);
4067     if (!server_id) {
4068       silc_free(client_id);
4069       return;
4070     }
4071
4072     /* Get server entry */
4073     server_entry = silc_idlist_find_server_by_id(server->global_list,
4074                                                  server_id, TRUE, NULL);
4075     local = FALSE;
4076     if (!server_entry) {
4077       server_entry = silc_idlist_find_server_by_id(server->local_list,
4078                                                    server_id, TRUE, NULL);
4079       local = TRUE;
4080       if (!server_entry) {
4081         silc_free(server_id);
4082         silc_free(client_id);
4083         return;
4084       }
4085     }
4086
4087     if (server->server_type == SILC_ROUTER &&
4088         sock->type == SILC_SOCKET_TYPE_ROUTER &&
4089         server_entry->server_type == SILC_ROUTER)
4090       local = FALSE;
4091
4092     /* Change the client to correct list. */
4093     if (!silc_idcache_del_by_context(server->local_list->clients,
4094                                      detached_client))
4095       silc_idcache_del_by_context(server->global_list->clients,
4096                                   detached_client);
4097     silc_idcache_add(local && server->server_type == SILC_ROUTER ?
4098                      server->local_list->clients :
4099                      server->global_list->clients,
4100                      detached_client->nickname,
4101                      detached_client->id, detached_client, FALSE, NULL);
4102
4103     /* Change the owner of the client */
4104     detached_client->router = server_entry;
4105
4106     /* Update channel information regarding global clients on channel. */
4107     if (server->server_type != SILC_ROUTER) {
4108       silc_hash_table_list(detached_client->channels, &htl);
4109       while (silc_hash_table_get(&htl, NULL, (void *)&chl))
4110         chl->channel->global_users =
4111           silc_server_channel_has_global(chl->channel);
4112       silc_hash_table_list_reset(&htl);
4113     }
4114
4115     silc_free(server_id);
4116   }
4117
4118   silc_free(client_id);
4119 }