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