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