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