Preliminary SILC Server 1.1 commit.
[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 }
1674
1675 void silc_server_notify_list(SilcServer server,
1676                              SilcPacketStream sock,
1677                              SilcPacket packet)
1678 {
1679   SilcIDListData idata = silc_packet_get_context(sock);
1680   SilcUInt16 len;
1681   SilcBuffer buffer;
1682
1683   SILC_LOG_DEBUG(("Processing Notify List"));
1684
1685   if (idata->conn_type == SILC_CONN_CLIENT ||
1686       packet->src_id_type != SILC_ID_SERVER)
1687     return;
1688
1689   buffer = silc_buffer_alloc(1024);
1690   if (!buffer)
1691     return;
1692
1693   while (silc_buffer_len(&packet->buffer)) {
1694     SILC_GET16_MSB(len, packet->buffer.data + 2);
1695     if (len > silc_buffer_len(&packet->buffer))
1696       break;
1697
1698     if (len > silc_buffer_truelen(buffer)) {
1699       silc_buffer_free(buffer);
1700       buffer = silc_buffer_alloc(1024 + len);
1701     }
1702
1703     silc_buffer_pull_tail(buffer, len);
1704     silc_buffer_put(buffer, packet->buffer.data, len);
1705
1706     /* Process the Notify */
1707     silc_server_notify_process(server, sock, packet, buffer);
1708
1709     silc_buffer_push_tail(buffer, len);
1710     silc_buffer_pull(&packet->buffer, len);
1711   }
1712
1713   silc_buffer_free(buffer);
1714 }
1715
1716 /* Received private message. This resolves the destination of the message
1717    and sends the packet. This is used by both server and router.  If the
1718    destination is our locally connected client this sends the packet to
1719    the client. This may also send the message for further routing if
1720    the destination is not in our server (or router). */
1721
1722 void silc_server_private_message(SilcServer server,
1723                                  SilcPacketStream sock,
1724                                  SilcPacket packet)
1725 {
1726   SilcPacketStream dst_sock;
1727   SilcIDListData idata;
1728   SilcClientEntry client;
1729   SilcClientID client_id;
1730
1731   SILC_LOG_DEBUG(("Start"));
1732
1733   if (packet->src_id_type != SILC_ID_CLIENT ||
1734       packet->dst_id_type != SILC_ID_CLIENT || !packet->dst_id)
1735     return;
1736
1737   /* Get the route to the client */
1738   dst_sock = silc_server_get_client_route(server, packet->dst_id,
1739                                           packet->dst_id_len, NULL,
1740                                           &idata, &client);
1741   if (!dst_sock) {
1742     SilcBuffer idp;
1743     unsigned char error;
1744
1745     if (client && client->mode & SILC_UMODE_DETACHED) {
1746       SILC_LOG_DEBUG(("Client is detached, discarding packet"));
1747       return;
1748     }
1749
1750     /* Send SILC_NOTIFY_TYPE_ERROR to indicate that such destination ID
1751        does not exist or is invalid. */
1752     idp = silc_id_payload_encode_data(packet->dst_id,
1753                                       packet->dst_id_len,
1754                                       packet->dst_id_type);
1755     if (!idp)
1756       return;
1757
1758     error = SILC_STATUS_ERR_NO_SUCH_CLIENT_ID;
1759     if (packet->src_id_type == SILC_ID_CLIENT) {
1760       silc_id_str2id(packet->src_id, packet->src_id_len,
1761                      packet->src_id_type, &client_id, sizeof(client_id));
1762       silc_server_send_notify_dest(server, sock, FALSE,
1763                                    &client_id, SILC_ID_CLIENT,
1764                                    SILC_NOTIFY_TYPE_ERROR, 2,
1765                                    &error, 1,
1766                                    idp->data, silc_buffer_len(idp));
1767     } else {
1768       silc_server_send_notify(server, sock, FALSE,
1769                               SILC_NOTIFY_TYPE_ERROR, 2,
1770                               &error, 1,
1771                               idp->data, silc_buffer_len(idp));
1772     }
1773
1774     silc_buffer_free(idp);
1775     return;
1776   }
1777
1778   /* Check whether destination client wishes to receive private messages */
1779   if (client && !(packet->flags & SILC_PACKET_FLAG_PRIVMSG_KEY) &&
1780       client->mode & SILC_UMODE_BLOCK_PRIVMSG) {
1781     SILC_LOG_DEBUG(("Client blocks private messages, discarding packet"));
1782     return;
1783   }
1784
1785   /* Send the private message */
1786   silc_server_packet_route(server, dst_sock, packet);
1787 }
1788
1789 /* Received private message key packet.. This packet is never for us. It is to
1790    the client in the packet's destination ID. Sending of this sort of packet
1791    equals sending private message, ie. it is sent point to point from
1792    one client to another. */
1793
1794 void silc_server_private_message_key(SilcServer server,
1795                                      SilcPacketStream sock,
1796                                      SilcPacket packet)
1797 {
1798   SilcPacketStream dst_sock;
1799   SilcIDListData idata;
1800
1801   SILC_LOG_DEBUG(("Start"));
1802
1803   if (packet->src_id_type != SILC_ID_CLIENT ||
1804       packet->dst_id_type != SILC_ID_CLIENT)
1805     return;
1806
1807   if (!packet->dst_id)
1808     return;
1809
1810   /* Get the route to the client */
1811   dst_sock = silc_server_get_client_route(server, packet->dst_id,
1812                                           packet->dst_id_len, NULL,
1813                                           &idata, NULL);
1814   if (!dst_sock)
1815     return;
1816
1817   /* Relay the packet */
1818   silc_server_packet_route(server, dst_sock, packet);
1819 }
1820
1821 /* Processes incoming command reply packet. The command reply packet may
1822    be destined to one of our clients or it may directly for us. We will
1823    call the command reply routine after processing the packet. */
1824
1825 void silc_server_command_reply(SilcServer server,
1826                                SilcPacketStream sock,
1827                                SilcPacket packet)
1828 {
1829   SilcBuffer buffer = &packet->buffer;
1830   SilcClientEntry client = NULL;
1831   SilcClientID id;
1832
1833   SILC_LOG_DEBUG(("Start"));
1834
1835   if (packet->dst_id_type == SILC_ID_CHANNEL)
1836     return;
1837
1838   if (packet->dst_id_type == SILC_ID_CLIENT) {
1839     /* Destination must be one of ours */
1840     if (!silc_id_str2id(packet->dst_id, packet->dst_id_len, SILC_ID_CLIENT,
1841                         &id, sizeof(id)))
1842       return;
1843     client = silc_idlist_find_client_by_id(server->local_list, &id,
1844                                            TRUE, NULL);
1845     if (!client) {
1846       SILC_LOG_ERROR(("Cannot process command reply to unknown client"));
1847       return;
1848     }
1849   }
1850
1851   if (packet->dst_id_type == SILC_ID_SERVER) {
1852     /* For now this must be for us */
1853     if (memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
1854       SILC_LOG_ERROR(("Cannot process command reply to unknown server"));
1855       return;
1856     }
1857   }
1858
1859   /* Execute command reply locally for the command */
1860   silc_server_command_reply_process(server, sock, buffer);
1861
1862   /* Relay the packet to the client */
1863   if (packet->dst_id_type == SILC_ID_CLIENT && client)
1864     silc_server_packet_route(server, client->connection, packet);
1865 }
1866
1867 /* Process received channel message. The message can be originated from
1868    client or server. */
1869
1870 void silc_server_channel_message(SilcServer server,
1871                                  SilcPacketStream sock,
1872                                  SilcPacket packet)
1873 {
1874   SilcChannelEntry channel = NULL;
1875   SilcChannelID id;
1876   SilcClientID cid;
1877   SilcID sid;
1878   void *sender_id = NULL;
1879   SilcClientEntry sender_entry = NULL;
1880   SilcIDListData idata;
1881   SilcChannelClientEntry chl;
1882   SilcBool local = TRUE;
1883
1884   SILC_LOG_DEBUG(("Processing channel message"));
1885
1886   /* Sanity checks */
1887   if (packet->dst_id_type != SILC_ID_CHANNEL) {
1888     SILC_LOG_DEBUG(("Received bad message for channel, dropped"));
1889     return;
1890   }
1891
1892   /* Find channel entry */
1893   if (!silc_id_str2id(packet->dst_id, packet->dst_id_len, SILC_ID_CHANNEL,
1894                       &id, sizeof(id)))
1895     return;
1896   channel = silc_idlist_find_channel_by_id(server->local_list, &id, NULL);
1897   if (!channel) {
1898     channel = silc_idlist_find_channel_by_id(server->global_list, &id, NULL);
1899     if (!channel) {
1900       SilcBuffer idp;
1901       unsigned char error;
1902
1903       /* Send SILC_NOTIFY_TYPE_ERROR to indicate that such destination ID
1904          does not exist or is invalid. */
1905       idp = silc_id_payload_encode_data(packet->dst_id,
1906                                         packet->dst_id_len,
1907                                         packet->dst_id_type);
1908       if (!idp)
1909         return;
1910
1911       error = SILC_STATUS_ERR_NO_SUCH_CHANNEL_ID;
1912       if (packet->src_id_type == SILC_ID_CLIENT) {
1913         silc_id_str2id(packet->src_id, packet->src_id_len,
1914                        packet->src_id_type, &cid, sizeof(cid));
1915         silc_server_send_notify_dest(server, sock, FALSE,
1916                                      &cid, SILC_ID_CLIENT,
1917                                      SILC_NOTIFY_TYPE_ERROR, 2,
1918                                      &error, 1, idp->data,
1919                                      silc_buffer_len(idp));
1920       } else {
1921         silc_server_send_notify(server, sock, FALSE,
1922                                 SILC_NOTIFY_TYPE_ERROR, 2,
1923                                 &error, 1, idp->data, silc_buffer_len(idp));
1924       }
1925
1926       silc_buffer_free(idp);
1927       return;
1928     }
1929   }
1930
1931   /* See that this client is on the channel. If the original sender is
1932      not client (as it can be server as well) we don't do the check. */
1933   if (!silc_id_str2id2(packet->src_id, packet->src_id_len,
1934                        packet->src_id_type, &sid))
1935     return;
1936   if (sid.type == SILC_ID_CLIENT) {
1937     sender_entry = silc_idlist_find_client_by_id(server->local_list,
1938                                                  SILC_ID_GET_ID(sid),
1939                                                  TRUE, NULL);
1940     if (!sender_entry) {
1941       local = FALSE;
1942       sender_entry = silc_idlist_find_client_by_id(server->global_list,
1943                                                    SILC_ID_GET_ID(sid),
1944                                                    TRUE, NULL);
1945     }
1946     if (!sender_entry || !silc_server_client_on_channel(sender_entry,
1947                                                         channel, &chl)) {
1948       SILC_LOG_DEBUG(("Client not on channel"));
1949       return;
1950     }
1951
1952     /* If channel is moderated check that client is allowed to send
1953        messages. */
1954     if (channel->mode & SILC_CHANNEL_MODE_SILENCE_USERS &&
1955         !(chl->mode & SILC_CHANNEL_UMODE_CHANOP) &&
1956         !(chl->mode & SILC_CHANNEL_UMODE_CHANFO)) {
1957       SILC_LOG_DEBUG(("Channel is silenced from normal users"));
1958       return;
1959     }
1960     if (channel->mode & SILC_CHANNEL_MODE_SILENCE_OPERS &&
1961         chl->mode & SILC_CHANNEL_UMODE_CHANOP &&
1962         !(chl->mode & SILC_CHANNEL_UMODE_CHANFO)) {
1963       SILC_LOG_DEBUG(("Channel is silenced from operators"));
1964       return;
1965     }
1966     if (chl->mode & SILC_CHANNEL_UMODE_QUIET) {
1967       SILC_LOG_DEBUG(("Sender is quieted on the channel"));
1968       return;
1969     }
1970
1971     /* If the packet is coming from router, but the client entry is local
1972        entry to us then some router is rerouting this to us and it is not
1973        allowed. When the client is local to us it means that we've routed
1974        this packet to network, and now someone is routing it back to us. */
1975     idata = silc_packet_get_context(sock);
1976     if (server->server_type == SILC_ROUTER &&
1977         idata->conn_type == SILC_CONN_ROUTER && local) {
1978       SILC_LOG_DEBUG(("Channel message rerouted to the sender, drop it"));
1979       return;
1980     }
1981   }
1982
1983   /* Distribute the packet to our local clients. This will send the
1984      packet for further routing as well, if needed. */
1985   silc_server_packet_relay_to_channel(server, sock, channel, sender_id,
1986                                       packet->src_id_type, sender_entry,
1987                                       packet->buffer.data,
1988                                       silc_buffer_len(&packet->buffer));
1989 }
1990
1991 /* Received channel key packet. We distribute the key to all of our locally
1992    connected clients on the channel. */
1993
1994 void silc_server_channel_key(SilcServer server,
1995                              SilcPacketStream sock,
1996                              SilcPacket packet)
1997 {
1998   SilcBuffer buffer = &packet->buffer;
1999   SilcIDListData idata = silc_packet_get_context(sock);
2000   SilcChannelEntry channel;
2001
2002   if (packet->src_id_type != SILC_ID_SERVER ||
2003       (server->server_type == SILC_ROUTER && !server->backup_router &&
2004        idata->conn_type == SILC_CONN_ROUTER))
2005     return;
2006
2007   /* Save the channel key */
2008   channel = silc_server_save_channel_key(server, buffer, NULL);
2009   if (!channel) {
2010     SILC_LOG_ERROR(("Bad channel key from %s", idata->sconn->remote_host));
2011     return;
2012   }
2013
2014   /* Distribute the key to everybody who is on the channel. If we are router
2015      we will also send it to locally connected servers. */
2016   silc_server_send_channel_key(server, sock, channel, FALSE);
2017
2018   if (server->server_type != SILC_BACKUP_ROUTER) {
2019     /* Distribute to local cell backup routers. */
2020     silc_server_backup_send(server, (SilcServerEntry)idata,
2021                             SILC_PACKET_CHANNEL_KEY, 0,
2022                             buffer->data, silc_buffer_len(buffer),
2023                             FALSE, TRUE);
2024   }
2025 }
2026
2027 /* Received New Client packet and processes it.  Creates Client ID for the
2028    client. Client becomes registered after calling this functions. */
2029
2030 SilcClientEntry silc_server_new_client(SilcServer server,
2031                                        SilcPacketStream sock,
2032                                        SilcPacket packet)
2033 {
2034   SilcBuffer buffer = &packet->buffer;
2035   SilcIDListData idata = silc_packet_get_context(sock);
2036   SilcClientEntry client;
2037   SilcClientID *client_id;
2038   char *username = NULL, *realname = NULL;
2039   SilcUInt16 username_len;
2040   SilcUInt32 id_len, tmp_len;
2041   int ret;
2042   char *host, *nickname, *nicknamec;
2043   const char *hostname, *ip;
2044
2045   SILC_LOG_DEBUG(("Creating new client"));
2046
2047   if (idata->conn_type != SILC_CONN_CLIENT)
2048     return NULL;
2049
2050   /* Take client entry */
2051   client = (SilcClientEntry)idata;
2052   silc_socket_stream_get_info(sock, NULL, &hostname, &ip, NULL);
2053
2054   /* Remove the old cache entry. */
2055   if (!silc_idcache_del_by_context(server->local_list->clients, client,
2056                                    NULL)) {
2057     SILC_LOG_INFO(("Unauthenticated client attempted to register to network"));
2058     silc_server_disconnect_remote(server, sock,
2059                                   SILC_STATUS_ERR_NOT_AUTHENTICATED, NULL);
2060     silc_server_free_sock_user_data(server, sock, NULL);
2061     return NULL;
2062   }
2063
2064   /* Make sure this client hasn't registered already */
2065   if (idata->status & SILC_IDLIST_STATUS_REGISTERED) {
2066     silc_server_disconnect_remote(server, sock,
2067                                   SILC_STATUS_ERR_OPERATION_ALLOWED,
2068                                   "Too many registrations");
2069     silc_server_free_sock_user_data(server, sock, NULL);
2070     return NULL;
2071   }
2072
2073   /* Parse incoming packet */
2074   ret = silc_buffer_unformat(buffer,
2075                              SILC_STR_UI16_NSTRING_ALLOC(&username,
2076                                                          &username_len),
2077                              SILC_STR_UI16_STRING_ALLOC(&realname),
2078                              SILC_STR_END);
2079   if (ret == -1) {
2080     silc_free(username);
2081     silc_free(realname);
2082     SILC_LOG_ERROR(("Client %s (%s) sent incomplete information, closing "
2083                     "connection", hostname, ip));
2084     silc_server_disconnect_remote(server, sock,
2085                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2086                                   NULL);
2087     silc_server_free_sock_user_data(server, sock, NULL);
2088     return NULL;
2089   }
2090
2091   if (!username) {
2092     silc_free(username);
2093     silc_free(realname);
2094     SILC_LOG_ERROR(("Client %s (%s) did not send its username, closing "
2095                     "connection", hostname, ip));
2096     silc_server_disconnect_remote(server, sock,
2097                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2098                                   NULL);
2099     silc_server_free_sock_user_data(server, sock, NULL);
2100     return NULL;
2101   }
2102
2103   if (username_len > 128) {
2104     username[128] = '\0';
2105     username_len = 128;
2106   }
2107
2108   /* Check for valid username string */
2109   nicknamec = silc_identifier_check(username, username_len,
2110                                     SILC_STRING_UTF8, 128, &tmp_len);
2111   if (!nicknamec) {
2112     silc_free(username);
2113     silc_free(realname);
2114     SILC_LOG_ERROR(("Client %s (%s) sent bad username string '%s', closing "
2115                     "connection", hostname, ip, username));
2116     silc_server_disconnect_remote(server, sock,
2117                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2118                                   NULL);
2119     silc_server_free_sock_user_data(server, sock, NULL);
2120     return NULL;
2121   }
2122
2123   /* Nickname is initially same as username */
2124   nickname = strdup(username);
2125
2126   /* Make sanity checks for the hostname of the client. If the hostname
2127      is provided in the `username' check that it is the same than the
2128      resolved hostname, or if not resolved the hostname that appears in
2129      the client's public key. If the hostname is not present then put
2130      it from the resolved name or from the public key. */
2131   if (strchr(username, '@')) {
2132     SilcSILCPublicKey silc_pubkey;
2133     int tlen = strcspn(username, "@");
2134     char *phostname = NULL;
2135
2136     host = silc_memdup(username + tlen + 1, strlen(username) - tlen - 1);
2137
2138     if (strcmp(hostname, ip) && strcmp(hostname, host)) {
2139       silc_free(username);
2140       silc_free(host);
2141       silc_free(realname);
2142       SILC_LOG_ERROR(("Client %s (%s) sent incomplete information, closing "
2143                       "connection", hostname, ip));
2144       silc_server_disconnect_remote(server, sock,
2145                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2146                                     NULL);
2147       silc_server_free_sock_user_data(server, sock, NULL);
2148       return NULL;
2149     }
2150
2151     silc_pubkey = silc_pkcs_get_context(SILC_PKCS_SILC,
2152                                         client->data.public_key);
2153     phostname = strdup(silc_pubkey->identifier.host);
2154     if (!strcmp(hostname, ip) && phostname && strcmp(phostname, host)) {
2155       silc_free(username);
2156       silc_free(host);
2157       silc_free(phostname);
2158       silc_free(realname);
2159       SILC_LOG_ERROR(("Client %s (%s) sent incomplete information, closing "
2160                       "connection", hostname, ip));
2161       silc_server_disconnect_remote(server, sock,
2162                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2163                                     NULL);
2164       silc_server_free_sock_user_data(server, sock, NULL);
2165       return NULL;
2166     }
2167
2168     silc_free(phostname);
2169   } else {
2170     /* The hostname is not present, add it. */
2171     char *newusername;
2172     newusername = silc_calloc(strlen(username) + strlen(hostname) + 2,
2173                               sizeof(*newusername));
2174     strncat(newusername, username, strlen(username));
2175     strncat(newusername, "@", 1);
2176     strncat(newusername, hostname, strlen(hostname));
2177     silc_free(username);
2178     username = newusername;
2179   }
2180
2181   /* Create Client ID */
2182   if (!silc_id_create_client_id(server, server->id, server->rng,
2183                                 server->md5hash, nicknamec,
2184                                 strlen(nicknamec), &client_id)) {
2185     silc_server_disconnect_remote(server, sock,
2186                                   SILC_STATUS_ERR_BAD_NICKNAME, NULL);
2187     silc_server_free_sock_user_data(server, sock, NULL);
2188     return NULL;
2189   }
2190
2191   /* If client marked as anonymous, scramble the username and hostname */
2192   if (client->mode & SILC_UMODE_ANONYMOUS) {
2193     char *scramble;
2194
2195     if (strlen(username) >= 2) {
2196       username[0] = silc_rng_get_byte_fast(server->rng);
2197       username[1] = silc_rng_get_byte_fast(server->rng);
2198     }
2199
2200     scramble = silc_hash_babbleprint(server->sha1hash, username,
2201                                      strlen(username));
2202     scramble[5] = '@';
2203     scramble[11] = '.';
2204     memcpy(&scramble[16], ".silc", 5);
2205     scramble[21] = '\0';
2206     silc_free(username);
2207     username = scramble;
2208   }
2209
2210   /* Update client entry */
2211   idata->status |= SILC_IDLIST_STATUS_REGISTERED;
2212   client->nickname = nickname;
2213   client->username = username;
2214   client->userinfo = realname ? realname : strdup(username);
2215   client->id = client_id;
2216   id_len = silc_id_get_len(client_id, SILC_ID_CLIENT);
2217
2218   /* Add the client again to the ID cache */
2219   silc_idcache_add(server->local_list->clients, nicknamec,
2220                    client_id, client);
2221
2222   /* Notify our router about new client on the SILC network */
2223   silc_server_send_new_id(server, SILC_PRIMARY_ROUTE(server),
2224                           SILC_BROADCAST(server), client->id,
2225                           SILC_ID_CLIENT, id_len);
2226
2227   /* Distribute to backup routers */
2228   if (server->server_type == SILC_ROUTER) {
2229     SilcBuffer idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2230     silc_server_backup_send(server, NULL, SILC_PACKET_NEW_ID, 0,
2231                             idp->data, silc_buffer_len(idp), FALSE, TRUE);
2232     silc_buffer_free(idp);
2233   }
2234
2235   /* Send the new client ID to the client. */
2236   silc_server_send_new_id(server, sock, FALSE, client->id, SILC_ID_CLIENT,
2237                           silc_id_get_len(client->id, SILC_ID_CLIENT));
2238
2239   /* Send some nice info to the client */
2240   silc_server_send_connect_notifys(server, sock, client);
2241
2242   /* Check if anyone is watching this nickname */
2243   if (server->server_type == SILC_ROUTER)
2244     silc_server_check_watcher_list(server, client, NULL, 0);
2245
2246   return client;
2247 }
2248
2249 /* Create new server. This processes received New Server packet and
2250    saves the received Server ID. The server is our locally connected
2251    server thus we save all the information and save it to local list.
2252    This funtion can be used by both normal server and router server.
2253    If normal server uses this it means that its router has connected
2254    to the server. If router uses this it means that one of the cell's
2255    servers is connected to the router. */
2256
2257 SilcServerEntry silc_server_new_server(SilcServer server,
2258                                        SilcPacketStream sock,
2259                                        SilcPacket packet)
2260 {
2261   SilcBuffer buffer = &packet->buffer;
2262   SilcIDListData idata = silc_packet_get_context(sock);
2263   SilcServerEntry new_server, server_entry;
2264   SilcServerID server_id;
2265   unsigned char *server_name, *server_namec, *id_string;
2266   SilcUInt16 id_len, name_len;
2267   int ret;
2268   SilcBool local = TRUE;
2269   const char *hostname, *ip;
2270
2271   SILC_LOG_DEBUG(("Creating new server"));
2272
2273   if (idata->conn_type != SILC_CONN_SERVER &&
2274       idata->conn_type != SILC_CONN_ROUTER)
2275     return NULL;
2276
2277   /* Take server entry */
2278   new_server = (SilcServerEntry)idata;
2279   silc_socket_stream_get_info(sock, NULL, &hostname, &ip, NULL);
2280
2281   /* Statistics */
2282   if (server->server_type == SILC_ROUTER)
2283     server->stat.cell_servers++;
2284
2285   /* Remove the old cache entry */
2286   if (!silc_idcache_del_by_context(server->local_list->servers, new_server,
2287                                    NULL)) {
2288     if (!silc_idcache_del_by_context(server->global_list->servers,
2289                                      new_server, NULL)) {
2290       SILC_LOG_INFO(("Unauthenticated %s attempted to register to "
2291                      "network", (idata->conn_type == SILC_CONN_SERVER ?
2292                                  "server" : "router")));
2293       silc_server_disconnect_remote(server, sock,
2294                                     SILC_STATUS_ERR_NOT_AUTHENTICATED, NULL);
2295       silc_server_free_sock_user_data(server, sock, NULL);
2296       return NULL;
2297     }
2298     local = FALSE;
2299   }
2300
2301   /* Make sure this server hasn't registered already */
2302   if (idata->status & SILC_IDLIST_STATUS_REGISTERED) {
2303     silc_server_disconnect_remote(server, sock,
2304                                   SILC_STATUS_ERR_OPERATION_ALLOWED,
2305                                   "Too many registrations");
2306     silc_server_free_sock_user_data(server, sock, NULL);
2307     return NULL;
2308   }
2309
2310   /* Parse the incoming packet */
2311   ret = silc_buffer_unformat(buffer,
2312                              SILC_STR_UI16_NSTRING_ALLOC(&id_string, &id_len),
2313                              SILC_STR_UI16_NSTRING_ALLOC(&server_name,
2314                                                          &name_len),
2315                              SILC_STR_END);
2316   if (ret == -1) {
2317     silc_free(id_string);
2318     silc_free(server_name);
2319     silc_server_disconnect_remote(server, sock,
2320                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2321                                   NULL);
2322     silc_server_free_sock_user_data(server, sock, NULL);
2323     return NULL;
2324   }
2325
2326   if (id_len > silc_buffer_len(buffer)) {
2327     silc_free(id_string);
2328     silc_free(server_name);
2329     silc_server_disconnect_remote(server, sock,
2330                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2331                                   NULL);
2332     silc_server_free_sock_user_data(server, sock, NULL);
2333     return NULL;
2334   }
2335
2336   if (name_len > 256) {
2337     server_name[256] = '\0';
2338     name_len = 256;
2339   }
2340
2341   /* Get Server ID */
2342   if (!silc_id_str2id(id_string, id_len, SILC_ID_SERVER, &server_id,
2343                       sizeof(server_id))) {
2344     silc_free(id_string);
2345     silc_free(server_name);
2346     silc_server_disconnect_remote(server, sock,
2347                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2348                                   NULL);
2349     silc_server_free_sock_user_data(server, sock, NULL);
2350     return NULL;
2351   }
2352   silc_free(id_string);
2353
2354   /* Check for valid server ID */
2355   if (!silc_id_is_valid_server_id(server, &server_id, sock)) {
2356     SILC_LOG_INFO(("Invalid server ID sent by %s (%s)",
2357                    ip, hostname));
2358     silc_server_disconnect_remote(server, sock,
2359                                   SILC_STATUS_ERR_BAD_SERVER_ID, NULL);
2360     silc_server_free_sock_user_data(server, sock, NULL);
2361     silc_free(server_name);
2362     return NULL;
2363   }
2364
2365   /* Check that we do not have this ID already */
2366   server_entry = silc_idlist_find_server_by_id(server->local_list,
2367                                                &server_id, TRUE, NULL);
2368   if (server_entry) {
2369     if (SILC_IS_LOCAL(server_entry)) {
2370       SILC_LOG_ERROR(("Too many registrations from %s (%s)",
2371                       ip, hostname));
2372       silc_server_disconnect_remote(server, sock,
2373                                     SILC_STATUS_ERR_OPERATION_ALLOWED,
2374                                     "Too many registrations");
2375       silc_server_free_sock_user_data(server, sock, NULL);
2376       return NULL;
2377     } else {
2378       silc_idcache_del_by_context(server->local_list->servers, server_entry,
2379                                   NULL);
2380     }
2381   } else {
2382     server_entry = silc_idlist_find_server_by_id(server->global_list,
2383                                                  &server_id, TRUE, NULL);
2384     if (server_entry) {
2385       if (SILC_IS_LOCAL(server_entry)) {
2386         SILC_LOG_ERROR(("Too many registrations from %s (%s)",
2387                         ip, hostname));
2388         silc_server_disconnect_remote(server, sock,
2389                                       SILC_STATUS_ERR_OPERATION_ALLOWED,
2390                                       "Too many registrations");
2391         silc_server_free_sock_user_data(server, sock, NULL);
2392         return NULL;
2393       } else {
2394         silc_idcache_del_by_context(server->global_list->servers,
2395                                     server_entry, NULL);
2396       }
2397     }
2398   }
2399
2400   /* Check server name */
2401   server_namec = silc_identifier_check(server_name, strlen(server_name),
2402                                        SILC_STRING_UTF8, 256, NULL);
2403   if (!server_namec) {
2404     SILC_LOG_ERROR(("Malformed server name from %s (%s)",
2405                     ip, hostname));
2406     silc_server_disconnect_remote(server, sock,
2407                                   SILC_STATUS_ERR_OPERATION_ALLOWED,
2408                                   "Malfromed server name");
2409     silc_server_free_sock_user_data(server, sock, NULL);
2410     return NULL;
2411   }
2412
2413   /* Update server entry */
2414   idata->status |= SILC_IDLIST_STATUS_REGISTERED;
2415   new_server->server_name = server_name;
2416   new_server->id = silc_id_dup(&server_id, SILC_ID_SERVER);
2417
2418   SILC_LOG_DEBUG(("New server id(%s)",
2419                   silc_id_render(&server_id, SILC_ID_SERVER)));
2420
2421   /* Add again the entry to the ID cache. */
2422   silc_idcache_add(local ? server->local_list->servers :
2423                    server->global_list->servers, server_namec,
2424                    new_server->id, new_server);
2425
2426   /* Distribute the information about new server in the SILC network
2427      to our router. If we are normal server we won't send anything
2428      since this connection must be our router connection. */
2429   if (server->server_type == SILC_ROUTER && !server->standalone &&
2430       SILC_PRIMARY_ROUTE(server) != sock)
2431     silc_server_send_new_id(server, SILC_PRIMARY_ROUTE(server),
2432                             TRUE, new_server->id, SILC_ID_SERVER,
2433                             silc_id_get_len(&server_id, SILC_ID_SERVER));
2434
2435   if (server->server_type == SILC_ROUTER) {
2436     /* Distribute to backup routers */
2437     SilcBuffer idp = silc_id_payload_encode(new_server->id, SILC_ID_SERVER);
2438     silc_server_backup_send(server, NULL, SILC_PACKET_NEW_ID, 0, idp->data,
2439                             silc_buffer_len(idp), FALSE, TRUE);
2440     silc_buffer_free(idp);
2441   }
2442
2443   /* Check whether this router connection has been replaced by an
2444      backup router. If it has been then we'll disable the server and will
2445      ignore everything it will send until the backup router resuming
2446      protocol has been completed. */
2447   if (idata->conn_type == SILC_CONN_ROUTER &&
2448       silc_server_backup_replaced_get(server, &server_id, NULL)) {
2449     /* Send packet to the router indicating that it cannot use this
2450        connection as it has been replaced by backup router. */
2451     SILC_LOG_DEBUG(("Remote router has been replaced by backup router, "
2452                     "disabling its connection"));
2453
2454     silc_server_backup_send_replaced(server, sock);
2455
2456     /* Mark the router disabled. The data sent earlier will go but nothing
2457        after this goes to this connection. */
2458     idata->status |= SILC_IDLIST_STATUS_DISABLED;
2459   } else {
2460     /* If it is router announce our stuff to it. */
2461     if (idata->conn_type == SILC_CONN_ROUTER &&
2462         server->server_type == SILC_ROUTER) {
2463       silc_server_announce_servers(server, FALSE, 0, sock);
2464       silc_server_announce_clients(server, 0, sock);
2465       silc_server_announce_channels(server, 0, sock);
2466     }
2467
2468     /* Announce our information to backup router */
2469     if (new_server->server_type == SILC_BACKUP_ROUTER &&
2470         idata->conn_type == SILC_CONN_SERVER &&
2471         server->server_type == SILC_ROUTER) {
2472       silc_server_announce_servers(server, TRUE, 0, sock);
2473       silc_server_announce_clients(server, 0, sock);
2474       silc_server_announce_channels(server, 0, sock);
2475     }
2476
2477     /* If backup router, mark it as one of ours.  This server is considered
2478        to be backup router after this setting. */
2479     if (new_server->server_type == SILC_BACKUP_ROUTER) {
2480       SilcServerConfigRouter *backup;
2481       backup = silc_server_config_find_backup_conn(server, (char *)ip);
2482       if (!backup)
2483         backup = silc_server_config_find_backup_conn(server, (char *)hostname);
2484       if (backup) {
2485         /* Add as our backup router */
2486         silc_server_backup_add(server, new_server, backup->backup_replace_ip,
2487                                backup->backup_replace_port,
2488                                backup->backup_local);
2489       }
2490     }
2491
2492     /* By default the servers connected to backup router are disabled
2493        until backup router has become the primary */
2494     if (server->server_type == SILC_BACKUP_ROUTER &&
2495         idata->conn_type == SILC_CONN_SERVER)
2496       idata->status |= SILC_IDLIST_STATUS_DISABLED;
2497   }
2498
2499   return new_server;
2500 }
2501
2502 /* Processes incoming New ID packet. New ID Payload is used to distribute
2503    information about newly registered clients and servers. */
2504
2505 static void silc_server_new_id_real(SilcServer server,
2506                                     SilcPacketStream sock,
2507                                     SilcPacket packet,
2508                                     SilcBuffer buffer,
2509                                     SilcBool broadcast)
2510 {
2511   SilcIDListData idata = silc_packet_get_context(sock);
2512   SilcIDList id_list;
2513   SilcServerEntry router, server_entry;
2514   SilcPacketStream router_sock;
2515   SilcIDPayload idp;
2516   SilcIdType id_type;
2517   SilcServerID sender_id;
2518   const char *hostname, *ip;
2519
2520   SILC_LOG_DEBUG(("Processing new ID"));
2521
2522   if (idata->conn_type == SILC_CONN_CLIENT ||
2523       server->server_type == SILC_SERVER ||
2524       packet->src_id_type != SILC_ID_SERVER)
2525     return;
2526
2527   idp = silc_id_payload_parse(buffer->data, silc_buffer_len(buffer));
2528   if (!idp)
2529     return;
2530
2531   id_type = silc_id_payload_get_type(idp);
2532
2533   silc_socket_stream_get_info(sock, NULL, &hostname, &ip, NULL);
2534
2535   /* Normal server cannot have other normal server connections */
2536   server_entry = (SilcServerEntry)idata;
2537   if (id_type == SILC_ID_SERVER && idata->conn_type == SILC_CONN_SERVER &&
2538       server_entry->server_type == SILC_SERVER)
2539     goto out;
2540
2541   /* If the packet is coming from server then use the sender as the
2542      origin of the the packet. If it came from router then check the real
2543      sender of the packet and use that as the origin. */
2544   if (idata->conn_type == SILC_CONN_SERVER) {
2545     id_list = server->local_list;
2546     router_sock = sock;
2547     router = server_entry;
2548
2549     /* If the sender is backup router and ID is server (and we are not
2550        backup router) then switch the entry to global list. */
2551     if (server_entry->server_type == SILC_BACKUP_ROUTER &&
2552         id_type == SILC_ID_SERVER &&
2553         server->id_entry->server_type != SILC_BACKUP_ROUTER) {
2554       id_list = server->global_list;
2555       router_sock = server->router ? SILC_PRIMARY_ROUTE(server) : sock;
2556     }
2557   } else {
2558     silc_id_str2id(packet->src_id, packet->src_id_len,
2559                    packet->src_id_type, &sender_id, sizeof(sender_id));
2560     router = silc_idlist_find_server_by_id(server->global_list,
2561                                            &sender_id, TRUE, NULL);
2562     if (!router)
2563       router = silc_idlist_find_server_by_id(server->local_list,
2564                                              &sender_id, TRUE, NULL);
2565     router_sock = sock;
2566     id_list = server->global_list;
2567   }
2568
2569   if (!router)
2570     goto out;
2571
2572   switch(id_type) {
2573   case SILC_ID_CLIENT:
2574     {
2575       SilcClientEntry entry;
2576       SilcClientID id;
2577
2578       if (!silc_id_payload_get_id(idp, &id, sizeof(id)))
2579         goto out;
2580
2581       /* Check that we do not have this client already */
2582       entry = silc_idlist_find_client_by_id(server->global_list,
2583                                             &id, server->server_type,
2584                                             NULL);
2585       if (!entry)
2586         entry = silc_idlist_find_client_by_id(server->local_list,
2587                                               &id, server->server_type,
2588                                               NULL);
2589       if (entry) {
2590         SILC_LOG_DEBUG(("Ignoring client that we already have"));
2591         goto out;
2592       }
2593
2594       SILC_LOG_DEBUG(("New client id(%s) from [%s] %s",
2595                       silc_id_render(&id, SILC_ID_CLIENT),
2596                       idata->conn_type == SILC_CONN_SERVER ?
2597                       "Server" : "Router", hostname));
2598
2599       /* As a router we keep information of all global information in our
2600          global list. Cell wide information however is kept in the local
2601          list. */
2602       entry = silc_idlist_add_client(id_list, NULL, NULL, NULL,
2603                                      &id, router, NULL);
2604       if (!entry) {
2605         SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
2606
2607         /* Inform the sender that the ID is not usable */
2608         silc_server_send_notify_signoff(server, sock, FALSE, &id, NULL);
2609         goto out;
2610       }
2611       entry->nickname = NULL;
2612       entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
2613
2614       if (idata->conn_type == SILC_CONN_SERVER)
2615         server->stat.cell_clients++;
2616       server->stat.clients++;
2617
2618       /* Check if anyone is watching this nickname */
2619       if (server->server_type == SILC_ROUTER && id_list == server->local_list)
2620         silc_server_check_watcher_list(server, entry, NULL, 0);
2621
2622       if (server->server_type == SILC_ROUTER) {
2623         /* Add the client's public key to hash table or get the key with
2624            GETKEY command. */
2625         if (entry->data.public_key) {
2626           if (!silc_hash_table_find_by_context(server->pk_hash,
2627                                                entry->data.public_key,
2628                                                entry, NULL))
2629             silc_hash_table_add(server->pk_hash, entry->data.public_key,
2630                                 entry);
2631         } else
2632           silc_server_send_command(server, router_sock,
2633                                    SILC_COMMAND_GETKEY, ++server->cmd_ident,
2634                                    1, 1, buffer->data,
2635                                    silc_buffer_len(buffer));
2636       }
2637     }
2638     break;
2639
2640   case SILC_ID_SERVER:
2641     {
2642       SilcServerEntry entry;
2643       SilcServerID id;
2644
2645       if (!silc_id_payload_get_id(idp, &id, sizeof(id)))
2646         goto out;
2647
2648       /* If the ID is mine, ignore it. */
2649       if (SILC_ID_SERVER_COMPARE(&id, server->id)) {
2650         SILC_LOG_DEBUG(("Ignoring my own ID as new ID"));
2651         break;
2652       }
2653
2654       /* If the ID is the sender's ID, ignore it (we have it already) */
2655       if (SILC_ID_SERVER_COMPARE(&id, router->id)) {
2656         SILC_LOG_DEBUG(("Ignoring sender's own ID"));
2657         break;
2658       }
2659
2660       /* Check that we do not have this server already */
2661       entry = silc_idlist_find_server_by_id(server->global_list,
2662                                             &id, server->server_type,
2663                                             NULL);
2664       if (!entry)
2665         entry = silc_idlist_find_server_by_id(server->local_list,
2666                                               &id, server->server_type,
2667                                               NULL);
2668       if (entry) {
2669         SILC_LOG_DEBUG(("Ignoring server that we already have"));
2670         goto out;
2671       }
2672
2673       SILC_LOG_DEBUG(("New server id(%s) from [%s] %s",
2674                       silc_id_render(&id, SILC_ID_SERVER),
2675                       idata->conn_type == SILC_CONN_SERVER ?
2676                       "Server" : "Router", hostname));
2677
2678       /* As a router we keep information of all global information in our
2679          global list. Cell wide information however is kept in the local
2680          list. */
2681       entry = silc_idlist_add_server(id_list, NULL, 0, &id, router,
2682                                      router_sock);
2683       if (!entry) {
2684         SILC_LOG_ERROR(("Could not add new server to the ID Cache"));
2685         goto out;
2686       }
2687       entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
2688
2689       if (idata->conn_type == SILC_CONN_SERVER)
2690         server->stat.cell_servers++;
2691       server->stat.servers++;
2692     }
2693     break;
2694
2695   case SILC_ID_CHANNEL:
2696     SILC_LOG_ERROR(("Channel cannot be registered with NEW_ID packet"));
2697     goto out;
2698     break;
2699
2700   default:
2701     goto out;
2702     break;
2703   }
2704
2705   /* If the sender of this packet is server and we are router we need to
2706      broadcast this packet to other routers in the network. */
2707   if (broadcast && server->server_type == SILC_ROUTER &&
2708       idata->conn_type == SILC_CONN_SERVER &&
2709       !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
2710     SILC_LOG_DEBUG(("Broadcasting received New ID packet"));
2711     silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
2712                             packet->type,
2713                             packet->flags | SILC_PACKET_FLAG_BROADCAST,
2714                             buffer->data, silc_buffer_len(buffer));
2715     silc_server_backup_send(server, (SilcServerEntry)idata,
2716                             packet->type, packet->flags,
2717                             packet->buffer.data,
2718                             silc_buffer_len(&packet->buffer),
2719                             FALSE, TRUE);
2720   }
2721
2722  out:
2723   silc_id_payload_free(idp);
2724 }
2725
2726
2727 /* Processes incoming New ID packet. New ID Payload is used to distribute
2728    information about newly registered clients and servers. */
2729
2730 void silc_server_new_id(SilcServer server, SilcPacketStream sock,
2731                         SilcPacket packet)
2732 {
2733   silc_server_new_id_real(server, sock, packet, &packet->buffer, TRUE);
2734 }
2735
2736 /* Receoved New Id List packet, list of New ID payloads inside one
2737    packet. Process the New ID payloads one by one. */
2738
2739 void silc_server_new_id_list(SilcServer server, SilcPacketStream sock,
2740                              SilcPacket packet)
2741 {
2742   SilcIDListData idata = silc_packet_get_context(sock);
2743   SilcBuffer idp;
2744   SilcUInt16 id_len;
2745
2746   SILC_LOG_DEBUG(("Processing New ID List"));
2747
2748   if (idata->conn_type == SILC_CONN_CLIENT ||
2749       packet->src_id_type != SILC_ID_SERVER)
2750     return;
2751
2752   /* If the sender of this packet is server and we are router we need to
2753      broadcast this packet to other routers in the network. Broadcast
2754      this list packet instead of multiple New ID packets. */
2755   if (server->server_type == SILC_ROUTER &&
2756       idata->conn_type == SILC_CONN_SERVER &&
2757       !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
2758     SILC_LOG_DEBUG(("Broadcasting received New ID List packet"));
2759     silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
2760                             packet->type,
2761                             packet->flags | SILC_PACKET_FLAG_BROADCAST,
2762                             packet->buffer.data,
2763                             silc_buffer_len(&packet->buffer));
2764     silc_server_backup_send(server, (SilcServerEntry)idata,
2765                             packet->type, packet->flags,
2766                             packet->buffer.data,
2767                             silc_buffer_len(&packet->buffer),
2768                             FALSE, TRUE);
2769   }
2770
2771   idp = silc_buffer_alloc(256);
2772   if (!idp)
2773     return;
2774
2775   while (silc_buffer_len(&packet->buffer)) {
2776     SILC_GET16_MSB(id_len, packet->buffer.data + 2);
2777     if ((id_len > silc_buffer_len(&packet->buffer)) ||
2778         (id_len > silc_buffer_truelen(idp)))
2779       break;
2780
2781     silc_buffer_pull_tail(idp, 4 + id_len);
2782     silc_buffer_put(idp, packet->buffer.data, 4 + id_len);
2783
2784     /* Process the New ID */
2785     silc_server_new_id_real(server, sock, packet, idp, FALSE);
2786
2787     silc_buffer_push_tail(idp, 4 + id_len);
2788     silc_buffer_pull(&packet->buffer, 4 + id_len);
2789   }
2790
2791   silc_buffer_free(idp);
2792 }
2793
2794 /* Received New Channel packet. Information about new channels in the
2795    network are distributed using this packet. Save the information about
2796    the new channel. This usually comes from router but also normal server
2797    can send this to notify channels it has when it connects to us. */
2798
2799 static void silc_server_new_channel_process(SilcServer server,
2800                                             SilcPacketStream sock,
2801                                             SilcPacket packet,
2802                                             SilcBuffer buffer)
2803 {
2804   SilcIDListData idata = silc_packet_get_context(sock);
2805   SilcChannelPayload payload;
2806   SilcChannelID channel_id;
2807   char *channel_name, *channel_namec = NULL;
2808   SilcUInt32 name_len;
2809   unsigned char *id, cid[32];
2810   SilcUInt32 id_len, cipher_len;
2811   SilcServerEntry server_entry;
2812   SilcChannelEntry channel;
2813   const char *cipher;
2814
2815   if (idata->conn_type == SILC_CONN_CLIENT ||
2816       packet->src_id_type != SILC_ID_SERVER ||
2817       server->server_type == SILC_SERVER)
2818     return;
2819
2820   /* Parse the channel payload */
2821   payload = silc_channel_payload_parse(buffer->data, silc_buffer_len(buffer));
2822   if (!payload)
2823     return;
2824
2825   /* Get the channel ID */
2826   if (!silc_channel_get_id_parse(payload, &channel_id)) {
2827     silc_channel_payload_free(payload);
2828     return;
2829   }
2830
2831   channel_name = silc_channel_get_name(payload, &name_len);
2832   if (name_len > 256) {
2833     channel_name[256] = '\0';
2834     name_len = 256;
2835   }
2836
2837   /* Check channel name */
2838   channel_namec = silc_channel_name_check(channel_name, strlen(channel_name),
2839                                           SILC_STRING_UTF8, 256, NULL);
2840   if (!channel_namec)
2841     return;
2842
2843   id = silc_channel_get_id(payload, &id_len);
2844
2845   server_entry = (SilcServerEntry)idata;
2846
2847   if (idata->conn_type == SILC_CONN_ROUTER) {
2848     /* Add the channel to global list as it is coming from router. It
2849        cannot be our own channel as it is coming from router. */
2850
2851     /* Check that we don't already have this channel */
2852     channel = silc_idlist_find_channel_by_name(server->local_list,
2853                                                channel_namec, NULL);
2854     if (!channel)
2855       channel = silc_idlist_find_channel_by_name(server->global_list,
2856                                                  channel_namec, NULL);
2857     if (!channel) {
2858       SILC_LOG_DEBUG(("New channel id(%s) from [Router] %s",
2859                       silc_id_render(&channel_id, SILC_ID_CHANNEL),
2860                       idata->sconn->remote_host));
2861
2862       channel =
2863         silc_idlist_add_channel(server->global_list, strdup(channel_name),
2864                                 0, silc_id_dup(&channel_id, SILC_ID_CHANNEL),
2865                                 (SilcServerEntry)idata, NULL, NULL, NULL);
2866       if (!channel) {
2867         silc_channel_payload_free(payload);
2868         return;
2869       }
2870       channel->disabled = TRUE;    /* Disabled until someone JOINs */
2871
2872       server->stat.channels++;
2873       if (server->server_type == SILC_ROUTER)
2874         channel->users_resolved = TRUE;
2875     }
2876   } else {
2877     /* The channel is coming from our server, thus it is in our cell
2878        we will add it to our local list. */
2879     SilcBuffer chk;
2880
2881     SILC_LOG_DEBUG(("Channel id(%s) from [Server] %s",
2882                     silc_id_render(&channel_id, SILC_ID_CHANNEL),
2883                     idata->sconn->remote_host));
2884
2885     /* Check that we don't already have this channel */
2886     channel = silc_idlist_find_channel_by_name(server->local_list,
2887                                                channel_namec, NULL);
2888     if (!channel)
2889       channel = silc_idlist_find_channel_by_name(server->global_list,
2890                                                  channel_namec, NULL);
2891
2892     /* If the channel does not exist, then create it. This creates a new
2893        key to the channel as well that we will send to the server. */
2894     if (!channel) {
2895       SILC_LOG_DEBUG(("Channel is new to us"));
2896
2897       /* The protocol says that the Channel ID's IP address must be based
2898          on the router's IP address.  Check whether the ID is based in our
2899          IP and if it is not then create a new ID and enforce the server
2900          to switch the ID. */
2901       if (server_entry->server_type != SILC_BACKUP_ROUTER &&
2902           !SILC_ID_COMPARE(&channel_id, server->id, server->id->ip.data_len)) {
2903         SilcChannelID *tmp;
2904         SILC_LOG_DEBUG(("Forcing the server to change Channel ID"));
2905         if (silc_id_create_channel_id(server, server->id, server->rng, &tmp)) {
2906           silc_server_send_notify_channel_change(server, sock, FALSE,
2907                                                  &channel_id, tmp);
2908           silc_channel_payload_free(payload);
2909           silc_free(tmp);
2910         }
2911
2912         /* Wait that server re-announces this channel */
2913         return;
2914       }
2915
2916       /* Create the channel with the provided Channel ID */
2917       channel = silc_server_create_new_channel_with_id(server, NULL, NULL,
2918                                                        channel_name,
2919                                                        &channel_id, FALSE);
2920       if (!channel) {
2921         silc_channel_payload_free(payload);
2922         return;
2923       }
2924       channel->disabled = TRUE;    /* Disabled until someone JOINs */
2925
2926 #if 0 /* We assume that CMODE_CHANGE notify is sent to us after this. */
2927
2928       /* XXX Dunno if this is supposed to be set in any server type.  If set
2929          here the CMODE_CHANGE that may follow sets mode that we already
2930          have, and we may loose data from the CMODE_CHANGE notify. */
2931       if (server_entry->server_type != SILC_BACKUP_ROUTER)
2932         channel->mode = silc_channel_get_mode(payload);
2933 #endif
2934
2935       /* Send the new channel key to the server */
2936       silc_id_id2str(channel->id, SILC_ID_CHANNEL, cid, sizeof(cid),
2937                      &id_len);
2938       cipher = silc_cipher_get_name(channel->send_key);
2939       cipher_len = strlen(cipher);
2940       chk = silc_channel_key_payload_encode(id_len, cid,
2941                                             cipher_len, cipher,
2942                                             channel->key_len / 8,
2943                                             channel->key);
2944       silc_server_packet_send(server, sock, SILC_PACKET_CHANNEL_KEY, 0,
2945                               chk->data, silc_buffer_len(chk));
2946       silc_buffer_free(chk);
2947     } else {
2948       /* The channel exist by that name, check whether the ID's match.
2949          If they don't then we'll force the server to use the ID we have.
2950          We also create a new key for the channel. */
2951       SilcBuffer modes = NULL, users = NULL, users_modes = NULL;
2952
2953       SILC_LOG_DEBUG(("Channel already exists"));
2954
2955       if (!SILC_ID_CHANNEL_COMPARE(&channel_id, channel->id)) {
2956         /* They don't match, send CHANNEL_CHANGE notify to the server to
2957            force the ID change. */
2958         SILC_LOG_DEBUG(("Forcing the server to change Channel ID"));
2959         silc_server_send_notify_channel_change(server, sock, FALSE,
2960                                                &channel_id, channel->id);
2961         silc_channel_payload_free(payload);
2962
2963         /* Wait that server re-announces this channel */
2964         return;
2965       }
2966
2967 #if 0 /* We will announce our CMODE anyway for this channel, so no need
2968          to check it (implicit enforce). */
2969
2970       /* If the mode is different from what we have then enforce the
2971          mode change. */
2972       mode = silc_channel_get_mode(payload);
2973       if (channel->mode != mode) {
2974         SILC_LOG_DEBUG(("Forcing the server to change channel mode"));
2975         silc_server_send_notify_cmode(server, sock, FALSE, channel,
2976                                       channel->mode, server->id,
2977                                       SILC_ID_SERVER, channel->cipher,
2978                                       channel->hmac_name,
2979                                       channel->passphrase,
2980                                       channel->founder_key);
2981       }
2982 #endif
2983
2984       /* Create new key for the channel and send it to the server and
2985          everybody else possibly on the channel. */
2986       if (!(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
2987
2988         if (silc_hash_table_count(channel->user_list)) {
2989           if (!silc_server_create_channel_key(server, channel, 0)) {
2990             silc_channel_payload_free(payload);
2991             return;
2992           }
2993
2994           /* Send to the channel */
2995           silc_server_send_channel_key(server, sock, channel, FALSE);
2996         }
2997
2998         /* Send to the server */
2999         silc_id_id2str(channel->id, SILC_ID_CHANNEL, cid, sizeof(cid),
3000                        &id_len);
3001         cipher = silc_cipher_get_name(channel->send_key);
3002         cipher_len = strlen(cipher);
3003         chk = silc_channel_key_payload_encode(id_len, cid,
3004                                               cipher_len, cipher,
3005                                               channel->key_len / 8,
3006                                               channel->key);
3007         silc_server_packet_send(server, sock, SILC_PACKET_CHANNEL_KEY, 0,
3008                                 chk->data, silc_buffer_len(chk));
3009         silc_buffer_free(chk);
3010       }
3011
3012       /* Since the channel is coming from server and we also know about it
3013          then send the JOIN notify to the server so that it see's our
3014          users on the channel "joining" the channel. */
3015       silc_server_announce_get_channel_users(server, channel, &modes, &users,
3016                                              &users_modes);
3017       if (users) {
3018         silc_buffer_push(users, users->data - users->head);
3019         silc_server_packet_send(server, sock,
3020                                 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3021                                 users->data, silc_buffer_len(users));
3022         silc_buffer_free(users);
3023       }
3024       if (modes) {
3025         silc_buffer_push(modes, modes->data - modes->head);
3026         silc_server_packet_send_dest(server, sock,
3027                                      SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3028                                      channel->id, SILC_ID_CHANNEL,
3029                                      modes->data, silc_buffer_len(modes));
3030         silc_buffer_free(modes);
3031       }
3032       if (users_modes) {
3033         silc_buffer_push(users_modes, users_modes->data - users_modes->head);
3034         silc_server_packet_send_dest(server, sock,
3035                                      SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3036                                      channel->id, SILC_ID_CHANNEL,
3037                                      users_modes->data,
3038                                      silc_buffer_len(users_modes));
3039         silc_buffer_free(users_modes);
3040       }
3041       if (channel->topic) {
3042         silc_server_send_notify_topic_set(server, sock,
3043                                           server->server_type == SILC_ROUTER ?
3044                                           TRUE : FALSE, channel,
3045                                           server->id, SILC_ID_SERVER,
3046                                           channel->topic);
3047       }
3048     }
3049   }
3050
3051   /* If the sender of this packet is server and we are router we need to
3052      broadcast this packet to other routers in the network. Broadcast
3053      this list packet instead of multiple New Channel packets. */
3054   if (server->server_type == SILC_ROUTER &&
3055       idata->conn_type == SILC_CONN_SERVER &&
3056       !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
3057     SILC_LOG_DEBUG(("Broadcasting received New Channel packet"));
3058     silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
3059                             packet->type,
3060                             packet->flags | SILC_PACKET_FLAG_BROADCAST,
3061                             buffer->data, silc_buffer_len(buffer));
3062     silc_server_backup_send(server, (SilcServerEntry)idata,
3063                             packet->type, packet->flags,
3064                             buffer->data, silc_buffer_len(buffer),
3065                             FALSE, TRUE);
3066   }
3067
3068   silc_free(channel_namec);
3069   silc_channel_payload_free(payload);
3070 }
3071
3072 /* Received New Channel packet. Information about new channels in the
3073    network are distributed using this packet. Save the information about
3074    the new channel. This usually comes from router but also normal server
3075    can send this to notify channels it has when it connects to us. */
3076
3077 void silc_server_new_channel(SilcServer server,
3078                              SilcPacketStream sock,
3079                              SilcPacket packet)
3080 {
3081   silc_server_new_channel_process(server, sock, packet, &packet->buffer);
3082 }
3083
3084 /* Received New Channel List packet, list of New Channel List payloads inside
3085    one packet. Process the New Channel payloads one by one. */
3086
3087 void silc_server_new_channel_list(SilcServer server,
3088                                   SilcPacketStream sock,
3089                                   SilcPacket packet)
3090 {
3091   SilcIDListData idata = silc_packet_get_context(sock);
3092   SilcBuffer buffer;
3093   SilcUInt16 len1, len2;
3094
3095   SILC_LOG_DEBUG(("Processing New Channel List"));
3096
3097   if (idata->conn_type == SILC_CONN_CLIENT ||
3098       packet->src_id_type != SILC_ID_SERVER ||
3099       server->server_type == SILC_SERVER)
3100     return;
3101
3102   buffer = silc_buffer_alloc(512);
3103   if (!buffer)
3104     return;
3105
3106   while (silc_buffer_len(&packet->buffer)) {
3107     SILC_GET16_MSB(len1, packet->buffer.data);
3108     if ((len1 > silc_buffer_len(&packet->buffer)) ||
3109         (len1 > silc_buffer_truelen(buffer)))
3110       break;
3111
3112     SILC_GET16_MSB(len2, packet->buffer.data + 2 + len1);
3113     if ((len2 > silc_buffer_len(&packet->buffer)) ||
3114         (len2 > silc_buffer_truelen(buffer)))
3115       break;
3116
3117     silc_buffer_pull_tail(buffer, 8 + len1 + len2);
3118     silc_buffer_put(buffer, packet->buffer.data, 8 + len1 + len2);
3119
3120     /* Process the New Channel */
3121     silc_server_new_channel_process(server, sock, packet, buffer);
3122
3123     silc_buffer_push_tail(buffer, 8 + len1 + len2);
3124     silc_buffer_pull(&packet->buffer, 8 + len1 + len2);
3125   }
3126
3127   silc_buffer_free(buffer);
3128 }
3129
3130 /* Received key agreement packet. This packet is never for us. It is to
3131    the client in the packet's destination ID. Sending of this sort of packet
3132    equals sending private message, ie. it is sent point to point from
3133    one client to another. */
3134
3135 void silc_server_key_agreement(SilcServer server,
3136                                SilcPacketStream sock,
3137                                SilcPacket packet)
3138 {
3139   SilcPacketStream dst_sock;
3140   SilcIDListData idata;
3141
3142   SILC_LOG_DEBUG(("Start"));
3143
3144   if (packet->src_id_type != SILC_ID_CLIENT ||
3145       packet->dst_id_type != SILC_ID_CLIENT)
3146     return;
3147
3148   if (!packet->dst_id)
3149     return;
3150
3151   /* Get the route to the client */
3152   dst_sock = silc_server_get_client_route(server, packet->dst_id,
3153                                           packet->dst_id_len, NULL,
3154                                           &idata, NULL);
3155   if (!dst_sock)
3156     return;
3157
3158   /* Relay the packet */
3159   silc_server_packet_route(server, dst_sock, packet);
3160 }
3161
3162 /* Received connection auth request packet that is used during connection
3163    phase to resolve the mandatory authentication method.  This packet can
3164    actually be received at anytime but usually it is used only during
3165    the connection authentication phase. Now, protocol says that this packet
3166    can come from client or server, however, we support only this coming
3167    from client and expect that server always knows what authentication
3168    method to use. */
3169
3170 void silc_server_connection_auth_request(SilcServer server,
3171                                          SilcPacketStream sock,
3172                                          SilcPacket packet)
3173 {
3174   SilcServerConfigClient *client = NULL;
3175   SilcUInt16 conn_type;
3176   int ret;
3177   SilcAuthMethod auth_meth = SILC_AUTH_NONE;
3178   const char *hostname, *ip;
3179
3180   if (packet->src_id_type && packet->src_id_type != SILC_ID_CLIENT) {
3181     SILC_LOG_DEBUG(("Request not from client"));
3182     return;
3183   }
3184
3185   silc_socket_stream_get_info(sock, NULL, &hostname, &ip, NULL);
3186
3187   /* Parse the payload */
3188   ret = silc_buffer_unformat(&packet->buffer,
3189                              SILC_STR_UI_SHORT(&conn_type),
3190                              SILC_STR_UI_SHORT(NULL),
3191                              SILC_STR_END);
3192   if (ret == -1)
3193     return;
3194
3195   if (conn_type != SILC_CONN_CLIENT)
3196     return;
3197
3198   /* Get the authentication method for the client */
3199   auth_meth = SILC_AUTH_NONE;
3200   client = silc_server_config_find_client(server, (char *)ip);
3201   if (!client)
3202     client = silc_server_config_find_client(server, (char *)hostname);
3203   if (client) {
3204     if (client->passphrase) {
3205       if (client->publickeys && !server->config->prefer_passphrase_auth)
3206         auth_meth = SILC_AUTH_PUBLIC_KEY;
3207       else
3208         auth_meth = SILC_AUTH_PASSWORD;
3209     } else if (client->publickeys)
3210       auth_meth = SILC_AUTH_PUBLIC_KEY;
3211   }
3212
3213   SILC_LOG_DEBUG(("Authentication method is [%s]",
3214                   (auth_meth == SILC_AUTH_NONE ? "None" :
3215                    auth_meth == SILC_AUTH_PASSWORD ? "Passphrase" :
3216                    "Digital signatures")));
3217
3218   /* Send it back to the client */
3219   silc_server_send_connection_auth_request(server, sock, conn_type, auth_meth);
3220 }
3221
3222 /* Received file transger packet. This packet is never for us. It is to
3223    the client in the packet's destination ID. Sending of this sort of packet
3224    equals sending private message, ie. it is sent point to point from
3225    one client to another. */
3226
3227 void silc_server_ftp(SilcServer server,
3228                      SilcPacketStream sock,
3229                      SilcPacket packet)
3230 {
3231   SilcPacketStream dst_sock;
3232   SilcIDListData idata;
3233
3234   SILC_LOG_DEBUG(("Start"));
3235
3236   if (packet->src_id_type != SILC_ID_CLIENT ||
3237       packet->dst_id_type != SILC_ID_CLIENT)
3238     return;
3239
3240   if (!packet->dst_id)
3241     return;
3242
3243   /* Get the route to the client */
3244   dst_sock = silc_server_get_client_route(server, packet->dst_id,
3245                                           packet->dst_id_len, NULL,
3246                                           &idata, NULL);
3247   if (!dst_sock)
3248     return;
3249
3250   /* Relay the packet */
3251   silc_server_packet_route(server, dst_sock, packet);
3252 }
3253
3254 typedef struct {
3255   SilcServer server;
3256   SilcPacketStream sock;
3257   SilcPacket packet;
3258   SilcClientID client_id;
3259 } *SilcServerResumeResolve;
3260
3261 SILC_SERVER_CMD_FUNC(resume_resolve)
3262 {
3263   SilcServerResumeResolve r = (SilcServerResumeResolve)context;
3264   SilcServer server = r->server;
3265   SilcPacketStream sock = r->sock;
3266   SilcServerCommandReplyContext reply = context2;
3267   SilcClientEntry client;
3268   const char *hostname, *ip;
3269
3270   SILC_LOG_DEBUG(("Start"));
3271
3272   silc_socket_stream_get_info(sock, NULL, &hostname, &ip, NULL);
3273
3274   if (!reply || !silc_command_get_status(reply->payload, NULL, NULL)) {
3275     SILC_LOG_ERROR(("Client %s (%s) tried to resume unknown client, "
3276                     "closing connection", hostname, ip));
3277     silc_server_disconnect_remote(server, sock,
3278                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3279                                   "Resuming not possible");
3280     silc_server_free_sock_user_data(server, sock, NULL);
3281     goto out;
3282   }
3283
3284   if (reply && silc_command_get(reply->payload) == SILC_COMMAND_WHOIS) {
3285     /* Get entry to the client, and resolve it if we don't have it. */
3286     client = silc_idlist_find_client_by_id(server->local_list,
3287                                            &r->client_id, TRUE, NULL);
3288     if (!client) {
3289       client = silc_idlist_find_client_by_id(server->global_list,
3290                                              &r->client_id, TRUE, NULL);
3291       if (!client) {
3292         SILC_LOG_ERROR(("Client %s (%s) tried to resume unknown client, "
3293                         "closing connection", hostname, ip));
3294         silc_server_disconnect_remote(server, sock,
3295                                       SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3296                                       "Resuming not possible");
3297         silc_server_free_sock_user_data(server, sock, NULL);
3298         goto out;
3299       }
3300     }
3301
3302     if (!(client->mode & SILC_UMODE_DETACHED)) {
3303       SILC_LOG_ERROR(("Client %s (%s) tried to resume un-detached client, "
3304                       "closing connection", hostname, ip));
3305       silc_server_disconnect_remote(server, sock,
3306                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3307                                     "Resuming not possible");
3308       silc_server_free_sock_user_data(server, sock, NULL);
3309       goto out;
3310     }
3311
3312     client->data.status |= SILC_IDLIST_STATUS_RESUME_RES;
3313   }
3314
3315   /* Reprocess the packet */
3316   silc_server_resume_client(server, sock, r->packet);
3317
3318  out:
3319   silc_packet_stream_unref(r->sock);
3320   silc_free(r);
3321 }
3322
3323 /* Received client resuming packet.  This is used to resume detached
3324    client session.  It can be sent by the client who wishes to resume
3325    but this is also sent by servers and routers to notify other routers
3326    that the client is not detached anymore. */
3327
3328 void silc_server_resume_client(SilcServer server,
3329                                SilcPacketStream sock,
3330                                SilcPacket packet)
3331 {
3332   SilcBuffer buffer = &packet->buffer, buf;
3333   SilcIDListData idata = silc_packet_get_context(sock);
3334   SilcIDCacheEntry id_cache = NULL;
3335   SilcClientEntry detached_client;
3336   SilcClientID client_id;
3337   unsigned char *id_string, *auth = NULL, *nicknamec = NULL;
3338   unsigned char cid[32];
3339   SilcUInt32 cid_len;
3340   SilcUInt16 id_len, auth_len = 0;
3341   SilcBool resolved, local, nick_change = FALSE, resolve = FALSE;
3342   SilcChannelEntry channel;
3343   SilcHashTableList htl;
3344   SilcChannelClientEntry chl;
3345   SilcServerResumeResolve r;
3346   const char *cipher, *hostname, *ip;
3347
3348   silc_socket_stream_get_info(sock, NULL, &hostname, &ip, NULL);
3349
3350   if (silc_buffer_unformat(buffer,
3351                            SILC_STR_UI16_NSTRING(&id_string, &id_len),
3352                            SILC_STR_END) < 0) {
3353     if (idata->conn_type == SILC_CONN_CLIENT) {
3354       SILC_LOG_ERROR(("Client %s (%s) sent incomplete resume information, "
3355                       "closing connection", hostname, ip));
3356       silc_server_disconnect_remote(server, sock,
3357                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3358                                     "Resuming not possible");
3359       silc_server_free_sock_user_data(server, sock, NULL);
3360     }
3361     goto out;
3362   }
3363
3364   silc_id_str2id(id_string, id_len, SILC_ID_CLIENT, &client_id,
3365                  sizeof(client_id));
3366
3367   if (idata->conn_type == SILC_CONN_CLIENT) {
3368     /* Client send this and is attempting to resume to old client session */
3369     SilcClientEntry client;
3370     SilcBuffer keyp;
3371
3372     silc_buffer_pull(buffer, 2 + id_len);
3373     auth = buffer->data;
3374     auth_len = silc_buffer_len(buffer);
3375     silc_buffer_push(buffer, 2 + id_len);
3376
3377     if (auth_len < 128) {
3378       SILC_LOG_ERROR(("Client %s (%s) sent incomplete resume information, "
3379                       "closing connection", hostname, ip));
3380       silc_server_disconnect_remote(server, sock,
3381                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3382                                     "Resuming not possible");
3383       silc_server_free_sock_user_data(server, sock, NULL);
3384       goto out;
3385     }
3386
3387     /* Take client entry of this connection */
3388     client = (SilcClientEntry)idata;
3389
3390     /* Get entry to the client, and resolve it if we don't have it. */
3391     detached_client = silc_server_query_client(server, &client_id, FALSE,
3392                                                &resolved);
3393     if (!detached_client) {
3394       if (resolved) {
3395         /* The client info is being resolved. Reprocess this packet after
3396            receiving the reply to the query. */
3397         SILC_LOG_DEBUG(("Resolving client"));
3398         r = silc_calloc(1, sizeof(*r));
3399         if (!r)
3400           goto out;
3401         silc_packet_stream_ref(sock);
3402         r->server = server;
3403         r->sock = sock;
3404         r->packet = packet;
3405         r->client_id = client_id;
3406         silc_server_command_pending(server, SILC_COMMAND_WHOIS,
3407                                     server->cmd_ident,
3408                                     silc_server_command_resume_resolve, r);
3409         return;
3410       } else {
3411         SILC_LOG_ERROR(("Client %s (%s) tried to resume unknown client, "
3412                         "closing connection", hostname, ip));
3413         silc_server_disconnect_remote(server, sock,
3414                                       SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3415                                       "Resuming not possible");
3416         silc_server_free_sock_user_data(server, sock, NULL);
3417         goto out;
3418       }
3419     }
3420
3421     if (detached_client->data.status & SILC_IDLIST_STATUS_RESUMED) {
3422       SILC_LOG_ERROR(("Client %s (%s) tried to attach more than once, "
3423                       "closing connection", hostname, ip));
3424       silc_server_disconnect_remote(server, sock,
3425                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3426                                     "Resuming not possible");
3427       silc_server_free_sock_user_data(server, sock, NULL);
3428       goto out;
3429     }
3430
3431     if (detached_client->resuming_client &&
3432         detached_client->resuming_client != client) {
3433       SILC_LOG_ERROR(("Client %s (%s) tried to attach more than once, "
3434                       "closing connection", hostname, ip));
3435       silc_server_disconnect_remote(server, sock,
3436                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3437                                     "Resuming not possible");
3438       silc_server_free_sock_user_data(server, sock, NULL);
3439       goto out;
3440     }
3441
3442     if (!detached_client->resuming_client)
3443       detached_client->resuming_client = client;
3444
3445     if (!(detached_client->mode & SILC_UMODE_DETACHED))
3446       resolve = TRUE;
3447     if (!silc_hash_table_count(detached_client->channels) &&
3448         detached_client->router)
3449       resolve = TRUE;
3450     if (!detached_client->nickname)
3451       resolve = TRUE;
3452     if (detached_client->data.status & SILC_IDLIST_STATUS_RESUME_RES)
3453       resolve = FALSE;
3454
3455     if (resolve) {
3456       if (server->server_type == SILC_SERVER && !server->standalone) {
3457         /* The client info is being resolved. Reprocess this packet after
3458            receiving the reply to the query. */
3459         SILC_LOG_DEBUG(("Resolving client info"));
3460         silc_server_query_client(server, &client_id, TRUE, NULL);
3461         r = silc_calloc(1, sizeof(*r));
3462         if (!r)
3463           return;
3464         silc_packet_stream_ref(sock);
3465         r->server = server;
3466         r->sock = sock;
3467         r->packet = packet;
3468         r->client_id = client_id;
3469         silc_server_command_pending(server, SILC_COMMAND_WHOIS,
3470                                     server->cmd_ident,
3471                                     silc_server_command_resume_resolve, r);
3472         return;
3473       }
3474       if (server->server_type == SILC_SERVER) {
3475         SILC_LOG_ERROR(("Client %s (%s) tried to resume un-detached client, "
3476                         "closing connection", hostname, ip));
3477         silc_server_disconnect_remote(server, sock,
3478                                       SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3479                                       "Resuming not possible");
3480         silc_server_free_sock_user_data(server, sock, NULL);
3481         goto out;
3482       }
3483     }
3484
3485     /* Check that we have the public key of the client, if not then we must
3486        resolve it first. */
3487     if (!detached_client->data.public_key) {
3488       if (server->server_type == SILC_SERVER && server->standalone) {
3489         SILC_LOG_ERROR(("Detached client's public key not present, "
3490                         "closing connection"));
3491         silc_server_disconnect_remote(server, sock,
3492                                       SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3493                                       "Resuming not possible");
3494         silc_server_free_sock_user_data(server, sock, NULL);
3495         goto out;
3496       } else {
3497         /* We must retrieve the detached client's public key by sending
3498            GETKEY command. Reprocess this packet after receiving the key */
3499         SilcBuffer idp = silc_id_payload_encode(&client_id, SILC_ID_CLIENT);
3500         SilcPacketStream dest_sock =
3501           silc_server_get_client_route(server, NULL, 0, &client_id,
3502                                        NULL, NULL);
3503
3504         SILC_LOG_DEBUG(("Resolving client public key"));
3505
3506         silc_server_send_command(server, dest_sock ? dest_sock :
3507                                  SILC_PRIMARY_ROUTE(server),
3508                                  SILC_COMMAND_GETKEY, ++server->cmd_ident,
3509                                  1, 1, idp->data, silc_buffer_len(idp));
3510
3511         r = silc_calloc(1, sizeof(*r));
3512         if (!r)
3513           return;
3514         silc_packet_stream_ref(sock);
3515         r->server = server;
3516         r->sock = sock;
3517         r->packet = packet;
3518         r->client_id = client_id;
3519         silc_server_command_pending(server, SILC_COMMAND_GETKEY,
3520                                     server->cmd_ident,
3521                                     silc_server_command_resume_resolve, r);
3522
3523         silc_buffer_free(idp);
3524         return;
3525       }
3526     } else if (!silc_pkcs_public_key_compare(detached_client->data.public_key,
3527                                              idata->public_key)) {
3528       /* We require that the connection and resuming authentication data
3529          must be using same key pair. */
3530       SILC_LOG_ERROR(("Resuming attempted with wrong public key, "
3531                       "closing connection"));
3532       silc_server_disconnect_remote(server, sock,
3533                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3534                                     "Resuming not possible");
3535       silc_server_free_sock_user_data(server, sock, NULL);
3536       goto out;
3537     }
3538
3539     /* Verify the authentication payload.  This has to be successful in
3540        order to allow the resuming */
3541     if (!idata->hash ||
3542         !silc_auth_verify_data(auth, auth_len, SILC_AUTH_PUBLIC_KEY,
3543                                detached_client->data.public_key, 0,
3544                                idata->hash, detached_client->id,
3545                                SILC_ID_CLIENT)) {
3546       SILC_LOG_ERROR(("Client %s (%s) resume authentication failed, "
3547                       "closing connection", hostname, ip));
3548       silc_server_disconnect_remote(server, sock,
3549                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3550                                     "Resuming not possible");
3551       silc_server_free_sock_user_data(server, sock, NULL);
3552       goto out;
3553     }
3554
3555     /* Check nickname */
3556     nicknamec = silc_identifier_check(detached_client->nickname,
3557                                       strlen(detached_client->nickname),
3558                                       SILC_STRING_UTF8, 128, NULL);
3559     if (!nicknamec) {
3560       silc_server_disconnect_remote(server, sock,
3561                                     SILC_STATUS_ERR_BAD_NICKNAME,
3562                                     "Malformed nickname, cannot resume");
3563       silc_server_free_sock_user_data(server, sock, NULL);
3564       goto out;
3565     }
3566
3567     /* If the ID is not based in our ID then change it */
3568     if (!SILC_ID_COMPARE(detached_client->id, server->id,
3569                          server->id->ip.data_len)) {
3570       SilcClientID *new_id;
3571       if (!silc_id_create_client_id(server, server->id, server->rng,
3572                                     server->md5hash, nicknamec,
3573                                     strlen(nicknamec), &new_id)) {
3574         silc_server_disconnect_remote(server, sock,
3575                                       SILC_STATUS_ERR_BAD_NICKNAME,
3576                                       "Resuming not possible");
3577         silc_server_free_sock_user_data(server, sock, NULL);
3578         goto out;
3579       }
3580       nick_change = TRUE;
3581       client_id = *new_id;
3582       silc_free(new_id);
3583     }
3584
3585     /* Now resume the client to the network */
3586
3587     silc_schedule_task_del_by_context(server->schedule, detached_client);
3588     silc_packet_set_context(sock, detached_client);
3589     detached_client->connection = sock;
3590
3591     if (detached_client->data.public_key)
3592       silc_hash_table_del_by_context(server->pk_hash,
3593                                      detached_client->data.public_key,
3594                                      detached_client);
3595     if (idata->public_key)
3596       silc_hash_table_del_by_context(server->pk_hash,
3597                                      idata->public_key, idata);
3598
3599     /* Take new keys and stuff into use in the old entry */
3600     silc_idlist_del_data(detached_client);
3601     silc_idlist_add_data(detached_client, idata);
3602
3603     if (detached_client->data.public_key)
3604       silc_hash_table_add(server->pk_hash,
3605                           detached_client->data.public_key, detached_client);
3606
3607     detached_client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
3608     detached_client->data.status |= SILC_IDLIST_STATUS_RESUMED;
3609     detached_client->data.status |= SILC_IDLIST_STATUS_LOCAL;
3610     detached_client->data.status &= ~SILC_IDLIST_STATUS_RESUME_RES;
3611     detached_client->mode &= ~SILC_UMODE_DETACHED;
3612     server->stat.my_detached--;
3613
3614     /* We are finished - reset resuming client */
3615     detached_client->resuming_client = NULL;
3616
3617     /* Check if anyone is watching this client */
3618     if (server->server_type == SILC_ROUTER)
3619       silc_server_check_watcher_list(server, detached_client, NULL,
3620                                      SILC_NOTIFY_TYPE_UMODE_CHANGE);
3621
3622     /* Delete this current client entry since we're resuming to old one. */
3623     server->stat.my_clients--;
3624     server->stat.clients--;
3625     if (server->stat.cell_clients)
3626       server->stat.cell_clients--;
3627     silc_server_remove_from_channels(server, NULL, client, FALSE,
3628                                      NULL, FALSE, FALSE);
3629     silc_server_del_from_watcher_list(server, client);
3630     if (!silc_idlist_del_client(server->local_list, client))
3631       silc_idlist_del_client(server->global_list, client);
3632     client = detached_client;
3633     silc_free(client->servername);
3634     client->servername = strdup(server->server_name);
3635
3636     /* Send the RESUME_CLIENT packet to our primary router so that others
3637        know this client isn't detached anymore. */
3638     buf = silc_buffer_alloc_size(2 + id_len);
3639     silc_buffer_format(buf,
3640                        SILC_STR_UI_SHORT(id_len),
3641                        SILC_STR_UI_XNSTRING(id_string, id_len),
3642                        SILC_STR_END);
3643
3644     /* Send to primary router */
3645     silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
3646                             SILC_PACKET_RESUME_CLIENT, 0,
3647                             buf->data, silc_buffer_len(buf));
3648     silc_server_backup_send(server, client->router,
3649                             SILC_PACKET_RESUME_CLIENT, 0,
3650                             buf->data, silc_buffer_len(buf), TRUE, TRUE);
3651
3652     /* As router we must deliver this packet directly to the original
3653        server whom this client was earlier. */
3654     if (server->server_type == SILC_ROUTER && client->router &&
3655         client->router->server_type != SILC_ROUTER)
3656       silc_server_packet_send(server, client->router->connection,
3657                               SILC_PACKET_RESUME_CLIENT, 0,
3658                               buf->data, silc_buffer_len(buf));
3659     silc_buffer_free(buf);
3660     client->router = NULL;
3661
3662     if (nick_change) {
3663       /* Notify about Client ID change, nickname doesn't actually change. */
3664       silc_server_send_notify_nick_change(server, SILC_PRIMARY_ROUTE(server),
3665                                           SILC_BROADCAST(server),
3666                                           client->id, &client_id,
3667                                           client->nickname);
3668     }
3669
3670     /* Resolve users on those channels that client has joined but we
3671        haven't resolved user list yet. */
3672     if (server->server_type == SILC_SERVER && !server->standalone) {
3673       silc_hash_table_list(client->channels, &htl);
3674       while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3675         channel = chl->channel;
3676         SILC_LOG_DEBUG(("Resolving users for %s channel",
3677                         channel->channel_name));
3678         if (channel->disabled || !channel->users_resolved) {
3679           silc_server_send_command(server, SILC_PRIMARY_ROUTE(server),
3680                                    SILC_COMMAND_USERS, ++server->cmd_ident,
3681                                    1, 2, channel->channel_name,
3682                                    strlen(channel->channel_name));
3683         }
3684       }
3685       silc_hash_table_list_reset(&htl);
3686     }
3687
3688     /* Send the new client ID to the client. After this client may start
3689        receiving other packets, and may start sending packets too. */
3690     silc_server_send_new_id(server, sock, FALSE, &client_id, SILC_ID_CLIENT,
3691                             silc_id_get_len(&client_id, SILC_ID_CLIENT));
3692
3693     if (nick_change) {
3694       /* Send NICK change notify to channels as well. */
3695       SilcBuffer oidp, nidp;
3696       oidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3697       nidp = silc_id_payload_encode(&client_id, SILC_ID_CLIENT);
3698       silc_server_send_notify_on_channels(server, NULL, client,
3699                                           SILC_NOTIFY_TYPE_NICK_CHANGE, 3,
3700                                           oidp->data, silc_buffer_len(oidp),
3701                                           nidp->data, silc_buffer_len(nidp),
3702                                           client->nickname,
3703                                           strlen(client->nickname));
3704       silc_buffer_free(oidp);
3705       silc_buffer_free(nidp);
3706     }
3707
3708     /* Add the client again to the ID cache to get it to correct list */
3709     if (!silc_idcache_del_by_context(server->local_list->clients, client,
3710                                      NULL))
3711       silc_idcache_del_by_context(server->global_list->clients, client, NULL);
3712     silc_free(client->id);
3713     *client->id = client_id;
3714     silc_idcache_add(server->local_list->clients, nicknamec,
3715                      client->id, client);
3716
3717     /* Send some nice info to the client */
3718     silc_server_send_connect_notifys(server, sock, client);
3719
3720     /* Send all channel keys of channels the client has joined */
3721     silc_hash_table_list(client->channels, &htl);
3722     while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3723       SilcBool created = FALSE;
3724       channel = chl->channel;
3725
3726       if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY)
3727         continue;
3728
3729       /* If we don't have channel key, then create one */
3730       if (!channel->send_key) {
3731         if (!silc_server_create_channel_key(server, channel, 0))
3732           continue;
3733         created = TRUE;
3734       }
3735
3736       silc_id_id2str(channel->id, SILC_ID_CHANNEL, cid, sizeof(cid),
3737                      &cid_len);
3738       cipher = silc_cipher_get_name(channel->send_key);
3739       keyp =
3740         silc_channel_key_payload_encode(cid_len, cid,
3741                                         strlen(cipher), cipher,
3742                                         channel->key_len / 8, channel->key);
3743
3744       /* Send the channel key to the client */
3745       silc_server_packet_send(server, sock, SILC_PACKET_CHANNEL_KEY, 0,
3746                               keyp->data, silc_buffer_len(keyp));
3747
3748       /* Distribute the channel key to channel */
3749       if (created) {
3750         silc_server_send_channel_key(server, NULL, channel,
3751                                      server->server_type == SILC_ROUTER ?
3752                                      FALSE : !server->standalone);
3753         silc_server_backup_send(server, NULL, SILC_PACKET_CHANNEL_KEY, 0,
3754                                 keyp->data, silc_buffer_len(keyp),
3755                                 FALSE, TRUE);
3756       }
3757
3758       silc_buffer_free(keyp);
3759     }
3760     silc_hash_table_list_reset(&htl);
3761
3762   } else if (idata->conn_type != SILC_CONN_CLIENT) {
3763     /* Server or router sent this to us to notify that that a client has
3764        been resumed. */
3765     SilcServerEntry server_entry;
3766     SilcServerID server_id;
3767
3768     /* Get entry to the client, and resolve it if we don't have it. */
3769     detached_client = silc_idlist_find_client_by_id(server->local_list,
3770                                                     &client_id, TRUE,
3771                                                     &id_cache);
3772     if (!detached_client) {
3773       detached_client = silc_idlist_find_client_by_id(server->global_list,
3774                                                       &client_id, TRUE,
3775                                                       &id_cache);
3776       if (!detached_client) {
3777         SILC_LOG_DEBUG(("Resuming client is unknown"));
3778         goto out;
3779       }
3780     }
3781
3782     /* Check that the client has not been resumed already because it is
3783        protocol error to attempt to resume more than once.  The client
3784        will be killed if this protocol error occurs. */
3785     if (detached_client->data.status & SILC_IDLIST_STATUS_RESUMED &&
3786         !(detached_client->mode & SILC_UMODE_DETACHED)) {
3787       /* The client is clearly attempting to resume more than once and
3788          perhaps playing around by resuming from several different places
3789          at the same time. */
3790       SILC_LOG_DEBUG(("Attempting to re-resume client, killing both"));
3791       silc_server_kill_client(server, detached_client, NULL,
3792                               server->id, SILC_ID_SERVER);
3793       goto out;
3794     }
3795
3796     /* Check whether client is detached at all */
3797     if (!(detached_client->mode & SILC_UMODE_DETACHED)) {
3798       SILC_LOG_DEBUG(("Client is not detached"));
3799       goto out;
3800     }
3801
3802     /* Check nickname */
3803     if (detached_client->nickname) {
3804       nicknamec = silc_identifier_check(detached_client->nickname,
3805                                         strlen(detached_client->nickname),
3806                                         SILC_STRING_UTF8, 128, NULL);
3807       if (!nicknamec)
3808         goto out;
3809     }
3810
3811     SILC_LOG_DEBUG(("Resuming detached client"));
3812
3813     /* If the sender of this packet is server and we are router we need to
3814        broadcast this packet to other routers in the network. */
3815     if (server->server_type == SILC_ROUTER &&
3816         idata->conn_type == SILC_CONN_SERVER &&
3817         !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
3818       SILC_LOG_DEBUG(("Broadcasting received Resume Client packet"));
3819       silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
3820                               packet->type,
3821                               packet->flags | SILC_PACKET_FLAG_BROADCAST,
3822                               buffer->data, silc_buffer_len(buffer));
3823       silc_server_backup_send(server, (SilcServerEntry)idata,
3824                               packet->type, packet->flags,
3825                               packet->buffer.data,
3826                               silc_buffer_len(&packet->buffer),
3827                               FALSE, TRUE);
3828     }
3829
3830     /* Client is detached, and now it is resumed.  Remove the detached
3831        mode and mark that it is resumed. */
3832
3833     if (detached_client->data.public_key)
3834       silc_hash_table_del_by_context(server->pk_hash,
3835                                      detached_client->data.public_key,
3836                                      detached_client);
3837
3838     silc_idlist_del_data(detached_client);
3839     detached_client->mode &= ~SILC_UMODE_DETACHED;
3840     detached_client->data.status |= SILC_IDLIST_STATUS_RESUMED;
3841     detached_client->data.status &= ~SILC_IDLIST_STATUS_LOCAL;
3842
3843     /* Check if anyone is watching this client */
3844     if (server->server_type == SILC_ROUTER)
3845       silc_server_check_watcher_list(server, detached_client, NULL,
3846                                      SILC_NOTIFY_TYPE_UMODE_CHANGE);
3847
3848     silc_schedule_task_del_by_context(server->schedule, detached_client);
3849
3850     /* Get the new owner of the resumed client */
3851     if (!silc_id_str2id(packet->src_id, packet->src_id_len,
3852                         packet->src_id_type, &server_id, sizeof(server_id)))
3853       goto out;
3854
3855     /* Get server entry */
3856     server_entry = silc_idlist_find_server_by_id(server->global_list,
3857                                                  &server_id, TRUE, NULL);
3858     local = FALSE;
3859     if (!server_entry) {
3860       server_entry = silc_idlist_find_server_by_id(server->local_list,
3861                                                    &server_id, TRUE, NULL);
3862       local = TRUE;
3863       if (!server_entry)
3864         goto out;
3865     }
3866
3867     if (server->server_type == SILC_ROUTER &&
3868         idata->conn_type == SILC_CONN_ROUTER &&
3869         server_entry->server_type == SILC_ROUTER)
3870       local = FALSE;
3871
3872     /* Change the client to correct list. */
3873     if (!silc_idcache_del_by_context(server->local_list->clients,
3874                                      detached_client, NULL))
3875       silc_idcache_del_by_context(server->global_list->clients,
3876                                   detached_client, NULL);
3877     silc_idcache_add(local && server->server_type == SILC_ROUTER ?
3878                      server->local_list->clients :
3879                      server->global_list->clients, nicknamec,
3880                      detached_client->id, detached_client);
3881
3882     /* Change the owner of the client */
3883     detached_client->router = server_entry;
3884
3885     /* Update channel information regarding global clients on channel. */
3886     if (server->server_type != SILC_ROUTER) {
3887       silc_hash_table_list(detached_client->channels, &htl);
3888       while (silc_hash_table_get(&htl, NULL, (void *)&chl))
3889         chl->channel->global_users =
3890           silc_server_channel_has_global(chl->channel);
3891       silc_hash_table_list_reset(&htl);
3892     }
3893   }
3894
3895  out:
3896   silc_packet_free(packet);
3897 }