97340d5f6f762620cb4be8087abcec59d294ee90
[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           silc_hash_table_add(server->pk_hash, entry->data.public_key, entry);
2898         else
2899           silc_server_send_command(server, router_sock,
2900                                    SILC_COMMAND_GETKEY, ++server->cmd_ident,
2901                                    1, 1, buffer->data, buffer->len);
2902       }
2903     }
2904     break;
2905
2906   case SILC_ID_SERVER:
2907     {
2908       SilcServerEntry entry;
2909
2910       /* If the ID is mine, ignore it. */
2911       if (SILC_ID_SERVER_COMPARE(id, server->id)) {
2912         SILC_LOG_DEBUG(("Ignoring my own ID as new ID"));
2913         break;
2914       }
2915
2916       /* If the ID is the sender's ID, ignore it (we have it already) */
2917       if (SILC_ID_SERVER_COMPARE(id, router->id)) {
2918         SILC_LOG_DEBUG(("Ignoring sender's own ID"));
2919         break;
2920       }
2921
2922       /* Check that we do not have this server already */
2923       entry = silc_idlist_find_server_by_id(server->global_list,
2924                                             id, server->server_type,
2925                                             NULL);
2926       if (!entry)
2927         entry = silc_idlist_find_server_by_id(server->local_list,
2928                                               id, server->server_type,
2929                                               NULL);
2930       if (entry) {
2931         SILC_LOG_DEBUG(("Ignoring server that we already have"));
2932         goto out;
2933       }
2934
2935       SILC_LOG_DEBUG(("New server id(%s) from [%s] %s",
2936                       silc_id_render(id, SILC_ID_SERVER),
2937                       sock->type == SILC_SOCKET_TYPE_SERVER ?
2938                       "Server" : "Router", sock->hostname));
2939
2940       /* As a router we keep information of all global information in our
2941          global list. Cell wide information however is kept in the local
2942          list. */
2943       entry = silc_idlist_add_server(id_list, NULL, 0, id, router,
2944                                      router_sock);
2945       if (!entry) {
2946         SILC_LOG_ERROR(("Could not add new server to the ID Cache"));
2947         goto out;
2948       }
2949       entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
2950
2951       if (sock->type == SILC_SOCKET_TYPE_SERVER)
2952         server->stat.cell_servers++;
2953       server->stat.servers++;
2954     }
2955     break;
2956
2957   case SILC_ID_CHANNEL:
2958     SILC_LOG_ERROR(("Channel cannot be registered with NEW_ID packet"));
2959     goto out;
2960     break;
2961
2962   default:
2963     goto out;
2964     break;
2965   }
2966
2967   /* If the sender of this packet is server and we are router we need to
2968      broadcast this packet to other routers in the network. */
2969   if (broadcast && server->server_type == SILC_ROUTER &&
2970       sock->type == SILC_SOCKET_TYPE_SERVER &&
2971       !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
2972     SILC_LOG_DEBUG(("Broadcasting received New ID packet"));
2973     silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
2974                             packet->type,
2975                             packet->flags | SILC_PACKET_FLAG_BROADCAST,
2976                             buffer->data, buffer->len, FALSE);
2977     silc_server_backup_send(server, sock->user_data,
2978                             packet->type, packet->flags,
2979                             packet->buffer->data, packet->buffer->len,
2980                             FALSE, TRUE);
2981   }
2982
2983  out:
2984   silc_id_payload_free(idp);
2985 }
2986
2987
2988 /* Processes incoming New ID packet. New ID Payload is used to distribute
2989    information about newly registered clients and servers. */
2990
2991 void silc_server_new_id(SilcServer server, SilcSocketConnection sock,
2992                         SilcPacketContext *packet)
2993 {
2994   silc_server_new_id_real(server, sock, packet, TRUE);
2995 }
2996
2997 /* Receoved New Id List packet, list of New ID payloads inside one
2998    packet. Process the New ID payloads one by one. */
2999
3000 void silc_server_new_id_list(SilcServer server, SilcSocketConnection sock,
3001                              SilcPacketContext *packet)
3002 {
3003   SilcPacketContext *new_id;
3004   SilcBuffer idp;
3005   SilcUInt16 id_len;
3006
3007   SILC_LOG_DEBUG(("Processing New ID List"));
3008
3009   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
3010       packet->src_id_type != SILC_ID_SERVER)
3011     return;
3012
3013   /* If the sender of this packet is server and we are router we need to
3014      broadcast this packet to other routers in the network. Broadcast
3015      this list packet instead of multiple New ID packets. */
3016   if (server->server_type == SILC_ROUTER &&
3017       sock->type == SILC_SOCKET_TYPE_SERVER &&
3018       !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
3019     SILC_LOG_DEBUG(("Broadcasting received New ID List packet"));
3020     silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
3021                             packet->type,
3022                             packet->flags | SILC_PACKET_FLAG_BROADCAST,
3023                             packet->buffer->data,
3024                             packet->buffer->len, FALSE);
3025     silc_server_backup_send(server, sock->user_data,
3026                             packet->type, packet->flags,
3027                             packet->buffer->data, packet->buffer->len,
3028                             FALSE, TRUE);
3029   }
3030
3031   /* Make copy of the original packet context, except for the actual
3032      data buffer, which we will here now fetch from the original buffer. */
3033   new_id = silc_packet_context_alloc();
3034   new_id->type = SILC_PACKET_NEW_ID;
3035   new_id->flags = packet->flags & (~SILC_PACKET_FLAG_LIST);
3036   new_id->src_id = packet->src_id;
3037   new_id->src_id_len = packet->src_id_len;
3038   new_id->src_id_type = packet->src_id_type;
3039   new_id->dst_id = packet->dst_id;
3040   new_id->dst_id_len = packet->dst_id_len;
3041   new_id->dst_id_type = packet->dst_id_type;
3042
3043   idp = silc_buffer_alloc(256);
3044   new_id->buffer = idp;
3045
3046   while (packet->buffer->len) {
3047     SILC_GET16_MSB(id_len, packet->buffer->data + 2);
3048     if ((id_len > packet->buffer->len) ||
3049         (id_len > idp->truelen))
3050       break;
3051
3052     silc_buffer_pull_tail(idp, 4 + id_len);
3053     silc_buffer_put(idp, packet->buffer->data, 4 + id_len);
3054
3055     /* Process the New ID */
3056     silc_server_new_id_real(server, sock, new_id, FALSE);
3057
3058     silc_buffer_push_tail(idp, 4 + id_len);
3059     silc_buffer_pull(packet->buffer, 4 + id_len);
3060   }
3061
3062   silc_buffer_free(idp);
3063   silc_free(new_id);
3064 }
3065
3066 /* Received New Channel packet. Information about new channels in the
3067    network are distributed using this packet. Save the information about
3068    the new channel. This usually comes from router but also normal server
3069    can send this to notify channels it has when it connects to us. */
3070
3071 void silc_server_new_channel(SilcServer server,
3072                              SilcSocketConnection sock,
3073                              SilcPacketContext *packet)
3074 {
3075   SilcChannelPayload payload;
3076   SilcChannelID *channel_id;
3077   char *channel_name, *channel_namec = NULL;
3078   SilcUInt32 name_len;
3079   unsigned char *id;
3080   SilcUInt32 id_len, cipher_len;
3081   SilcServerEntry server_entry;
3082   SilcChannelEntry channel;
3083   const char *cipher;
3084
3085   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
3086       packet->src_id_type != SILC_ID_SERVER ||
3087       server->server_type == SILC_SERVER)
3088     return;
3089
3090   /* Parse the channel payload */
3091   payload = silc_channel_payload_parse(packet->buffer->data,
3092                                        packet->buffer->len);
3093   if (!payload)
3094     return;
3095
3096   /* Get the channel ID */
3097   channel_id = silc_channel_get_id_parse(payload);
3098   if (!channel_id) {
3099     silc_channel_payload_free(payload);
3100     return;
3101   }
3102
3103   channel_name = silc_channel_get_name(payload, &name_len);
3104   if (name_len > 256) {
3105     channel_name[256] = '\0';
3106     name_len = 256;
3107   }
3108
3109   /* Check channel name */
3110   channel_namec = silc_identifier_check(channel_name, strlen(channel_name),
3111                                         SILC_STRING_UTF8, 256, NULL);
3112   if (!channel_namec)
3113     return;
3114
3115   id = silc_channel_get_id(payload, &id_len);
3116
3117   server_entry = (SilcServerEntry)sock->user_data;
3118
3119   if (sock->type == SILC_SOCKET_TYPE_ROUTER) {
3120     /* Add the channel to global list as it is coming from router. It
3121        cannot be our own channel as it is coming from router. */
3122
3123     /* Check that we don't already have this channel */
3124     channel = silc_idlist_find_channel_by_name(server->local_list,
3125                                                channel_namec, NULL);
3126     if (!channel)
3127       channel = silc_idlist_find_channel_by_name(server->global_list,
3128                                                  channel_namec, NULL);
3129     if (!channel) {
3130       SILC_LOG_DEBUG(("New channel id(%s) from [Router] %s",
3131                       silc_id_render(channel_id, SILC_ID_CHANNEL),
3132                       sock->hostname));
3133
3134       channel =
3135         silc_idlist_add_channel(server->global_list, strdup(channel_name),
3136                                 0, channel_id, sock->user_data, NULL, NULL, 0);
3137       if (!channel) {
3138         silc_channel_payload_free(payload);
3139         silc_free(channel_id);
3140         return;
3141       }
3142       channel->disabled = TRUE;    /* Disabled until someone JOINs */
3143
3144       server->stat.channels++;
3145       if (server->server_type == SILC_ROUTER)
3146         channel->users_resolved = TRUE;
3147     }
3148   } else {
3149     /* The channel is coming from our server, thus it is in our cell
3150        we will add it to our local list. */
3151     SilcBuffer chk;
3152
3153     SILC_LOG_DEBUG(("Channel id(%s) from [Server] %s",
3154                     silc_id_render(channel_id, SILC_ID_CHANNEL),
3155                     sock->hostname));
3156
3157     /* Check that we don't already have this channel */
3158     channel = silc_idlist_find_channel_by_name(server->local_list,
3159                                                channel_namec, NULL);
3160     if (!channel)
3161       channel = silc_idlist_find_channel_by_name(server->global_list,
3162                                                  channel_namec, NULL);
3163
3164     /* If the channel does not exist, then create it. This creates a new
3165        key to the channel as well that we will send to the server. */
3166     if (!channel) {
3167       SILC_LOG_DEBUG(("Channel is new to us"));
3168
3169       /* The protocol says that the Channel ID's IP address must be based
3170          on the router's IP address.  Check whether the ID is based in our
3171          IP and if it is not then create a new ID and enforce the server
3172          to switch the ID. */
3173       if (server_entry->server_type != SILC_BACKUP_ROUTER &&
3174           !SILC_ID_COMPARE(channel_id, server->id, server->id->ip.data_len)) {
3175         SilcChannelID *tmp;
3176         SILC_LOG_DEBUG(("Forcing the server to change Channel ID"));
3177         if (silc_id_create_channel_id(server, server->id, server->rng, &tmp)) {
3178           silc_server_send_notify_channel_change(server, sock, FALSE,
3179                                                  channel_id, tmp);
3180           silc_channel_payload_free(payload);
3181           silc_free(channel_id);
3182           silc_free(tmp);
3183         }
3184
3185         /* Wait that server re-announces this channel */
3186         return;
3187       }
3188
3189       /* Create the channel with the provided Channel ID */
3190       channel = silc_server_create_new_channel_with_id(server, NULL, NULL,
3191                                                        channel_name,
3192                                                        channel_id, FALSE);
3193       if (!channel) {
3194         silc_channel_payload_free(payload);
3195         silc_free(channel_id);
3196         return;
3197       }
3198       channel->disabled = TRUE;    /* Disabled until someone JOINs */
3199
3200 #if 0 /* We assume that CMODE_CHANGE notify is sent to us after this. */
3201
3202       /* XXX Dunno if this is supposed to be set in any server type.  If set
3203          here the CMODE_CHANGE that may follow sets mode that we already
3204          have, and we may loose data from the CMODE_CHANGE notify. */
3205       if (server_entry->server_type != SILC_BACKUP_ROUTER)
3206         channel->mode = silc_channel_get_mode(payload);
3207 #endif
3208
3209       /* Send the new channel key to the server */
3210       id = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3211       id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3212       cipher = silc_cipher_get_name(channel->channel_key);
3213       cipher_len = strlen(cipher);
3214       chk = silc_channel_key_payload_encode(id_len, id,
3215                                             cipher_len, cipher,
3216                                             channel->key_len / 8,
3217                                             channel->key);
3218       silc_server_packet_send(server, sock, SILC_PACKET_CHANNEL_KEY, 0,
3219                               chk->data, chk->len, FALSE);
3220       silc_buffer_free(chk);
3221       silc_free(id);
3222     } else {
3223       /* The channel exist by that name, check whether the ID's match.
3224          If they don't then we'll force the server to use the ID we have.
3225          We also create a new key for the channel. */
3226       SilcBuffer modes = NULL, users = NULL, users_modes = NULL;
3227
3228       SILC_LOG_DEBUG(("Channel already exists"));
3229
3230       if (!SILC_ID_CHANNEL_COMPARE(channel_id, channel->id)) {
3231         /* They don't match, send CHANNEL_CHANGE notify to the server to
3232            force the ID change. */
3233         SILC_LOG_DEBUG(("Forcing the server to change Channel ID"));
3234         silc_server_send_notify_channel_change(server, sock, FALSE,
3235                                                channel_id, channel->id);
3236         silc_channel_payload_free(payload);
3237         silc_free(channel_id);
3238
3239         /* Wait that server re-announces this channel */
3240         return;
3241       }
3242
3243 #if 0 /* We will announce our CMODE anyway for this channel, so no need
3244          to check it (implicit enforce). */
3245
3246       /* If the mode is different from what we have then enforce the
3247          mode change. */
3248       mode = silc_channel_get_mode(payload);
3249       if (channel->mode != mode) {
3250         SILC_LOG_DEBUG(("Forcing the server to change channel mode"));
3251         silc_server_send_notify_cmode(server, sock, FALSE, channel,
3252                                       channel->mode, server->id,
3253                                       SILC_ID_SERVER, channel->cipher,
3254                                       channel->hmac_name,
3255                                       channel->passphrase,
3256                                       channel->founder_key);
3257       }
3258 #endif
3259
3260       /* Create new key for the channel and send it to the server and
3261          everybody else possibly on the channel. */
3262       if (!(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
3263
3264         if (silc_hash_table_count(channel->user_list)) {
3265           if (!silc_server_create_channel_key(server, channel, 0)) {
3266             silc_channel_payload_free(payload);
3267             silc_free(channel_id);
3268             return;
3269           }
3270
3271           /* Send to the channel */
3272           silc_server_send_channel_key(server, sock, channel, FALSE);
3273         }
3274
3275         /* Send to the server */
3276         id = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3277         id_len = silc_id_get_len(channel->id, SILC_ID_CHANNEL);
3278         cipher = silc_cipher_get_name(channel->channel_key);
3279         cipher_len = strlen(cipher);
3280         chk = silc_channel_key_payload_encode(id_len, id,
3281                                               cipher_len, cipher,
3282                                               channel->key_len / 8,
3283                                               channel->key);
3284         silc_server_packet_send(server, sock, SILC_PACKET_CHANNEL_KEY, 0,
3285                                 chk->data, chk->len, FALSE);
3286         silc_buffer_free(chk);
3287         silc_free(id);
3288       }
3289
3290       silc_free(channel_id);
3291
3292       /* Since the channel is coming from server and we also know about it
3293          then send the JOIN notify to the server so that it see's our
3294          users on the channel "joining" the channel. */
3295       silc_server_announce_get_channel_users(server, channel, &modes, &users,
3296                                              &users_modes);
3297       if (users) {
3298         silc_buffer_push(users, users->data - users->head);
3299         silc_server_packet_send(server, sock,
3300                                 SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3301                                 users->data, users->len, FALSE);
3302         silc_buffer_free(users);
3303       }
3304       if (modes) {
3305         silc_buffer_push(modes, modes->data - modes->head);
3306         silc_server_packet_send_dest(server, sock,
3307                                      SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3308                                      channel->id, SILC_ID_CHANNEL,
3309                                      modes->data, modes->len, FALSE);
3310         silc_buffer_free(modes);
3311       }
3312       if (users_modes) {
3313         silc_buffer_push(users_modes, users_modes->data - users_modes->head);
3314         silc_server_packet_send_dest(server, sock,
3315                                      SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3316                                      channel->id, SILC_ID_CHANNEL,
3317                                      users_modes->data,
3318                                      users_modes->len, FALSE);
3319         silc_buffer_free(users_modes);
3320       }
3321       if (channel->topic) {
3322         silc_server_send_notify_topic_set(server, sock,
3323                                           server->server_type == SILC_ROUTER ?
3324                                           TRUE : FALSE, channel,
3325                                           server->id, SILC_ID_SERVER,
3326                                           channel->topic);
3327       }
3328     }
3329   }
3330
3331   /* If the sender of this packet is server and we are router we need to
3332      broadcast this packet to other routers in the network. Broadcast
3333      this list packet instead of multiple New Channel packets. */
3334   if (server->server_type == SILC_ROUTER &&
3335       sock->type == SILC_SOCKET_TYPE_SERVER &&
3336       !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
3337     SILC_LOG_DEBUG(("Broadcasting received New Channel packet"));
3338     silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
3339                             packet->type,
3340                             packet->flags | SILC_PACKET_FLAG_BROADCAST,
3341                             packet->buffer->data,
3342                             packet->buffer->len, FALSE);
3343     silc_server_backup_send(server, sock->user_data,
3344                             packet->type, packet->flags,
3345                             packet->buffer->data, packet->buffer->len,
3346                             FALSE, TRUE);
3347   }
3348
3349   silc_free(channel_namec);
3350   silc_channel_payload_free(payload);
3351 }
3352
3353 /* Received New Channel List packet, list of New Channel List payloads inside
3354    one packet. Process the New Channel payloads one by one. */
3355
3356 void silc_server_new_channel_list(SilcServer server,
3357                                   SilcSocketConnection sock,
3358                                   SilcPacketContext *packet)
3359 {
3360   SilcPacketContext *new;
3361   SilcBuffer buffer;
3362   SilcUInt16 len1, len2;
3363
3364   SILC_LOG_DEBUG(("Processing New Channel List"));
3365
3366   if (sock->type == SILC_SOCKET_TYPE_CLIENT ||
3367       packet->src_id_type != SILC_ID_SERVER ||
3368       server->server_type == SILC_SERVER)
3369     return;
3370
3371   /* Make copy of the original packet context, except for the actual
3372      data buffer, which we will here now fetch from the original buffer. */
3373   new = silc_packet_context_alloc();
3374   new->type = SILC_PACKET_NEW_CHANNEL;
3375   new->flags = packet->flags & (~SILC_PACKET_FLAG_LIST);
3376   new->src_id = packet->src_id;
3377   new->src_id_len = packet->src_id_len;
3378   new->src_id_type = packet->src_id_type;
3379   new->dst_id = packet->dst_id;
3380   new->dst_id_len = packet->dst_id_len;
3381   new->dst_id_type = packet->dst_id_type;
3382
3383   buffer = silc_buffer_alloc(512);
3384   new->buffer = buffer;
3385
3386   while (packet->buffer->len) {
3387     SILC_GET16_MSB(len1, packet->buffer->data);
3388     if ((len1 > packet->buffer->len) ||
3389         (len1 > buffer->truelen))
3390       break;
3391
3392     SILC_GET16_MSB(len2, packet->buffer->data + 2 + len1);
3393     if ((len2 > packet->buffer->len) ||
3394         (len2 > buffer->truelen))
3395       break;
3396
3397     silc_buffer_pull_tail(buffer, 8 + len1 + len2);
3398     silc_buffer_put(buffer, packet->buffer->data, 8 + len1 + len2);
3399
3400     /* Process the New Channel */
3401     silc_server_new_channel(server, sock, new);
3402
3403     silc_buffer_push_tail(buffer, 8 + len1 + len2);
3404     silc_buffer_pull(packet->buffer, 8 + len1 + len2);
3405   }
3406
3407   silc_buffer_free(buffer);
3408   silc_free(new);
3409 }
3410
3411 /* Received key agreement packet. This packet is never for us. It is to
3412    the client in the packet's destination ID. Sending of this sort of packet
3413    equals sending private message, ie. it is sent point to point from
3414    one client to another. */
3415
3416 void silc_server_key_agreement(SilcServer server,
3417                                SilcSocketConnection sock,
3418                                SilcPacketContext *packet)
3419 {
3420   SilcSocketConnection dst_sock;
3421   SilcIDListData idata;
3422
3423   SILC_LOG_DEBUG(("Start"));
3424
3425   if (packet->src_id_type != SILC_ID_CLIENT ||
3426       packet->dst_id_type != SILC_ID_CLIENT)
3427     return;
3428
3429   if (!packet->dst_id)
3430     return;
3431
3432   /* Get the route to the client */
3433   dst_sock = silc_server_get_client_route(server, packet->dst_id,
3434                                           packet->dst_id_len, NULL,
3435                                           &idata, NULL);
3436   if (!dst_sock)
3437     return;
3438
3439   /* Relay the packet */
3440   silc_server_relay_packet(server, dst_sock, idata->send_key,
3441                            idata->hmac_send, idata->psn_send++,
3442                            packet, FALSE);
3443 }
3444
3445 /* Received connection auth request packet that is used during connection
3446    phase to resolve the mandatory authentication method.  This packet can
3447    actually be received at anytime but usually it is used only during
3448    the connection authentication phase. Now, protocol says that this packet
3449    can come from client or server, however, we support only this coming
3450    from client and expect that server always knows what authentication
3451    method to use. */
3452
3453 void silc_server_connection_auth_request(SilcServer server,
3454                                          SilcSocketConnection sock,
3455                                          SilcPacketContext *packet)
3456 {
3457   SilcServerConfigClient *client = NULL;
3458   SilcUInt16 conn_type;
3459   int ret;
3460   SilcAuthMethod auth_meth = SILC_AUTH_NONE;
3461
3462   if (packet->src_id_type && packet->src_id_type != SILC_ID_CLIENT) {
3463     SILC_LOG_DEBUG(("Request not from client"));
3464     return;
3465   }
3466
3467   /* Parse the payload */
3468   ret = silc_buffer_unformat(packet->buffer,
3469                              SILC_STR_UI_SHORT(&conn_type),
3470                              SILC_STR_UI_SHORT(NULL),
3471                              SILC_STR_END);
3472   if (ret == -1)
3473     return;
3474
3475   if (conn_type != SILC_SOCKET_TYPE_CLIENT)
3476     return;
3477
3478   /* Get the authentication method for the client */
3479   auth_meth = SILC_AUTH_NONE;
3480   client = silc_server_config_find_client(server, sock->ip);
3481   if (!client)
3482     client = silc_server_config_find_client(server, sock->hostname);
3483   if (client) {
3484     if (client->passphrase) {
3485       if (client->publickeys && !server->config->prefer_passphrase_auth)
3486         auth_meth = SILC_AUTH_PUBLIC_KEY;
3487       else
3488         auth_meth = SILC_AUTH_PASSWORD;
3489     } else if (client->publickeys)
3490       auth_meth = SILC_AUTH_PUBLIC_KEY;
3491   }
3492
3493   SILC_LOG_DEBUG(("Authentication method is [%s]",
3494                   (auth_meth == SILC_AUTH_NONE ? "None" :
3495                    auth_meth == SILC_AUTH_PASSWORD ? "Passphrase" :
3496                    "Digital signatures")));
3497
3498   /* Send it back to the client */
3499   silc_server_send_connection_auth_request(server, sock, conn_type, auth_meth);
3500 }
3501
3502 /* Received REKEY packet. The sender of the packet wants to regenerate
3503    its session keys. This starts the REKEY protocol. */
3504
3505 void silc_server_rekey(SilcServer server,
3506                        SilcSocketConnection sock,
3507                        SilcPacketContext *packet)
3508 {
3509   SilcProtocol protocol;
3510   SilcServerRekeyInternalContext *proto_ctx;
3511   SilcIDListData idata = (SilcIDListData)sock->user_data;
3512
3513   SILC_LOG_DEBUG(("Received rekey request"));
3514
3515   /* If we have other protocol executing we have no other choice but to
3516      not execute rekey. XXX This is very bad thing.  Let's hope this
3517      doesn't happen often. */
3518   if (sock->protocol) {
3519     SILC_LOG_WARNING(("Cannot execute REKEY protocol because other protocol "
3520                       "is executing at the same time"));
3521     return;
3522   }
3523
3524   /* Allocate internal protocol context. This is sent as context
3525      to the protocol. */
3526   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
3527   proto_ctx->server = (void *)server;
3528   proto_ctx->sock = silc_socket_dup(sock);
3529   proto_ctx->responder = TRUE;
3530   proto_ctx->pfs = idata->rekey->pfs;
3531
3532   /* Perform rekey protocol. Will call the final callback after the
3533      protocol is over. */
3534   silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY,
3535                       &protocol, proto_ctx, silc_server_rekey_final);
3536   sock->protocol = protocol;
3537
3538   if (proto_ctx->pfs == FALSE)
3539     /* Run the protocol */
3540     silc_protocol_execute(protocol, server->schedule, 0, 0);
3541 }
3542
3543 /* Received file transger packet. This packet is never for us. It is to
3544    the client in the packet's destination ID. Sending of this sort of packet
3545    equals sending private message, ie. it is sent point to point from
3546    one client to another. */
3547
3548 void silc_server_ftp(SilcServer server,
3549                      SilcSocketConnection sock,
3550                      SilcPacketContext *packet)
3551 {
3552   SilcSocketConnection dst_sock;
3553   SilcIDListData idata;
3554
3555   SILC_LOG_DEBUG(("Start"));
3556
3557   if (packet->src_id_type != SILC_ID_CLIENT ||
3558       packet->dst_id_type != SILC_ID_CLIENT)
3559     return;
3560
3561   if (!packet->dst_id)
3562     return;
3563
3564   /* Get the route to the client */
3565   dst_sock = silc_server_get_client_route(server, packet->dst_id,
3566                                           packet->dst_id_len, NULL,
3567                                           &idata, NULL);
3568   if (!dst_sock)
3569     return;
3570
3571   /* Relay the packet */
3572   silc_server_relay_packet(server, dst_sock, idata->send_key,
3573                            idata->hmac_send, idata->psn_send++,
3574                            packet, FALSE);
3575 }
3576
3577 typedef struct {
3578   SilcServer server;
3579   SilcSocketConnection sock;
3580   SilcPacketContext *packet;
3581   void *data;
3582 } *SilcServerResumeResolve;
3583
3584 SILC_SERVER_CMD_FUNC(resume_resolve)
3585 {
3586   SilcServerResumeResolve r = (SilcServerResumeResolve)context;
3587   SilcServer server = r->server;
3588   SilcSocketConnection sock = r->sock;
3589   SilcServerCommandReplyContext reply = context2;
3590   SilcClientEntry client;
3591
3592   SILC_LOG_DEBUG(("Start"));
3593
3594   if (!reply || !silc_command_get_status(reply->payload, NULL, NULL)) {
3595     SILC_LOG_ERROR(("Client %s (%s) tried to resume unknown client, "
3596                     "closing connection", sock->hostname, sock->ip));
3597     silc_server_disconnect_remote(server, sock,
3598                                   SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3599                                   "Resuming not possible");
3600     if (sock->user_data)
3601       silc_server_free_sock_user_data(server, sock, NULL);
3602     goto out;
3603   }
3604
3605   if (reply && silc_command_get(reply->payload) == SILC_COMMAND_WHOIS) {
3606     /* Get entry to the client, and resolve it if we don't have it. */
3607     client = silc_idlist_find_client_by_id(server->local_list,
3608                                            r->data, TRUE, NULL);
3609     if (!client) {
3610       client = silc_idlist_find_client_by_id(server->global_list,
3611                                              r->data, TRUE, NULL);
3612       if (!client) {
3613         SILC_LOG_ERROR(("Client %s (%s) tried to resume unknown client, "
3614                         "closing connection", sock->hostname, sock->ip));
3615         silc_server_disconnect_remote(server, sock,
3616                                       SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3617                                       "Resuming not possible");
3618         if (sock->user_data)
3619           silc_server_free_sock_user_data(server, sock, NULL);
3620         goto out;
3621       }
3622     }
3623
3624     if (!(client->mode & SILC_UMODE_DETACHED)) {
3625       SILC_LOG_ERROR(("Client %s (%s) tried to resume un-detached client, "
3626                       "closing connection", sock->hostname, sock->ip));
3627       silc_server_disconnect_remote(server, sock,
3628                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3629                                     "Resuming not possible");
3630       if (sock->user_data)
3631         silc_server_free_sock_user_data(server, sock, NULL);
3632       goto out;
3633     }
3634
3635     client->data.status |= SILC_IDLIST_STATUS_RESUME_RES;
3636   }
3637
3638   /* Reprocess the packet */
3639   silc_server_resume_client(server, sock, r->packet);
3640
3641  out:
3642   silc_socket_free(r->sock);
3643   silc_packet_context_free(r->packet);
3644   silc_free(r->data);
3645   silc_free(r);
3646 }
3647
3648 /* Received client resuming packet.  This is used to resume detached
3649    client session.  It can be sent by the client who wishes to resume
3650    but this is also sent by servers and routers to notify other routers
3651    that the client is not detached anymore. */
3652
3653 void silc_server_resume_client(SilcServer server,
3654                                SilcSocketConnection sock,
3655                                SilcPacketContext *packet)
3656 {
3657   SilcBuffer buffer = packet->buffer, buf;
3658   SilcIDListData idata;
3659   SilcIDCacheEntry id_cache = NULL;
3660   SilcClientEntry detached_client;
3661   SilcClientID *client_id = NULL;
3662   unsigned char *id_string, *auth = NULL, *nicknamec = NULL;
3663   SilcUInt16 id_len, auth_len = 0;
3664   int ret;
3665   bool resolved, local, nick_change = FALSE, resolve = FALSE;
3666   SilcChannelEntry channel;
3667   SilcHashTableList htl;
3668   SilcChannelClientEntry chl;
3669   SilcServerResumeResolve r;
3670   const char *cipher;
3671
3672   ret = silc_buffer_unformat(buffer,
3673                              SILC_STR_UI16_NSTRING(&id_string, &id_len),
3674                              SILC_STR_END);
3675   if (ret != -1)
3676     client_id = silc_id_str2id(id_string, id_len, SILC_ID_CLIENT);
3677
3678   if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
3679     /* Client send this and is attempting to resume to old client session */
3680     SilcClientEntry client;
3681     SilcBuffer keyp;
3682
3683     if (ret != -1) {
3684       silc_buffer_pull(buffer, 2 + id_len);
3685       auth = buffer->data;
3686       auth_len = buffer->len;
3687       silc_buffer_push(buffer, 2 + id_len);
3688     }
3689
3690     if (!client_id || auth_len < 128) {
3691       SILC_LOG_ERROR(("Client %s (%s) sent incomplete resume information, "
3692                       "closing connection", sock->hostname, sock->ip));
3693       silc_server_disconnect_remote(server, sock,
3694                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3695                                     "Resuming not possible");
3696       if (sock->user_data)
3697         silc_server_free_sock_user_data(server, sock, NULL);
3698       silc_free(client_id);
3699       return;
3700     }
3701
3702     /* Take client entry of this connection */
3703     client = (SilcClientEntry)sock->user_data;
3704     idata = (SilcIDListData)client;
3705
3706     /* Get entry to the client, and resolve it if we don't have it. */
3707     detached_client = silc_server_query_client(server, client_id, FALSE,
3708                                                &resolved);
3709     if (!detached_client) {
3710       if (resolved) {
3711         /* The client info is being resolved. Reprocess this packet after
3712            receiving the reply to the query. */
3713         SILC_LOG_DEBUG(("Resolving client"));
3714         r = silc_calloc(1, sizeof(*r));
3715         if (!r)
3716           return;
3717         r->server = server;
3718         r->sock = silc_socket_dup(sock);
3719         r->packet = silc_packet_context_dup(packet);
3720         r->data = client_id;
3721         silc_server_command_pending(server, SILC_COMMAND_WHOIS,
3722                                     server->cmd_ident,
3723                                     silc_server_command_resume_resolve, r);
3724       } else {
3725         SILC_LOG_ERROR(("Client %s (%s) tried to resume unknown client, "
3726                         "closing connection", sock->hostname, sock->ip));
3727         silc_server_disconnect_remote(server, sock,
3728                                       SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3729                                       "Resuming not possible");
3730         if (sock->user_data)
3731           silc_server_free_sock_user_data(server, sock, NULL);
3732         silc_free(client_id);
3733       }
3734       return;
3735     }
3736
3737     if (detached_client->data.status & SILC_IDLIST_STATUS_RESUMED) {
3738       SILC_LOG_ERROR(("Client %s (%s) tried to attach more than once, "
3739                       "closing connection", sock->hostname, sock->ip));
3740       silc_server_disconnect_remote(server, sock,
3741                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3742                                     "Resuming not possible");
3743       if (sock->user_data)
3744         silc_server_free_sock_user_data(server, sock, NULL);
3745       silc_free(client_id);
3746
3747       return;
3748     }
3749
3750     if (detached_client->resuming_client &&
3751         detached_client->resuming_client != client) {
3752       SILC_LOG_ERROR(("Client %s (%s) tried to attach more than once, "
3753                       "closing connection", sock->hostname, sock->ip));
3754       silc_server_disconnect_remote(server, sock,
3755                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3756                                     "Resuming not possible");
3757       if (sock->user_data)
3758         silc_server_free_sock_user_data(server, sock, NULL);
3759       silc_free(client_id);
3760
3761       return;
3762     }
3763
3764     if (!detached_client->resuming_client)
3765       detached_client->resuming_client = client;
3766
3767     if (!(detached_client->mode & SILC_UMODE_DETACHED))
3768       resolve = TRUE;
3769     if (!silc_hash_table_count(detached_client->channels) &&
3770         detached_client->router)
3771       resolve = TRUE;
3772     if (!detached_client->nickname)
3773       resolve = TRUE;
3774     if (detached_client->data.status & SILC_IDLIST_STATUS_RESUME_RES)
3775       resolve = FALSE;
3776
3777     if (resolve) {
3778       if (server->server_type == SILC_SERVER && !server->standalone) {
3779         /* The client info is being resolved. Reprocess this packet after
3780            receiving the reply to the query. */
3781         SILC_LOG_DEBUG(("Resolving client info"));
3782         silc_server_query_client(server, client_id, TRUE, NULL);
3783         r = silc_calloc(1, sizeof(*r));
3784         if (!r)
3785           return;
3786         r->server = server;
3787         r->sock = silc_socket_dup(sock);
3788         r->packet = silc_packet_context_dup(packet);
3789         r->data = client_id;
3790         silc_server_command_pending(server, SILC_COMMAND_WHOIS,
3791                                     server->cmd_ident,
3792                                     silc_server_command_resume_resolve, r);
3793         return;
3794       }
3795       if (server->server_type == SILC_SERVER) {
3796         SILC_LOG_ERROR(("Client %s (%s) tried to resume un-detached client, "
3797                         "closing connection", sock->hostname, sock->ip));
3798         silc_server_disconnect_remote(server, sock,
3799                                       SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3800                                       "Resuming not possible");
3801         if (sock->user_data)
3802           silc_server_free_sock_user_data(server, sock, NULL);
3803         silc_free(client_id);
3804         return;
3805       }
3806     }
3807
3808     /* Check that we have the public key of the client, if not then we must
3809        resolve it first. */
3810     if (!detached_client->data.public_key) {
3811       if (server->server_type == SILC_SERVER && server->standalone) {
3812         SILC_LOG_ERROR(("Detached client's public key not present, "
3813                         "closing connection"));
3814         silc_server_disconnect_remote(server, sock,
3815                                       SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3816                                       "Resuming not possible");
3817         if (sock->user_data)
3818           silc_server_free_sock_user_data(server, sock, NULL);
3819         silc_free(client_id);
3820       } else {
3821         /* We must retrieve the detached client's public key by sending
3822            GETKEY command. Reprocess this packet after receiving the key */
3823         SilcBuffer idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
3824         SilcSocketConnection dest_sock =
3825           silc_server_get_client_route(server, NULL, 0, client_id, NULL, NULL);
3826
3827         SILC_LOG_DEBUG(("Resolving client public key"));
3828
3829         silc_server_send_command(server, dest_sock ? dest_sock :
3830                                  SILC_PRIMARY_ROUTE(server),
3831                                  SILC_COMMAND_GETKEY, ++server->cmd_ident,
3832                                  1, 1, idp->data, idp->len);
3833
3834         r = silc_calloc(1, sizeof(*r));
3835         if (!r) {
3836           silc_free(client_id);
3837           return;
3838         }
3839
3840         r->server = server;
3841         r->sock = silc_socket_dup(sock);
3842         r->packet = silc_packet_context_dup(packet);
3843         silc_server_command_pending(server, SILC_COMMAND_GETKEY,
3844                                     server->cmd_ident,
3845                                     silc_server_command_resume_resolve, r);
3846
3847         silc_buffer_free(idp);
3848       }
3849       silc_free(client_id);
3850       return;
3851     } else if (!silc_pkcs_public_key_compare(detached_client->data.public_key,
3852                                              idata->public_key)) {
3853       /* We require that the connection and resuming authentication data
3854          must be using same key pair. */
3855       SILC_LOG_ERROR(("Resuming attempted with wrong public key, "
3856                       "closing connection"));
3857       silc_server_disconnect_remote(server, sock,
3858                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3859                                     "Resuming not possible");
3860       if (sock->user_data)
3861         silc_server_free_sock_user_data(server, sock, NULL);
3862       silc_free(client_id);
3863       return;
3864     }
3865
3866     /* Verify the authentication payload.  This has to be successful in
3867        order to allow the resuming */
3868     if (!idata->hash ||
3869         !silc_auth_verify_data(auth, auth_len, SILC_AUTH_PUBLIC_KEY,
3870                                detached_client->data.public_key, 0,
3871                                idata->hash, detached_client->id,
3872                                SILC_ID_CLIENT)) {
3873       SILC_LOG_ERROR(("Client %s (%s) resume authentication failed, "
3874                       "closing connection", sock->hostname, sock->ip));
3875       silc_server_disconnect_remote(server, sock,
3876                                     SILC_STATUS_ERR_INCOMPLETE_INFORMATION,
3877                                     "Resuming not possible");
3878       if (sock->user_data)
3879         silc_server_free_sock_user_data(server, sock, NULL);
3880       silc_free(client_id);
3881       return;
3882     }
3883
3884     /* Check nickname */
3885     nicknamec = silc_identifier_check(detached_client->nickname,
3886                                       strlen(detached_client->nickname),
3887                                       SILC_STRING_UTF8, 128, NULL);
3888     if (!nicknamec) {
3889       silc_server_disconnect_remote(server, sock,
3890                                     SILC_STATUS_ERR_BAD_NICKNAME,
3891                                     "Malformed nickname, cannot resume");
3892       if (sock->user_data)
3893         silc_server_free_sock_user_data(server, sock, NULL);
3894       return;
3895     }
3896
3897     /* If the ID is not based in our ID then change it */
3898     if (!SILC_ID_COMPARE(detached_client->id, server->id,
3899                          server->id->ip.data_len)) {
3900       silc_free(client_id);
3901       if (!silc_id_create_client_id(server, server->id, server->rng,
3902                                     server->md5hash, nicknamec,
3903                                     strlen(nicknamec), &client_id)) {
3904         silc_server_disconnect_remote(server, sock,
3905                                       SILC_STATUS_ERR_BAD_NICKNAME,
3906                                       "Resuming not possible");
3907         if (sock->user_data)
3908           silc_server_free_sock_user_data(server, sock, NULL);
3909         return;
3910       }
3911       nick_change = TRUE;
3912     }
3913
3914     /* Now resume the client to the network */
3915
3916     silc_schedule_task_del_by_context(server->schedule, detached_client);
3917     sock->user_data = detached_client;
3918     detached_client->connection = sock;
3919
3920     if (detached_client->data.public_key)
3921       silc_hash_table_del_by_context(server->pk_hash,
3922                                      detached_client->data.public_key,
3923                                      detached_client);
3924     if (idata->public_key)
3925       silc_hash_table_del_by_context(server->pk_hash,
3926                                      idata->public_key, idata);
3927
3928     /* Take new keys and stuff into use in the old entry */
3929     silc_idlist_del_data(detached_client);
3930     silc_idlist_add_data(detached_client, idata);
3931
3932     if (detached_client->data.public_key)
3933       silc_hash_table_add(server->pk_hash,
3934                           detached_client->data.public_key, detached_client);
3935
3936     detached_client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
3937     detached_client->data.status |= SILC_IDLIST_STATUS_RESUMED;
3938     detached_client->data.status |= SILC_IDLIST_STATUS_LOCAL;
3939     detached_client->data.status &= ~SILC_IDLIST_STATUS_RESUME_RES;
3940     detached_client->mode &= ~SILC_UMODE_DETACHED;
3941     server->stat.my_detached--;
3942
3943     /* We are finished - reset resuming client */
3944     detached_client->resuming_client = NULL;
3945
3946     /* Check if anyone is watching this client */
3947     if (server->server_type == SILC_ROUTER)
3948       silc_server_check_watcher_list(server, detached_client, NULL,
3949                                      SILC_NOTIFY_TYPE_UMODE_CHANGE);
3950
3951     /* Delete this current client entry since we're resuming to old one. */
3952     server->stat.my_clients--;
3953     server->stat.clients--;
3954     if (server->stat.cell_clients)
3955       server->stat.cell_clients--;
3956     silc_server_remove_from_channels(server, NULL, client, FALSE,
3957                                      NULL, FALSE, FALSE);
3958     silc_server_del_from_watcher_list(server, client);
3959     if (!silc_idlist_del_client(server->local_list, client))
3960       silc_idlist_del_client(server->global_list, client);
3961     client = detached_client;
3962     silc_free(client->servername);
3963     client->servername = strdup(server->server_name);
3964
3965     /* Send the RESUME_CLIENT packet to our primary router so that others
3966        know this client isn't detached anymore. */
3967     buf = silc_buffer_alloc_size(2 + id_len);
3968     silc_buffer_format(buf,
3969                        SILC_STR_UI_SHORT(id_len),
3970                        SILC_STR_UI_XNSTRING(id_string, id_len),
3971                        SILC_STR_END);
3972
3973     /* Send to primary router */
3974     silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
3975                             SILC_PACKET_RESUME_CLIENT, 0,
3976                             buf->data, buf->len, TRUE);
3977     silc_server_backup_send(server, client->router,
3978                             SILC_PACKET_RESUME_CLIENT, 0,
3979                             buf->data, buf->len, TRUE, TRUE);
3980
3981     /* As router we must deliver this packet directly to the original
3982        server whom this client was earlier. */
3983     if (server->server_type == SILC_ROUTER && client->router &&
3984         client->router->server_type != SILC_ROUTER)
3985       silc_server_packet_send(server, client->router->connection,
3986                               SILC_PACKET_RESUME_CLIENT, 0,
3987                               buf->data, buf->len, TRUE);
3988     silc_buffer_free(buf);
3989     client->router = NULL;
3990
3991     if (nick_change) {
3992       /* Notify about Client ID change, nickname doesn't actually change. */
3993       silc_server_send_notify_nick_change(server, SILC_PRIMARY_ROUTE(server),
3994                                           SILC_BROADCAST(server),
3995                                           client->id, client_id,
3996                                           client->nickname);
3997     }
3998
3999     /* Resolve users on those channels that client has joined but we
4000        haven't resolved user list yet. */
4001     if (server->server_type == SILC_SERVER && !server->standalone) {
4002       silc_hash_table_list(client->channels, &htl);
4003       while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4004         channel = chl->channel;
4005         SILC_LOG_DEBUG(("Resolving users for %s channel",
4006                         channel->channel_name));
4007         if (channel->disabled || !channel->users_resolved) {
4008           silc_server_send_command(server, SILC_PRIMARY_ROUTE(server),
4009                                    SILC_COMMAND_USERS, ++server->cmd_ident,
4010                                    1, 2, channel->channel_name,
4011                                    strlen(channel->channel_name));
4012         }
4013       }
4014       silc_hash_table_list_reset(&htl);
4015     }
4016
4017     /* Send the new client ID to the client. After this client may start
4018        receiving other packets, and may start sending packets too. */
4019     silc_server_send_new_id(server, sock, FALSE, client_id, SILC_ID_CLIENT,
4020                             silc_id_get_len(client_id, SILC_ID_CLIENT));
4021
4022     if (nick_change) {
4023       /* Send NICK change notify to channels as well. */
4024       SilcBuffer oidp, nidp;
4025       oidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
4026       nidp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
4027       silc_server_send_notify_on_channels(server, NULL, client,
4028                                           SILC_NOTIFY_TYPE_NICK_CHANGE, 3,
4029                                           oidp->data, oidp->len,
4030                                           nidp->data, nidp->len,
4031                                           client->nickname,
4032                                           strlen(client->nickname));
4033       silc_buffer_free(oidp);
4034       silc_buffer_free(nidp);
4035     }
4036
4037     /* Add the client again to the ID cache to get it to correct list */
4038     if (!silc_idcache_del_by_context(server->local_list->clients, client))
4039       silc_idcache_del_by_context(server->global_list->clients, client);
4040     silc_free(client->id);
4041     client->id = client_id;
4042     client_id = NULL;
4043     silc_idcache_add(server->local_list->clients, nicknamec,
4044                      client->id, client, 0, NULL);
4045
4046     /* Send some nice info to the client */
4047     silc_server_send_connect_notifys(server, sock, client);
4048
4049     /* Send all channel keys of channels the client has joined */
4050     silc_hash_table_list(client->channels, &htl);
4051     while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4052       bool created = FALSE;
4053       channel = chl->channel;
4054
4055       if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY)
4056         continue;
4057
4058       /* If we don't have channel key, then create one */
4059       if (!channel->channel_key) {
4060         if (!silc_server_create_channel_key(server, channel, 0))
4061           continue;
4062         created = TRUE;
4063       }
4064
4065       id_string = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
4066       cipher = silc_cipher_get_name(channel->channel_key);
4067       keyp =
4068         silc_channel_key_payload_encode(silc_id_get_len(channel->id,
4069                                                         SILC_ID_CHANNEL),
4070                                         id_string,
4071                                         strlen(cipher), cipher,
4072                                         channel->key_len / 8, channel->key);
4073       silc_free(id_string);
4074
4075       /* Send the channel key to the client */
4076       silc_server_packet_send(server, sock, SILC_PACKET_CHANNEL_KEY, 0,
4077                               keyp->data, keyp->len, FALSE);
4078
4079       /* Distribute the channel key to channel */
4080       if (created) {
4081         silc_server_send_channel_key(server, NULL, channel,
4082                                      server->server_type == SILC_ROUTER ?
4083                                      FALSE : !server->standalone);
4084         silc_server_backup_send(server, NULL, SILC_PACKET_CHANNEL_KEY, 0,
4085                                 keyp->data, keyp->len, FALSE, TRUE);
4086       }
4087
4088       silc_buffer_free(keyp);
4089     }
4090     silc_hash_table_list_reset(&htl);
4091
4092   } else if (sock->type != SILC_SOCKET_TYPE_CLIENT) {
4093     /* Server or router sent this to us to notify that that a client has
4094        been resumed. */
4095     SilcServerEntry server_entry;
4096     SilcServerID *server_id;
4097
4098     if (!client_id) {
4099       SILC_LOG_DEBUG(("Malformed resuming packet"));
4100       return;
4101     }
4102
4103     /* Get entry to the client, and resolve it if we don't have it. */
4104     detached_client = silc_idlist_find_client_by_id(server->local_list,
4105                                                     client_id, TRUE,
4106                                                     &id_cache);
4107     if (!detached_client) {
4108       detached_client = silc_idlist_find_client_by_id(server->global_list,
4109                                                       client_id, TRUE,
4110                                                       &id_cache);
4111       if (!detached_client) {
4112         SILC_LOG_DEBUG(("Resuming client is unknown"));
4113         silc_free(client_id);
4114         return;
4115       }
4116     }
4117
4118     /* Check that the client has not been resumed already because it is
4119        protocol error to attempt to resume more than once.  The client
4120        will be killed if this protocol error occurs. */
4121     if (detached_client->data.status & SILC_IDLIST_STATUS_RESUMED &&
4122         !(detached_client->mode & SILC_UMODE_DETACHED)) {
4123       /* The client is clearly attempting to resume more than once and
4124          perhaps playing around by resuming from several different places
4125          at the same time. */
4126       SILC_LOG_DEBUG(("Attempting to re-resume client, killing both"));
4127       silc_server_kill_client(server, detached_client, NULL,
4128                               server->id, SILC_ID_SERVER);
4129       silc_free(client_id);
4130       return;
4131     }
4132
4133     /* Check whether client is detached at all */
4134     if (!(detached_client->mode & SILC_UMODE_DETACHED)) {
4135       SILC_LOG_DEBUG(("Client is not detached"));
4136       silc_free(client_id);
4137       return;
4138     }
4139
4140     /* Check nickname */
4141     if (detached_client->nickname) {
4142       nicknamec = silc_identifier_check(detached_client->nickname,
4143                                         strlen(detached_client->nickname),
4144                                         SILC_STRING_UTF8, 128, NULL);
4145       if (!nicknamec) {
4146         silc_free(client_id);
4147         return;
4148       }
4149     }
4150
4151     SILC_LOG_DEBUG(("Resuming detached client"));
4152
4153     /* If the sender of this packet is server and we are router we need to
4154        broadcast this packet to other routers in the network. */
4155     if (server->server_type == SILC_ROUTER &&
4156         sock->type == SILC_SOCKET_TYPE_SERVER &&
4157         !(packet->flags & SILC_PACKET_FLAG_BROADCAST)) {
4158       SILC_LOG_DEBUG(("Broadcasting received Resume Client packet"));
4159       silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
4160                               packet->type,
4161                               packet->flags | SILC_PACKET_FLAG_BROADCAST,
4162                               buffer->data, buffer->len, FALSE);
4163       silc_server_backup_send(server, sock->user_data,
4164                               packet->type, packet->flags,
4165                               packet->buffer->data, packet->buffer->len,
4166                               FALSE, TRUE);
4167     }
4168
4169     /* Client is detached, and now it is resumed.  Remove the detached
4170        mode and mark that it is resumed. */
4171
4172     if (detached_client->data.public_key)
4173       silc_hash_table_del_by_context(server->pk_hash,
4174                                      detached_client->data.public_key,
4175                                      detached_client);
4176
4177     silc_idlist_del_data(detached_client);
4178     detached_client->mode &= ~SILC_UMODE_DETACHED;
4179     detached_client->data.status |= SILC_IDLIST_STATUS_RESUMED;
4180     detached_client->data.status &= ~SILC_IDLIST_STATUS_LOCAL;
4181     id_cache->expire = 0;
4182
4183     /* Check if anyone is watching this client */
4184     if (server->server_type == SILC_ROUTER)
4185       silc_server_check_watcher_list(server, detached_client, NULL,
4186                                      SILC_NOTIFY_TYPE_UMODE_CHANGE);
4187
4188     silc_schedule_task_del_by_context(server->schedule, detached_client);
4189
4190     /* Get the new owner of the resumed client */
4191     server_id = silc_id_str2id(packet->src_id, packet->src_id_len,
4192                                packet->src_id_type);
4193     if (!server_id) {
4194       silc_free(client_id);
4195       return;
4196     }
4197
4198     /* Get server entry */
4199     server_entry = silc_idlist_find_server_by_id(server->global_list,
4200                                                  server_id, TRUE, NULL);
4201     local = FALSE;
4202     if (!server_entry) {
4203       server_entry = silc_idlist_find_server_by_id(server->local_list,
4204                                                    server_id, TRUE, NULL);
4205       local = TRUE;
4206       if (!server_entry) {
4207         silc_free(server_id);
4208         silc_free(client_id);
4209         return;
4210       }
4211     }
4212
4213     if (server->server_type == SILC_ROUTER &&
4214         sock->type == SILC_SOCKET_TYPE_ROUTER &&
4215         server_entry->server_type == SILC_ROUTER)
4216       local = FALSE;
4217
4218     /* Change the client to correct list. */
4219     if (!silc_idcache_del_by_context(server->local_list->clients,
4220                                      detached_client))
4221       silc_idcache_del_by_context(server->global_list->clients,
4222                                   detached_client);
4223     silc_idcache_add(local && server->server_type == SILC_ROUTER ?
4224                      server->local_list->clients :
4225                      server->global_list->clients, nicknamec,
4226                      detached_client->id, detached_client, FALSE, NULL);
4227
4228     /* Change the owner of the client */
4229     detached_client->router = server_entry;
4230
4231     /* Update channel information regarding global clients on channel. */
4232     if (server->server_type != SILC_ROUTER) {
4233       silc_hash_table_list(detached_client->channels, &htl);
4234       while (silc_hash_table_get(&htl, NULL, (void *)&chl))
4235         chl->channel->global_users =
4236           silc_server_channel_has_global(chl->channel);
4237       silc_hash_table_list_reset(&htl);
4238     }
4239
4240     silc_free(server_id);
4241   }
4242
4243   silc_free(client_id);
4244 }