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