56435eb6b69420dadddc9d62d9aa711e57be3b95
[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     if (!newusername) {
2267       silc_free(username);
2268       silc_free(realname);
2269       silc_free(nickname);
2270       silc_server_disconnect_remote(server, sock,
2271                                     SILC_STATUS_ERR_OPERATION_ALLOWED, NULL);
2272       silc_server_free_sock_user_data(server, sock, NULL);
2273       silc_packet_free(packet);
2274       return NULL;
2275     }
2276     strncat(newusername, username, strlen(username));
2277     strncat(newusername, "@", 1);
2278     strncat(newusername, hostname, strlen(hostname));
2279     silc_free(username);
2280     username = newusername;
2281   }
2282
2283   SILC_LOG_DEBUG(("%s %s", ip, hostname));
2284
2285   /* Create Client ID */
2286   if (!silc_id_create_client_id(server, server->id, server->rng,
2287                                 server->md5hash, nicknamec,
2288                                 strlen(nicknamec), &client_id)) {
2289     silc_free(username);
2290     silc_free(realname);
2291     silc_free(nickname);
2292     silc_server_disconnect_remote(server, sock,
2293                                   SILC_STATUS_ERR_BAD_NICKNAME, NULL);
2294     silc_server_free_sock_user_data(server, sock, NULL);
2295     silc_packet_free(packet);
2296     return NULL;
2297   }
2298
2299   /* If client marked as anonymous, scramble the username and hostname */
2300   if (client->mode & SILC_UMODE_ANONYMOUS) {
2301     char *scramble;
2302
2303     if (strlen(username) >= 2) {
2304       username[0] = silc_rng_get_byte_fast(server->rng);
2305       username[1] = silc_rng_get_byte_fast(server->rng);
2306     }
2307
2308     scramble = silc_hash_babbleprint(server->sha1hash, username,
2309                                      strlen(username));
2310     scramble[5] = '@';
2311     scramble[11] = '.';
2312     memcpy(&scramble[16], ".silc", 5);
2313     scramble[21] = '\0';
2314     silc_free(username);
2315     username = scramble;
2316   }
2317
2318   /* Update client entry */
2319   idata->status |= SILC_IDLIST_STATUS_REGISTERED;
2320   client->nickname = nickname;
2321   client->username = username;
2322   client->userinfo = realname ? realname : strdup(username);
2323   client->id = client_id;
2324   id_len = silc_id_get_len(client_id, SILC_ID_CLIENT);
2325   silc_idcache_update_by_context(server->local_list->clients, client,
2326                                  client_id, nicknamec, TRUE);
2327
2328   /* Notify our router about new client on the SILC network */
2329   silc_server_send_new_id(server, SILC_PRIMARY_ROUTE(server),
2330                           SILC_BROADCAST(server), client->id,
2331                           SILC_ID_CLIENT, id_len);
2332
2333   /* Distribute to backup routers */
2334   if (server->server_type == SILC_ROUTER) {
2335     SilcBuffer idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2336     silc_server_backup_send(server, NULL, SILC_PACKET_NEW_ID, 0,
2337                             idp->data, silc_buffer_len(idp), FALSE, TRUE);
2338     silc_buffer_free(idp);
2339   }
2340
2341   /* Send the new client ID to the client. */
2342   silc_server_send_new_id(server, sock, FALSE, client->id, SILC_ID_CLIENT,
2343                           silc_id_get_len(client->id, SILC_ID_CLIENT));
2344
2345   /* Send some nice info to the client */
2346   silc_server_send_connect_notifys(server, sock, client);
2347
2348   /* Check if anyone is watching this nickname */
2349   if (server->server_type == SILC_ROUTER)
2350     silc_server_check_watcher_list(server, client, NULL, 0);
2351
2352   silc_packet_free(packet);
2353   return client;
2354 }
2355
2356 /* Create new server. This processes received New Server packet and
2357    saves the received Server ID. The server is our locally connected
2358    server thus we save all the information and save it to local list.
2359    This funtion can be used by both normal server and router server.
2360    If normal server uses this it means that its router has connected
2361    to the server. If router uses this it means that one of the cell's
2362    servers is connected to the router. */
2363
2364 SilcServerEntry silc_server_new_server(SilcServer server,
2365                                        SilcPacketStream sock,
2366                                        SilcPacket packet)
2367 {
2368   SilcBuffer buffer = &packet->buffer;
2369   SilcIDListData idata = silc_packet_get_context(sock);
2370   SilcServerEntry new_server, server_entry;
2371   SilcServerID server_id;
2372   unsigned char *server_name, *server_namec, *id_string;
2373   SilcUInt16 id_len, name_len;
2374   int ret;
2375   SilcBool local = TRUE;
2376   const char *hostname, *ip;
2377
2378   SILC_LOG_DEBUG(("Creating new server"));
2379
2380   if (idata->conn_type != SILC_CONN_SERVER &&
2381       idata->conn_type != SILC_CONN_ROUTER) {
2382     silc_packet_free(packet);
2383     return NULL;
2384   }
2385
2386   /* Take server entry */
2387   new_server = (SilcServerEntry)idata;
2388   silc_socket_stream_get_info(silc_packet_stream_get_stream(sock),
2389                               NULL, &hostname, &ip, NULL);
2390
2391   /* Statistics */
2392   if (server->server_type == SILC_ROUTER)
2393     server->stat.cell_servers++;
2394
2395   /* Remove the old cache entry */
2396   if (!silc_idcache_del_by_context(server->local_list->servers, new_server,
2397                                    NULL)) {
2398     if (!silc_idcache_del_by_context(server->global_list->servers,
2399                                      new_server, NULL)) {
2400       SILC_LOG_INFO(("Unauthenticated %s attempted to register to "
2401                      "network", (idata->conn_type == SILC_CONN_SERVER ?
2402                                  "server" : "router")));
2403       silc_server_disconnect_remote(server, sock,
2404                                     SILC_STATUS_ERR_NOT_AUTHENTICATED, NULL);
2405       silc_server_free_sock_user_data(server, sock, NULL);
2406       return NULL;
2407     }
2408     local = FALSE;
2409   }
2410
2411   /* Make sure this server hasn't registered already */
2412   if (idata->status & SILC_IDLIST_STATUS_REGISTERED) {
2413     silc_server_disconnect_remote(server, sock,
2414                                   SILC_STATUS_ERR_OPERATION_ALLOWED,
2415                                   "Too many registrations");
2416     silc_server_free_sock_user_data(server, sock, NULL);
2417     return NULL;
2418   }
2419
2420   /* Parse the incoming packet */
2421   ret = silc_buffer_unformat(buffer,
2422                              SILC_STR_UI16_NSTRING_ALLOC(&id_string, &id_len),
2423                              SILC_STR_UI16_NSTRING_ALLOC(&server_name,
2424                                                          &name_len),
2425                              SILC_STR_END);
2426   if (ret == -1) {
2427     silc_free(id_string);
2428     silc_free(server_name);
2429     silc_server_disconnect_remote(server, sock,
2430                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2431                                   NULL);
2432     silc_server_free_sock_user_data(server, sock, NULL);
2433     return NULL;
2434   }
2435
2436   if (id_len > silc_buffer_len(buffer)) {
2437     silc_free(id_string);
2438     silc_free(server_name);
2439     silc_server_disconnect_remote(server, sock,
2440                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2441                                   NULL);
2442     silc_server_free_sock_user_data(server, sock, NULL);
2443     return NULL;
2444   }
2445
2446   if (name_len > 256) {
2447     server_name[256] = '\0';
2448     name_len = 256;
2449   }
2450
2451   /* Get Server ID */
2452   if (!silc_id_str2id(id_string, id_len, SILC_ID_SERVER, &server_id,
2453                       sizeof(server_id))) {
2454     silc_free(id_string);
2455     silc_free(server_name);
2456     silc_server_disconnect_remote(server, sock,
2457                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
2458                                   NULL);
2459     silc_server_free_sock_user_data(server, sock, NULL);
2460     return NULL;
2461   }
2462   silc_free(id_string);
2463
2464   /* Check for valid server ID */
2465   if (!silc_id_is_valid_server_id(server, &server_id, sock)) {
2466     SILC_LOG_INFO(("Invalid server ID sent by %s (%s)",
2467                    ip, hostname));
2468     silc_server_disconnect_remote(server, sock,
2469                                   SILC_STATUS_ERR_BAD_SERVER_ID, NULL);
2470     silc_server_free_sock_user_data(server, sock, NULL);
2471     silc_free(server_name);
2472     return NULL;
2473   }
2474
2475   /* Check that we do not have this ID already */
2476   server_entry = silc_idlist_find_server_by_id(server->local_list,
2477                                                &server_id, TRUE, NULL);
2478   if (server_entry) {
2479     if (SILC_IS_LOCAL(server_entry)) {
2480       SILC_LOG_ERROR(("Too many registrations from %s (%s)",
2481                       ip, hostname));
2482       silc_server_disconnect_remote(server, sock,
2483                                     SILC_STATUS_ERR_OPERATION_ALLOWED,
2484                                     "Too many registrations");
2485       silc_server_free_sock_user_data(server, sock, NULL);
2486       return NULL;
2487     } else {
2488       silc_idcache_del_by_context(server->local_list->servers, server_entry,
2489                                   NULL);
2490     }
2491   } else {
2492     server_entry = silc_idlist_find_server_by_id(server->global_list,
2493                                                  &server_id, TRUE, NULL);
2494     if (server_entry) {
2495       if (SILC_IS_LOCAL(server_entry)) {
2496         SILC_LOG_ERROR(("Too many registrations from %s (%s)",
2497                         ip, hostname));
2498         silc_server_disconnect_remote(server, sock,
2499                                       SILC_STATUS_ERR_OPERATION_ALLOWED,
2500                                       "Too many registrations");
2501         silc_server_free_sock_user_data(server, sock, NULL);
2502         return NULL;
2503       } else {
2504         silc_idcache_del_by_context(server->global_list->servers,
2505                                     server_entry, NULL);
2506       }
2507     }
2508   }
2509
2510   /* Check server name */
2511   server_namec = silc_identifier_check(server_name, strlen(server_name),
2512                                        SILC_STRING_UTF8, 256, NULL);
2513   if (!server_namec) {
2514     SILC_LOG_ERROR(("Malformed server name from %s (%s)",
2515                     ip, hostname));
2516     silc_server_disconnect_remote(server, sock,
2517                                   SILC_STATUS_ERR_OPERATION_ALLOWED,
2518                                   "Malfromed server name");
2519     silc_server_free_sock_user_data(server, sock, NULL);
2520     return NULL;
2521   }
2522
2523   /* Update server entry */
2524   idata->status |= SILC_IDLIST_STATUS_REGISTERED;
2525   new_server->server_name = server_name;
2526   new_server->id = silc_id_dup(&server_id, SILC_ID_SERVER);
2527
2528   SILC_LOG_DEBUG(("New server id(%s)",
2529                   silc_id_render(&server_id, SILC_ID_SERVER)));
2530
2531   /* Add again the entry to the ID cache. */
2532   silc_idcache_add(local ? server->local_list->servers :
2533                    server->global_list->servers, server_namec,
2534                    new_server->id, new_server);
2535
2536   /* Distribute the information about new server in the SILC network
2537      to our router. If we are normal server we won't send anything
2538      since this connection must be our router connection. */
2539   if (server->server_type == SILC_ROUTER && !server->standalone &&
2540       SILC_PRIMARY_ROUTE(server) != sock)
2541     silc_server_send_new_id(server, SILC_PRIMARY_ROUTE(server),
2542                             TRUE, new_server->id, SILC_ID_SERVER,
2543                             silc_id_get_len(&server_id, SILC_ID_SERVER));
2544
2545   if (server->server_type == SILC_ROUTER) {
2546     /* Distribute to backup routers */
2547     SilcBuffer idp = silc_id_payload_encode(new_server->id, SILC_ID_SERVER);
2548     silc_server_backup_send(server, NULL, SILC_PACKET_NEW_ID, 0, idp->data,
2549                             silc_buffer_len(idp), FALSE, TRUE);
2550     silc_buffer_free(idp);
2551   }
2552
2553   /* Check whether this router connection has been replaced by an
2554      backup router. If it has been then we'll disable the server and will
2555      ignore everything it will send until the backup router resuming
2556      protocol has been completed. */
2557   if (idata->conn_type == SILC_CONN_ROUTER &&
2558       silc_server_backup_replaced_get(server, &server_id, NULL)) {
2559     /* Send packet to the router indicating that it cannot use this
2560        connection as it has been replaced by backup router. */
2561     SILC_LOG_DEBUG(("Remote router has been replaced by backup router, "
2562                     "disabling its connection"));
2563
2564     silc_server_backup_send_replaced(server, sock);
2565
2566     /* Mark the router disabled. The data sent earlier will go but nothing
2567        after this goes to this connection. */
2568     idata->status |= SILC_IDLIST_STATUS_DISABLED;
2569   } else {
2570     /* If it is router announce our stuff to it. */
2571     if (idata->conn_type == SILC_CONN_ROUTER &&
2572         server->server_type == SILC_ROUTER) {
2573       silc_server_announce_servers(server, FALSE, 0, sock);
2574       silc_server_announce_clients(server, 0, sock);
2575       silc_server_announce_channels(server, 0, sock);
2576     }
2577
2578     /* Announce our information to backup router */
2579     if (new_server->server_type == SILC_BACKUP_ROUTER &&
2580         idata->conn_type == SILC_CONN_SERVER &&
2581         server->server_type == SILC_ROUTER) {
2582       silc_server_announce_servers(server, TRUE, 0, sock);
2583       silc_server_announce_clients(server, 0, sock);
2584       silc_server_announce_channels(server, 0, sock);
2585     }
2586
2587     /* If backup router, mark it as one of ours.  This server is considered
2588        to be backup router after this setting. */
2589     if (new_server->server_type == SILC_BACKUP_ROUTER) {
2590       SilcServerConfigRouter *backup;
2591       backup = silc_server_config_find_backup_conn(server, (char *)ip);
2592       if (!backup)
2593         backup = silc_server_config_find_backup_conn(server, (char *)hostname);
2594       if (backup) {
2595         /* Add as our backup router */
2596         silc_server_backup_add(server, new_server, backup->backup_replace_ip,
2597                                backup->backup_replace_port,
2598                                backup->backup_local);
2599       }
2600     }
2601
2602     /* By default the servers connected to backup router are disabled
2603        until backup router has become the primary */
2604     if (server->server_type == SILC_BACKUP_ROUTER &&
2605         idata->conn_type == SILC_CONN_SERVER)
2606       idata->status |= SILC_IDLIST_STATUS_DISABLED;
2607   }
2608
2609   return new_server;
2610 }
2611
2612 /* Processes incoming New ID packet. New ID Payload is used to distribute
2613    information about newly registered clients and servers. */
2614
2615 static void silc_server_new_id_real(SilcServer server,
2616                                     SilcPacketStream sock,
2617                                     SilcPacket packet,
2618                                     SilcBuffer buffer,
2619                                     SilcBool broadcast)
2620 {
2621   SilcIDListData idata = silc_packet_get_context(sock);
2622   SilcIDList id_list;
2623   SilcServerEntry router, server_entry;
2624   SilcPacketStream router_sock;
2625   SilcIDPayload idp;
2626   SilcIdType id_type;
2627   SilcServerID sender_id;
2628   const char *hostname, *ip;
2629
2630   SILC_LOG_DEBUG(("Processing new ID"));
2631
2632   if (idata->conn_type == SILC_CONN_CLIENT ||
2633       server->server_type == SILC_SERVER ||
2634       packet->src_id_type != SILC_ID_SERVER)
2635     return;
2636
2637   idp = silc_id_payload_parse(buffer->data, silc_buffer_len(buffer));
2638   if (!idp)
2639     return;
2640
2641   id_type = silc_id_payload_get_type(idp);
2642
2643   silc_socket_stream_get_info(silc_packet_stream_get_stream(sock),
2644                               NULL, &hostname, &ip, NULL);
2645
2646   /* Normal server cannot have other normal server connections */
2647   server_entry = (SilcServerEntry)idata;
2648   if (id_type == SILC_ID_SERVER && idata->conn_type == SILC_CONN_SERVER &&
2649       server_entry->server_type == SILC_SERVER)
2650     goto out;
2651
2652   /* If the packet is coming from server then use the sender as the
2653      origin of the the packet. If it came from router then check the real
2654      sender of the packet and use that as the origin. */
2655   if (idata->conn_type == SILC_CONN_SERVER) {
2656     id_list = server->local_list;
2657     router_sock = sock;
2658     router = server_entry;
2659
2660     /* If the sender is backup router and ID is server (and we are not
2661        backup router) then switch the entry to global list. */
2662     if (server_entry->server_type == SILC_BACKUP_ROUTER &&
2663         id_type == SILC_ID_SERVER &&
2664         server->id_entry->server_type != SILC_BACKUP_ROUTER) {
2665       id_list = server->global_list;
2666       router_sock = server->router ? SILC_PRIMARY_ROUTE(server) : sock;
2667     }
2668   } else {
2669     silc_id_str2id(packet->src_id, packet->src_id_len,
2670                    packet->src_id_type, &sender_id, sizeof(sender_id));
2671     router = silc_idlist_find_server_by_id(server->global_list,
2672                                            &sender_id, TRUE, NULL);
2673     if (!router)
2674       router = silc_idlist_find_server_by_id(server->local_list,
2675                                              &sender_id, TRUE, NULL);
2676     router_sock = sock;
2677     id_list = server->global_list;
2678   }
2679
2680   if (!router)
2681     goto out;
2682
2683   switch(id_type) {
2684   case SILC_ID_CLIENT:
2685     {
2686       SilcClientEntry entry;
2687       SilcClientID id;
2688
2689       if (!silc_id_payload_get_id(idp, &id, sizeof(id)))
2690         goto out;
2691
2692       /* Check that we do not have this client already */
2693       entry = silc_idlist_find_client_by_id(server->global_list,
2694                                             &id, server->server_type,
2695                                             NULL);
2696       if (!entry)
2697         entry = silc_idlist_find_client_by_id(server->local_list,
2698                                               &id, server->server_type,
2699                                               NULL);
2700       if (entry) {
2701         SILC_LOG_DEBUG(("Ignoring client that we already have"));
2702         goto out;
2703       }
2704
2705       SILC_LOG_DEBUG(("New client id(%s) from [%s] %s",
2706                       silc_id_render(&id, SILC_ID_CLIENT),
2707                       idata->conn_type == SILC_CONN_SERVER ?
2708                       "Server" : "Router", hostname));
2709
2710       /* As a router we keep information of all global information in our
2711          global list. Cell wide information however is kept in the local
2712          list. */
2713       entry = silc_idlist_add_client(id_list, NULL, NULL, NULL,
2714                                      silc_id_dup(&id, SILC_ID_CLIENT),
2715                                      router, NULL);
2716       if (!entry) {
2717         SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
2718
2719         /* Inform the sender that the ID is not usable */
2720         silc_server_send_notify_signoff(server, sock, FALSE, &id, NULL);
2721         goto out;
2722       }
2723       entry->nickname = NULL;
2724       entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
2725
2726       if (idata->conn_type == SILC_CONN_SERVER)
2727         server->stat.cell_clients++;
2728       SILC_LOG_DEBUG(("stat.clients %d->%d", server->stat.clients,
2729                       server->stat.clients + 1));
2730       server->stat.clients++;
2731
2732       /* Check if anyone is watching this nickname */
2733       if (server->server_type == SILC_ROUTER && id_list == server->local_list)
2734         silc_server_check_watcher_list(server, entry, NULL, 0);
2735
2736       if (server->server_type == SILC_ROUTER) {
2737         /* Add the client's public key to repository or get the key with
2738            GETKEY command. */
2739         if (entry->data.public_key) {
2740           if (!silc_server_get_public_key_by_client(server, entry, NULL))
2741             silc_skr_add_public_key_simple(server->repository,
2742                                            entry->data.public_key,
2743                                            SILC_SKR_USAGE_IDENTIFICATION,
2744                                            entry, NULL);
2745         } else {
2746           silc_server_send_command(server, router_sock,
2747                                    SILC_COMMAND_GETKEY, ++server->cmd_ident,
2748                                    1, 1, buffer->data,
2749                                    silc_buffer_len(buffer));
2750         }
2751       }
2752     }
2753     break;
2754
2755   case SILC_ID_SERVER:
2756     {
2757       SilcServerEntry entry;
2758       SilcServerID id;
2759
2760       if (!silc_id_payload_get_id(idp, &id, sizeof(id)))
2761         goto out;
2762
2763       /* If the ID is mine, ignore it. */
2764       if (SILC_ID_SERVER_COMPARE(&id, server->id)) {
2765         SILC_LOG_DEBUG(("Ignoring my own ID as new ID"));
2766         break;
2767       }
2768
2769       /* If the ID is the sender's ID, ignore it (we have it already) */
2770       if (SILC_ID_SERVER_COMPARE(&id, router->id)) {
2771         SILC_LOG_DEBUG(("Ignoring sender's own ID"));
2772         break;
2773       }
2774
2775       /* Check that we do not have this server already */
2776       entry = silc_idlist_find_server_by_id(server->global_list,
2777                                             &id, server->server_type,
2778                                             NULL);
2779       if (!entry)
2780         entry = silc_idlist_find_server_by_id(server->local_list,
2781                                               &id, server->server_type,
2782                                               NULL);
2783       if (entry) {
2784         SILC_LOG_DEBUG(("Ignoring server that we already have"));
2785         goto out;
2786       }
2787
2788       SILC_LOG_DEBUG(("New server id(%s) from [%s] %s",
2789                       silc_id_render(&id, SILC_ID_SERVER),
2790                       idata->conn_type == SILC_CONN_SERVER ?
2791                       "Server" : "Router", hostname));
2792
2793       /* As a router we keep information of all global information in our
2794          global list. Cell wide information however is kept in the local
2795          list. */
2796       entry = silc_idlist_add_server(id_list, NULL, 0,
2797                                      silc_id_dup(&id, SILC_ID_SERVER), router,
2798                                      router_sock);
2799       if (!entry) {
2800         SILC_LOG_ERROR(("Could not add new server to the ID Cache"));
2801         goto out;
2802       }
2803       entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
2804
2805       if (idata->conn_type == SILC_CONN_SERVER)
2806         server->stat.cell_servers++;
2807       server->stat.servers++;
2808     }
2809     break;
2810
2811   case SILC_ID_CHANNEL:
2812     SILC_LOG_ERROR(("Channel cannot be registered with NEW_ID packet"));
2813     goto out;
2814     break;
2815
2816   default:
2817     goto out;
2818     break;
2819   }
2820
2821   /* If the sender of this packet is server and we are router we need to
2822      broadcast this packet to other routers in the network. */
2823   if (broadcast && server->server_type == SILC_ROUTER &&
2824       idata->conn_type == SILC_CONN_SERVER &&
2825       !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
2826     SILC_LOG_DEBUG(("Broadcasting received New ID packet"));
2827     silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
2828                             packet->type,
2829                             packet->flags | SILC_PACKET_FLAG_BROADCAST,
2830                             buffer->data, silc_buffer_len(buffer));
2831     silc_server_backup_send(server, (SilcServerEntry)idata,
2832                             packet->type, packet->flags,
2833                             packet->buffer.data,
2834                             silc_buffer_len(&packet->buffer),
2835                             FALSE, TRUE);
2836   }
2837
2838  out:
2839   silc_id_payload_free(idp);
2840 }
2841
2842
2843 /* Processes incoming New ID packet. New ID Payload is used to distribute
2844    information about newly registered clients and servers. */
2845
2846 void silc_server_new_id(SilcServer server, SilcPacketStream sock,
2847                         SilcPacket packet)
2848 {
2849   silc_server_new_id_real(server, sock, packet, &packet->buffer, TRUE);
2850   silc_packet_free(packet);
2851 }
2852
2853 /* Receoved New Id List packet, list of New ID payloads inside one
2854    packet. Process the New ID payloads one by one. */
2855
2856 void silc_server_new_id_list(SilcServer server, SilcPacketStream sock,
2857                              SilcPacket packet)
2858 {
2859   SilcIDListData idata = silc_packet_get_context(sock);
2860   SilcBuffer idp;
2861   SilcUInt16 id_len;
2862
2863   SILC_LOG_DEBUG(("Processing New ID List"));
2864
2865   if (idata->conn_type == SILC_CONN_CLIENT ||
2866       packet->src_id_type != SILC_ID_SERVER) {
2867     silc_packet_free(packet);
2868     return;
2869   }
2870
2871   /* If the sender of this packet is server and we are router we need to
2872      broadcast this packet to other routers in the network. Broadcast
2873      this list packet instead of multiple New ID packets. */
2874   if (server->server_type == SILC_ROUTER &&
2875       idata->conn_type == SILC_CONN_SERVER &&
2876       !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
2877     SILC_LOG_DEBUG(("Broadcasting received New ID List packet"));
2878     silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
2879                             packet->type,
2880                             packet->flags | SILC_PACKET_FLAG_BROADCAST,
2881                             packet->buffer.data,
2882                             silc_buffer_len(&packet->buffer));
2883     silc_server_backup_send(server, (SilcServerEntry)idata,
2884                             packet->type, packet->flags,
2885                             packet->buffer.data,
2886                             silc_buffer_len(&packet->buffer),
2887                             FALSE, TRUE);
2888   }
2889
2890   idp = silc_buffer_alloc(256);
2891   if (!idp) {
2892     silc_packet_free(packet);
2893     return;
2894   }
2895
2896   while (silc_buffer_len(&packet->buffer)) {
2897     SILC_GET16_MSB(id_len, packet->buffer.data + 2);
2898     if ((id_len > silc_buffer_len(&packet->buffer)) ||
2899         (id_len > silc_buffer_truelen(idp)))
2900       break;
2901
2902     silc_buffer_pull_tail(idp, 4 + id_len);
2903     silc_buffer_put(idp, packet->buffer.data, 4 + id_len);
2904
2905     /* Process the New ID */
2906     silc_server_new_id_real(server, sock, packet, idp, FALSE);
2907
2908     silc_buffer_push_tail(idp, 4 + id_len);
2909     silc_buffer_pull(&packet->buffer, 4 + id_len);
2910   }
2911
2912   silc_buffer_free(idp);
2913   silc_packet_free(packet);
2914 }
2915
2916 /* Received New Channel packet. Information about new channels in the
2917    network are distributed using this packet. Save the information about
2918    the new channel. This usually comes from router but also normal server
2919    can send this to notify channels it has when it connects to us. */
2920
2921 static void silc_server_new_channel_process(SilcServer server,
2922                                             SilcPacketStream sock,
2923                                             SilcPacket packet,
2924                                             SilcBuffer buffer)
2925 {
2926   SilcIDListData idata = silc_packet_get_context(sock);
2927   SilcChannelPayload payload;
2928   SilcChannelID channel_id;
2929   char *channel_name, *channel_namec = NULL;
2930   SilcUInt32 name_len;
2931   unsigned char cid[32];
2932   SilcUInt32 id_len, cipher_len;
2933   SilcServerEntry server_entry;
2934   SilcChannelEntry channel;
2935   const char *cipher;
2936
2937   if (idata->conn_type == SILC_CONN_CLIENT ||
2938       packet->src_id_type != SILC_ID_SERVER ||
2939       server->server_type == SILC_SERVER)
2940     return;
2941
2942   /* Parse the channel payload */
2943   payload = silc_channel_payload_parse(buffer->data, silc_buffer_len(buffer));
2944   if (!payload)
2945     return;
2946
2947   /* Get the channel ID */
2948   if (!silc_channel_get_id_parse(payload, &channel_id)) {
2949     silc_channel_payload_free(payload);
2950     return;
2951   }
2952
2953   channel_name = silc_channel_get_name(payload, &name_len);
2954   if (name_len > 256) {
2955     channel_name[256] = '\0';
2956     name_len = 256;
2957   }
2958
2959   /* Check channel name */
2960   channel_namec = silc_channel_name_check(channel_name, strlen(channel_name),
2961                                           SILC_STRING_UTF8, 256, NULL);
2962   if (!channel_namec)
2963     return;
2964
2965   server_entry = (SilcServerEntry)idata;
2966
2967   if (idata->conn_type == SILC_CONN_ROUTER) {
2968     /* Add the channel to global list as it is coming from router. It
2969        cannot be our own channel as it is coming from router. */
2970
2971     /* Check that we don't already have this channel */
2972     channel = silc_idlist_find_channel_by_name(server->local_list,
2973                                                channel_namec, NULL);
2974     if (!channel)
2975       channel = silc_idlist_find_channel_by_name(server->global_list,
2976                                                  channel_namec, NULL);
2977     if (!channel) {
2978       SILC_LOG_DEBUG(("New channel id(%s) from [Router] %s",
2979                       silc_id_render(&channel_id, SILC_ID_CHANNEL),
2980                       idata->sconn->remote_host));
2981
2982       channel =
2983         silc_idlist_add_channel(server->global_list, strdup(channel_name),
2984                                 0, silc_id_dup(&channel_id, SILC_ID_CHANNEL),
2985                                 (SilcServerEntry)idata, NULL, NULL, NULL);
2986       if (!channel) {
2987         silc_channel_payload_free(payload);
2988         return;
2989       }
2990       channel->disabled = TRUE;    /* Disabled until someone JOINs */
2991
2992       server->stat.channels++;
2993       if (server->server_type == SILC_ROUTER)
2994         channel->users_resolved = TRUE;
2995     }
2996   } else {
2997     /* The channel is coming from our server, thus it is in our cell
2998        we will add it to our local list. */
2999     SilcBuffer chk;
3000
3001     SILC_LOG_DEBUG(("Channel id(%s) from [Server] %s",
3002                     silc_id_render(&channel_id, SILC_ID_CHANNEL),
3003                     idata->sconn->remote_host));
3004
3005     /* Check that we don't already have this channel */
3006     channel = silc_idlist_find_channel_by_name(server->local_list,
3007                                                channel_namec, NULL);
3008     if (!channel)
3009       channel = silc_idlist_find_channel_by_name(server->global_list,
3010                                                  channel_namec, NULL);
3011
3012     /* If the channel does not exist, then create it. This creates a new
3013        key to the channel as well that we will send to the server. */
3014     if (!channel) {
3015       SILC_LOG_DEBUG(("Channel is new to us"));
3016
3017       /* The protocol says that the Channel ID's IP address must be based
3018          on the router's IP address.  Check whether the ID is based in our
3019          IP and if it is not then create a new ID and enforce the server
3020          to switch the ID. */
3021       if (server_entry->server_type != SILC_BACKUP_ROUTER &&
3022           !SILC_ID_COMPARE(&channel_id, server->id, server->id->ip.data_len)) {
3023         SilcChannelID *tmp;
3024         SILC_LOG_DEBUG(("Forcing the server to change Channel ID"));
3025         if (silc_id_create_channel_id(server, server->id, server->rng, &tmp)) {
3026           silc_server_send_notify_channel_change(server, sock, FALSE,
3027                                                  &channel_id, tmp);
3028           silc_channel_payload_free(payload);
3029           silc_free(tmp);
3030         }
3031
3032         /* Wait that server re-announces this channel */
3033         return;
3034       }
3035
3036       /* Create the channel with the provided Channel ID */
3037       channel =
3038         silc_server_create_new_channel_with_id(
3039                                      server, NULL, NULL,
3040                                      channel_name,
3041                                      silc_id_dup(&channel_id, SILC_ID_CHANNEL),
3042                                      FALSE);
3043       if (!channel) {
3044         silc_channel_payload_free(payload);
3045         return;
3046       }
3047       channel->disabled = TRUE;    /* Disabled until someone JOINs */
3048
3049 #if 0 /* We assume that CMODE_CHANGE notify is sent to us after this. */
3050
3051       /* XXX Dunno if this is supposed to be set in any server type.  If set
3052          here the CMODE_CHANGE that may follow sets mode that we already
3053          have, and we may loose data from the CMODE_CHANGE notify. */
3054       if (server_entry->server_type != SILC_BACKUP_ROUTER)
3055         channel->mode = silc_channel_get_mode(payload);
3056 #endif
3057
3058       /* Send the new channel key to the server */
3059       silc_id_id2str(channel->id, SILC_ID_CHANNEL, cid, sizeof(cid),
3060                      &id_len);
3061       cipher = silc_cipher_get_name(channel->send_key);
3062       cipher_len = strlen(cipher);
3063       chk = silc_channel_key_payload_encode(id_len, cid,
3064                                             cipher_len, cipher,
3065                                             channel->key_len / 8,
3066                                             channel->key);
3067       silc_server_packet_send(server, sock, SILC_PACKET_CHANNEL_KEY, 0,
3068                               chk->data, silc_buffer_len(chk));
3069       silc_buffer_free(chk);
3070     } else {
3071       /* The channel exist by that name, check whether the ID's match.
3072          If they don't then we'll force the server to use the ID we have.
3073          We also create a new key for the channel. */
3074       SilcBuffer modes = NULL, users = NULL, users_modes = NULL;
3075
3076       SILC_LOG_DEBUG(("Channel already exists"));
3077
3078       if (!SILC_ID_CHANNEL_COMPARE(&channel_id, channel->id)) {
3079         /* They don't match, send CHANNEL_CHANGE notify to the server to
3080            force the ID change. */
3081         SILC_LOG_DEBUG(("Forcing the server to change Channel ID"));
3082         silc_server_send_notify_channel_change(server, sock, FALSE,
3083                                                &channel_id, channel->id);
3084         silc_channel_payload_free(payload);
3085
3086         /* Wait that server re-announces this channel */
3087         return;
3088       }
3089
3090 #if 0 /* We will announce our CMODE anyway for this channel, so no need
3091          to check it (implicit enforce). */
3092
3093       /* If the mode is different from what we have then enforce the
3094          mode change. */
3095       mode = silc_channel_get_mode(payload);
3096       if (channel->mode != mode) {
3097         SILC_LOG_DEBUG(("Forcing the server to change channel mode"));
3098         silc_server_send_notify_cmode(server, sock, FALSE, channel,
3099                                       channel->mode, server->id,
3100                                       SILC_ID_SERVER, channel->cipher,
3101                                       channel->hmac_name,
3102                                       channel->passphrase,
3103                                       channel->founder_key);
3104       }
3105 #endif
3106
3107       /* Create new key for the channel and send it to the server and
3108          everybody else possibly on the channel. */
3109       if (!(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
3110
3111         if (silc_hash_table_count(channel->user_list)) {
3112           if (!silc_server_create_channel_key(server, channel, 0)) {
3113             silc_channel_payload_free(payload);
3114             return;
3115           }
3116
3117           /* Send to the channel */
3118           silc_server_send_channel_key(server, sock, channel, FALSE);
3119         }
3120
3121         /* Send to the server */
3122         silc_id_id2str(channel->id, SILC_ID_CHANNEL, cid, sizeof(cid),
3123                        &id_len);
3124         cipher = silc_cipher_get_name(channel->send_key);
3125         cipher_len = strlen(cipher);
3126         chk = silc_channel_key_payload_encode(id_len, cid,
3127                                               cipher_len, cipher,
3128                                               channel->key_len / 8,
3129                                               channel->key);
3130         silc_server_packet_send(server, sock, SILC_PACKET_CHANNEL_KEY, 0,
3131                                 chk->data, silc_buffer_len(chk));
3132         silc_buffer_free(chk);
3133       }
3134
3135       /* Since the channel is coming from server and we also know about it
3136          then send the JOIN notify to the server so that it see's our
3137          users on the channel "joining" the channel. */
3138       silc_server_announce_get_channel_users(server, channel, &modes, &users,
3139                                              &users_modes);
3140       if (users) {
3141         silc_buffer_push(users, users->data - users->head);
3142         silc_server_packet_send(server, sock,
3143                                 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3144                                 users->data, silc_buffer_len(users));
3145         silc_buffer_free(users);
3146       }
3147       if (modes) {
3148         silc_buffer_push(modes, modes->data - modes->head);
3149         silc_server_packet_send_dest(server, sock,
3150                                      SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3151                                      channel->id, SILC_ID_CHANNEL,
3152                                      modes->data, silc_buffer_len(modes));
3153         silc_buffer_free(modes);
3154       }
3155       if (users_modes) {
3156         silc_buffer_push(users_modes, users_modes->data - users_modes->head);
3157         silc_server_packet_send_dest(server, sock,
3158                                      SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3159                                      channel->id, SILC_ID_CHANNEL,
3160                                      users_modes->data,
3161                                      silc_buffer_len(users_modes));
3162         silc_buffer_free(users_modes);
3163       }
3164       if (channel->topic) {
3165         silc_server_send_notify_topic_set(server, sock,
3166                                           server->server_type == SILC_ROUTER ?
3167                                           TRUE : FALSE, channel,
3168                                           server->id, SILC_ID_SERVER,
3169                                           channel->topic);
3170       }
3171     }
3172   }
3173
3174   /* If the sender of this packet is server and we are router we need to
3175      broadcast this packet to other routers in the network. Broadcast
3176      this list packet instead of multiple New Channel packets. */
3177   if (server->server_type == SILC_ROUTER &&
3178       idata->conn_type == SILC_CONN_SERVER &&
3179       !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
3180     SILC_LOG_DEBUG(("Broadcasting received New Channel packet"));
3181     silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
3182                             packet->type,
3183                             packet->flags | SILC_PACKET_FLAG_BROADCAST,
3184                             buffer->data, silc_buffer_len(buffer));
3185     silc_server_backup_send(server, (SilcServerEntry)idata,
3186                             packet->type, packet->flags,
3187                             buffer->data, silc_buffer_len(buffer),
3188                             FALSE, TRUE);
3189   }
3190
3191   silc_free(channel_namec);
3192   silc_channel_payload_free(payload);
3193 }
3194
3195 /* Received New Channel packet. Information about new channels in the
3196    network are distributed using this packet. Save the information about
3197    the new channel. This usually comes from router but also normal server
3198    can send this to notify channels it has when it connects to us. */
3199
3200 void silc_server_new_channel(SilcServer server,
3201                              SilcPacketStream sock,
3202                              SilcPacket packet)
3203 {
3204   silc_server_new_channel_process(server, sock, packet, &packet->buffer);
3205   silc_packet_free(packet);
3206 }
3207
3208 /* Received New Channel List packet, list of New Channel List payloads inside
3209    one packet. Process the New Channel payloads one by one. */
3210
3211 void silc_server_new_channel_list(SilcServer server,
3212                                   SilcPacketStream sock,
3213                                   SilcPacket packet)
3214 {
3215   SilcIDListData idata = silc_packet_get_context(sock);
3216   SilcBuffer buffer;
3217   SilcUInt16 len1, len2;
3218
3219   SILC_LOG_DEBUG(("Processing New Channel List"));
3220
3221   if (idata->conn_type == SILC_CONN_CLIENT ||
3222       packet->src_id_type != SILC_ID_SERVER ||
3223       server->server_type == SILC_SERVER) {
3224     silc_packet_free(packet);
3225     return;
3226   }
3227
3228   buffer = silc_buffer_alloc(512);
3229   if (!buffer) {
3230     silc_packet_free(packet);
3231     return;
3232   }
3233
3234   while (silc_buffer_len(&packet->buffer)) {
3235     SILC_GET16_MSB(len1, packet->buffer.data);
3236     if ((len1 > silc_buffer_len(&packet->buffer)) ||
3237         (len1 > silc_buffer_truelen(buffer)))
3238       break;
3239
3240     SILC_GET16_MSB(len2, packet->buffer.data + 2 + len1);
3241     if ((len2 > silc_buffer_len(&packet->buffer)) ||
3242         (len2 > silc_buffer_truelen(buffer)))
3243       break;
3244
3245     silc_buffer_pull_tail(buffer, 8 + len1 + len2);
3246     silc_buffer_put(buffer, packet->buffer.data, 8 + len1 + len2);
3247
3248     /* Process the New Channel */
3249     silc_server_new_channel_process(server, sock, packet, buffer);
3250
3251     silc_buffer_push_tail(buffer, 8 + len1 + len2);
3252     silc_buffer_pull(&packet->buffer, 8 + len1 + len2);
3253   }
3254
3255   silc_buffer_free(buffer);
3256   silc_packet_free(packet);
3257 }
3258
3259 /* Received key agreement packet. This packet is never for us. It is to
3260    the client in the packet's destination ID. Sending of this sort of packet
3261    equals sending private message, ie. it is sent point to point from
3262    one client to another. */
3263
3264 void silc_server_key_agreement(SilcServer server,
3265                                SilcPacketStream sock,
3266                                SilcPacket packet)
3267 {
3268   SilcPacketStream dst_sock;
3269   SilcIDListData idata;
3270
3271   SILC_LOG_DEBUG(("Start"));
3272
3273   if (packet->src_id_type != SILC_ID_CLIENT ||
3274       packet->dst_id_type != SILC_ID_CLIENT || !packet->dst_id) {
3275     silc_packet_free(packet);
3276     return;
3277   }
3278
3279   /* Get the route to the client */
3280   dst_sock = silc_server_get_client_route(server, packet->dst_id,
3281                                           packet->dst_id_len, NULL,
3282                                           &idata, NULL);
3283   if (!dst_sock) {
3284     silc_packet_free(packet);
3285     return;
3286   }
3287
3288   /* Relay the packet */
3289   silc_server_packet_route(server, dst_sock, packet);
3290   silc_packet_free(packet);
3291 }
3292
3293 /* Received connection auth request packet that is used during connection
3294    phase to resolve the mandatory authentication method.  This packet can
3295    actually be received at anytime but usually it is used only during
3296    the connection authentication phase. Now, protocol says that this packet
3297    can come from client or server, however, we support only this coming
3298    from client and expect that server always knows what authentication
3299    method to use. */
3300
3301 void silc_server_connection_auth_request(SilcServer server,
3302                                          SilcPacketStream sock,
3303                                          SilcPacket packet)
3304 {
3305   SilcServerConfigClient *client = NULL;
3306   SilcUInt16 conn_type;
3307   int ret;
3308   SilcAuthMethod auth_meth = SILC_AUTH_NONE;
3309   const char *hostname, *ip;
3310
3311   if (packet->src_id_type && packet->src_id_type != SILC_ID_CLIENT) {
3312     SILC_LOG_DEBUG(("Request not from client"));
3313     silc_packet_free(packet);
3314     return;
3315   }
3316
3317   silc_socket_stream_get_info(silc_packet_stream_get_stream(sock),
3318                               NULL, &hostname, &ip, NULL);
3319
3320   /* Parse the payload */
3321   ret = silc_buffer_unformat(&packet->buffer,
3322                              SILC_STR_UI_SHORT(&conn_type),
3323                              SILC_STR_UI_SHORT(NULL),
3324                              SILC_STR_END);
3325   if (ret == -1 || conn_type != SILC_CONN_CLIENT) {
3326     silc_packet_free(packet);
3327     return;
3328   }
3329
3330   /* Get the authentication method for the client */
3331   auth_meth = SILC_AUTH_NONE;
3332   client = silc_server_config_find_client(server, (char *)ip);
3333   if (!client)
3334     client = silc_server_config_find_client(server, (char *)hostname);
3335   if (client) {
3336     if (client->passphrase) {
3337       if (client->publickeys && !server->config->prefer_passphrase_auth)
3338         auth_meth = SILC_AUTH_PUBLIC_KEY;
3339       else
3340         auth_meth = SILC_AUTH_PASSWORD;
3341     } else if (client->publickeys)
3342       auth_meth = SILC_AUTH_PUBLIC_KEY;
3343   }
3344
3345   SILC_LOG_DEBUG(("Authentication method is [%s]",
3346                   (auth_meth == SILC_AUTH_NONE ? "None" :
3347                    auth_meth == SILC_AUTH_PASSWORD ? "Passphrase" :
3348                    "Digital signatures")));
3349
3350   /* Send it back to the client */
3351   silc_server_send_connection_auth_request(server, sock, conn_type, auth_meth);
3352   silc_packet_free(packet);
3353 }
3354
3355 /* Received file transger packet. This packet is never for us. It is to
3356    the client in the packet's destination ID. Sending of this sort of packet
3357    equals sending private message, ie. it is sent point to point from
3358    one client to another. */
3359
3360 void silc_server_ftp(SilcServer server,
3361                      SilcPacketStream sock,
3362                      SilcPacket packet)
3363 {
3364   SilcPacketStream dst_sock;
3365   SilcIDListData idata;
3366
3367   SILC_LOG_DEBUG(("Start"));
3368
3369   if (packet->src_id_type != SILC_ID_CLIENT ||
3370       packet->dst_id_type != SILC_ID_CLIENT || !packet->dst_id) {
3371     silc_packet_free(packet);
3372     return;
3373   }
3374
3375   /* Get the route to the client */
3376   dst_sock = silc_server_get_client_route(server, packet->dst_id,
3377                                           packet->dst_id_len, NULL,
3378                                           &idata, NULL);
3379   if (!dst_sock) {
3380     silc_packet_free(packet);
3381     return;
3382   }
3383
3384   /* Relay the packet */
3385   silc_server_packet_route(server, dst_sock, packet);
3386   silc_packet_free(packet);
3387 }
3388
3389 typedef struct {
3390   SilcServer server;
3391   SilcPacketStream sock;
3392   SilcPacket packet;
3393   SilcClientID client_id;
3394 } *SilcServerResumeResolve;
3395
3396 SILC_SERVER_CMD_FUNC(resume_resolve)
3397 {
3398   SilcServerResumeResolve r = (SilcServerResumeResolve)context;
3399   SilcServer server = r->server;
3400   SilcPacketStream sock = r->sock;
3401   SilcServerCommandReplyContext reply = context2;
3402   SilcClientEntry client;
3403   const char *hostname, *ip;
3404
3405   SILC_LOG_DEBUG(("Start"));
3406
3407   silc_socket_stream_get_info(silc_packet_stream_get_stream(sock),
3408                               NULL, &hostname, &ip, NULL);
3409
3410   if (!reply || !silc_command_get_status(reply->payload, NULL, NULL)) {
3411     SILC_LOG_ERROR(("Client %s (%s) tried to resume unknown client, "
3412                     "closing connection", hostname, ip));
3413     silc_server_disconnect_remote(server, sock,
3414                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3415                                   "Resuming not possible");
3416     silc_server_free_sock_user_data(server, sock, NULL);
3417     goto out;
3418   }
3419
3420   if (reply && silc_command_get(reply->payload) == SILC_COMMAND_WHOIS) {
3421     /* Get entry to the client, and resolve it if we don't have it. */
3422     client = silc_idlist_find_client_by_id(server->local_list,
3423                                            &r->client_id, TRUE, NULL);
3424     if (!client) {
3425       client = silc_idlist_find_client_by_id(server->global_list,
3426                                              &r->client_id, TRUE, NULL);
3427       if (!client) {
3428         SILC_LOG_ERROR(("Client %s (%s) tried to resume unknown 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
3438     if (!(client->mode & SILC_UMODE_DETACHED)) {
3439       SILC_LOG_ERROR(("Client %s (%s) tried to resume un-detached client, "
3440                       "closing connection", hostname, ip));
3441       silc_server_disconnect_remote(server, sock,
3442                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3443                                     "Resuming not possible");
3444       silc_server_free_sock_user_data(server, sock, NULL);
3445       goto out;
3446     }
3447
3448     client->data.status |= SILC_IDLIST_STATUS_RESUME_RES;
3449   }
3450
3451   /* Reprocess the packet */
3452   silc_server_resume_client(server, sock, r->packet);
3453
3454  out:
3455   silc_packet_stream_unref(r->sock);
3456   silc_free(r);
3457 }
3458
3459 /* Received client resuming packet.  This is used to resume detached
3460    client session.  It can be sent by the client who wishes to resume
3461    but this is also sent by servers and routers to notify other routers
3462    that the client is not detached anymore. */
3463
3464 void silc_server_resume_client(SilcServer server,
3465                                SilcPacketStream sock,
3466                                SilcPacket packet)
3467 {
3468   SilcBuffer buffer = &packet->buffer, buf;
3469   SilcIDListData idata = silc_packet_get_context(sock);
3470   SilcIDCacheEntry id_cache = NULL;
3471   SilcClientEntry detached_client;
3472   SilcClientID client_id;
3473   unsigned char *id_string, *auth = NULL, *nicknamec = NULL;
3474   unsigned char cid[32];
3475   SilcUInt32 cid_len;
3476   SilcUInt16 id_len, auth_len = 0;
3477   SilcBool resolved, local, nick_change = FALSE, resolve = FALSE;
3478   SilcChannelEntry channel;
3479   SilcHashTableList htl;
3480   SilcChannelClientEntry chl;
3481   SilcServerResumeResolve r;
3482   SilcPublicKey public_key;
3483   const char *cipher, *hostname, *ip;
3484
3485   SILC_LOG_DEBUG(("Resuming client"));
3486
3487   silc_socket_stream_get_info(silc_packet_stream_get_stream(sock),
3488                               NULL, &hostname, &ip, NULL);
3489
3490   if (silc_buffer_unformat(buffer,
3491                            SILC_STR_UI16_NSTRING(&id_string, &id_len),
3492                            SILC_STR_END) < 0) {
3493     if (idata->conn_type == SILC_CONN_CLIENT) {
3494       SILC_LOG_ERROR(("Client %s (%s) sent incomplete resume information, "
3495                       "closing connection", hostname, ip));
3496       silc_server_disconnect_remote(server, sock,
3497                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3498                                     "Resuming not possible");
3499       silc_server_free_sock_user_data(server, sock, NULL);
3500     }
3501     goto out;
3502   }
3503
3504   silc_id_str2id(id_string, id_len, SILC_ID_CLIENT, &client_id,
3505                  sizeof(client_id));
3506
3507   if (idata->conn_type == SILC_CONN_CLIENT) {
3508     /* Client send this and is attempting to resume to old client session */
3509     SilcClientEntry client;
3510     SilcBuffer keyp;
3511
3512     silc_buffer_pull(buffer, 2 + id_len);
3513     auth = buffer->data;
3514     auth_len = silc_buffer_len(buffer);
3515     silc_buffer_push(buffer, 2 + id_len);
3516
3517     if (auth_len < 128) {
3518       SILC_LOG_ERROR(("Client %s (%s) sent incomplete resume information, "
3519                       "closing connection", hostname, ip));
3520       silc_server_disconnect_remote(server, sock,
3521                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3522                                     "Resuming not possible");
3523       silc_server_free_sock_user_data(server, sock, NULL);
3524       goto out;
3525     }
3526
3527     /* Take client entry of this connection */
3528     client = (SilcClientEntry)idata;
3529
3530     /* Get entry to the client, and resolve it if we don't have it. */
3531     detached_client = silc_server_query_client(server, &client_id, FALSE,
3532                                                &resolved);
3533     if (!detached_client) {
3534       if (resolved) {
3535         /* The client info is being resolved. Reprocess this packet after
3536            receiving the reply to the query. */
3537         SILC_LOG_DEBUG(("Resolving client"));
3538         r = silc_calloc(1, sizeof(*r));
3539         if (!r)
3540           goto out;
3541         silc_packet_stream_ref(sock);
3542         r->server = server;
3543         r->sock = sock;
3544         r->packet = packet;
3545         r->client_id = client_id;
3546         silc_server_command_pending(server, SILC_COMMAND_WHOIS,
3547                                     server->cmd_ident,
3548                                     silc_server_command_resume_resolve, r);
3549         return;
3550       } else {
3551         SILC_LOG_ERROR(("Client %s (%s) tried to resume unknown client, "
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
3561     if (detached_client->data.status & SILC_IDLIST_STATUS_RESUMED) {
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       SILC_LOG_ERROR(("Client %s (%s) tried to attach more than once, "
3574                       "closing connection", hostname, ip));
3575       silc_server_disconnect_remote(server, sock,
3576                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3577                                     "Resuming not possible");
3578       silc_server_free_sock_user_data(server, sock, NULL);
3579       goto out;
3580     }
3581
3582     if (!detached_client->resuming_client)
3583       detached_client->resuming_client = client;
3584
3585     if (!(detached_client->mode & SILC_UMODE_DETACHED))
3586       resolve = TRUE;
3587     if (!silc_hash_table_count(detached_client->channels) &&
3588         detached_client->router)
3589       resolve = TRUE;
3590     if (!detached_client->nickname)
3591       resolve = TRUE;
3592     if (detached_client->data.status & SILC_IDLIST_STATUS_RESUME_RES)
3593       resolve = FALSE;
3594
3595     if (resolve) {
3596       if (server->server_type == SILC_SERVER && !server->standalone) {
3597         /* The client info is being resolved. Reprocess this packet after
3598            receiving the reply to the query. */
3599         SILC_LOG_DEBUG(("Resolving client info"));
3600         silc_server_query_client(server, &client_id, TRUE, NULL);
3601         r = silc_calloc(1, sizeof(*r));
3602         if (!r)
3603           return;
3604         silc_packet_stream_ref(sock);
3605         r->server = server;
3606         r->sock = sock;
3607         r->packet = packet;
3608         r->client_id = client_id;
3609         silc_server_command_pending(server, SILC_COMMAND_WHOIS,
3610                                     server->cmd_ident,
3611                                     silc_server_command_resume_resolve, r);
3612         return;
3613       }
3614       if (server->server_type == SILC_SERVER) {
3615         SILC_LOG_ERROR(("Client %s (%s) tried to resume un-detached client, "
3616                         "closing connection", hostname, ip));
3617         silc_server_disconnect_remote(server, sock,
3618                                       SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3619                                       "Resuming not possible");
3620         silc_server_free_sock_user_data(server, sock, NULL);
3621         goto out;
3622       }
3623     }
3624
3625     /* Check that we have the public key of the client, if not then we must
3626        resolve it first. */
3627     if (!detached_client->data.public_key) {
3628       if (server->server_type == SILC_SERVER && server->standalone) {
3629         SILC_LOG_ERROR(("Detached client's public key not present, "
3630                         "closing connection"));
3631         silc_server_disconnect_remote(server, sock,
3632                                       SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3633                                       "Resuming not possible");
3634         silc_server_free_sock_user_data(server, sock, NULL);
3635         goto out;
3636       } else {
3637         /* We must retrieve the detached client's public key by sending
3638            GETKEY command. Reprocess this packet after receiving the key */
3639         SilcBuffer idp = silc_id_payload_encode(&client_id, SILC_ID_CLIENT);
3640         SilcPacketStream dest_sock =
3641           silc_server_get_client_route(server, NULL, 0, &client_id,
3642                                        NULL, NULL);
3643
3644         SILC_LOG_DEBUG(("Resolving client public key"));
3645
3646         silc_server_send_command(server, dest_sock ? dest_sock :
3647                                  SILC_PRIMARY_ROUTE(server),
3648                                  SILC_COMMAND_GETKEY, ++server->cmd_ident,
3649                                  1, 1, idp->data, silc_buffer_len(idp));
3650
3651         r = silc_calloc(1, sizeof(*r));
3652         if (!r)
3653           return;
3654         silc_packet_stream_ref(sock);
3655         r->server = server;
3656         r->sock = sock;
3657         r->packet = packet;
3658         r->client_id = client_id;
3659         silc_server_command_pending(server, SILC_COMMAND_GETKEY,
3660                                     server->cmd_ident,
3661                                     silc_server_command_resume_resolve, r);
3662
3663         silc_buffer_free(idp);
3664         return;
3665       }
3666     } else if (!silc_pkcs_public_key_compare(detached_client->data.public_key,
3667                                              idata->public_key)) {
3668       /* We require that the connection and resuming authentication data
3669          must be using same key pair. */
3670       SILC_LOG_ERROR(("Resuming attempted with wrong public key, "
3671                       "closing connection"));
3672       silc_server_disconnect_remote(server, sock,
3673                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3674                                     "Resuming not possible");
3675       silc_server_free_sock_user_data(server, sock, NULL);
3676       goto out;
3677     }
3678
3679     /* Verify the authentication payload.  This has to be successful in
3680        order to allow the resuming */
3681     if (!idata->hash ||
3682         !silc_auth_verify_data(auth, auth_len, SILC_AUTH_PUBLIC_KEY,
3683                                detached_client->data.public_key, 0,
3684                                idata->hash, detached_client->id,
3685                                SILC_ID_CLIENT)) {
3686       SILC_LOG_ERROR(("Client %s (%s) resume authentication failed, "
3687                       "closing connection", hostname, ip));
3688       silc_server_disconnect_remote(server, sock,
3689                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3690                                     "Resuming not possible");
3691       silc_server_free_sock_user_data(server, sock, NULL);
3692       goto out;
3693     }
3694
3695     /* Check nickname */
3696     nicknamec = silc_identifier_check(detached_client->nickname,
3697                                       strlen(detached_client->nickname),
3698                                       SILC_STRING_UTF8, 128, NULL);
3699     if (!nicknamec) {
3700       silc_server_disconnect_remote(server, sock,
3701                                     SILC_STATUS_ERR_BAD_NICKNAME,
3702                                     "Malformed nickname, cannot resume");
3703       silc_server_free_sock_user_data(server, sock, NULL);
3704       goto out;
3705     }
3706
3707     /* If the ID is not based in our ID then change it */
3708     if (!SILC_ID_COMPARE(detached_client->id, server->id,
3709                          server->id->ip.data_len)) {
3710       SilcClientID *new_id;
3711       if (!silc_id_create_client_id(server, server->id, server->rng,
3712                                     server->md5hash, nicknamec,
3713                                     strlen(nicknamec), &new_id)) {
3714         silc_server_disconnect_remote(server, sock,
3715                                       SILC_STATUS_ERR_BAD_NICKNAME,
3716                                       "Resuming not possible");
3717         silc_server_free_sock_user_data(server, sock, NULL);
3718         goto out;
3719       }
3720       nick_change = TRUE;
3721       client_id = *new_id;
3722       silc_free(new_id);
3723     }
3724
3725     /* Now resume the client to the network */
3726
3727     silc_schedule_task_del_by_context(server->schedule, detached_client);
3728     silc_packet_set_context(sock, detached_client);
3729     detached_client->connection = sock;
3730
3731     if (detached_client->data.public_key) {
3732       /* Delete the detached client's public key from repository */
3733       silc_skr_del_public_key(server->repository,
3734                               detached_client->data.public_key,
3735                               detached_client);
3736       detached_client->data.public_key = NULL;
3737     }
3738
3739     if (idata->public_key) {
3740       /* Delete the resuming client's public key from repository.  It will
3741          be added later again. */
3742       public_key = silc_pkcs_public_key_copy(idata->public_key);
3743       silc_skr_del_public_key(server->repository, idata->public_key, idata);
3744       idata->public_key = public_key;
3745     }
3746
3747     /* Take new keys and stuff into use in the old entry */
3748     silc_idlist_del_data(detached_client);
3749     silc_idlist_add_data(detached_client, idata);
3750     idata->public_key = NULL;
3751
3752     if (detached_client->data.public_key) {
3753       /* Add the resumed client's public key back to repository. */
3754       if (!silc_server_get_public_key_by_client(server, detached_client, NULL))
3755         silc_skr_add_public_key_simple(server->repository,
3756                                        detached_client->data.public_key,
3757                                        SILC_SKR_USAGE_IDENTIFICATION,
3758                                        detached_client, NULL);
3759     }
3760
3761     detached_client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
3762     detached_client->data.status |= SILC_IDLIST_STATUS_RESUMED;
3763     detached_client->data.status |= SILC_IDLIST_STATUS_LOCAL;
3764     detached_client->data.status &= ~SILC_IDLIST_STATUS_RESUME_RES;
3765     detached_client->mode &= ~SILC_UMODE_DETACHED;
3766     server->stat.my_detached--;
3767     silc_dlist_del(server->expired_clients, detached_client);
3768
3769     /* We are finished - reset resuming client */
3770     detached_client->resuming_client = NULL;
3771
3772     /* Check if anyone is watching this client */
3773     if (server->server_type == SILC_ROUTER)
3774       silc_server_check_watcher_list(server, detached_client, NULL,
3775                                      SILC_NOTIFY_TYPE_UMODE_CHANGE);
3776
3777     /* Delete this current client entry since we're resuming to old one.
3778        We decrement clients/cell_clients as we are getting rid of the
3779        current client and replacing it with the detached one.  We keep the
3780        server user count as-is (incremented by the current client entry) as
3781        we decremented the count already during detach, thus we'd be undoing
3782        that operation. */
3783     detached_client->local_detached = FALSE;
3784     SILC_LOG_DEBUG(("stat.clients %d->%d", server->stat.clients,
3785                     server->stat.clients - 1));
3786     SILC_VERIFY(server->stat.clients > 0);
3787     server->stat.clients--;
3788     if (server->stat.cell_clients)
3789       server->stat.cell_clients--;
3790     silc_server_remove_from_channels(server, NULL, client, FALSE,
3791                                      NULL, FALSE, FALSE);
3792     silc_server_del_from_watcher_list(server, client);
3793     silc_dlist_del(server->expired_clients, client);
3794     if (!silc_idlist_del_client(server->local_list, client))
3795       silc_idlist_del_client(server->global_list, client);
3796     client = detached_client;
3797     silc_free(client->servername);
3798     client->servername = strdup(server->server_name);
3799
3800     /* Send the RESUME_CLIENT packet to our primary router so that others
3801        know this client isn't detached anymore. */
3802     buf = silc_buffer_alloc_size(2 + id_len);
3803     silc_buffer_format(buf,
3804                        SILC_STR_UI_SHORT(id_len),
3805                        SILC_STR_UI_XNSTRING(id_string, id_len),
3806                        SILC_STR_END);
3807
3808     /* Send to primary router */
3809     silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
3810                             SILC_PACKET_RESUME_CLIENT, 0,
3811                             buf->data, silc_buffer_len(buf));
3812     silc_server_backup_send(server, client->router,
3813                             SILC_PACKET_RESUME_CLIENT, 0,
3814                             buf->data, silc_buffer_len(buf), TRUE, TRUE);
3815
3816     /* As router we must deliver this packet directly to the original
3817        server whom this client was earlier. */
3818     if (server->server_type == SILC_ROUTER && client->router &&
3819         client->router->server_type != SILC_ROUTER)
3820       silc_server_packet_send(server, client->router->connection,
3821                               SILC_PACKET_RESUME_CLIENT, 0,
3822                               buf->data, silc_buffer_len(buf));
3823     silc_buffer_free(buf);
3824     client->router = NULL;
3825
3826     if (nick_change) {
3827       /* Notify about Client ID change, nickname doesn't actually change. */
3828       silc_server_send_notify_nick_change(server, SILC_PRIMARY_ROUTE(server),
3829                                           SILC_BROADCAST(server),
3830                                           client->id, &client_id,
3831                                           client->nickname);
3832     }
3833
3834     /* Resolve users on those channels that client has joined but we
3835        haven't resolved user list yet. */
3836     if (server->server_type == SILC_SERVER && !server->standalone) {
3837       silc_hash_table_list(client->channels, &htl);
3838       while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3839         channel = chl->channel;
3840         SILC_LOG_DEBUG(("Resolving users for %s channel",
3841                         channel->channel_name));
3842         if (channel->disabled || !channel->users_resolved) {
3843           silc_server_send_command(server, SILC_PRIMARY_ROUTE(server),
3844                                    SILC_COMMAND_USERS, ++server->cmd_ident,
3845                                    1, 2, channel->channel_name,
3846                                    strlen(channel->channel_name));
3847         }
3848       }
3849       silc_hash_table_list_reset(&htl);
3850     }
3851
3852     /* Send the new client ID to the client. After this client may start
3853        receiving other packets, and may start sending packets too. */
3854     silc_server_send_new_id(server, sock, FALSE, &client_id, SILC_ID_CLIENT,
3855                             silc_id_get_len(&client_id, SILC_ID_CLIENT));
3856
3857     if (nick_change) {
3858       /* Send NICK change notify to channels as well. */
3859       SilcBuffer oidp, nidp;
3860       oidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3861       nidp = silc_id_payload_encode(&client_id, SILC_ID_CLIENT);
3862       silc_server_send_notify_on_channels(server, NULL, client,
3863                                           SILC_NOTIFY_TYPE_NICK_CHANGE, 3,
3864                                           oidp->data, silc_buffer_len(oidp),
3865                                           nidp->data, silc_buffer_len(nidp),
3866                                           client->nickname,
3867                                           strlen(client->nickname));
3868       silc_buffer_free(oidp);
3869       silc_buffer_free(nidp);
3870     }
3871
3872     /* Update entry */
3873     if (!silc_idcache_update_by_context(server->local_list->clients, client,
3874                                         &client_id, NULL, FALSE))
3875       silc_idcache_update_by_context(server->global_list->clients, client,
3876                                      &client_id, NULL, FALSE);
3877
3878     /* Move entry to local list if it is in global list */
3879     if (silc_idcache_find_by_context(server->global_list->clients, client,
3880                                      &id_cache))
3881       silc_idcache_move(server->global_list->clients,
3882                         server->local_list->clients, id_cache);
3883
3884     /* Send some nice info to the client */
3885     silc_server_send_connect_notifys(server, sock, client);
3886
3887     /* Send all channel keys of channels the client has joined */
3888     silc_hash_table_list(client->channels, &htl);
3889     while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3890       SilcBool created = FALSE;
3891       channel = chl->channel;
3892
3893       if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY)
3894         continue;
3895
3896       /* If we don't have channel key, then create one */
3897       if (!channel->send_key) {
3898         if (!silc_server_create_channel_key(server, channel, 0))
3899           continue;
3900         created = TRUE;
3901       }
3902
3903       silc_id_id2str(channel->id, SILC_ID_CHANNEL, cid, sizeof(cid),
3904                      &cid_len);
3905       cipher = silc_cipher_get_name(channel->send_key);
3906       keyp =
3907         silc_channel_key_payload_encode(cid_len, cid,
3908                                         strlen(cipher), cipher,
3909                                         channel->key_len / 8, channel->key);
3910
3911       /* Send the channel key to the client */
3912       silc_server_packet_send(server, sock, SILC_PACKET_CHANNEL_KEY, 0,
3913                               keyp->data, silc_buffer_len(keyp));
3914
3915       /* Distribute the channel key to channel */
3916       if (created) {
3917         silc_server_send_channel_key(server, NULL, channel,
3918                                      server->server_type == SILC_ROUTER ?
3919                                      FALSE : !server->standalone);
3920         silc_server_backup_send(server, NULL, SILC_PACKET_CHANNEL_KEY, 0,
3921                                 keyp->data, silc_buffer_len(keyp),
3922                                 FALSE, TRUE);
3923       }
3924
3925       silc_buffer_free(keyp);
3926     }
3927     silc_hash_table_list_reset(&htl);
3928
3929   } else if (idata->conn_type != SILC_CONN_CLIENT) {
3930     /* Server or router sent this to us to notify that that a client has
3931        been resumed. */
3932     SilcServerEntry server_entry;
3933     SilcServerID server_id;
3934
3935     /* Get entry to the client, and resolve it if we don't have it. */
3936     detached_client = silc_idlist_find_client_by_id(server->local_list,
3937                                                     &client_id, TRUE,
3938                                                     &id_cache);
3939     if (!detached_client) {
3940       detached_client = silc_idlist_find_client_by_id(server->global_list,
3941                                                       &client_id, TRUE,
3942                                                       &id_cache);
3943       if (!detached_client) {
3944         SILC_LOG_DEBUG(("Resuming client is unknown"));
3945         goto out;
3946       }
3947     }
3948
3949     /* Check that the client has not been resumed already because it is
3950        protocol error to attempt to resume more than once.  The client
3951        will be killed if this protocol error occurs. */
3952     if (detached_client->data.status & SILC_IDLIST_STATUS_RESUMED &&
3953         !(detached_client->mode & SILC_UMODE_DETACHED)) {
3954       /* The client is clearly attempting to resume more than once and
3955          perhaps playing around by resuming from several different places
3956          at the same time. */
3957       SILC_LOG_DEBUG(("Attempting to re-resume client, killing both"));
3958       silc_server_kill_client(server, detached_client, NULL,
3959                               server->id, SILC_ID_SERVER);
3960       goto out;
3961     }
3962
3963     /* Check whether client is detached at all */
3964     if (!(detached_client->mode & SILC_UMODE_DETACHED)) {
3965       SILC_LOG_DEBUG(("Client is not detached"));
3966       goto out;
3967     }
3968
3969     /* Check nickname */
3970     if (detached_client->nickname) {
3971       nicknamec = silc_identifier_check(detached_client->nickname,
3972                                         strlen(detached_client->nickname),
3973                                         SILC_STRING_UTF8, 128, NULL);
3974       if (!nicknamec)
3975         goto out;
3976     }
3977
3978     SILC_LOG_DEBUG(("Resuming detached client"));
3979
3980     /* If the sender of this packet is server and we are router we need to
3981        broadcast this packet to other routers in the network. */
3982     if (server->server_type == SILC_ROUTER &&
3983         idata->conn_type == SILC_CONN_SERVER &&
3984         !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
3985       SILC_LOG_DEBUG(("Broadcasting received Resume Client packet"));
3986       silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
3987                               packet->type,
3988                               packet->flags | SILC_PACKET_FLAG_BROADCAST,
3989                               buffer->data, silc_buffer_len(buffer));
3990       silc_server_backup_send(server, (SilcServerEntry)idata,
3991                               packet->type, packet->flags,
3992                               packet->buffer.data,
3993                               silc_buffer_len(&packet->buffer),
3994                               FALSE, TRUE);
3995     }
3996
3997     /* If the client has a locally-connected previous owner, then we
3998        will need to notify them that the resume has completed.  Note
3999        that if the previous owner was a router, this case is already
4000        handled above by the broadcast, so we shouldn't attempt to
4001        send another notification in that case.   Additionally, if
4002        the previous owner was the server that sent the packet, then
4003        we'll not send the notification as it will have already done
4004        the necessary work locally. */
4005     if (server->server_type == SILC_ROUTER &&
4006         idata->conn_type == SILC_CONN_SERVER &&
4007         detached_client->router &&
4008         SILC_IS_LOCAL(detached_client->router) &&
4009         detached_client->router->server_type != SILC_ROUTER)
4010       silc_server_packet_send(server, detached_client->router->connection,
4011                               SILC_PACKET_RESUME_CLIENT, 0,
4012                               buffer->data, silc_buffer_len(buffer));
4013
4014     /* Client is detached, and now it is resumed.  Remove the detached
4015        mode and mark that it is resumed. */
4016
4017     if (detached_client->data.public_key) {
4018       /* Delete the detached client's public key from repository */
4019       silc_skr_del_public_key(server->repository,
4020                               detached_client->data.public_key,
4021                               detached_client);
4022       detached_client->data.public_key = NULL;
4023     }
4024
4025     silc_idlist_del_data(detached_client);
4026     detached_client->mode &= ~SILC_UMODE_DETACHED;
4027     detached_client->data.status |= SILC_IDLIST_STATUS_RESUMED;
4028     detached_client->data.status &= ~SILC_IDLIST_STATUS_LOCAL;
4029     silc_dlist_del(server->expired_clients, detached_client);
4030
4031     /* Check if anyone is watching this client */
4032     if (server->server_type == SILC_ROUTER)
4033       silc_server_check_watcher_list(server, detached_client, NULL,
4034                                      SILC_NOTIFY_TYPE_UMODE_CHANGE);
4035
4036     silc_schedule_task_del_by_context(server->schedule, detached_client);
4037
4038     /* Get the new owner of the resumed client */
4039     if (!silc_id_str2id(packet->src_id, packet->src_id_len,
4040                         packet->src_id_type, &server_id, sizeof(server_id)))
4041       goto out;
4042
4043     /* Get server entry */
4044     server_entry = silc_idlist_find_server_by_id(server->global_list,
4045                                                  &server_id, TRUE, NULL);
4046     local = FALSE;
4047     if (!server_entry) {
4048       server_entry = silc_idlist_find_server_by_id(server->local_list,
4049                                                    &server_id, TRUE, NULL);
4050       local = TRUE;
4051       if (!server_entry)
4052         goto out;
4053     }
4054
4055     if (server->server_type == SILC_ROUTER &&
4056         idata->conn_type == SILC_CONN_ROUTER &&
4057         server_entry->server_type == SILC_ROUTER)
4058       local = FALSE;
4059
4060     /* Move entry to correct list */
4061     if (local && server->server_type == SILC_ROUTER) {
4062       if (silc_idcache_find_by_context(server->global_list->clients,
4063                                        detached_client, &id_cache))
4064         silc_idcache_move(server->global_list->clients,
4065                           server->local_list->clients, id_cache);
4066     } else {
4067       if (silc_idcache_find_by_context(server->local_list->clients,
4068                                        detached_client, &id_cache))
4069         silc_idcache_move(server->local_list->clients,
4070                           server->global_list->clients, id_cache);
4071       }
4072
4073     /* We don't own this client anymore, if we ever did, as we were just
4074      * told that someone else resumed it.  Thus, it is most definitely no
4075      * a detached client.*/
4076     detached_client->local_detached = FALSE;
4077     /* Change the owner of the client */
4078     detached_client->router = server_entry;
4079
4080     /* Update channel information regarding global clients on channel. */
4081     if (server->server_type != SILC_ROUTER) {
4082       silc_hash_table_list(detached_client->channels, &htl);
4083       while (silc_hash_table_get(&htl, NULL, (void *)&chl))
4084         chl->channel->global_users =
4085           silc_server_channel_has_global(chl->channel);
4086       silc_hash_table_list_reset(&htl);
4087     }
4088   }
4089
4090  out:
4091   silc_packet_free(packet);
4092 }