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