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