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