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