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