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