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