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