More preliminary changes for 1.1 Server. Fixed quitting,
[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 from public key hash table. */
320     if (client->data.public_key)
321       silc_hash_table_del_by_context(server->pk_hash, client->data.public_key,
322                                      client);
323
324     /* Remove the client from all channels. */
325     silc_server_remove_from_channels(server, NULL, client, TRUE,
326                                      tmp, FALSE, FALSE);
327
328     /* Check if anyone is watching this nickname */
329     if (server->server_type == SILC_ROUTER)
330       silc_server_check_watcher_list(server, client, NULL,
331                                      SILC_NOTIFY_TYPE_SIGNOFF);
332
333     /* Remove this client from watcher list if it is */
334     silc_server_del_from_watcher_list(server, client);
335
336     client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
337     client->mode = 0;
338     client->router = NULL;
339     client->connection = NULL;
340     break;
341
342   case SILC_NOTIFY_TYPE_TOPIC_SET:
343     /*
344      * Distribute the notify to local clients on the channel
345      */
346
347     SILC_LOG_DEBUG(("TOPIC SET notify"));
348
349     /* Get client ID */
350     if (!silc_argument_get_decoded(args, 1, SILC_ARGUMENT_ID, &id, NULL))
351       goto out;
352
353     /* Get client entry */
354     if (id.type == SILC_ID_CLIENT) {
355       client = silc_idlist_find_client_by_id(server->global_list,
356                                              SILC_ID_GET_ID(id), TRUE, &cache);
357       if (!client) {
358         client = silc_idlist_find_client_by_id(server->local_list,
359                                                SILC_ID_GET_ID(id),
360                                                TRUE, &cache);
361         if (!client)
362           goto out;
363       }
364     }
365
366     /* Get the topic */
367     tmp = silc_argument_get_arg_type(args, 2, &tmp_len);
368     if (!tmp)
369       goto out;
370
371     if (!silc_id_str2id(packet->dst_id, packet->dst_id_len,
372                         packet->dst_id_type, &channel_id,
373                         sizeof(channel_id)))
374       goto out;
375
376     /* Get channel entry */
377     channel = silc_idlist_find_channel_by_id(server->global_list,
378                                              &channel_id, NULL);
379     if (!channel) {
380       channel = silc_idlist_find_channel_by_id(server->local_list,
381                                                &channel_id, NULL);
382       if (!channel) {
383         SILC_LOG_DEBUG(("Notify for unknown channel"));
384         goto out;
385       }
386     }
387
388     if (channel->topic && !strcmp(channel->topic, tmp)) {
389       SILC_LOG_DEBUG(("Topic is already set and same"));
390       goto out;
391     }
392
393     if (client) {
394       /* Get user's channel entry and check that topic set is allowed. */
395       if (!silc_server_client_on_channel(client, channel, &chl))
396         goto out;
397       if (channel->mode & SILC_CHANNEL_MODE_TOPIC &&
398           !(chl->mode & SILC_CHANNEL_UMODE_CHANOP) &&
399           !(chl->mode & SILC_CHANNEL_UMODE_CHANFO)) {
400         SILC_LOG_DEBUG(("Topic change is not allowed"));
401         goto out;
402       }
403     }
404
405     /* Change the topic */
406     silc_free(channel->topic);
407     channel->topic = strdup(tmp);
408
409     /* Send the same notify to the channel */
410     silc_server_packet_send_to_channel(server, NULL, channel, packet->type,
411                                        FALSE, TRUE, buffer->data,
412                                        silc_buffer_len(buffer));
413     break;
414
415   case SILC_NOTIFY_TYPE_NICK_CHANGE:
416     {
417       /*
418        * Distribute the notify to local clients on the channel
419        */
420       char *nickname;
421       SilcUInt32 nickname_len;
422
423       SILC_LOG_DEBUG(("NICK CHANGE notify"));
424
425       /* Get old client ID */
426       if (!silc_argument_get_decoded(args, 1, SILC_ARGUMENT_ID, &id, NULL))
427         goto out;
428
429       /* Get new client ID */
430       if (!silc_argument_get_decoded(args, 2, SILC_ARGUMENT_ID, &id2, NULL))
431         goto out;
432
433       SILC_LOG_DEBUG(("Old Client ID id(%s)",
434                       silc_id_render(SILC_ID_GET_ID(id), SILC_ID_CLIENT)));
435       SILC_LOG_DEBUG(("New Client ID id(%s)",
436                       silc_id_render(SILC_ID_GET_ID(id2), SILC_ID_CLIENT)));
437
438       /* From protocol version 1.1 we also get the new nickname */
439       nickname = silc_argument_get_arg_type(args, 3, &nickname_len);;
440
441       /* Replace the Client ID */
442       client = silc_idlist_replace_client_id(server,
443                                              server->global_list,
444                                              SILC_ID_GET_ID(id),
445                                              SILC_ID_GET_ID(id2), nickname);
446       if (!client)
447         client = silc_idlist_replace_client_id(server,
448                                                server->local_list,
449                                                SILC_ID_GET_ID(id),
450                                                SILC_ID_GET_ID(id2), nickname);
451
452       if (client) {
453         /* Send the NICK_CHANGE notify type to local clients on the channels
454            this client is joined to. */
455         tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
456         tmp2 = silc_argument_get_arg_type(args, 2, &tmp2_len);
457         silc_server_send_notify_on_channels(server, client, client,
458                                             SILC_NOTIFY_TYPE_NICK_CHANGE, 3,
459                                             tmp, tmp_len, tmp2, tmp2_len,
460                                             nickname, nickname ?
461                                             nickname_len : 0);
462       }
463
464       break;
465     }
466
467   case SILC_NOTIFY_TYPE_CMODE_CHANGE:
468     /*
469      * Distribute the notify to local clients on the channel
470      */
471
472     SILC_LOG_DEBUG(("CMODE CHANGE notify"));
473
474     /* Get client ID */
475     if (!silc_argument_get_decoded(args, 1, SILC_ARGUMENT_ID, &id, NULL))
476       goto out;
477
478     /* Get client entry */
479     if (id.type == SILC_ID_CLIENT) {
480       client = silc_idlist_find_client_by_id(server->global_list,
481                                              SILC_ID_GET_ID(id), TRUE, &cache);
482       if (!client) {
483         client = silc_idlist_find_client_by_id(server->local_list,
484                                                SILC_ID_GET_ID(id),
485                                                TRUE, &cache);
486         if (!client)
487           goto out;
488       }
489     }
490
491     if (!silc_id_str2id(packet->dst_id, packet->dst_id_len,
492                         packet->dst_id_type, &channel_id,
493                         sizeof(channel_id)))
494       goto out;
495
496     /* Get channel entry */
497     channel = silc_idlist_find_channel_by_id(server->global_list,
498                                              &channel_id, NULL);
499     if (!channel) {
500       channel = silc_idlist_find_channel_by_id(server->local_list,
501                                                &channel_id, NULL);
502       if (!channel) {
503         SILC_LOG_DEBUG(("Notify for unknown channel"));
504         goto out;
505       }
506     }
507
508     /* Get the mode */
509     tmp = silc_argument_get_arg_type(args, 2, &tmp_len);
510     if (!tmp)
511       goto out;
512     SILC_GET32_MSB(mode, tmp);
513
514     /* Check if mode changed */
515     if (channel->mode == mode) {
516       SILC_LOG_DEBUG(("Mode is changed already"));
517
518       /* If this mode change has founder mode then we'll enforce the
519          change so that the server gets the real founder public key */
520       if (server->server_type != SILC_SERVER &&
521           sock != SILC_PRIMARY_ROUTE(server) &&
522           mode & SILC_CHANNEL_MODE_FOUNDER_AUTH && channel->founder_key) {
523         SILC_LOG_DEBUG(("Sending founder public key to server"));
524         silc_server_send_notify_cmode(server, sock, FALSE, channel,
525                                       channel->mode, server->id,
526                                       SILC_ID_SERVER, channel->cipher,
527                                       channel->hmac_name,
528                                       channel->passphrase,
529                                       channel->founder_key, NULL);
530       }
531
532       /* If we received same mode from our primary check whether founder
533          mode and key in the notify is set.  We update the founder key
534          here since we may have wrong one */
535       if (server->server_type != SILC_ROUTER &&
536           sock == SILC_PRIMARY_ROUTE(server) &&
537           mode & SILC_CHANNEL_MODE_FOUNDER_AUTH) {
538         SILC_LOG_DEBUG(("Founder public key received from router"));
539         tmp = silc_argument_get_arg_type(args, 6, &tmp_len);
540         if (!tmp)
541           break;
542
543         if (channel->founder_key)
544           silc_pkcs_public_key_free(channel->founder_key);
545         channel->founder_key = NULL;
546         silc_public_key_payload_decode(tmp, tmp_len,
547                                        &channel->founder_key);
548       }
549
550       /* Check also for channel public key list */
551       if (server->server_type == SILC_SERVER &&
552           sock == SILC_PRIMARY_ROUTE(server) &&
553           mode & SILC_CHANNEL_MODE_CHANNEL_AUTH) {
554         SilcBuffer chpklist;
555         SilcBuffer sidp;
556         unsigned char mask[4], ulimit[4];
557
558         SILC_LOG_DEBUG(("Channel public key list received from router"));
559         tmp = silc_argument_get_arg_type(args, 7, &tmp_len);
560         if (!tmp)
561           break;
562
563         /* Set the router's list, and send the notify to channel too so that
564            channel gets the list */
565         silc_server_set_channel_pk_list(server, sock, channel, tmp, tmp_len);
566         chpklist = silc_server_get_channel_pk_list(server, channel,
567                                                    FALSE, FALSE);
568         if (!chpklist)
569           break;
570         sidp = silc_id_payload_encode(server->router->id, SILC_ID_SERVER);
571         SILC_PUT32_MSB(channel->mode, mask);
572         if (channel->mode & SILC_CHANNEL_MODE_ULIMIT)
573           SILC_PUT32_MSB(channel->user_limit, ulimit);
574         silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
575                                            SILC_NOTIFY_TYPE_CMODE_CHANGE, 8,
576                                            sidp->data, silc_buffer_len(sidp),
577                                            mask, 4,
578                                            channel->cipher,
579                                            channel->cipher ?
580                                            strlen(channel->cipher) : 0,
581                                            channel->hmac_name,
582                                            channel->hmac_name ?
583                                            strlen(channel->hmac_name) : 0,
584                                            channel->passphrase,
585                                            channel->passphrase ?
586                                            strlen(channel->passphrase) : 0,
587                                            NULL, 0,
588                                            chpklist->data,
589                                            silc_buffer_len(chpklist),
590                                            (channel->mode &
591                                             SILC_CHANNEL_MODE_ULIMIT ?
592                                             ulimit : NULL),
593                                            (channel->mode &
594                                             SILC_CHANNEL_MODE_ULIMIT ?
595                                             sizeof(ulimit) : 0));
596         silc_buffer_free(sidp);
597         silc_buffer_free(chpklist);
598         goto out;
599       }
600
601       break;
602     }
603
604     /* Get user's channel entry and check that mode change is allowed */
605     if (client) {
606       if (!silc_server_client_on_channel(client, channel, &chl))
607         goto out;
608       if (!silc_server_check_cmode_rights(server, channel, chl, mode)) {
609         SILC_LOG_DEBUG(("CMODE change is not allowed"));
610         silc_server_send_notify_cmode(server, sock, FALSE, channel,
611                                       channel->mode, server->id,
612                                       SILC_ID_SERVER, channel->cipher,
613                                       channel->hmac_name,
614                                       channel->passphrase,
615                                       channel->founder_key, NULL);
616         goto out;
617       }
618     } else {
619       /* Assure that server is not removing founder mode from us */
620       if (server->server_type == SILC_ROUTER &&
621           sock != SILC_PRIMARY_ROUTE(server) &&
622           channel->mode & SILC_CHANNEL_MODE_FOUNDER_AUTH &&
623           !(mode & SILC_CHANNEL_MODE_FOUNDER_AUTH)) {
624         SILC_LOG_DEBUG(("Enforcing sender to change channel mode"));
625         silc_server_send_notify_cmode(server, sock, FALSE, channel,
626                                       channel->mode, server->id,
627                                       SILC_ID_SERVER, channel->cipher,
628                                       channel->hmac_name,
629                                       channel->passphrase,
630                                       channel->founder_key, NULL);
631         goto out;
632       }
633
634       /* If server is adding founder mode, check whether there is founder
635          on channel already and is not from this server */
636       if (server->server_type == SILC_ROUTER &&
637           sock != SILC_PRIMARY_ROUTE(server) &&
638           mode & SILC_CHANNEL_MODE_FOUNDER_AUTH) {
639         silc_hash_table_list(channel->user_list, &htl);
640         while (silc_hash_table_get(&htl, NULL, (void *)&chl))
641           if (chl->mode & SILC_CHANNEL_UMODE_CHANFO &&
642               chl->client->router != (SilcServerEntry)idata) {
643             SILC_LOG_DEBUG(("Enforcing sender to change channel mode"));
644             silc_server_send_notify_cmode(server, sock, FALSE, channel,
645                                           channel->mode, server->id,
646                                           SILC_ID_SERVER, channel->cipher,
647                                           channel->hmac_name,
648                                           channel->passphrase,
649                                           channel->founder_key, NULL);
650             silc_hash_table_list_reset(&htl);
651             goto out;
652           }
653         silc_hash_table_list_reset(&htl);
654       }
655     }
656
657     /* If the channel had private keys set and the mode was removed then
658        we must re-generate and re-distribute a new channel key */
659     if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY &&
660         !(mode & SILC_CHANNEL_MODE_PRIVKEY)) {
661       /* Re-generate channel key */
662       if (!silc_server_create_channel_key(server, channel, 0))
663         goto out;
664
665       /* Send the channel key. This sends it to our local clients and if
666          we are normal server to our router as well. */
667       silc_server_send_channel_key(server, NULL, channel,
668                                    server->server_type == SILC_ROUTER ?
669                                    FALSE : !server->standalone);
670     }
671
672     /* Get the hmac */
673     tmp = silc_argument_get_arg_type(args, 4, &tmp_len);
674     if (tmp) {
675       unsigned char hash[SILC_HASH_MAXLEN];
676
677       if (channel->hmac)
678         silc_hmac_free(channel->hmac);
679       if (!silc_hmac_alloc(tmp, NULL, &channel->hmac))
680         goto out;
681
682       /* Set the HMAC key out of current channel key. The client must do
683          this locally. */
684       silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key,
685                      channel->key_len / 8, hash);
686       silc_hmac_set_key(channel->hmac, hash,
687                         silc_hash_len(silc_hmac_get_hash(channel->hmac)));
688       memset(hash, 0, sizeof(hash));
689     }
690
691     /* Get the passphrase */
692     tmp = silc_argument_get_arg_type(args, 5, &tmp_len);
693     if (tmp) {
694       silc_free(channel->passphrase);
695       channel->passphrase = silc_memdup(tmp, tmp_len);
696     }
697
698     /* Get founder public key */
699     tmp = silc_argument_get_arg_type(args, 6, &tmp_len);
700     if (tmp && mode & SILC_CHANNEL_MODE_FOUNDER_AUTH) {
701       if (channel->founder_key)
702         silc_pkcs_public_key_free(channel->founder_key);
703       channel->founder_key = NULL;
704       SILC_LOG_DEBUG(("Founder public key received"));
705       if (!silc_public_key_payload_decode(tmp, tmp_len,
706                                           &channel->founder_key)) {
707         SILC_LOG_DEBUG(("Enforcing sender to change channel mode"));
708         mode &= ~SILC_CHANNEL_MODE_FOUNDER_AUTH;
709         silc_server_send_notify_cmode(server, sock, FALSE, channel,
710                                       mode, server->id, SILC_ID_SERVER,
711                                       channel->cipher,
712                                       channel->hmac_name,
713                                       channel->passphrase, NULL, NULL);
714         if (channel->founder_key)
715           silc_pkcs_public_key_free(channel->founder_key);
716         channel->founder_key = NULL;
717       }
718     }
719
720     if (mode & SILC_CHANNEL_MODE_FOUNDER_AUTH && !channel->founder_key &&
721         server->server_type == SILC_ROUTER) {
722       SILC_LOG_DEBUG(("Enforcing sender to change channel mode"));
723       mode &= ~SILC_CHANNEL_MODE_FOUNDER_AUTH;
724       silc_server_send_notify_cmode(server, sock, FALSE, channel,
725                                     mode, server->id, SILC_ID_SERVER,
726                                     channel->cipher,
727                                     channel->hmac_name,
728                                     channel->passphrase, NULL, NULL);
729     }
730
731     /* Process channel public key(s). */
732     tmp = silc_argument_get_arg_type(args, 7, &tmp_len);
733     if (tmp && mode & SILC_CHANNEL_MODE_CHANNEL_AUTH) {
734       SilcStatus ret;
735       SILC_LOG_DEBUG(("Channel public key list received from router"));
736
737       ret =
738         silc_server_set_channel_pk_list(server, sock, channel, tmp, tmp_len);
739
740       /* If list was set already we will enforce the same list to server. */
741       if (ret == SILC_STATUS_ERR_OPERATION_ALLOWED) {
742         SilcBuffer chpklist = silc_server_get_channel_pk_list(server, channel,
743                                                               TRUE, FALSE);
744         silc_server_send_notify_cmode(server, sock, FALSE, channel,
745                                       mode, server->id, SILC_ID_SERVER,
746                                       channel->cipher,
747                                       channel->hmac_name,
748                                       channel->passphrase, NULL,
749                                       chpklist);
750         silc_buffer_free(chpklist);
751       }
752     }
753
754     /* Get the user limit */
755     tmp = silc_argument_get_arg_type(args, 8, &tmp_len);
756     if (tmp && tmp_len == 4 && mode & SILC_CHANNEL_MODE_ULIMIT)
757       SILC_GET32_MSB(channel->user_limit, tmp);
758
759     /* Send the same notify to the channel */
760     silc_server_packet_send_to_channel(server, NULL, channel, packet->type,
761                                        FALSE, TRUE, buffer->data,
762                                        silc_buffer_len(buffer));
763
764     /* Change mode */
765     channel->mode = mode;
766
767     /* Cleanup if some modes are removed */
768
769     if (!(channel->mode & SILC_CHANNEL_MODE_FOUNDER_AUTH) &&
770         channel->founder_key) {
771       silc_pkcs_public_key_free(channel->founder_key);
772       channel->founder_key = NULL;
773     }
774
775     if (!(channel->mode & SILC_CHANNEL_MODE_CHANNEL_AUTH) &&
776         channel->channel_pubkeys) {
777       silc_hash_table_free(channel->channel_pubkeys);
778       channel->channel_pubkeys = NULL;
779     }
780
781     break;
782
783   case SILC_NOTIFY_TYPE_CUMODE_CHANGE:
784     {
785       /*
786        * Distribute the notify to local clients on the channel
787        */
788       SilcChannelClientEntry chl2 = NULL;
789       SilcBool notify_sent = FALSE;
790
791       SILC_LOG_DEBUG(("CUMODE CHANGE notify"));
792
793       /* Get client ID */
794       if (!silc_argument_get_decoded(args, 1, SILC_ARGUMENT_ID, &id, NULL))
795         goto out;
796
797       /* Get client entry */
798       if (id.type == SILC_ID_CLIENT) {
799         client = silc_idlist_find_client_by_id(server->global_list,
800                                                SILC_ID_GET_ID(id),
801                                                TRUE, &cache);
802         if (!client) {
803           client = silc_idlist_find_client_by_id(server->local_list,
804                                                  SILC_ID_GET_ID(id),
805                                                  TRUE, &cache);
806           if (!client)
807             goto out;
808         }
809       }
810
811       if (!silc_id_str2id(packet->dst_id, packet->dst_id_len,
812                           packet->dst_id_type, &channel_id,
813                           sizeof(channel_id)))
814         goto out;
815
816       /* Get channel entry */
817       channel = silc_idlist_find_channel_by_id(server->global_list,
818                                                &channel_id, NULL);
819       if (!channel) {
820         channel = silc_idlist_find_channel_by_id(server->local_list,
821                                                  &channel_id, NULL);
822         if (!channel) {
823           SILC_LOG_DEBUG(("Notify for unknown channel"));
824           goto out;
825         }
826       }
827
828       /* Get the mode */
829       tmp = silc_argument_get_arg_type(args, 2, &tmp_len);
830       if (!tmp)
831         goto out;
832
833       SILC_GET32_MSB(mode, tmp);
834
835       /* Get target client */
836       if (!silc_argument_get_decoded(args, 3, SILC_ARGUMENT_ID, &id, NULL))
837         goto out;
838
839       /* Get client entry */
840       client2 = silc_idlist_find_client_by_id(server->global_list,
841                                               SILC_ID_GET_ID(id), TRUE, NULL);
842       if (!client2) {
843         client2 = silc_idlist_find_client_by_id(server->local_list,
844                                                 SILC_ID_GET_ID(id),
845                                                 TRUE, NULL);
846         if (!client2)
847           goto out;
848       }
849
850       if (client) {
851         /* Check that sender is on channel */
852         if (!silc_server_client_on_channel(client, channel, &chl))
853           goto out;
854
855         if (client != client2 && server->server_type == SILC_ROUTER) {
856           /* Sender must be operator */
857           if (!(chl->mode & SILC_CHANNEL_UMODE_CHANOP) &&
858               !(chl->mode & SILC_CHANNEL_UMODE_CHANFO)) {
859             SILC_LOG_DEBUG(("CUMODE change is not allowed"));
860             goto out;
861           }
862
863           if (!silc_server_client_on_channel(client2, channel, &chl))
864             goto out;
865
866           /* If target is founder mode change is not allowed. */
867           if (chl->mode & SILC_CHANNEL_UMODE_CHANFO) {
868             SILC_LOG_DEBUG(("CUMODE change is not allowed"));
869             goto out;
870           }
871         }
872       }
873
874       /* Get target channel user entry */
875       if (!silc_server_client_on_channel(client2, channel, &chl))
876         goto out;
877
878       if (server->server_type == SILC_SERVER && chl->mode == mode) {
879         SILC_LOG_DEBUG(("Mode is changed already"));
880         break;
881       }
882
883       /* Check whether to give founder rights to this user or not.  The
884          problem here is that we get only the public key of the client,
885          but no authentication data.  We must assume that server has
886          already authenticated the user (and thus we must trust the
887          server). */
888       if (mode & SILC_CHANNEL_UMODE_CHANFO &&
889           !(chl->mode & SILC_CHANNEL_UMODE_CHANFO) &&
890           server->server_type == SILC_ROUTER &&
891           sock != SILC_PRIMARY_ROUTE(server)) {
892         SilcPublicKey founder_key = NULL;
893
894         /* If channel doesn't have founder auth mode then it's impossible
895            that someone would be getting founder rights with CUMODE command.
896            In that case there already either is founder or there isn't
897            founder at all on the channel (valid only when 'client' is
898            valid). */
899         if (client && !(channel->mode & SILC_CHANNEL_MODE_FOUNDER_AUTH)) {
900           /* Force the mode to not have founder mode */
901           chl->mode = mode &= ~SILC_CHANNEL_UMODE_CHANFO;
902           silc_server_force_cumode_change(server, sock, channel, chl, mode);
903           notify_sent = TRUE;
904           break;
905         }
906
907         /* Get the founder of the channel and if found then this client
908            cannot be the founder since there already is one. */
909         silc_hash_table_list(channel->user_list, &htl);
910         while (silc_hash_table_get(&htl, NULL, (void *)&chl2))
911           if (chl2->mode & SILC_CHANNEL_UMODE_CHANFO) {
912             SILC_LOG_DEBUG(("Founder already on channel"));
913             chl->mode = mode &= ~SILC_CHANNEL_UMODE_CHANFO;
914             silc_server_force_cumode_change(server, sock, channel,
915                                             chl, mode);
916             notify_sent = TRUE;
917             break;
918           }
919         silc_hash_table_list_reset(&htl);
920         if (!(mode & SILC_CHANNEL_UMODE_CHANFO))
921           break;
922
923         /* Founder not found on the channel.  Since the founder auth mode
924            is set on the channel now check whether this is the client that
925            originally set the mode. */
926
927         if (channel->founder_key) {
928           /* Get public key that must be present in notify */
929           tmp = silc_argument_get_arg_type(args, 4, &tmp_len);
930           if (!tmp || !silc_public_key_payload_decode(tmp, tmp_len,
931                                                       &founder_key)) {
932             chl->mode = mode &= ~SILC_CHANNEL_UMODE_CHANFO;
933             SILC_LOG_DEBUG(("Founder public key not present"));
934             silc_server_force_cumode_change(server, sock, channel, chl, mode);
935             notify_sent = TRUE;
936             break;
937           }
938
939           /* Now match the public key we have cached and public key sent.
940              They must match. */
941           if (!silc_pkcs_public_key_compare(channel->founder_key,
942                                             founder_key)) {
943             chl->mode = mode &= ~SILC_CHANNEL_UMODE_CHANFO;
944             SILC_LOG_DEBUG(("Founder public key mismatch"));
945             silc_server_force_cumode_change(server, sock, channel, chl, mode);
946             notify_sent = TRUE;
947             break;
948           }
949         }
950
951         /* There cannot be anyone else as founder on the channel now.  This
952            client is definitely the founder due to this 'authentication'.
953            We trust the server did the actual signature verification
954            earlier (bad, yes). */
955         silc_hash_table_list(channel->user_list, &htl);
956         while (silc_hash_table_get(&htl, NULL, (void *)&chl2))
957           if (chl2->mode & SILC_CHANNEL_UMODE_CHANFO) {
958             chl2->mode &= ~SILC_CHANNEL_UMODE_CHANFO;
959             SILC_LOG_DEBUG(("Removing old founder rights, new authenticated"));
960             silc_server_force_cumode_change(server, NULL, channel, chl2,
961                                             chl2->mode);
962             break;
963           }
964         silc_hash_table_list_reset(&htl);
965
966         if (founder_key)
967           silc_pkcs_public_key_free(founder_key);
968       }
969
970       if (server->server_type != SILC_SERVER && chl->mode == mode) {
971         SILC_LOG_DEBUG(("Mode is changed already"));
972         break;
973       }
974
975       SILC_LOG_DEBUG(("Changing %s channel user mode",
976                       chl->client->nickname ? chl->client->nickname :
977                       (unsigned char *)""));
978
979       /* Change the mode */
980       chl->mode = mode;
981
982       /* Send the same notify to the channel */
983       if (!notify_sent)
984         silc_server_packet_send_to_channel(server, sock, channel,
985                                            packet->type,
986                                            FALSE, TRUE, buffer->data,
987                                            silc_buffer_len(buffer));
988
989       break;
990     }
991
992   case SILC_NOTIFY_TYPE_INVITE:
993
994     if (packet->dst_id_type == SILC_ID_CLIENT)
995       goto out;
996
997     SILC_LOG_DEBUG(("INVITE notify"));
998
999     /* Get Channel ID */
1000     if (!silc_argument_get_decoded(args, 1, SILC_ARGUMENT_ID, &id, NULL))
1001       goto out;
1002
1003     /* Get channel entry */
1004     channel = silc_idlist_find_channel_by_id(server->global_list,
1005                                              SILC_ID_GET_ID(id), NULL);
1006     if (!channel) {
1007       channel = silc_idlist_find_channel_by_id(server->local_list,
1008                                                SILC_ID_GET_ID(id), NULL);
1009       if (!channel) {
1010         SILC_LOG_DEBUG(("Notify for unknown channel"));
1011         goto out;
1012       }
1013     }
1014
1015     /* Get the invite action */
1016     tmp = silc_argument_get_arg_type(args, 4, &tmp_len);
1017     if (tmp && tmp_len == 1) {
1018       SilcUInt8 action = (SilcUInt8)tmp[0];
1019       SilcUInt16 iargc = 0;
1020       SilcArgumentPayload iargs;
1021
1022       /* Get invite list */
1023       tmp = silc_argument_get_arg_type(args, 5, &tmp_len);
1024       if (!tmp || tmp_len < 2)
1025         goto out;
1026
1027       /* Parse the arguments to see they are constructed correctly */
1028       SILC_GET16_MSB(iargc, tmp);
1029       iargs = silc_argument_payload_parse(tmp + 2, tmp_len - 2, iargc);
1030       if (!iargs)
1031         goto out;
1032
1033       if (!channel->invite_list)
1034         channel->invite_list =
1035           silc_hash_table_alloc(0, silc_hash_ptr,
1036                                 NULL, NULL, NULL,
1037                                 silc_server_inviteban_destruct, channel, TRUE);
1038
1039       /* Proces the invite action */
1040       if (!silc_server_inviteban_process(server, channel->invite_list, action,
1041                                          iargs))
1042         goto out;
1043       silc_argument_payload_free(iargs);
1044
1045       /* If we are router we must send this notify to our local servers on
1046          the channel.  Normal server does nothing.  The notify is not
1047          sent to clients. */
1048       if (server->server_type == SILC_ROUTER)
1049         silc_server_packet_send_to_channel(server, sock, channel,
1050                                            packet->type, FALSE, FALSE,
1051                                            buffer->data,
1052                                            silc_buffer_len(buffer));
1053     }
1054
1055     break;
1056
1057   case SILC_NOTIFY_TYPE_CHANNEL_CHANGE:
1058     /*
1059      * Distribute to the local clients on the channel and change the
1060      * channel ID.
1061      */
1062
1063     SILC_LOG_DEBUG(("CHANNEL CHANGE"));
1064
1065     if (idata->conn_type != SILC_CONN_ROUTER)
1066       break;
1067
1068     /* Get the old Channel ID */
1069     if (!silc_argument_get_decoded(args, 1, SILC_ARGUMENT_ID, &id, NULL))
1070       goto out;
1071
1072     /* Get the channel entry */
1073     channel = silc_idlist_find_channel_by_id(server->local_list,
1074                                              SILC_ID_GET_ID(id), NULL);
1075     if (!channel) {
1076       channel = silc_idlist_find_channel_by_id(server->global_list,
1077                                                SILC_ID_GET_ID(id), NULL);
1078       if (!channel) {
1079         SILC_LOG_DEBUG(("Notify for unknown channel"));
1080         goto out;
1081       }
1082     }
1083
1084     /* Send the notify to the channel */
1085     silc_server_packet_send_to_channel(server, sock, channel, packet->type,
1086                                        FALSE, TRUE, buffer->data,
1087                                        silc_buffer_len(buffer));
1088
1089     /* Get the new Channel ID */
1090     if (!silc_argument_get_decoded(args, 2, SILC_ARGUMENT_ID, &id2, NULL))
1091       goto out;
1092
1093     SILC_LOG_DEBUG(("Old Channel ID id(%s)",
1094                     silc_id_render(SILC_ID_GET_ID(id), SILC_ID_CHANNEL)));
1095     SILC_LOG_DEBUG(("New Channel ID id(%s)",
1096                     silc_id_render(SILC_ID_GET_ID(id2), SILC_ID_CHANNEL)));
1097
1098     /* Replace the Channel ID */
1099     ret = TRUE;
1100     if (!silc_idlist_replace_channel_id(server->local_list,
1101                                         SILC_ID_GET_ID(id),
1102                                         SILC_ID_GET_ID(id2)))
1103       if (!silc_idlist_replace_channel_id(server->global_list,
1104                                           SILC_ID_GET_ID(id),
1105                                           SILC_ID_GET_ID(id2)))
1106         ret = FALSE;
1107
1108     if (ret) {
1109       SilcBuffer modes = NULL, users = NULL, users_modes = NULL;
1110
1111       /* Re-announce this channel which ID was changed. */
1112       silc_server_send_new_channel(server, sock, FALSE, channel->channel_name,
1113                                    channel->id,
1114                                    silc_id_get_len(channel->id,
1115                                                    SILC_ID_CHANNEL),
1116                                    channel->mode);
1117
1118       /* Re-announce our clients on the channel as the ID has changed now */
1119       silc_server_announce_get_channel_users(server, channel, &modes, &users,
1120                                              &users_modes);
1121       if (users) {
1122         silc_buffer_push(users, users->data - users->head);
1123         silc_server_packet_send(server, sock,
1124                                 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
1125                                 users->data, silc_buffer_len(users));
1126         silc_buffer_free(users);
1127       }
1128       if (modes) {
1129         silc_buffer_push(modes, modes->data - modes->head);
1130         silc_server_packet_send_dest(server, sock,
1131                                      SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
1132                                      channel->id, SILC_ID_CHANNEL,
1133                                      modes->data, silc_buffer_len(modes));
1134         silc_buffer_free(modes);
1135       }
1136       if (users_modes) {
1137         silc_buffer_push(users_modes, users_modes->data - users_modes->head);
1138         silc_server_packet_send_dest(server, sock,
1139                                      SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
1140                                      channel->id, SILC_ID_CHANNEL,
1141                                      users_modes->data,
1142                                      silc_buffer_len(users_modes));
1143         silc_buffer_free(users_modes);
1144       }
1145
1146       /* Re-announce channel's topic */
1147       if (channel->topic) {
1148         silc_server_send_notify_topic_set(server, sock,
1149                                           server->server_type == SILC_ROUTER ?
1150                                           TRUE : FALSE, channel,
1151                                           server->id, SILC_ID_SERVER,
1152                                           channel->topic);
1153       }
1154     }
1155
1156     break;
1157
1158   case SILC_NOTIFY_TYPE_SERVER_SIGNOFF:
1159     /*
1160      * Remove the server entry and all clients that this server owns.
1161      */
1162
1163     SILC_LOG_DEBUG(("SERVER SIGNOFF notify"));
1164
1165     /* Backup router shouldn't accept SERVER_SIGNOFF's from normal routers
1166        when the backup isn't acting as primary router. */
1167     if (idata->conn_type == SILC_CONN_SERVER &&
1168         server->backup_router && server->server_type == SILC_BACKUP_ROUTER)
1169       return;
1170
1171     /* Get Server ID */
1172     if (!silc_argument_get_decoded(args, 1, SILC_ARGUMENT_ID, &id, NULL))
1173       goto out;
1174
1175     /* If the ID is mine, this notify is not allowed. */
1176     if (SILC_ID_SERVER_COMPARE(SILC_ID_GET_ID(id), server->id)) {
1177       SILC_LOG_DEBUG(("Ignoring my own ID for SERVER_SIGNOFF"));
1178       break;
1179     }
1180
1181     /* Get server entry */
1182     server_entry = silc_idlist_find_server_by_id(server->global_list,
1183                                                  SILC_ID_GET_ID(id),
1184                                                  TRUE, NULL);
1185     local = FALSE;
1186     if (!server_entry) {
1187       server_entry = silc_idlist_find_server_by_id(server->local_list,
1188                                                    SILC_ID_GET_ID(id),
1189                                                    TRUE, NULL);
1190       local = TRUE;
1191       if (!server_entry) {
1192         /* If we are normal server then we might not have the server. Check
1193            whether router was kind enough to send the list of all clients
1194            that actually was to be removed. Remove them if the list is
1195            available. */
1196         if (server->server_type != SILC_ROUTER &&
1197             silc_argument_get_arg_num(args) > 1) {
1198           int i;
1199
1200           for (i = 1; i < silc_argument_get_arg_num(args); i++) {
1201             /* Get Client ID */
1202             if (!silc_argument_get_decoded(args, i + 1, SILC_ARGUMENT_ID,
1203                                            &id2, NULL))
1204               continue;
1205
1206             /* Get client entry */
1207             client = silc_idlist_find_client_by_id(server->global_list,
1208                                                    SILC_ID_GET_ID(id),
1209                                                    TRUE, &cache);
1210             local = FALSE;
1211             if (!client) {
1212               client = silc_idlist_find_client_by_id(server->local_list,
1213                                                      SILC_ID_GET_ID(id),
1214                                                      TRUE, &cache);
1215               local = TRUE;
1216               if (!client)
1217                 continue;
1218             }
1219
1220             /* Update statistics */
1221             server->stat.clients--;
1222             if (server->stat.cell_clients)
1223               server->stat.cell_clients--;
1224             SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
1225             SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
1226
1227             /* Remove the client from all channels. */
1228             silc_server_remove_from_channels(server, NULL, client,
1229                                              TRUE, NULL, FALSE, FALSE);
1230
1231             /* Check if anyone is watching this nickname */
1232             if (server->server_type == SILC_ROUTER)
1233               silc_server_check_watcher_list(server, client, NULL,
1234                                              SILC_NOTIFY_TYPE_SERVER_SIGNOFF);
1235
1236             /* Remove this client from watcher list if it is */
1237             if (local)
1238               silc_server_del_from_watcher_list(server, client);
1239
1240             /* Remove from public key hash table. */
1241             if (client->data.public_key)
1242               silc_hash_table_del_by_context(server->pk_hash,
1243                                              client->data.public_key,
1244                                              client);
1245
1246             /* Remove the client */
1247             silc_idlist_del_data(client);
1248             silc_idlist_del_client(local ? server->local_list :
1249                                    server->global_list, client);
1250           }
1251         }
1252
1253         goto out;
1254       }
1255     }
1256
1257     /* For local entrys SERVER_SIGNOFF is processed only on backup router.
1258        It is possible that router sends server signoff for a server.  If
1259        backup router has it as local connection it will be closed. */
1260     if (SILC_IS_LOCAL(server_entry)) {
1261       if (server->server_type == SILC_BACKUP_ROUTER) {
1262         sock = server_entry->connection;
1263         SILC_LOG_DEBUG(("Closing connection after SERVER_SIGNOFF"));
1264         silc_server_free_sock_user_data(server, sock, NULL);
1265         silc_server_close_connection(server, sock);
1266       }
1267
1268       break;
1269     }
1270
1271     /* Remove all servers that are originated from this server, and
1272        remove the clients of those servers too. */
1273     silc_server_remove_servers_by_server(server, server_entry, TRUE);
1274
1275     /* Remove the clients that this server owns as they will become
1276        invalid now too. */
1277     silc_server_remove_clients_by_server(server, server_entry->router,
1278                                          server_entry, TRUE);
1279     silc_server_backup_del(server, server_entry);
1280
1281     /* Remove the server entry */
1282     silc_idlist_del_server(local ? server->local_list :
1283                            server->global_list, server_entry);
1284
1285     /* Update statistics */
1286     if (server->server_type == SILC_ROUTER)
1287       server->stat.servers--;
1288
1289     break;
1290
1291   case SILC_NOTIFY_TYPE_KICKED:
1292     /*
1293      * Distribute the notify to local clients on the channel
1294      */
1295
1296     SILC_LOG_DEBUG(("KICKED notify"));
1297
1298     if (!silc_id_str2id(packet->dst_id, packet->dst_id_len,
1299                         packet->dst_id_type, &channel_id,
1300                         sizeof(channel_id)))
1301       goto out;
1302
1303     /* Get channel entry */
1304     channel = silc_idlist_find_channel_by_id(server->global_list,
1305                                              &channel_id, NULL);
1306     if (!channel) {
1307       channel = silc_idlist_find_channel_by_id(server->local_list,
1308                                                &channel_id, NULL);
1309       if (!channel) {
1310         SILC_LOG_DEBUG(("Notify for unknown channel"));
1311         goto out;
1312       }
1313     }
1314
1315     /* Get client ID */
1316     if (!silc_argument_get_decoded(args, 1, SILC_ARGUMENT_ID, &id, NULL))
1317       goto out;
1318
1319     /* If the the client is not in local list we check global list */
1320     client = silc_idlist_find_client_by_id(server->global_list,
1321                                            SILC_ID_GET_ID(id), TRUE, NULL);
1322     if (!client) {
1323       client = silc_idlist_find_client_by_id(server->local_list,
1324                                              SILC_ID_GET_ID(id), TRUE, NULL);
1325       if (!client)
1326         goto out;
1327     }
1328
1329     /* If target is founder they cannot be kicked */
1330     if (!silc_server_client_on_channel(client, channel, &chl))
1331       goto out;
1332     if (chl->mode & SILC_CHANNEL_UMODE_CHANFO)
1333       goto out;
1334
1335     /* Get the kicker's Client ID */
1336     if (!silc_argument_get_decoded(args, 3, SILC_ARGUMENT_ID, &id, NULL))
1337       goto out;
1338
1339     /* If the the client is not in local list we check global list */
1340     client2 = silc_idlist_find_client_by_id(server->global_list,
1341                                             SILC_ID_GET_ID(id), TRUE, NULL);
1342     if (!client2) {
1343       client2 = silc_idlist_find_client_by_id(server->local_list,
1344                                               SILC_ID_GET_ID(id), TRUE, NULL);
1345       if (!client2)
1346         goto out;
1347     }
1348
1349     /* Kicker must be operator on channel */
1350     if (!silc_server_client_on_channel(client2, channel, &chl))
1351       goto out;
1352     if (!(chl->mode & SILC_CHANNEL_UMODE_CHANOP) &&
1353         !(chl->mode & SILC_CHANNEL_UMODE_CHANFO)) {
1354       SILC_LOG_DEBUG(("Kicking is not allowed"));
1355       goto out;
1356     }
1357
1358     /* Send to channel */
1359     silc_server_packet_send_to_channel(server, sock, channel, packet->type,
1360                                        FALSE, TRUE, buffer->data,
1361                                        silc_buffer_len(buffer));
1362
1363     /* Remove the client from channel's invite list */
1364     if (channel->invite_list && silc_hash_table_count(channel->invite_list)) {
1365       SilcBuffer ab;
1366       SilcArgumentPayload iargs;
1367       tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
1368       ab = silc_argument_payload_encode_one(NULL, tmp, tmp_len, 3);
1369       iargs = silc_argument_payload_parse(ab->data, silc_buffer_len(ab), 1);
1370       silc_server_inviteban_process(server, channel->invite_list, 1, iargs);
1371       silc_buffer_free(ab);
1372       silc_argument_payload_free(iargs);
1373     }
1374
1375     /* Remove the client from channel */
1376     silc_server_remove_from_one_channel(server, sock, channel, client, FALSE);
1377
1378     break;
1379
1380   case SILC_NOTIFY_TYPE_KILLED:
1381     {
1382       /*
1383        * Distribute the notify to local clients on channels
1384        */
1385       unsigned char *comment;
1386       SilcUInt32 comment_len;
1387
1388       SILC_LOG_DEBUG(("KILLED notify"));
1389
1390       /* Get client ID */
1391       if (!silc_argument_get_decoded(args, 1, SILC_ARGUMENT_ID, &id, NULL))
1392         goto out;
1393
1394       /* If the the client is not in local list we check global list */
1395       client = silc_idlist_find_client_by_id(server->global_list,
1396                                              SILC_ID_GET_ID(id), TRUE, &cache);
1397       if (!client) {
1398         client = silc_idlist_find_client_by_id(server->local_list,
1399                                                SILC_ID_GET_ID(id),
1400                                                TRUE, &cache);
1401         if (!client)
1402           goto out;
1403       }
1404
1405       /* If the client is one of ours, then close the connection to the
1406          client now. This removes the client from all channels as well. */
1407       if (packet->dst_id_type == SILC_ID_CLIENT && client->connection) {
1408         sock = client->connection;
1409         silc_server_free_client_data(server, NULL, client, FALSE, NULL);
1410         silc_server_close_connection(server, sock);
1411         break;
1412       }
1413
1414       /* Get comment */
1415       comment = silc_argument_get_arg_type(args, 2, &comment_len);
1416       if (comment_len > 128)
1417         comment_len = 127;
1418
1419       /* Get the killer's Client ID */
1420       if (!silc_argument_get_decoded(args, 3, SILC_ARGUMENT_ID, &id, NULL))
1421         goto out;
1422
1423       if (id.type == SILC_ID_CLIENT) {
1424         /* If the the client is not in local list we check global list */
1425         client2 = silc_idlist_find_client_by_id(server->global_list,
1426                                                 SILC_ID_GET_ID(id),
1427                                                 TRUE, NULL);
1428         if (!client2) {
1429           client2 = silc_idlist_find_client_by_id(server->local_list,
1430                                                   SILC_ID_GET_ID(id),
1431                                                   TRUE, NULL);
1432           if (!client2)
1433             goto out;
1434         }
1435
1436         /* Killer must be router operator */
1437         if (server->server_type != SILC_SERVER &&
1438             !(client2->mode & SILC_UMODE_ROUTER_OPERATOR)) {
1439           SILC_LOG_DEBUG(("Killing is not allowed"));
1440           goto out;
1441         }
1442       }
1443
1444       /* Send the notify to local clients on the channels except to the
1445          client who is killed. */
1446       tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
1447       tmp2 = silc_argument_get_arg_type(args, 3, &tmp2_len);
1448       silc_server_send_notify_on_channels(server, client, client,
1449                                           SILC_NOTIFY_TYPE_KILLED, 3,
1450                                           tmp, tmp_len, comment, comment_len,
1451                                           tmp2, tmp2_len);
1452
1453       /* Remove the client from all channels */
1454       silc_server_remove_from_channels(server, NULL, client, FALSE, NULL,
1455                                        FALSE, TRUE);
1456
1457       /* Check if anyone is watching this nickname */
1458       if (server->server_type == SILC_ROUTER)
1459         silc_server_check_watcher_list(server, client, NULL,
1460                                        SILC_NOTIFY_TYPE_KILLED);
1461
1462       /* Remove from public key hash table. */
1463       if (client->data.public_key)
1464         silc_hash_table_del_by_context(server->pk_hash,
1465                                        client->data.public_key,
1466                                        client);
1467
1468       /* Update statistics */
1469       server->stat.clients--;
1470       if (server->stat.cell_clients)
1471         server->stat.cell_clients--;
1472       SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
1473       SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
1474
1475       if (SILC_IS_LOCAL(client)) {
1476         server->stat.my_clients--;
1477         silc_schedule_task_del_by_context(server->schedule, client);
1478         silc_idlist_del_data(client);
1479         client->mode = 0;
1480       }
1481
1482       client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
1483       client->mode = 0;
1484       client->router = NULL;
1485       client->connection = NULL;
1486       break;
1487     }
1488
1489   case SILC_NOTIFY_TYPE_UMODE_CHANGE:
1490     /*
1491      * Save the mode of the client.
1492      */
1493
1494     SILC_LOG_DEBUG(("UMODE_CHANGE notify"));
1495
1496     /* Get client ID */
1497     if (!silc_argument_get_decoded(args, 1, SILC_ARGUMENT_ID, &id, NULL))
1498       goto out;
1499
1500     /* Get client entry */
1501     client = silc_idlist_find_client_by_id(server->global_list,
1502                                            SILC_ID_GET_ID(id), TRUE, NULL);
1503     if (!client) {
1504       client = silc_idlist_find_client_by_id(server->local_list,
1505                                              SILC_ID_GET_ID(id), TRUE, NULL);
1506       if (!client)
1507         goto out;
1508     }
1509
1510     /* Get the mode */
1511     tmp = silc_argument_get_arg_type(args, 2, &tmp_len);
1512     if (!tmp)
1513       goto out;
1514     SILC_GET32_MSB(mode, tmp);
1515
1516     /* Remove internal resumed flag if client is marked detached now */
1517     if (mode & SILC_UMODE_DETACHED)
1518       client->data.status &= ~SILC_IDLIST_STATUS_RESUMED;
1519
1520     /* Update statistics */
1521     if (server->server_type == SILC_ROUTER) {
1522       if (mode & SILC_UMODE_GONE) {
1523         if (!(client->mode & SILC_UMODE_GONE))
1524           server->stat.aways++;
1525       } else {
1526         if (client->mode & SILC_UMODE_GONE)
1527           server->stat.aways--;
1528       }
1529       if (mode & SILC_UMODE_DETACHED) {
1530         if (!(client->mode & SILC_UMODE_DETACHED))
1531           server->stat.detached++;
1532       } else {
1533         if (client->mode & SILC_UMODE_DETACHED)
1534           server->stat.detached--;
1535       }
1536     }
1537     SILC_UMODE_STATS_UPDATE(server, SILC_UMODE_SERVER_OPERATOR);
1538     SILC_UMODE_STATS_UPDATE(router, SILC_UMODE_ROUTER_OPERATOR);
1539
1540     /* Change the mode */
1541     client->mode = mode;
1542
1543     /* Check if anyone is watching this nickname */
1544     if (server->server_type == SILC_ROUTER)
1545       silc_server_check_watcher_list(server, client, NULL,
1546                                      SILC_NOTIFY_TYPE_UMODE_CHANGE);
1547
1548     break;
1549
1550   case SILC_NOTIFY_TYPE_BAN:
1551     /*
1552      * Save the ban
1553      */
1554
1555     SILC_LOG_DEBUG(("BAN notify"));
1556
1557     /* Get Channel ID */
1558     if (!silc_argument_get_decoded(args, 1, SILC_ARGUMENT_ID, &id, NULL))
1559       goto out;
1560
1561     /* Get channel entry */
1562     channel = silc_idlist_find_channel_by_id(server->global_list,
1563                                              SILC_ID_GET_ID(id), NULL);
1564     if (!channel) {
1565       channel = silc_idlist_find_channel_by_id(server->local_list,
1566                                                SILC_ID_GET_ID(id), NULL);
1567       if (!channel) {
1568         SILC_LOG_DEBUG(("Notify for unknown channel"));
1569         goto out;
1570       }
1571     }
1572
1573     /* Get the ban action */
1574     tmp = silc_argument_get_arg_type(args, 2, &tmp_len);
1575     if (tmp && tmp_len == 1) {
1576       SilcUInt8 action = (SilcUInt8)tmp[0];
1577       SilcUInt16 iargc = 0;
1578       SilcArgumentPayload iargs;
1579
1580       /* Get ban list */
1581       tmp = silc_argument_get_arg_type(args, 3, &tmp_len);
1582       if (!tmp || tmp_len < 2)
1583         goto out;
1584
1585       /* Parse the arguments to see they are constructed correctly */
1586       SILC_GET16_MSB(iargc, tmp);
1587       iargs = silc_argument_payload_parse(tmp + 2, tmp_len - 2, iargc);
1588       if (!iargs)
1589         goto out;
1590
1591       if (!channel->ban_list)
1592         channel->ban_list =
1593           silc_hash_table_alloc(0, silc_hash_ptr,
1594                                 NULL, NULL, NULL,
1595                                 silc_server_inviteban_destruct, channel, TRUE);
1596
1597       /* Proces the ban action */
1598       if (!silc_server_inviteban_process(server, channel->ban_list, action,
1599                                          iargs))
1600         goto out;
1601       silc_argument_payload_free(iargs);
1602
1603       /* If we are router we must send this notify to our local servers on
1604          the channel.  Normal server does nothing.  The notify is not
1605          sent to clients. */
1606       if (server->server_type == SILC_ROUTER)
1607         silc_server_packet_send_to_channel(server, sock, channel,
1608                                            packet->type, FALSE, FALSE,
1609                                            buffer->data,
1610                                            silc_buffer_len(buffer));
1611     }
1612     break;
1613
1614   case SILC_NOTIFY_TYPE_ERROR:
1615     {
1616       /*
1617        * Error notify
1618        */
1619       SilcStatus error;
1620
1621       tmp = silc_argument_get_arg_type(args, 1, &tmp_len);
1622       if (!tmp && tmp_len != 1)
1623         goto out;
1624       error = (SilcStatus)tmp[0];
1625
1626       SILC_LOG_DEBUG(("ERROR notify (%d)", error));
1627
1628       if (error == SILC_STATUS_ERR_NO_SUCH_CLIENT_ID &&
1629           idata->conn_type == SILC_CONN_ROUTER) {
1630         if (!silc_argument_get_decoded(args, 2, SILC_ARGUMENT_ID, &id, NULL))
1631           goto out;
1632
1633         SILC_LOG_DEBUG(("Received invalid client ID notification, deleting "
1634                         "the entry from cache"));
1635
1636         client = silc_idlist_find_client_by_id(server->global_list,
1637                                                SILC_ID_GET_ID(id),
1638                                                FALSE, NULL);
1639         if (!client)
1640           goto out;
1641
1642         if (client->data.public_key)
1643           silc_hash_table_del_by_context(server->pk_hash,
1644                                          client->data.public_key,
1645                                          client);
1646
1647         silc_server_remove_from_channels(server, NULL, client, TRUE,
1648                                          NULL, TRUE, FALSE);
1649         silc_idlist_del_data(client);
1650         silc_idlist_del_client(server->global_list, client);
1651       }
1652     }
1653     break;
1654
1655     /* Ignore rest of the notify types for now */
1656   case SILC_NOTIFY_TYPE_NONE:
1657   case SILC_NOTIFY_TYPE_MOTD:
1658     break;
1659
1660   default:
1661     break;
1662   }
1663
1664  out:
1665   silc_notify_payload_free(payload);
1666 }
1667
1668 void silc_server_notify(SilcServer server,
1669                         SilcPacketStream sock,
1670                         SilcPacket packet)
1671 {
1672   silc_server_notify_process(server, sock, packet, &packet->buffer);
1673   silc_packet_free(packet);
1674 }
1675
1676 void silc_server_notify_list(SilcServer server,
1677                              SilcPacketStream sock,
1678                              SilcPacket packet)
1679 {
1680   SilcIDListData idata = silc_packet_get_context(sock);
1681   SilcUInt16 len;
1682   SilcBuffer buffer;
1683
1684   SILC_LOG_DEBUG(("Processing Notify List"));
1685
1686   if (idata->conn_type == SILC_CONN_CLIENT ||
1687       packet->src_id_type != SILC_ID_SERVER)
1688     return;
1689
1690   buffer = silc_buffer_alloc(1024);
1691   if (!buffer)
1692     return;
1693
1694   while (silc_buffer_len(&packet->buffer)) {
1695     SILC_GET16_MSB(len, packet->buffer.data + 2);
1696     if (len > silc_buffer_len(&packet->buffer))
1697       break;
1698
1699     if (len > silc_buffer_truelen(buffer)) {
1700       silc_buffer_free(buffer);
1701       buffer = silc_buffer_alloc(1024 + len);
1702     }
1703
1704     silc_buffer_pull_tail(buffer, len);
1705     silc_buffer_put(buffer, packet->buffer.data, len);
1706
1707     /* Process the Notify */
1708     silc_server_notify_process(server, sock, packet, buffer);
1709
1710     silc_buffer_push_tail(buffer, len);
1711     silc_buffer_pull(&packet->buffer, len);
1712   }
1713
1714   silc_packet_free(packet);
1715   silc_buffer_free(buffer);
1716 }
1717
1718 /* Received private message. This resolves the destination of the message
1719    and sends the packet. This is used by both server and router.  If the
1720    destination is our locally connected client this sends the packet to
1721    the client. This may also send the message for further routing if
1722    the destination is not in our server (or router). */
1723
1724 void silc_server_private_message(SilcServer server,
1725                                  SilcPacketStream sock,
1726                                  SilcPacket packet)
1727 {
1728   SilcPacketStream dst_sock;
1729   SilcIDListData idata;
1730   SilcClientEntry client;
1731   SilcClientID client_id;
1732
1733   SILC_LOG_DEBUG(("Start"));
1734
1735   if (packet->src_id_type != SILC_ID_CLIENT ||
1736       packet->dst_id_type != SILC_ID_CLIENT || !packet->dst_id)
1737     goto out;
1738
1739   /* Get the route to the client */
1740   dst_sock = silc_server_get_client_route(server, packet->dst_id,
1741                                           packet->dst_id_len, NULL,
1742                                           &idata, &client);
1743   if (!dst_sock) {
1744     SilcBuffer idp;
1745     unsigned char error;
1746
1747     if (client && client->mode & SILC_UMODE_DETACHED) {
1748       SILC_LOG_DEBUG(("Client is detached, discarding packet"));
1749       goto out;
1750     }
1751
1752     /* Send SILC_NOTIFY_TYPE_ERROR to indicate that such destination ID
1753        does not exist or is invalid. */
1754     idp = silc_id_payload_encode_data(packet->dst_id,
1755                                       packet->dst_id_len,
1756                                       packet->dst_id_type);
1757     if (!idp)
1758       goto out;
1759
1760     error = SILC_STATUS_ERR_NO_SUCH_CLIENT_ID;
1761     if (packet->src_id_type == SILC_ID_CLIENT) {
1762       silc_id_str2id(packet->src_id, packet->src_id_len,
1763                      packet->src_id_type, &client_id, sizeof(client_id));
1764       silc_server_send_notify_dest(server, sock, FALSE,
1765                                    &client_id, SILC_ID_CLIENT,
1766                                    SILC_NOTIFY_TYPE_ERROR, 2,
1767                                    &error, 1,
1768                                    idp->data, silc_buffer_len(idp));
1769     } else {
1770       silc_server_send_notify(server, sock, FALSE,
1771                               SILC_NOTIFY_TYPE_ERROR, 2,
1772                               &error, 1,
1773                               idp->data, silc_buffer_len(idp));
1774     }
1775
1776     silc_buffer_free(idp);
1777     goto out;
1778   }
1779
1780   /* Check whether destination client wishes to receive private messages */
1781   if (client && !(packet->flags & SILC_PACKET_FLAG_PRIVMSG_KEY) &&
1782       client->mode & SILC_UMODE_BLOCK_PRIVMSG) {
1783     SILC_LOG_DEBUG(("Client blocks private messages, discarding packet"));
1784     goto out;
1785   }
1786
1787   /* Send the private message */
1788   silc_server_packet_route(server, dst_sock, packet);
1789
1790  out:
1791   silc_packet_free(packet);
1792 }
1793
1794 /* Received private message key packet.. This packet is never for us. It is to
1795    the client in the packet's destination ID. Sending of this sort of packet
1796    equals sending private message, ie. it is sent point to point from
1797    one client to another. */
1798
1799 void silc_server_private_message_key(SilcServer server,
1800                                      SilcPacketStream sock,
1801                                      SilcPacket packet)
1802 {
1803   SilcPacketStream dst_sock;
1804   SilcIDListData idata;
1805
1806   SILC_LOG_DEBUG(("Start"));
1807
1808   if (packet->src_id_type != SILC_ID_CLIENT ||
1809       packet->dst_id_type != SILC_ID_CLIENT || !packet->dst_id) {
1810     silc_packet_free(packet);
1811     return;
1812   }
1813
1814   /* Get the route to the client */
1815   dst_sock = silc_server_get_client_route(server, packet->dst_id,
1816                                           packet->dst_id_len, NULL,
1817                                           &idata, NULL);
1818   if (!dst_sock) {
1819     silc_packet_free(packet);
1820     return;
1821   }
1822
1823   /* Relay the packet */
1824   silc_server_packet_route(server, dst_sock, packet);
1825
1826   silc_packet_free(packet);
1827 }
1828
1829 /* Processes incoming command reply packet. The command reply packet may
1830    be destined to one of our clients or it may directly for us. We will
1831    call the command reply routine after processing the packet. */
1832
1833 void silc_server_command_reply(SilcServer server,
1834                                SilcPacketStream sock,
1835                                SilcPacket packet)
1836 {
1837   SilcBuffer buffer = &packet->buffer;
1838   SilcClientEntry client = NULL;
1839   SilcClientID id;
1840
1841   SILC_LOG_DEBUG(("Start"));
1842
1843   if (packet->dst_id_type == SILC_ID_CHANNEL) {
1844     silc_packet_free(packet);
1845     return;
1846   }
1847
1848   if (packet->dst_id_type == SILC_ID_CLIENT) {
1849     /* Destination must be one of ours */
1850     if (!silc_id_str2id(packet->dst_id, packet->dst_id_len, SILC_ID_CLIENT,
1851                         &id, sizeof(id))) {
1852       silc_packet_free(packet);
1853       return;
1854     }
1855     client = silc_idlist_find_client_by_id(server->local_list, &id,
1856                                            TRUE, NULL);
1857     if (!client) {
1858       SILC_LOG_ERROR(("Cannot process command reply to unknown client"));
1859       silc_packet_free(packet);
1860       return;
1861     }
1862   }
1863
1864   if (packet->dst_id_type == SILC_ID_SERVER) {
1865     /* For now this must be for us */
1866     if (memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
1867       SILC_LOG_ERROR(("Cannot process command reply to unknown server"));
1868       silc_packet_free(packet);
1869       return;
1870     }
1871   }
1872
1873   /* Execute command reply locally for the command */
1874   silc_server_command_reply_process(server, sock, buffer);
1875
1876   /* Relay the packet to the client */
1877   if (packet->dst_id_type == SILC_ID_CLIENT && client)
1878     silc_server_packet_route(server, client->connection, packet);
1879
1880   silc_packet_free(packet);
1881 }
1882
1883 /* Process received channel message. The message can be originated from
1884    client or server. */
1885
1886 void silc_server_channel_message(SilcServer server,
1887                                  SilcPacketStream sock,
1888                                  SilcPacket packet)
1889 {
1890   SilcChannelEntry channel = NULL;
1891   SilcChannelID id;
1892   SilcClientID cid;
1893   SilcID sid;
1894   void *sender_id = NULL;
1895   SilcClientEntry sender_entry = NULL;
1896   SilcIDListData idata;
1897   SilcChannelClientEntry chl;
1898   SilcBool local = TRUE;
1899
1900   SILC_LOG_DEBUG(("Processing channel message"));
1901
1902   /* Sanity checks */
1903   if (packet->dst_id_type != SILC_ID_CHANNEL) {
1904     SILC_LOG_DEBUG(("Received bad message for channel, dropped"));
1905     goto out;
1906   }
1907
1908   /* Find channel entry */
1909   if (!silc_id_str2id(packet->dst_id, packet->dst_id_len, SILC_ID_CHANNEL,
1910                       &id, sizeof(id)))
1911     goto out;
1912   channel = silc_idlist_find_channel_by_id(server->local_list, &id, NULL);
1913   if (!channel) {
1914     channel = silc_idlist_find_channel_by_id(server->global_list, &id, NULL);
1915     if (!channel) {
1916       SilcBuffer idp;
1917       unsigned char error;
1918
1919       /* Send SILC_NOTIFY_TYPE_ERROR to indicate that such destination ID
1920          does not exist or is invalid. */
1921       idp = silc_id_payload_encode_data(packet->dst_id,
1922                                         packet->dst_id_len,
1923                                         packet->dst_id_type);
1924       if (!idp)
1925         goto out;
1926
1927       error = SILC_STATUS_ERR_NO_SUCH_CHANNEL_ID;
1928       if (packet->src_id_type == SILC_ID_CLIENT) {
1929         silc_id_str2id(packet->src_id, packet->src_id_len,
1930                        packet->src_id_type, &cid, sizeof(cid));
1931         silc_server_send_notify_dest(server, sock, FALSE,
1932                                      &cid, SILC_ID_CLIENT,
1933                                      SILC_NOTIFY_TYPE_ERROR, 2,
1934                                      &error, 1, idp->data,
1935                                      silc_buffer_len(idp));
1936       } else {
1937         silc_server_send_notify(server, sock, FALSE,
1938                                 SILC_NOTIFY_TYPE_ERROR, 2,
1939                                 &error, 1, idp->data, silc_buffer_len(idp));
1940       }
1941
1942       silc_buffer_free(idp);
1943       goto out;
1944     }
1945   }
1946
1947   /* See that this client is on the channel. If the original sender is
1948      not client (as it can be server as well) we don't do the check. */
1949   if (!silc_id_str2id2(packet->src_id, packet->src_id_len,
1950                        packet->src_id_type, &sid))
1951     goto out;
1952   if (sid.type == SILC_ID_CLIENT) {
1953     sender_entry = silc_idlist_find_client_by_id(server->local_list,
1954                                                  SILC_ID_GET_ID(sid),
1955                                                  TRUE, NULL);
1956     if (!sender_entry) {
1957       local = FALSE;
1958       sender_entry = silc_idlist_find_client_by_id(server->global_list,
1959                                                    SILC_ID_GET_ID(sid),
1960                                                    TRUE, NULL);
1961     }
1962     if (!sender_entry || !silc_server_client_on_channel(sender_entry,
1963                                                         channel, &chl)) {
1964       SILC_LOG_DEBUG(("Client not on channel"));
1965       goto out;
1966     }
1967
1968     /* If channel is moderated check that client is allowed to send
1969        messages. */
1970     if (channel->mode & SILC_CHANNEL_MODE_SILENCE_USERS &&
1971         !(chl->mode & SILC_CHANNEL_UMODE_CHANOP) &&
1972         !(chl->mode & SILC_CHANNEL_UMODE_CHANFO)) {
1973       SILC_LOG_DEBUG(("Channel is silenced from normal users"));
1974       goto out;
1975     }
1976     if (channel->mode & SILC_CHANNEL_MODE_SILENCE_OPERS &&
1977         chl->mode & SILC_CHANNEL_UMODE_CHANOP &&
1978         !(chl->mode & SILC_CHANNEL_UMODE_CHANFO)) {
1979       SILC_LOG_DEBUG(("Channel is silenced from operators"));
1980       goto out;
1981     }
1982     if (chl->mode & SILC_CHANNEL_UMODE_QUIET) {
1983       SILC_LOG_DEBUG(("Sender is quieted on the channel"));
1984       goto out;
1985     }
1986
1987     /* If the packet is coming from router, but the client entry is local
1988        entry to us then some router is rerouting this to us and it is not
1989        allowed. When the client is local to us it means that we've routed
1990        this packet to network, and now someone is routing it back to us. */
1991     idata = silc_packet_get_context(sock);
1992     if (server->server_type == SILC_ROUTER &&
1993         idata->conn_type == SILC_CONN_ROUTER && local) {
1994       SILC_LOG_DEBUG(("Channel message rerouted to the sender, drop it"));
1995       goto out;
1996     }
1997   }
1998
1999   /* Distribute the packet to our local clients. This will send the
2000      packet for further routing as well, if needed. */
2001   silc_server_packet_relay_to_channel(server, sock, channel, sender_id,
2002                                       packet->src_id_type, sender_entry,
2003                                       packet->buffer.data,
2004                                       silc_buffer_len(&packet->buffer));
2005
2006  out:
2007   silc_packet_free(packet);
2008 }
2009
2010 /* Received channel key packet. We distribute the key to all of our locally
2011    connected clients on the channel. */
2012
2013 void silc_server_channel_key(SilcServer server,
2014                              SilcPacketStream sock,
2015                              SilcPacket packet)
2016 {
2017   SilcBuffer buffer = &packet->buffer;
2018   SilcIDListData idata = silc_packet_get_context(sock);
2019   SilcChannelEntry channel;
2020
2021   if (packet->src_id_type != SILC_ID_SERVER ||
2022       (server->server_type == SILC_ROUTER && !server->backup_router &&
2023        idata->conn_type == SILC_CONN_ROUTER)) {
2024     silc_packet_free(packet);
2025     return;
2026   }
2027
2028   /* Save the channel key */
2029   channel = silc_server_save_channel_key(server, buffer, NULL);
2030   if (!channel) {
2031     SILC_LOG_ERROR(("Bad channel key from %s", idata->sconn->remote_host));
2032     silc_packet_free(packet);
2033     return;
2034   }
2035
2036   /* Distribute the key to everybody who is on the channel. If we are router
2037      we will also send it to locally connected servers. */
2038   silc_server_send_channel_key(server, sock, channel, FALSE);
2039
2040   if (server->server_type != SILC_BACKUP_ROUTER)
2041     /* Distribute to local cell backup routers. */
2042     silc_server_backup_send(server, (SilcServerEntry)idata,
2043                             SILC_PACKET_CHANNEL_KEY, 0,
2044                             buffer->data, silc_buffer_len(buffer),
2045                             FALSE, TRUE);
2046
2047   silc_packet_free(packet);
2048 }
2049
2050 /* Received New Client packet and processes it.  Creates Client ID for the
2051    client. Client becomes registered after calling this functions. */
2052
2053 SilcClientEntry silc_server_new_client(SilcServer server,
2054                                        SilcPacketStream sock,
2055                                        SilcPacket packet)
2056 {
2057   SilcBuffer buffer = &packet->buffer;
2058   SilcIDListData idata = silc_packet_get_context(sock);
2059   SilcClientEntry client;
2060   SilcClientID *client_id;
2061   char *username = NULL, *realname = NULL;
2062   SilcUInt16 username_len, nickname_len;
2063   SilcUInt32 id_len, tmp_len;
2064   int ret;
2065   char *host, *nickname = NULL, *nicknamec;
2066   const char *hostname, *ip;
2067
2068   SILC_LOG_DEBUG(("Creating new client"));
2069
2070   if (idata->conn_type != SILC_CONN_CLIENT) {
2071     silc_packet_free(packet);
2072     return NULL;
2073   }
2074
2075   /* Take client entry */
2076   client = (SilcClientEntry)idata;
2077   silc_socket_stream_get_info(silc_packet_stream_get_stream(sock),
2078                               NULL, &hostname, &ip, NULL);
2079
2080   SILC_LOG_DEBUG(("%s %s", ip, hostname));
2081
2082   /* Make sure this client hasn't registered already */
2083   if (idata->status & SILC_IDLIST_STATUS_REGISTERED) {
2084     silc_packet_free(packet);
2085     return NULL;
2086   }
2087
2088   /* Parse incoming packet */
2089   ret = silc_buffer_unformat(buffer,
2090                              SILC_STR_ADVANCE,
2091                              SILC_STR_UI16_NSTRING_ALLOC(&username,
2092                                                          &username_len),
2093                              SILC_STR_UI16_STRING_ALLOC(&realname),
2094                              SILC_STR_END);
2095   if (ret == -1) {
2096     silc_free(username);
2097     silc_free(realname);
2098     SILC_LOG_ERROR(("Client %s (%s) sent incomplete information, closing "
2099                     "connection", hostname, ip));
2100     silc_server_disconnect_remote(server, sock,
2101                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2102                                   NULL);
2103     silc_server_free_sock_user_data(server, sock, NULL);
2104     silc_packet_free(packet);
2105     return NULL;
2106   }
2107
2108   if (!username) {
2109     silc_free(username);
2110     silc_free(realname);
2111     SILC_LOG_ERROR(("Client %s (%s) did not send its username, closing "
2112                     "connection", hostname, ip));
2113     silc_server_disconnect_remote(server, sock,
2114                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2115                                   NULL);
2116     silc_server_free_sock_user_data(server, sock, NULL);
2117     silc_packet_free(packet);
2118     return NULL;
2119   }
2120
2121   if (username_len > 128) {
2122     username_len = 128;
2123     username[username_len - 1] = '\0';
2124   }
2125
2126   /* Check for valid username string */
2127   nicknamec = silc_identifier_check(username, username_len,
2128                                     SILC_STRING_UTF8, 128, &tmp_len);
2129   if (!nicknamec) {
2130     silc_free(username);
2131     silc_free(realname);
2132     SILC_LOG_ERROR(("Client %s (%s) sent bad username string '%s', closing "
2133                     "connection", hostname, ip, username));
2134     silc_server_disconnect_remote(server, sock,
2135                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2136                                   NULL);
2137     silc_server_free_sock_user_data(server, sock, NULL);
2138     silc_packet_free(packet);
2139     return NULL;
2140   }
2141
2142   /* Take nickname from NEW_CLIENT packet, if present */
2143   if (silc_buffer_unformat(buffer,
2144                            SILC_STR_UI16_NSTRING_ALLOC(&nickname,
2145                                                        &nickname_len),
2146                            SILC_STR_END)) {
2147     if (nickname_len > 128) {
2148       nickname_len = 128;
2149       nickname[nickname_len - 1] = '\0';
2150     }
2151   }
2152
2153   /* Nickname is initially same as username, if not present in NEW_CLIENT */
2154   if (!nickname)
2155     nickname = strdup(username);
2156
2157   /* Make sanity checks for the hostname of the client. If the hostname
2158      is provided in the `username' check that it is the same than the
2159      resolved hostname, or if not resolved the hostname that appears in
2160      the client's public key. If the hostname is not present then put
2161      it from the resolved name or from the public key. */
2162   if (strchr(username, '@')) {
2163     SilcSILCPublicKey silc_pubkey;
2164     int tlen = strcspn(username, "@");
2165     char *phostname = NULL;
2166
2167     host = silc_memdup(username + tlen + 1, strlen(username) - tlen - 1);
2168
2169     if (strcmp(hostname, ip) && strcmp(hostname, host)) {
2170       silc_free(username);
2171       silc_free(host);
2172       silc_free(realname);
2173       SILC_LOG_ERROR(("Client %s (%s) sent incomplete information, closing "
2174                       "connection", hostname, ip));
2175       silc_server_disconnect_remote(server, sock,
2176                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2177                                     NULL);
2178       silc_server_free_sock_user_data(server, sock, NULL);
2179       silc_packet_free(packet);
2180       return NULL;
2181     }
2182
2183     silc_pubkey = silc_pkcs_get_context(SILC_PKCS_SILC,
2184                                         client->data.public_key);
2185     phostname = strdup(silc_pubkey->identifier.host);
2186     if (!strcmp(hostname, ip) && phostname && strcmp(phostname, host)) {
2187       silc_free(username);
2188       silc_free(host);
2189       silc_free(phostname);
2190       silc_free(realname);
2191       SILC_LOG_ERROR(("Client %s (%s) sent incomplete information, closing "
2192                       "connection", hostname, ip));
2193       silc_server_disconnect_remote(server, sock,
2194                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2195                                     NULL);
2196       silc_server_free_sock_user_data(server, sock, NULL);
2197       silc_packet_free(packet);
2198       return NULL;
2199     }
2200
2201     silc_free(phostname);
2202   } else {
2203     /* The hostname is not present, add it. */
2204     char *newusername;
2205     newusername = silc_calloc(strlen(username) + strlen(hostname) + 2,
2206                               sizeof(*newusername));
2207     strncat(newusername, username, strlen(username));
2208     strncat(newusername, "@", 1);
2209     strncat(newusername, hostname, strlen(hostname));
2210     silc_free(username);
2211     username = newusername;
2212   }
2213
2214   SILC_LOG_DEBUG(("%s %s", ip, hostname));
2215
2216   /* Create Client ID */
2217   if (!silc_id_create_client_id(server, server->id, server->rng,
2218                                 server->md5hash, nicknamec,
2219                                 strlen(nicknamec), &client_id)) {
2220     silc_server_disconnect_remote(server, sock,
2221                                   SILC_STATUS_ERR_BAD_NICKNAME, NULL);
2222     silc_server_free_sock_user_data(server, sock, NULL);
2223     silc_packet_free(packet);
2224     return NULL;
2225   }
2226
2227   /* If client marked as anonymous, scramble the username and hostname */
2228   if (client->mode & SILC_UMODE_ANONYMOUS) {
2229     char *scramble;
2230
2231     if (strlen(username) >= 2) {
2232       username[0] = silc_rng_get_byte_fast(server->rng);
2233       username[1] = silc_rng_get_byte_fast(server->rng);
2234     }
2235
2236     scramble = silc_hash_babbleprint(server->sha1hash, username,
2237                                      strlen(username));
2238     scramble[5] = '@';
2239     scramble[11] = '.';
2240     memcpy(&scramble[16], ".silc", 5);
2241     scramble[21] = '\0';
2242     silc_free(username);
2243     username = scramble;
2244   }
2245
2246   /* Update client entry */
2247   idata->status |= SILC_IDLIST_STATUS_REGISTERED;
2248   client->nickname = nickname;
2249   client->username = username;
2250   client->userinfo = realname ? realname : strdup(username);
2251   client->id = client_id;
2252   id_len = silc_id_get_len(client_id, SILC_ID_CLIENT);
2253   silc_idcache_update_by_context(server->local_list->clients, client,
2254                                  client_id, nicknamec, TRUE);
2255
2256   /* Notify our router about new client on the SILC network */
2257   silc_server_send_new_id(server, SILC_PRIMARY_ROUTE(server),
2258                           SILC_BROADCAST(server), client->id,
2259                           SILC_ID_CLIENT, id_len);
2260
2261   /* Distribute to backup routers */
2262   if (server->server_type == SILC_ROUTER) {
2263     SilcBuffer idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2264     silc_server_backup_send(server, NULL, SILC_PACKET_NEW_ID, 0,
2265                             idp->data, silc_buffer_len(idp), FALSE, TRUE);
2266     silc_buffer_free(idp);
2267   }
2268
2269   /* Send the new client ID to the client. */
2270   silc_server_send_new_id(server, sock, FALSE, client->id, SILC_ID_CLIENT,
2271                           silc_id_get_len(client->id, SILC_ID_CLIENT));
2272
2273   /* Send some nice info to the client */
2274   silc_server_send_connect_notifys(server, sock, client);
2275
2276   /* Check if anyone is watching this nickname */
2277   if (server->server_type == SILC_ROUTER)
2278     silc_server_check_watcher_list(server, client, NULL, 0);
2279
2280   silc_packet_free(packet);
2281   return client;
2282 }
2283
2284 /* Create new server. This processes received New Server packet and
2285    saves the received Server ID. The server is our locally connected
2286    server thus we save all the information and save it to local list.
2287    This funtion can be used by both normal server and router server.
2288    If normal server uses this it means that its router has connected
2289    to the server. If router uses this it means that one of the cell's
2290    servers is connected to the router. */
2291
2292 SilcServerEntry silc_server_new_server(SilcServer server,
2293                                        SilcPacketStream sock,
2294                                        SilcPacket packet)
2295 {
2296   SilcBuffer buffer = &packet->buffer;
2297   SilcIDListData idata = silc_packet_get_context(sock);
2298   SilcServerEntry new_server, server_entry;
2299   SilcServerID server_id;
2300   unsigned char *server_name, *server_namec, *id_string;
2301   SilcUInt16 id_len, name_len;
2302   int ret;
2303   SilcBool local = TRUE;
2304   const char *hostname, *ip;
2305
2306   SILC_LOG_DEBUG(("Creating new server"));
2307
2308   if (idata->conn_type != SILC_CONN_SERVER &&
2309       idata->conn_type != SILC_CONN_ROUTER) {
2310     silc_packet_free(packet);
2311     return NULL;
2312   }
2313
2314   /* Take server entry */
2315   new_server = (SilcServerEntry)idata;
2316   silc_socket_stream_get_info(silc_packet_stream_get_stream(sock),
2317                               NULL, &hostname, &ip, NULL);
2318
2319   /* Statistics */
2320   if (server->server_type == SILC_ROUTER)
2321     server->stat.cell_servers++;
2322
2323   /* Remove the old cache entry */
2324   if (!silc_idcache_del_by_context(server->local_list->servers, new_server,
2325                                    NULL)) {
2326     if (!silc_idcache_del_by_context(server->global_list->servers,
2327                                      new_server, NULL)) {
2328       SILC_LOG_INFO(("Unauthenticated %s attempted to register to "
2329                      "network", (idata->conn_type == SILC_CONN_SERVER ?
2330                                  "server" : "router")));
2331       silc_server_disconnect_remote(server, sock,
2332                                     SILC_STATUS_ERR_NOT_AUTHENTICATED, NULL);
2333       silc_server_free_sock_user_data(server, sock, NULL);
2334       return NULL;
2335     }
2336     local = FALSE;
2337   }
2338
2339   /* Make sure this server hasn't registered already */
2340   if (idata->status & SILC_IDLIST_STATUS_REGISTERED) {
2341     silc_server_disconnect_remote(server, sock,
2342                                   SILC_STATUS_ERR_OPERATION_ALLOWED,
2343                                   "Too many registrations");
2344     silc_server_free_sock_user_data(server, sock, NULL);
2345     return NULL;
2346   }
2347
2348   /* Parse the incoming packet */
2349   ret = silc_buffer_unformat(buffer,
2350                              SILC_STR_UI16_NSTRING_ALLOC(&id_string, &id_len),
2351                              SILC_STR_UI16_NSTRING_ALLOC(&server_name,
2352                                                          &name_len),
2353                              SILC_STR_END);
2354   if (ret == -1) {
2355     silc_free(id_string);
2356     silc_free(server_name);
2357     silc_server_disconnect_remote(server, sock,
2358                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2359                                   NULL);
2360     silc_server_free_sock_user_data(server, sock, NULL);
2361     return NULL;
2362   }
2363
2364   if (id_len > silc_buffer_len(buffer)) {
2365     silc_free(id_string);
2366     silc_free(server_name);
2367     silc_server_disconnect_remote(server, sock,
2368                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2369                                   NULL);
2370     silc_server_free_sock_user_data(server, sock, NULL);
2371     return NULL;
2372   }
2373
2374   if (name_len > 256) {
2375     server_name[256] = '\0';
2376     name_len = 256;
2377   }
2378
2379   /* Get Server ID */
2380   if (!silc_id_str2id(id_string, id_len, SILC_ID_SERVER, &server_id,
2381                       sizeof(server_id))) {
2382     silc_free(id_string);
2383     silc_free(server_name);
2384     silc_server_disconnect_remote(server, sock,
2385                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2386                                   NULL);
2387     silc_server_free_sock_user_data(server, sock, NULL);
2388     return NULL;
2389   }
2390   silc_free(id_string);
2391
2392   /* Check for valid server ID */
2393   if (!silc_id_is_valid_server_id(server, &server_id, sock)) {
2394     SILC_LOG_INFO(("Invalid server ID sent by %s (%s)",
2395                    ip, hostname));
2396     silc_server_disconnect_remote(server, sock,
2397                                   SILC_STATUS_ERR_BAD_SERVER_ID, NULL);
2398     silc_server_free_sock_user_data(server, sock, NULL);
2399     silc_free(server_name);
2400     return NULL;
2401   }
2402
2403   /* Check that we do not have this ID already */
2404   server_entry = silc_idlist_find_server_by_id(server->local_list,
2405                                                &server_id, TRUE, NULL);
2406   if (server_entry) {
2407     if (SILC_IS_LOCAL(server_entry)) {
2408       SILC_LOG_ERROR(("Too many registrations from %s (%s)",
2409                       ip, hostname));
2410       silc_server_disconnect_remote(server, sock,
2411                                     SILC_STATUS_ERR_OPERATION_ALLOWED,
2412                                     "Too many registrations");
2413       silc_server_free_sock_user_data(server, sock, NULL);
2414       return NULL;
2415     } else {
2416       silc_idcache_del_by_context(server->local_list->servers, server_entry,
2417                                   NULL);
2418     }
2419   } else {
2420     server_entry = silc_idlist_find_server_by_id(server->global_list,
2421                                                  &server_id, TRUE, NULL);
2422     if (server_entry) {
2423       if (SILC_IS_LOCAL(server_entry)) {
2424         SILC_LOG_ERROR(("Too many registrations from %s (%s)",
2425                         ip, hostname));
2426         silc_server_disconnect_remote(server, sock,
2427                                       SILC_STATUS_ERR_OPERATION_ALLOWED,
2428                                       "Too many registrations");
2429         silc_server_free_sock_user_data(server, sock, NULL);
2430         return NULL;
2431       } else {
2432         silc_idcache_del_by_context(server->global_list->servers,
2433                                     server_entry, NULL);
2434       }
2435     }
2436   }
2437
2438   /* Check server name */
2439   server_namec = silc_identifier_check(server_name, strlen(server_name),
2440                                        SILC_STRING_UTF8, 256, NULL);
2441   if (!server_namec) {
2442     SILC_LOG_ERROR(("Malformed server name from %s (%s)",
2443                     ip, hostname));
2444     silc_server_disconnect_remote(server, sock,
2445                                   SILC_STATUS_ERR_OPERATION_ALLOWED,
2446                                   "Malfromed server name");
2447     silc_server_free_sock_user_data(server, sock, NULL);
2448     return NULL;
2449   }
2450
2451   /* Update server entry */
2452   idata->status |= SILC_IDLIST_STATUS_REGISTERED;
2453   new_server->server_name = server_name;
2454   new_server->id = silc_id_dup(&server_id, SILC_ID_SERVER);
2455
2456   SILC_LOG_DEBUG(("New server id(%s)",
2457                   silc_id_render(&server_id, SILC_ID_SERVER)));
2458
2459   /* Add again the entry to the ID cache. */
2460   silc_idcache_add(local ? server->local_list->servers :
2461                    server->global_list->servers, server_namec,
2462                    new_server->id, new_server);
2463
2464   /* Distribute the information about new server in the SILC network
2465      to our router. If we are normal server we won't send anything
2466      since this connection must be our router connection. */
2467   if (server->server_type == SILC_ROUTER && !server->standalone &&
2468       SILC_PRIMARY_ROUTE(server) != sock)
2469     silc_server_send_new_id(server, SILC_PRIMARY_ROUTE(server),
2470                             TRUE, new_server->id, SILC_ID_SERVER,
2471                             silc_id_get_len(&server_id, SILC_ID_SERVER));
2472
2473   if (server->server_type == SILC_ROUTER) {
2474     /* Distribute to backup routers */
2475     SilcBuffer idp = silc_id_payload_encode(new_server->id, SILC_ID_SERVER);
2476     silc_server_backup_send(server, NULL, SILC_PACKET_NEW_ID, 0, idp->data,
2477                             silc_buffer_len(idp), FALSE, TRUE);
2478     silc_buffer_free(idp);
2479   }
2480
2481   /* Check whether this router connection has been replaced by an
2482      backup router. If it has been then we'll disable the server and will
2483      ignore everything it will send until the backup router resuming
2484      protocol has been completed. */
2485   if (idata->conn_type == SILC_CONN_ROUTER &&
2486       silc_server_backup_replaced_get(server, &server_id, NULL)) {
2487     /* Send packet to the router indicating that it cannot use this
2488        connection as it has been replaced by backup router. */
2489     SILC_LOG_DEBUG(("Remote router has been replaced by backup router, "
2490                     "disabling its connection"));
2491
2492     silc_server_backup_send_replaced(server, sock);
2493
2494     /* Mark the router disabled. The data sent earlier will go but nothing
2495        after this goes to this connection. */
2496     idata->status |= SILC_IDLIST_STATUS_DISABLED;
2497   } else {
2498     /* If it is router announce our stuff to it. */
2499     if (idata->conn_type == SILC_CONN_ROUTER &&
2500         server->server_type == SILC_ROUTER) {
2501       silc_server_announce_servers(server, FALSE, 0, sock);
2502       silc_server_announce_clients(server, 0, sock);
2503       silc_server_announce_channels(server, 0, sock);
2504     }
2505
2506     /* Announce our information to backup router */
2507     if (new_server->server_type == SILC_BACKUP_ROUTER &&
2508         idata->conn_type == SILC_CONN_SERVER &&
2509         server->server_type == SILC_ROUTER) {
2510       silc_server_announce_servers(server, TRUE, 0, sock);
2511       silc_server_announce_clients(server, 0, sock);
2512       silc_server_announce_channels(server, 0, sock);
2513     }
2514
2515     /* If backup router, mark it as one of ours.  This server is considered
2516        to be backup router after this setting. */
2517     if (new_server->server_type == SILC_BACKUP_ROUTER) {
2518       SilcServerConfigRouter *backup;
2519       backup = silc_server_config_find_backup_conn(server, (char *)ip);
2520       if (!backup)
2521         backup = silc_server_config_find_backup_conn(server, (char *)hostname);
2522       if (backup) {
2523         /* Add as our backup router */
2524         silc_server_backup_add(server, new_server, backup->backup_replace_ip,
2525                                backup->backup_replace_port,
2526                                backup->backup_local);
2527       }
2528     }
2529
2530     /* By default the servers connected to backup router are disabled
2531        until backup router has become the primary */
2532     if (server->server_type == SILC_BACKUP_ROUTER &&
2533         idata->conn_type == SILC_CONN_SERVER)
2534       idata->status |= SILC_IDLIST_STATUS_DISABLED;
2535   }
2536
2537   return new_server;
2538 }
2539
2540 /* Processes incoming New ID packet. New ID Payload is used to distribute
2541    information about newly registered clients and servers. */
2542
2543 static void silc_server_new_id_real(SilcServer server,
2544                                     SilcPacketStream sock,
2545                                     SilcPacket packet,
2546                                     SilcBuffer buffer,
2547                                     SilcBool broadcast)
2548 {
2549   SilcIDListData idata = silc_packet_get_context(sock);
2550   SilcIDList id_list;
2551   SilcServerEntry router, server_entry;
2552   SilcPacketStream router_sock;
2553   SilcIDPayload idp;
2554   SilcIdType id_type;
2555   SilcServerID sender_id;
2556   const char *hostname, *ip;
2557
2558   SILC_LOG_DEBUG(("Processing new ID"));
2559
2560   if (idata->conn_type == SILC_CONN_CLIENT ||
2561       server->server_type == SILC_SERVER ||
2562       packet->src_id_type != SILC_ID_SERVER)
2563     return;
2564
2565   idp = silc_id_payload_parse(buffer->data, silc_buffer_len(buffer));
2566   if (!idp)
2567     return;
2568
2569   id_type = silc_id_payload_get_type(idp);
2570
2571   silc_socket_stream_get_info(silc_packet_stream_get_stream(sock),
2572                               NULL, &hostname, &ip, NULL);
2573
2574   /* Normal server cannot have other normal server connections */
2575   server_entry = (SilcServerEntry)idata;
2576   if (id_type == SILC_ID_SERVER && idata->conn_type == SILC_CONN_SERVER &&
2577       server_entry->server_type == SILC_SERVER)
2578     goto out;
2579
2580   /* If the packet is coming from server then use the sender as the
2581      origin of the the packet. If it came from router then check the real
2582      sender of the packet and use that as the origin. */
2583   if (idata->conn_type == SILC_CONN_SERVER) {
2584     id_list = server->local_list;
2585     router_sock = sock;
2586     router = server_entry;
2587
2588     /* If the sender is backup router and ID is server (and we are not
2589        backup router) then switch the entry to global list. */
2590     if (server_entry->server_type == SILC_BACKUP_ROUTER &&
2591         id_type == SILC_ID_SERVER &&
2592         server->id_entry->server_type != SILC_BACKUP_ROUTER) {
2593       id_list = server->global_list;
2594       router_sock = server->router ? SILC_PRIMARY_ROUTE(server) : sock;
2595     }
2596   } else {
2597     silc_id_str2id(packet->src_id, packet->src_id_len,
2598                    packet->src_id_type, &sender_id, sizeof(sender_id));
2599     router = silc_idlist_find_server_by_id(server->global_list,
2600                                            &sender_id, TRUE, NULL);
2601     if (!router)
2602       router = silc_idlist_find_server_by_id(server->local_list,
2603                                              &sender_id, TRUE, NULL);
2604     router_sock = sock;
2605     id_list = server->global_list;
2606   }
2607
2608   if (!router)
2609     goto out;
2610
2611   switch(id_type) {
2612   case SILC_ID_CLIENT:
2613     {
2614       SilcClientEntry entry;
2615       SilcClientID id;
2616
2617       if (!silc_id_payload_get_id(idp, &id, sizeof(id)))
2618         goto out;
2619
2620       /* Check that we do not have this client already */
2621       entry = silc_idlist_find_client_by_id(server->global_list,
2622                                             &id, server->server_type,
2623                                             NULL);
2624       if (!entry)
2625         entry = silc_idlist_find_client_by_id(server->local_list,
2626                                               &id, server->server_type,
2627                                               NULL);
2628       if (entry) {
2629         SILC_LOG_DEBUG(("Ignoring client that we already have"));
2630         goto out;
2631       }
2632
2633       SILC_LOG_DEBUG(("New client id(%s) from [%s] %s",
2634                       silc_id_render(&id, SILC_ID_CLIENT),
2635                       idata->conn_type == SILC_CONN_SERVER ?
2636                       "Server" : "Router", hostname));
2637
2638       /* As a router we keep information of all global information in our
2639          global list. Cell wide information however is kept in the local
2640          list. */
2641       entry = silc_idlist_add_client(id_list, NULL, NULL, NULL,
2642                                      &id, router, NULL);
2643       if (!entry) {
2644         SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
2645
2646         /* Inform the sender that the ID is not usable */
2647         silc_server_send_notify_signoff(server, sock, FALSE, &id, NULL);
2648         goto out;
2649       }
2650       entry->nickname = NULL;
2651       entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
2652
2653       if (idata->conn_type == SILC_CONN_SERVER)
2654         server->stat.cell_clients++;
2655       server->stat.clients++;
2656
2657       /* Check if anyone is watching this nickname */
2658       if (server->server_type == SILC_ROUTER && id_list == server->local_list)
2659         silc_server_check_watcher_list(server, entry, NULL, 0);
2660
2661       if (server->server_type == SILC_ROUTER) {
2662         /* Add the client's public key to hash table or get the key with
2663            GETKEY command. */
2664         if (entry->data.public_key) {
2665           if (!silc_hash_table_find_by_context(server->pk_hash,
2666                                                entry->data.public_key,
2667                                                entry, NULL))
2668             silc_hash_table_add(server->pk_hash, entry->data.public_key,
2669                                 entry);
2670         } else
2671           silc_server_send_command(server, router_sock,
2672                                    SILC_COMMAND_GETKEY, ++server->cmd_ident,
2673                                    1, 1, buffer->data,
2674                                    silc_buffer_len(buffer));
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   const char *cipher, *hostname, *ip;
3405
3406   silc_socket_stream_get_info(silc_packet_stream_get_stream(sock),
3407                               NULL, &hostname, &ip, NULL);
3408
3409   if (silc_buffer_unformat(buffer,
3410                            SILC_STR_UI16_NSTRING(&id_string, &id_len),
3411                            SILC_STR_END) < 0) {
3412     if (idata->conn_type == SILC_CONN_CLIENT) {
3413       SILC_LOG_ERROR(("Client %s (%s) sent incomplete resume information, "
3414                       "closing connection", hostname, ip));
3415       silc_server_disconnect_remote(server, sock,
3416                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3417                                     "Resuming not possible");
3418       silc_server_free_sock_user_data(server, sock, NULL);
3419     }
3420     goto out;
3421   }
3422
3423   silc_id_str2id(id_string, id_len, SILC_ID_CLIENT, &client_id,
3424                  sizeof(client_id));
3425
3426   if (idata->conn_type == SILC_CONN_CLIENT) {
3427     /* Client send this and is attempting to resume to old client session */
3428     SilcClientEntry client;
3429     SilcBuffer keyp;
3430
3431     silc_buffer_pull(buffer, 2 + id_len);
3432     auth = buffer->data;
3433     auth_len = silc_buffer_len(buffer);
3434     silc_buffer_push(buffer, 2 + id_len);
3435
3436     if (auth_len < 128) {
3437       SILC_LOG_ERROR(("Client %s (%s) sent incomplete resume information, "
3438                       "closing connection", hostname, ip));
3439       silc_server_disconnect_remote(server, sock,
3440                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3441                                     "Resuming not possible");
3442       silc_server_free_sock_user_data(server, sock, NULL);
3443       goto out;
3444     }
3445
3446     /* Take client entry of this connection */
3447     client = (SilcClientEntry)idata;
3448
3449     /* Get entry to the client, and resolve it if we don't have it. */
3450     detached_client = silc_server_query_client(server, &client_id, FALSE,
3451                                                &resolved);
3452     if (!detached_client) {
3453       if (resolved) {
3454         /* The client info is being resolved. Reprocess this packet after
3455            receiving the reply to the query. */
3456         SILC_LOG_DEBUG(("Resolving client"));
3457         r = silc_calloc(1, sizeof(*r));
3458         if (!r)
3459           goto out;
3460         silc_packet_stream_ref(sock);
3461         r->server = server;
3462         r->sock = sock;
3463         r->packet = packet;
3464         r->client_id = client_id;
3465         silc_server_command_pending(server, SILC_COMMAND_WHOIS,
3466                                     server->cmd_ident,
3467                                     silc_server_command_resume_resolve, r);
3468         return;
3469       } else {
3470         SILC_LOG_ERROR(("Client %s (%s) tried to resume unknown client, "
3471                         "closing connection", hostname, ip));
3472         silc_server_disconnect_remote(server, sock,
3473                                       SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3474                                       "Resuming not possible");
3475         silc_server_free_sock_user_data(server, sock, NULL);
3476         goto out;
3477       }
3478     }
3479
3480     if (detached_client->data.status & SILC_IDLIST_STATUS_RESUMED) {
3481       SILC_LOG_ERROR(("Client %s (%s) tried to attach more than once, "
3482                       "closing connection", hostname, ip));
3483       silc_server_disconnect_remote(server, sock,
3484                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3485                                     "Resuming not possible");
3486       silc_server_free_sock_user_data(server, sock, NULL);
3487       goto out;
3488     }
3489
3490     if (detached_client->resuming_client &&
3491         detached_client->resuming_client != client) {
3492       SILC_LOG_ERROR(("Client %s (%s) tried to attach more than once, "
3493                       "closing connection", hostname, ip));
3494       silc_server_disconnect_remote(server, sock,
3495                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3496                                     "Resuming not possible");
3497       silc_server_free_sock_user_data(server, sock, NULL);
3498       goto out;
3499     }
3500
3501     if (!detached_client->resuming_client)
3502       detached_client->resuming_client = client;
3503
3504     if (!(detached_client->mode & SILC_UMODE_DETACHED))
3505       resolve = TRUE;
3506     if (!silc_hash_table_count(detached_client->channels) &&
3507         detached_client->router)
3508       resolve = TRUE;
3509     if (!detached_client->nickname)
3510       resolve = TRUE;
3511     if (detached_client->data.status & SILC_IDLIST_STATUS_RESUME_RES)
3512       resolve = FALSE;
3513
3514     if (resolve) {
3515       if (server->server_type == SILC_SERVER && !server->standalone) {
3516         /* The client info is being resolved. Reprocess this packet after
3517            receiving the reply to the query. */
3518         SILC_LOG_DEBUG(("Resolving client info"));
3519         silc_server_query_client(server, &client_id, TRUE, NULL);
3520         r = silc_calloc(1, sizeof(*r));
3521         if (!r)
3522           return;
3523         silc_packet_stream_ref(sock);
3524         r->server = server;
3525         r->sock = sock;
3526         r->packet = packet;
3527         r->client_id = client_id;
3528         silc_server_command_pending(server, SILC_COMMAND_WHOIS,
3529                                     server->cmd_ident,
3530                                     silc_server_command_resume_resolve, r);
3531         return;
3532       }
3533       if (server->server_type == SILC_SERVER) {
3534         SILC_LOG_ERROR(("Client %s (%s) tried to resume un-detached client, "
3535                         "closing connection", hostname, ip));
3536         silc_server_disconnect_remote(server, sock,
3537                                       SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3538                                       "Resuming not possible");
3539         silc_server_free_sock_user_data(server, sock, NULL);
3540         goto out;
3541       }
3542     }
3543
3544     /* Check that we have the public key of the client, if not then we must
3545        resolve it first. */
3546     if (!detached_client->data.public_key) {
3547       if (server->server_type == SILC_SERVER && server->standalone) {
3548         SILC_LOG_ERROR(("Detached client's public key not present, "
3549                         "closing connection"));
3550         silc_server_disconnect_remote(server, sock,
3551                                       SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3552                                       "Resuming not possible");
3553         silc_server_free_sock_user_data(server, sock, NULL);
3554         goto out;
3555       } else {
3556         /* We must retrieve the detached client's public key by sending
3557            GETKEY command. Reprocess this packet after receiving the key */
3558         SilcBuffer idp = silc_id_payload_encode(&client_id, SILC_ID_CLIENT);
3559         SilcPacketStream dest_sock =
3560           silc_server_get_client_route(server, NULL, 0, &client_id,
3561                                        NULL, NULL);
3562
3563         SILC_LOG_DEBUG(("Resolving client public key"));
3564
3565         silc_server_send_command(server, dest_sock ? dest_sock :
3566                                  SILC_PRIMARY_ROUTE(server),
3567                                  SILC_COMMAND_GETKEY, ++server->cmd_ident,
3568                                  1, 1, idp->data, silc_buffer_len(idp));
3569
3570         r = silc_calloc(1, sizeof(*r));
3571         if (!r)
3572           return;
3573         silc_packet_stream_ref(sock);
3574         r->server = server;
3575         r->sock = sock;
3576         r->packet = packet;
3577         r->client_id = client_id;
3578         silc_server_command_pending(server, SILC_COMMAND_GETKEY,
3579                                     server->cmd_ident,
3580                                     silc_server_command_resume_resolve, r);
3581
3582         silc_buffer_free(idp);
3583         return;
3584       }
3585     } else if (!silc_pkcs_public_key_compare(detached_client->data.public_key,
3586                                              idata->public_key)) {
3587       /* We require that the connection and resuming authentication data
3588          must be using same key pair. */
3589       SILC_LOG_ERROR(("Resuming attempted with wrong public key, "
3590                       "closing connection"));
3591       silc_server_disconnect_remote(server, sock,
3592                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3593                                     "Resuming not possible");
3594       silc_server_free_sock_user_data(server, sock, NULL);
3595       goto out;
3596     }
3597
3598     /* Verify the authentication payload.  This has to be successful in
3599        order to allow the resuming */
3600     if (!idata->hash ||
3601         !silc_auth_verify_data(auth, auth_len, SILC_AUTH_PUBLIC_KEY,
3602                                detached_client->data.public_key, 0,
3603                                idata->hash, detached_client->id,
3604                                SILC_ID_CLIENT)) {
3605       SILC_LOG_ERROR(("Client %s (%s) resume authentication failed, "
3606                       "closing connection", hostname, ip));
3607       silc_server_disconnect_remote(server, sock,
3608                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3609                                     "Resuming not possible");
3610       silc_server_free_sock_user_data(server, sock, NULL);
3611       goto out;
3612     }
3613
3614     /* Check nickname */
3615     nicknamec = silc_identifier_check(detached_client->nickname,
3616                                       strlen(detached_client->nickname),
3617                                       SILC_STRING_UTF8, 128, NULL);
3618     if (!nicknamec) {
3619       silc_server_disconnect_remote(server, sock,
3620                                     SILC_STATUS_ERR_BAD_NICKNAME,
3621                                     "Malformed nickname, cannot resume");
3622       silc_server_free_sock_user_data(server, sock, NULL);
3623       goto out;
3624     }
3625
3626     /* If the ID is not based in our ID then change it */
3627     if (!SILC_ID_COMPARE(detached_client->id, server->id,
3628                          server->id->ip.data_len)) {
3629       SilcClientID *new_id;
3630       if (!silc_id_create_client_id(server, server->id, server->rng,
3631                                     server->md5hash, nicknamec,
3632                                     strlen(nicknamec), &new_id)) {
3633         silc_server_disconnect_remote(server, sock,
3634                                       SILC_STATUS_ERR_BAD_NICKNAME,
3635                                       "Resuming not possible");
3636         silc_server_free_sock_user_data(server, sock, NULL);
3637         goto out;
3638       }
3639       nick_change = TRUE;
3640       client_id = *new_id;
3641       silc_free(new_id);
3642     }
3643
3644     /* Now resume the client to the network */
3645
3646     silc_schedule_task_del_by_context(server->schedule, detached_client);
3647     silc_packet_set_context(sock, detached_client);
3648     detached_client->connection = sock;
3649
3650     if (detached_client->data.public_key)
3651       silc_hash_table_del_by_context(server->pk_hash,
3652                                      detached_client->data.public_key,
3653                                      detached_client);
3654     if (idata->public_key)
3655       silc_hash_table_del_by_context(server->pk_hash,
3656                                      idata->public_key, idata);
3657
3658     /* Take new keys and stuff into use in the old entry */
3659     silc_idlist_del_data(detached_client);
3660     silc_idlist_add_data(detached_client, idata);
3661
3662     if (detached_client->data.public_key)
3663       silc_hash_table_add(server->pk_hash,
3664                           detached_client->data.public_key, detached_client);
3665
3666     detached_client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
3667     detached_client->data.status |= SILC_IDLIST_STATUS_RESUMED;
3668     detached_client->data.status |= SILC_IDLIST_STATUS_LOCAL;
3669     detached_client->data.status &= ~SILC_IDLIST_STATUS_RESUME_RES;
3670     detached_client->mode &= ~SILC_UMODE_DETACHED;
3671     server->stat.my_detached--;
3672
3673     /* We are finished - reset resuming client */
3674     detached_client->resuming_client = NULL;
3675
3676     /* Check if anyone is watching this client */
3677     if (server->server_type == SILC_ROUTER)
3678       silc_server_check_watcher_list(server, detached_client, NULL,
3679                                      SILC_NOTIFY_TYPE_UMODE_CHANGE);
3680
3681     /* Delete this current client entry since we're resuming to old one. */
3682     server->stat.my_clients--;
3683     server->stat.clients--;
3684     if (server->stat.cell_clients)
3685       server->stat.cell_clients--;
3686     silc_server_remove_from_channels(server, NULL, client, FALSE,
3687                                      NULL, FALSE, FALSE);
3688     silc_server_del_from_watcher_list(server, client);
3689     if (!silc_idlist_del_client(server->local_list, client))
3690       silc_idlist_del_client(server->global_list, client);
3691     client = detached_client;
3692     silc_free(client->servername);
3693     client->servername = strdup(server->server_name);
3694
3695     /* Send the RESUME_CLIENT packet to our primary router so that others
3696        know this client isn't detached anymore. */
3697     buf = silc_buffer_alloc_size(2 + id_len);
3698     silc_buffer_format(buf,
3699                        SILC_STR_UI_SHORT(id_len),
3700                        SILC_STR_UI_XNSTRING(id_string, id_len),
3701                        SILC_STR_END);
3702
3703     /* Send to primary router */
3704     silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
3705                             SILC_PACKET_RESUME_CLIENT, 0,
3706                             buf->data, silc_buffer_len(buf));
3707     silc_server_backup_send(server, client->router,
3708                             SILC_PACKET_RESUME_CLIENT, 0,
3709                             buf->data, silc_buffer_len(buf), TRUE, TRUE);
3710
3711     /* As router we must deliver this packet directly to the original
3712        server whom this client was earlier. */
3713     if (server->server_type == SILC_ROUTER && client->router &&
3714         client->router->server_type != SILC_ROUTER)
3715       silc_server_packet_send(server, client->router->connection,
3716                               SILC_PACKET_RESUME_CLIENT, 0,
3717                               buf->data, silc_buffer_len(buf));
3718     silc_buffer_free(buf);
3719     client->router = NULL;
3720
3721     if (nick_change) {
3722       /* Notify about Client ID change, nickname doesn't actually change. */
3723       silc_server_send_notify_nick_change(server, SILC_PRIMARY_ROUTE(server),
3724                                           SILC_BROADCAST(server),
3725                                           client->id, &client_id,
3726                                           client->nickname);
3727     }
3728
3729     /* Resolve users on those channels that client has joined but we
3730        haven't resolved user list yet. */
3731     if (server->server_type == SILC_SERVER && !server->standalone) {
3732       silc_hash_table_list(client->channels, &htl);
3733       while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3734         channel = chl->channel;
3735         SILC_LOG_DEBUG(("Resolving users for %s channel",
3736                         channel->channel_name));
3737         if (channel->disabled || !channel->users_resolved) {
3738           silc_server_send_command(server, SILC_PRIMARY_ROUTE(server),
3739                                    SILC_COMMAND_USERS, ++server->cmd_ident,
3740                                    1, 2, channel->channel_name,
3741                                    strlen(channel->channel_name));
3742         }
3743       }
3744       silc_hash_table_list_reset(&htl);
3745     }
3746
3747     /* Send the new client ID to the client. After this client may start
3748        receiving other packets, and may start sending packets too. */
3749     silc_server_send_new_id(server, sock, FALSE, &client_id, SILC_ID_CLIENT,
3750                             silc_id_get_len(&client_id, SILC_ID_CLIENT));
3751
3752     if (nick_change) {
3753       /* Send NICK change notify to channels as well. */
3754       SilcBuffer oidp, nidp;
3755       oidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3756       nidp = silc_id_payload_encode(&client_id, SILC_ID_CLIENT);
3757       silc_server_send_notify_on_channels(server, NULL, client,
3758                                           SILC_NOTIFY_TYPE_NICK_CHANGE, 3,
3759                                           oidp->data, silc_buffer_len(oidp),
3760                                           nidp->data, silc_buffer_len(nidp),
3761                                           client->nickname,
3762                                           strlen(client->nickname));
3763       silc_buffer_free(oidp);
3764       silc_buffer_free(nidp);
3765     }
3766
3767     /* Add the client again to the ID cache to get it to correct list */
3768     if (!silc_idcache_del_by_context(server->local_list->clients, client,
3769                                      NULL))
3770       silc_idcache_del_by_context(server->global_list->clients, client, NULL);
3771     silc_free(client->id);
3772     *client->id = client_id;
3773     silc_idcache_add(server->local_list->clients, nicknamec,
3774                      client->id, client);
3775
3776     /* Send some nice info to the client */
3777     silc_server_send_connect_notifys(server, sock, client);
3778
3779     /* Send all channel keys of channels the client has joined */
3780     silc_hash_table_list(client->channels, &htl);
3781     while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3782       SilcBool created = FALSE;
3783       channel = chl->channel;
3784
3785       if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY)
3786         continue;
3787
3788       /* If we don't have channel key, then create one */
3789       if (!channel->send_key) {
3790         if (!silc_server_create_channel_key(server, channel, 0))
3791           continue;
3792         created = TRUE;
3793       }
3794
3795       silc_id_id2str(channel->id, SILC_ID_CHANNEL, cid, sizeof(cid),
3796                      &cid_len);
3797       cipher = silc_cipher_get_name(channel->send_key);
3798       keyp =
3799         silc_channel_key_payload_encode(cid_len, cid,
3800                                         strlen(cipher), cipher,
3801                                         channel->key_len / 8, channel->key);
3802
3803       /* Send the channel key to the client */
3804       silc_server_packet_send(server, sock, SILC_PACKET_CHANNEL_KEY, 0,
3805                               keyp->data, silc_buffer_len(keyp));
3806
3807       /* Distribute the channel key to channel */
3808       if (created) {
3809         silc_server_send_channel_key(server, NULL, channel,
3810                                      server->server_type == SILC_ROUTER ?
3811                                      FALSE : !server->standalone);
3812         silc_server_backup_send(server, NULL, SILC_PACKET_CHANNEL_KEY, 0,
3813                                 keyp->data, silc_buffer_len(keyp),
3814                                 FALSE, TRUE);
3815       }
3816
3817       silc_buffer_free(keyp);
3818     }
3819     silc_hash_table_list_reset(&htl);
3820
3821   } else if (idata->conn_type != SILC_CONN_CLIENT) {
3822     /* Server or router sent this to us to notify that that a client has
3823        been resumed. */
3824     SilcServerEntry server_entry;
3825     SilcServerID server_id;
3826
3827     /* Get entry to the client, and resolve it if we don't have it. */
3828     detached_client = silc_idlist_find_client_by_id(server->local_list,
3829                                                     &client_id, TRUE,
3830                                                     &id_cache);
3831     if (!detached_client) {
3832       detached_client = silc_idlist_find_client_by_id(server->global_list,
3833                                                       &client_id, TRUE,
3834                                                       &id_cache);
3835       if (!detached_client) {
3836         SILC_LOG_DEBUG(("Resuming client is unknown"));
3837         goto out;
3838       }
3839     }
3840
3841     /* Check that the client has not been resumed already because it is
3842        protocol error to attempt to resume more than once.  The client
3843        will be killed if this protocol error occurs. */
3844     if (detached_client->data.status & SILC_IDLIST_STATUS_RESUMED &&
3845         !(detached_client->mode & SILC_UMODE_DETACHED)) {
3846       /* The client is clearly attempting to resume more than once and
3847          perhaps playing around by resuming from several different places
3848          at the same time. */
3849       SILC_LOG_DEBUG(("Attempting to re-resume client, killing both"));
3850       silc_server_kill_client(server, detached_client, NULL,
3851                               server->id, SILC_ID_SERVER);
3852       goto out;
3853     }
3854
3855     /* Check whether client is detached at all */
3856     if (!(detached_client->mode & SILC_UMODE_DETACHED)) {
3857       SILC_LOG_DEBUG(("Client is not detached"));
3858       goto out;
3859     }
3860
3861     /* Check nickname */
3862     if (detached_client->nickname) {
3863       nicknamec = silc_identifier_check(detached_client->nickname,
3864                                         strlen(detached_client->nickname),
3865                                         SILC_STRING_UTF8, 128, NULL);
3866       if (!nicknamec)
3867         goto out;
3868     }
3869
3870     SILC_LOG_DEBUG(("Resuming detached client"));
3871
3872     /* If the sender of this packet is server and we are router we need to
3873        broadcast this packet to other routers in the network. */
3874     if (server->server_type == SILC_ROUTER &&
3875         idata->conn_type == SILC_CONN_SERVER &&
3876         !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
3877       SILC_LOG_DEBUG(("Broadcasting received Resume Client packet"));
3878       silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
3879                               packet->type,
3880                               packet->flags | SILC_PACKET_FLAG_BROADCAST,
3881                               buffer->data, silc_buffer_len(buffer));
3882       silc_server_backup_send(server, (SilcServerEntry)idata,
3883                               packet->type, packet->flags,
3884                               packet->buffer.data,
3885                               silc_buffer_len(&packet->buffer),
3886                               FALSE, TRUE);
3887     }
3888
3889     /* Client is detached, and now it is resumed.  Remove the detached
3890        mode and mark that it is resumed. */
3891
3892     if (detached_client->data.public_key)
3893       silc_hash_table_del_by_context(server->pk_hash,
3894                                      detached_client->data.public_key,
3895                                      detached_client);
3896
3897     silc_idlist_del_data(detached_client);
3898     detached_client->mode &= ~SILC_UMODE_DETACHED;
3899     detached_client->data.status |= SILC_IDLIST_STATUS_RESUMED;
3900     detached_client->data.status &= ~SILC_IDLIST_STATUS_LOCAL;
3901
3902     /* Check if anyone is watching this client */
3903     if (server->server_type == SILC_ROUTER)
3904       silc_server_check_watcher_list(server, detached_client, NULL,
3905                                      SILC_NOTIFY_TYPE_UMODE_CHANGE);
3906
3907     silc_schedule_task_del_by_context(server->schedule, detached_client);
3908
3909     /* Get the new owner of the resumed client */
3910     if (!silc_id_str2id(packet->src_id, packet->src_id_len,
3911                         packet->src_id_type, &server_id, sizeof(server_id)))
3912       goto out;
3913
3914     /* Get server entry */
3915     server_entry = silc_idlist_find_server_by_id(server->global_list,
3916                                                  &server_id, TRUE, NULL);
3917     local = FALSE;
3918     if (!server_entry) {
3919       server_entry = silc_idlist_find_server_by_id(server->local_list,
3920                                                    &server_id, TRUE, NULL);
3921       local = TRUE;
3922       if (!server_entry)
3923         goto out;
3924     }
3925
3926     if (server->server_type == SILC_ROUTER &&
3927         idata->conn_type == SILC_CONN_ROUTER &&
3928         server_entry->server_type == SILC_ROUTER)
3929       local = FALSE;
3930
3931     /* Change the client to correct list. */
3932     if (!silc_idcache_del_by_context(server->local_list->clients,
3933                                      detached_client, NULL))
3934       silc_idcache_del_by_context(server->global_list->clients,
3935                                   detached_client, NULL);
3936     silc_idcache_add(local && server->server_type == SILC_ROUTER ?
3937                      server->local_list->clients :
3938                      server->global_list->clients, nicknamec,
3939                      detached_client->id, detached_client);
3940
3941     /* Change the owner of the client */
3942     detached_client->router = server_entry;
3943
3944     /* Update channel information regarding global clients on channel. */
3945     if (server->server_type != SILC_ROUTER) {
3946       silc_hash_table_list(detached_client->channels, &htl);
3947       while (silc_hash_table_get(&htl, NULL, (void *)&chl))
3948         chl->channel->global_users =
3949           silc_server_channel_has_global(chl->channel);
3950       silc_hash_table_list_reset(&htl);
3951     }
3952   }
3953
3954  out:
3955   silc_packet_free(packet);
3956 }