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