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