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