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