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