Fixed packet stream destroy crashes when closing connections.
[silc.git] / apps / silcd / server.c
1 /*
2
3   server.c
4
5   Author: Pekka Riikonen <priikone@silcnet.org>
6
7   Copyright (C) 1997 - 2007 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; version 2 of the License.
12
13   This program is distributed in the hope that it will be useful,
14   but WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16   GNU General Public License for more details.
17
18 */
19
20 #include "serverincludes.h"
21 #include "server_internal.h"
22
23 /************************* Types and definitions ****************************/
24
25 SILC_TASK_CALLBACK(silc_server_get_stats);
26 SILC_TASK_CALLBACK(silc_server_connect_router);
27 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry);
28 SILC_TASK_CALLBACK(silc_server_do_rekey);
29 SILC_TASK_CALLBACK(silc_server_purge_expired_clients);
30 static void silc_server_accept_new_connection(SilcNetStatus status,
31                                               SilcStream stream,
32                                               void *context);
33 static void silc_server_packet_parse_type(SilcServer server,
34                                           SilcPacketStream sock,
35                                           SilcPacket packet);
36 static void silc_server_rekey(SilcServer server, SilcPacketStream sock,
37                               SilcPacket packet);
38
39
40 /************************ Static utility functions **************************/
41
42 /* SKE public key verification callback */
43
44 static void
45 silc_server_verify_key(SilcSKE ske,
46                        SilcPublicKey public_key,
47                        void *context,
48                        SilcSKEVerifyCbCompletion completion,
49                        void *completion_context)
50 {
51   SilcPacketStream sock = context;
52   SilcUnknownEntry entry = silc_packet_get_context(sock);
53
54   SILC_LOG_DEBUG(("Verifying public key"));
55
56   if (silc_pkcs_get_type(public_key) != SILC_SKE_PK_TYPE_SILC) {
57     SILC_LOG_WARNING(("We don't support %s (%s) port %d public key type %d",
58                       entry->hostname, entry->ip, entry->port,
59                       silc_pkcs_get_type(public_key)));
60     completion(ske, SILC_SKE_STATUS_UNSUPPORTED_PUBLIC_KEY,
61                completion_context);
62     return;
63   }
64
65   /* We accept all keys without explicit verification */
66   completion(ske, SILC_SKE_STATUS_OK, completion_context);
67 }
68
69
70 /************************ Packet engine callbacks ***************************/
71
72 /* Packet engine callback to receive a packet */
73
74 static SilcBool silc_server_packet_receive(SilcPacketEngine engine,
75                                            SilcPacketStream stream,
76                                            SilcPacket packet,
77                                            void *callback_context,
78                                            void *stream_context)
79 {
80   SilcServer server = callback_context;
81   SilcIDListData idata = stream_context;
82
83   if (!idata)
84     return FALSE;
85
86   /* Packets we do not handle */
87   switch (packet->type) {
88   case SILC_PACKET_HEARTBEAT:
89   case SILC_PACKET_SUCCESS:
90   case SILC_PACKET_FAILURE:
91   case SILC_PACKET_REJECT:
92   case SILC_PACKET_KEY_EXCHANGE:
93   case SILC_PACKET_KEY_EXCHANGE_1:
94   case SILC_PACKET_KEY_EXCHANGE_2:
95   case SILC_PACKET_REKEY_DONE:
96   case SILC_PACKET_CONNECTION_AUTH:
97     return FALSE;
98     break;
99   }
100
101   /* Only specific packets can come without source ID present. */
102   if ((!packet->src_id ||
103        !(idata->status & SILC_IDLIST_STATUS_REGISTERED)) &&
104       packet->type != SILC_PACKET_NEW_CLIENT &&
105       packet->type != SILC_PACKET_NEW_SERVER &&
106       packet->type != SILC_PACKET_RESUME_CLIENT &&
107       packet->type != SILC_PACKET_CONNECTION_AUTH_REQUEST &&
108       packet->type != SILC_PACKET_DISCONNECT)
109     return FALSE;
110
111   /* NEW_CLIENT and NEW_SERVER are accepted only without source ID and
112      for unregistered connection. */
113   if (packet->src_id && (packet->type == SILC_PACKET_NEW_CLIENT ||
114                          packet->type == SILC_PACKET_NEW_SERVER) &&
115       (idata->status & SILC_IDLIST_STATUS_REGISTERED))
116     return FALSE;
117
118   /* Ignore packets from disabled connection */
119   if (idata->status & SILC_IDLIST_STATUS_DISABLED &&
120       packet->type != SILC_PACKET_HEARTBEAT &&
121       packet->type != SILC_PACKET_RESUME_ROUTER &&
122       packet->type != SILC_PACKET_REKEY)
123     return FALSE;
124
125   /* Check that the the current client ID is same as in the client's packet. */
126   if (idata->conn_type == SILC_CONN_CLIENT) {
127     SilcClientEntry client = (SilcClientEntry)silc_packet_get_context(stream);
128     SilcClientID client_id;
129
130     if (client->id && packet->src_id &&
131         silc_id_str2id(packet->src_id, packet->src_id_len,
132                        packet->src_id_type, &client_id, sizeof(client_id))) {
133       if (!SILC_ID_CLIENT_COMPARE(client->id, &client_id)) {
134         SILC_LOG_DEBUG(("Packet source is not same as sender, packet %s",
135                         silc_get_packet_name(packet->type)));
136         return FALSE;
137       }
138     }
139   }
140
141   if (server->server_type == SILC_ROUTER) {
142     /* Route the packet if it is not destined to us. Other ID types but
143        server are handled separately after processing them. */
144     if (packet->dst_id &&
145         !(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
146         packet->dst_id_type == SILC_ID_SERVER &&
147         idata->conn_type != SILC_CONN_CLIENT &&
148         memcmp(packet->dst_id, server->id_string, server->id_string_len)) {
149       SilcPacketStream conn;
150       SilcServerID server_id;
151
152       silc_id_str2id(packet->dst_id, packet->dst_id_len, packet->dst_id_type,
153                      &server_id, sizeof(server_id));
154
155       conn = silc_server_route_get(server, &server_id, SILC_ID_SERVER);
156       if (!conn) {
157         SILC_LOG_WARNING(("Packet to unknown server ID %s, dropped (no route)",
158                           silc_id_render(&server_id, SILC_ID_SERVER)));
159         return FALSE;
160       }
161
162       silc_server_packet_route(server, conn, packet);
163       silc_packet_free(packet);
164       return TRUE;
165     }
166   }
167
168   /* Broadcast packet if it is marked as broadcast packet and it is
169      originated from router and we are router. */
170   if (server->server_type == SILC_ROUTER &&
171       idata->conn_type == SILC_CONN_ROUTER &&
172       packet->flags & SILC_PACKET_FLAG_BROADCAST) {
173     /* Broadcast to our primary route */
174     silc_server_packet_broadcast(server, SILC_PRIMARY_ROUTE(server), packet);
175
176     /* If we have backup routers then we need to feed all broadcast
177        data to those servers. */
178     silc_server_backup_broadcast(server, stream, packet);
179   }
180
181   /* Process packet */
182   silc_server_packet_parse_type(server, stream, packet);
183
184   return TRUE;
185 }
186
187 /* Packet engine callback to indicate end of stream */
188
189 static void silc_server_packet_eos(SilcPacketEngine engine,
190                                    SilcPacketStream stream,
191                                    void *callback_context,
192                                    void *stream_context)
193 {
194   SilcServer server = callback_context;
195   SilcIDListData idata = silc_packet_get_context(stream);
196
197   SILC_LOG_DEBUG(("End of stream received"));
198
199   if (!idata)
200     return;
201
202   if (server->router_conn && server->router_conn->sock == stream &&
203       !server->router && server->standalone) {
204     silc_server_create_connections(server);
205     silc_server_free_sock_user_data(server, stream, NULL);
206   } else {
207     /* If backup disconnected then mark that resuming will not be allowed */
208      if (server->server_type == SILC_ROUTER && !server->backup_router &&
209          idata->conn_type == SILC_CONN_SERVER) {
210       SilcServerEntry server_entry = (SilcServerEntry)idata;
211       if (server_entry->server_type == SILC_BACKUP_ROUTER)
212         server->backup_closed = TRUE;
213     }
214
215     silc_server_free_sock_user_data(server, stream, NULL);
216   }
217
218   silc_server_close_connection(server, stream);
219 }
220
221 SILC_TASK_CALLBACK(silc_server_packet_error_timeout)
222 {
223   SilcServer server = app_context;
224   SilcPacketStream stream = context;
225   SilcIDListData idata = silc_packet_get_context(stream);
226
227   if (!idata)
228     return;
229
230   if (server->router_conn && server->router_conn->sock == stream &&
231       !server->router && server->standalone) {
232     silc_server_create_connections(server);
233   } else {
234     /* If backup disconnected then mark that resuming will not be allowed */
235      if (server->server_type == SILC_ROUTER && !server->backup_router &&
236          idata->conn_type == SILC_CONN_SERVER) {
237       SilcServerEntry server_entry = (SilcServerEntry)idata;
238       if (server_entry->server_type == SILC_BACKUP_ROUTER)
239         server->backup_closed = TRUE;
240     }
241
242     silc_server_free_sock_user_data(server, stream, NULL);
243   }
244
245   silc_server_close_connection(server, stream);
246 }
247
248 /* Packet engine callback to indicate error */
249
250 static void silc_server_packet_error(SilcPacketEngine engine,
251                                      SilcPacketStream stream,
252                                      SilcPacketError error,
253                                      void *callback_context,
254                                      void *stream_context)
255 {
256   SilcServer server = callback_context;
257   SilcIDListData idata = silc_packet_get_context(stream);
258   SilcStream sock = silc_packet_stream_get_stream(stream);
259   const char *ip;
260   SilcUInt16 port;
261
262   if (!idata || !sock)
263     return;
264
265   if (!silc_socket_stream_get_info(sock, NULL, NULL, &ip, &port))
266     return;
267
268   SILC_LOG_ERROR(("Connection %s:%d [%s]: %s", ip, port,
269                   SILC_CONNTYPE_STRING(idata->conn_type),
270                   silc_packet_error_string(error)));
271
272   if (!silc_packet_stream_is_valid(stream))
273     return;
274
275   silc_schedule_task_add_timeout(server->schedule,
276                                  silc_server_packet_error_timeout,
277                                  stream, 0, 0);
278 }
279
280 /* Packet stream callbacks */
281 static SilcPacketCallbacks silc_server_stream_cbs =
282 {
283   silc_server_packet_receive,
284   silc_server_packet_eos,
285   silc_server_packet_error
286 };
287
288 /* Parses the packet type and calls what ever routines the packet type
289    requires. This is done for all incoming packets. */
290
291 static void silc_server_packet_parse_type(SilcServer server,
292                                           SilcPacketStream sock,
293                                           SilcPacket packet)
294 {
295   SilcPacketType type = packet->type;
296   SilcIDListData idata = silc_packet_get_context(sock);
297
298   SILC_LOG_DEBUG(("Received %s packet [flags %d]",
299                   silc_get_packet_name(type), packet->flags));
300
301   /* Parse the packet type */
302   switch (type) {
303   case SILC_PACKET_NOTIFY:
304     /*
305      * Received notify packet. Server can receive notify packets from
306      * router. Server then relays the notify messages to clients if needed.
307      */
308     if (packet->flags & SILC_PACKET_FLAG_LIST)
309       silc_server_notify_list(server, sock, packet);
310     else
311       silc_server_notify(server, sock, packet);
312     break;
313
314     /*
315      * Private Message packets
316      */
317   case SILC_PACKET_PRIVATE_MESSAGE:
318     /*
319      * Received private message packet. The packet is coming from either
320      * client or server.
321      */
322     if (packet->flags & SILC_PACKET_FLAG_LIST)
323       break;
324     idata->last_receive = time(NULL);
325     silc_server_private_message(server, sock, packet);
326     break;
327
328     /*
329      * Channel packets
330      */
331   case SILC_PACKET_CHANNEL_MESSAGE:
332     /*
333      * Received channel message. Channel messages are special packets
334      * (although probably most common ones) thus they are handled
335      * specially.
336      */
337     if (packet->flags & SILC_PACKET_FLAG_LIST)
338       break;
339     idata->last_receive = time(NULL);
340     silc_server_channel_message(server, sock, packet);
341     break;
342
343     /*
344      * Command packets
345      */
346   case SILC_PACKET_COMMAND:
347     /*
348      * Recived command. Processes the command request and allocates the
349      * command context and calls the command.
350      */
351     if (packet->flags & SILC_PACKET_FLAG_LIST)
352       break;
353     server->stat.commands_received++;
354     silc_server_command_process(server, sock, packet);
355     break;
356
357   case SILC_PACKET_COMMAND_REPLY:
358     /*
359      * Received command reply packet. Received command reply to command. It
360      * may be reply to command sent by us or reply to command sent by client
361      * that we've routed further.
362      */
363     if (packet->flags & SILC_PACKET_FLAG_LIST)
364       break;
365     server->stat.commands_received++;
366     silc_server_command_reply(server, sock, packet);
367     break;
368
369   case SILC_PACKET_DISCONNECT:
370     {
371       SilcStatus status;
372       char *message = NULL;
373       const char *hostname, *ip;
374
375       if (packet->flags & SILC_PACKET_FLAG_LIST)
376         break;
377       if (silc_buffer_len(&packet->buffer) < 1)
378         break;
379
380       status = (SilcStatus)packet->buffer.data[0];
381       if (silc_buffer_len(&packet->buffer) > 1 &&
382           silc_utf8_valid(packet->buffer.data + 1,
383                           silc_buffer_len(&packet->buffer) - 1))
384         message = silc_memdup(packet->buffer.data + 1,
385                               silc_buffer_len(&packet->buffer) - 1);
386
387       if (!silc_socket_stream_get_info(silc_packet_stream_get_stream(sock),
388                                        NULL, &hostname, &ip, NULL))
389         break;
390
391       SILC_LOG_INFO(("Disconnected by %s (%s): %s (%d) %s", ip, hostname,
392                      silc_get_status_message(status), status,
393                      message ? message : ""));
394
395       silc_free(message);
396
397       /* Do not switch to backup in case of error */
398       server->backup_noswitch = (status == SILC_STATUS_OK ? FALSE : TRUE);
399
400       /* If backup disconnected then mark that resuming will not be allowed */
401       if (server->server_type == SILC_ROUTER && !server->backup_router &&
402           idata->conn_type == SILC_CONN_SERVER) {
403         SilcServerEntry server_entry = (SilcServerEntry)idata;
404         if (server_entry->server_type == SILC_BACKUP_ROUTER)
405           server->backup_closed = TRUE;
406       }
407
408       /* Handle the disconnection from our end too */
409       if (SILC_IS_LOCAL(idata))
410         silc_server_free_sock_user_data(server, sock, NULL);
411       silc_server_close_connection(server, sock);
412       server->backup_noswitch = FALSE;
413     }
414     break;
415
416   case SILC_PACKET_CHANNEL_KEY:
417     /*
418      * Received key for channel. As channels are created by the router
419      * the keys are as well. We will distribute the key to all of our
420      * locally connected clients on the particular channel. Router
421      * never receives this channel and thus is ignored.
422      */
423     if (packet->flags & SILC_PACKET_FLAG_LIST)
424       break;
425     silc_server_channel_key(server, sock, packet);
426     break;
427
428   case SILC_PACKET_PRIVATE_MESSAGE_KEY:
429     /*
430      * Private message key packet.
431      */
432     if (packet->flags & SILC_PACKET_FLAG_LIST)
433       break;
434     silc_server_private_message_key(server, sock, packet);
435     break;
436
437   case SILC_PACKET_CONNECTION_AUTH_REQUEST:
438     /*
439      * Connection authentication request packet. When we receive this packet
440      * we will send to the other end information about our mandatory
441      * authentication method for the connection. This packet maybe received
442      * at any time.
443      */
444     if (packet->flags & SILC_PACKET_FLAG_LIST)
445       break;
446     silc_server_connection_auth_request(server, sock, packet);
447     break;
448
449   case SILC_PACKET_NEW_ID:
450     /*
451      * Received New ID packet. This includes some new ID that has been
452      * created. It may be for client, server or channel. This is the way
453      * to distribute information about new registered entities in the
454      * SILC network.
455      */
456     if (packet->flags & SILC_PACKET_FLAG_LIST)
457       silc_server_new_id_list(server, sock, packet);
458     else
459       silc_server_new_id(server, sock, packet);
460     break;
461
462   case SILC_PACKET_NEW_CLIENT:
463     /*
464      * Received new client packet. This includes client information that
465      * we will use to create initial client ID. After creating new
466      * ID we will send it to the client.
467      */
468     if (packet->flags & SILC_PACKET_FLAG_LIST)
469       break;
470     silc_server_new_client(server, sock, packet);
471     break;
472
473   case SILC_PACKET_NEW_SERVER:
474     /*
475      * Received new server packet. This includes Server ID and some other
476      * information that we may save. This is received after server has
477      * connected to us.
478      */
479     if (packet->flags & SILC_PACKET_FLAG_LIST)
480       break;
481     silc_server_new_server(server, sock, packet);
482     break;
483
484   case SILC_PACKET_NEW_CHANNEL:
485     /*
486      * Received new channel packet. Information about new channel in the
487      * network are distributed using this packet.
488      */
489     if (packet->flags & SILC_PACKET_FLAG_LIST)
490       silc_server_new_channel_list(server, sock, packet);
491     else
492       silc_server_new_channel(server, sock, packet);
493     break;
494
495   case SILC_PACKET_HEARTBEAT:
496     /*
497      * Received heartbeat.
498      */
499     if (packet->flags & SILC_PACKET_FLAG_LIST)
500       break;
501     break;
502
503   case SILC_PACKET_KEY_AGREEMENT:
504     /*
505      * Received heartbeat.
506      */
507     if (packet->flags & SILC_PACKET_FLAG_LIST)
508       break;
509     silc_server_key_agreement(server, sock, packet);
510     break;
511
512   case SILC_PACKET_REKEY:
513     /*
514      * Received re-key packet. The sender wants to regenerate the session
515      * keys.
516      */
517     if (packet->flags & SILC_PACKET_FLAG_LIST)
518       break;
519     silc_server_rekey(server, sock, packet);
520     break;
521
522   case SILC_PACKET_FTP:
523     /* FTP packet */
524     if (packet->flags & SILC_PACKET_FLAG_LIST)
525       break;
526     silc_server_ftp(server, sock, packet);
527     break;
528
529   case SILC_PACKET_RESUME_CLIENT:
530     /* Resume client */
531     if (packet->flags & SILC_PACKET_FLAG_LIST)
532       break;
533     silc_server_resume_client(server, sock, packet);
534     break;
535
536   case SILC_PACKET_RESUME_ROUTER:
537     /* Resume router packet received. This packet is received for backup
538        router resuming protocol. */
539     if (packet->flags & SILC_PACKET_FLAG_LIST)
540       break;
541     silc_server_backup_resume_router(server, sock, packet);
542     break;
543
544   default:
545     SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
546     break;
547   }
548 }
549
550 /****************************** Server API **********************************/
551
552 /* Allocates a new SILC server object. This has to be done before the server
553    can be used. After allocation one must call silc_server_init to initialize
554    the server. The new allocated server object is returned to the new_server
555    argument. */
556
557 SilcBool silc_server_alloc(SilcServer *new_server)
558 {
559   SilcServer server;
560
561   SILC_LOG_DEBUG(("Allocating new server object"));
562
563   server = silc_calloc(1, sizeof(*server));
564   if (!server)
565     return FALSE;
566   server->server_type = SILC_SERVER;
567   server->standalone = TRUE;
568   server->local_list = silc_calloc(1, sizeof(*server->local_list));
569   if (!server->local_list)
570     return FALSE;
571   server->global_list = silc_calloc(1, sizeof(*server->global_list));
572   if (!server->global_list)
573     return FALSE;
574   server->pending_commands = silc_dlist_init();
575   if (!server->pending_commands)
576     return FALSE;
577   server->listeners = silc_dlist_init();
578   if (!server->listeners)
579     return FALSE;
580   server->repository = silc_skr_alloc();
581   if (!server->repository)
582     return FALSE;
583   server->conns = silc_dlist_init();
584   if (!server->conns)
585     return FALSE;
586   server->expired_clients = silc_dlist_init();
587   if (!server->expired_clients)
588     return FALSE;
589
590   *new_server = server;
591
592   return TRUE;
593 }
594
595 /* Free's the SILC server object. This is called at the very end before
596    the program ends. */
597
598 void silc_server_free(SilcServer server)
599 {
600   SilcList list;
601   SilcIDCacheEntry cache;
602   SilcIDListData idata;
603
604   SILC_LOG_DEBUG(("Free server %p", server));
605
606   if (!server)
607     return;
608
609   silc_server_backup_free(server);
610   silc_server_config_unref(&server->config_ref);
611   if (server->rng)
612     silc_rng_free(server->rng);
613   if (server->public_key)
614     silc_pkcs_public_key_free(server->public_key);
615   if (server->private_key)
616     silc_pkcs_private_key_free(server->private_key);
617   if (server->pending_commands)
618     silc_dlist_uninit(server->pending_commands);
619   if (server->id_entry) {
620     if (server->id_entry->data.sconn)
621       silc_schedule_task_del_by_context(server->schedule,
622                                         server->id_entry->data.sconn->sock);
623     silc_idlist_del_server(server->local_list, server->id_entry);
624   }
625
626   /* Delete all channels */
627   if (silc_idcache_get_all(server->local_list->channels, &list)) {
628     silc_list_start(list);
629     while ((cache = silc_list_get(list)))
630       silc_idlist_del_channel(server->local_list, cache->context);
631   }
632   if (silc_idcache_get_all(server->global_list->channels, &list)) {
633     silc_list_start(list);
634     while ((cache = silc_list_get(list)))
635       silc_idlist_del_channel(server->global_list, cache->context);
636   }
637
638   /* Delete all clients */
639   if (silc_idcache_get_all(server->local_list->clients, &list)) {
640     silc_list_start(list);
641     while ((cache = silc_list_get(list))) {
642       silc_schedule_task_del_by_context(server->schedule, cache->context);
643       silc_idlist_del_client(server->local_list, cache->context);
644     }
645   }
646   if (silc_idcache_get_all(server->global_list->clients, &list)) {
647     silc_list_start(list);
648     while ((cache = silc_list_get(list))) {
649       silc_schedule_task_del_by_context(server->schedule, cache->context);
650       silc_idlist_del_client(server->global_list, cache->context);
651     }
652   }
653
654   /* Delete all servers */
655   if (silc_idcache_get_all(server->local_list->servers, &list)) {
656     silc_list_start(list);
657     while ((cache = silc_list_get(list))) {
658       idata = (SilcIDListData)cache->context;
659       if (idata->sconn)
660         silc_schedule_task_del_by_context(server->schedule,
661                                           idata->sconn->sock);
662       silc_idlist_del_server(server->local_list, cache->context);
663     }
664   }
665   if (silc_idcache_get_all(server->global_list->servers, &list)) {
666     while ((cache = silc_list_get(list))) {
667       idata = (SilcIDListData)cache->context;
668       if (idata->sconn)
669         silc_schedule_task_del_by_context(server->schedule,
670                                           idata->sconn->sock);
671       silc_idlist_del_server(server->global_list, cache->context);
672     }
673   }
674
675   silc_schedule_task_del_by_context(server->schedule, server);
676   silc_schedule_uninit(server->schedule);
677   server->schedule = NULL;
678
679   silc_idcache_free(server->local_list->clients);
680   silc_idcache_free(server->local_list->servers);
681   silc_idcache_free(server->local_list->channels);
682   silc_idcache_free(server->global_list->clients);
683   silc_idcache_free(server->global_list->servers);
684   silc_idcache_free(server->global_list->channels);
685   silc_hash_table_free(server->watcher_list);
686   silc_hash_table_free(server->watcher_list_pk);
687   silc_hash_free(server->md5hash);
688   silc_hash_free(server->sha1hash);
689
690   silc_dlist_uninit(server->listeners);
691   silc_dlist_uninit(server->conns);
692   silc_dlist_uninit(server->expired_clients);
693   silc_skr_free(server->repository);
694   silc_packet_engine_stop(server->packet_engine);
695
696   silc_free(server->local_list);
697   silc_free(server->global_list);
698   silc_free(server->server_name);
699   silc_free(server);
700
701   silc_hmac_unregister_all();
702   silc_hash_unregister_all();
703   silc_cipher_unregister_all();
704   silc_pkcs_unregister_all();
705 }
706
707 /* Creates a new server listener. */
708
709 static SilcNetListener
710 silc_server_listen(SilcServer server, const char *server_ip, SilcUInt16 port)
711 {
712   SilcNetListener listener;
713
714   listener =
715     silc_net_tcp_create_listener(&server_ip, 1, port, TRUE,
716                                  server->config->require_reverse_lookup,
717                                  server->schedule,
718                                  silc_server_accept_new_connection, server);
719   if (!listener) {
720     SILC_SERVER_LOG_ERROR(("Could not create server listener: %s on %hu",
721                            server_ip, port));
722     return NULL;
723   }
724
725   return listener;
726 }
727
728 /* Adds a secondary listener. */
729
730 SilcBool silc_server_init_secondary(SilcServer server)
731 {
732   SilcServerConfigServerInfoInterface *interface;
733   SilcNetListener listener;
734
735   for (interface = server->config->server_info->secondary; interface;
736        interface = interface->next) {
737     listener = silc_server_listen(server, interface->server_ip,
738                                   interface->port);
739     if (!listener)
740       return FALSE;
741     silc_dlist_add(server->listeners, listener);
742   }
743
744   return TRUE;
745 }
746
747 /* Initializes the entire SILC server. This is called always before running
748    the server. This is called only once at the initialization of the program.
749    This binds the server to its listenning port. After this function returns
750    one should call silc_server_run to start the server. This returns TRUE
751    when everything is ok to run the server. Configuration file must be
752    read and parsed before calling this. */
753
754 SilcBool silc_server_init(SilcServer server)
755 {
756   SilcServerID *id;
757   SilcServerEntry id_entry;
758   SilcNetListener listener;
759   SilcUInt16 *port;
760   char **ip;
761
762   SILC_LOG_DEBUG(("Initializing server"));
763
764   server->starttime = time(NULL);
765
766   /* Take config object for us */
767   silc_server_config_ref(&server->config_ref, server->config,
768                          server->config);
769
770 #ifdef SILC_DEBUG
771   /* Set debugging on if configured */
772   if (server->config->debug_string) {
773     silc_log_debug(TRUE);
774     silc_log_set_debug_string(server->config->debug_string);
775   }
776 #endif /* SILC_DEBUG */
777
778   /* Steal public and private key from the config object */
779   server->public_key = server->config->server_info->public_key;
780   server->private_key = server->config->server_info->private_key;
781   server->config->server_info->public_key = NULL;
782   server->config->server_info->private_key = NULL;
783
784   /* Register all configured ciphers, PKCS and hash functions. */
785   if (!silc_server_config_register_ciphers(server))
786     silc_cipher_register_default();
787   if (!silc_server_config_register_pkcs(server))
788     silc_pkcs_register_default();
789   if (!silc_server_config_register_hashfuncs(server))
790     silc_hash_register_default();
791   if (!silc_server_config_register_hmacs(server))
792     silc_hmac_register_default();
793
794   /* Initialize random number generator for the server. */
795   server->rng = silc_rng_alloc();
796   silc_rng_init(server->rng);
797   silc_rng_global_init(server->rng);
798
799   /* Initialize hash functions for server to use */
800   silc_hash_alloc("md5", &server->md5hash);
801   silc_hash_alloc("sha1", &server->sha1hash);
802
803   /* Initialize the scheduler */
804   server->schedule = silc_schedule_init(server->config->param.connections_max,
805                                         server);
806   if (!server->schedule)
807     goto err;
808
809   /* First, register log files configuration for error output */
810   silc_server_config_setlogfiles(server);
811
812   /* Initialize ID caches */
813   server->local_list->clients =
814     silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor,
815                        server);
816   server->local_list->servers =
817     silc_idcache_alloc(0, SILC_ID_SERVER, silc_idlist_server_destructor,
818                        server);
819   server->local_list->channels =
820     silc_idcache_alloc(0, SILC_ID_CHANNEL, silc_idlist_channel_destructor,
821                        NULL);
822
823   /* These are allocated for normal server as well as these hold some
824      global information that the server has fetched from its router. For
825      router these are used as they are supposed to be used on router. */
826   server->global_list->clients =
827     silc_idcache_alloc(0, SILC_ID_CLIENT, silc_idlist_client_destructor,
828                        server);
829   server->global_list->servers =
830     silc_idcache_alloc(0, SILC_ID_SERVER, silc_idlist_server_destructor,
831                        server);
832   server->global_list->channels =
833     silc_idcache_alloc(0, SILC_ID_CHANNEL, silc_idlist_channel_destructor,
834                        NULL);
835
836   /* Init watcher lists */
837   server->watcher_list =
838     silc_hash_table_alloc(1, silc_hash_client_id_hash, NULL,
839                           silc_hash_data_compare, (void *)CLIENTID_HASH_LEN,
840                           NULL, NULL, TRUE);
841   if (!server->watcher_list)
842     goto err;
843   server->watcher_list_pk =
844     silc_hash_table_alloc(1, silc_hash_public_key, NULL,
845                           silc_hash_public_key_compare, NULL,
846                           NULL, NULL, TRUE);
847   if (!server->watcher_list_pk)
848     goto err;
849
850   /* Create TCP listener */
851   listener = silc_server_listen(
852                    server,
853                    server->config->server_info->primary == NULL ? NULL :
854                    server->config->server_info->primary->server_ip,
855                    server->config->server_info->primary == NULL ? 0 :
856                    server->config->server_info->primary->port);
857   if (!listener)
858     goto err;
859   silc_dlist_add(server->listeners, listener);
860
861   /* Create a Server ID for the server. */
862   port = silc_net_listener_get_port(listener, NULL);
863   ip = silc_net_listener_get_ip(listener, NULL);
864   silc_id_create_server_id(server->config->server_info->primary->public_ip ?
865                            server->config->server_info->primary->public_ip :
866                            ip[0], port[0], server->rng, &id);
867   if (!id)
868     goto err;
869
870   silc_free(port);
871   silc_free(ip[0]);
872   silc_free(ip);
873
874   server->id = id;
875   server->server_name = server->config->server_info->server_name;
876   server->config->server_info->server_name = NULL;
877   silc_id_id2str(server->id, SILC_ID_SERVER, server->id_string,
878                  sizeof(server->id_string), &server->id_string_len);
879
880   /* Add ourselves to the server list. We don't have a router yet
881      beacuse we haven't established a route yet. It will be done later.
882      For now, NULL is sent as router. This allocates new entry to
883      the ID list. */
884   id_entry =
885     silc_idlist_add_server(server->local_list, strdup(server->server_name),
886                            server->server_type,
887                            silc_id_dup(server->id, SILC_ID_SERVER),
888                            NULL, NULL);
889   if (!id_entry) {
890     SILC_LOG_ERROR(("Could not add local server to cache"));
891     goto err;
892   }
893   id_entry->data.status |= SILC_IDLIST_STATUS_REGISTERED;
894   id_entry->data.conn_type = (server->server_type == SILC_SERVER ?
895                               SILC_CONN_SERVER : SILC_CONN_ROUTER);
896   server->id_entry = id_entry;
897
898   /* Create secondary TCP listeners */
899   if (silc_server_init_secondary(server) == FALSE)
900     goto err;
901
902   server->listenning = TRUE;
903
904   /* Create connections to configured routers. */
905   silc_server_create_connections(server);
906
907   /* If server connections has been configured then we must be router as
908      normal server cannot have server connections, only router connections. */
909   if (server->config->servers) {
910     SilcServerConfigServer *ptr = server->config->servers;
911
912     server->server_type = SILC_ROUTER;
913     while (ptr) {
914       if (ptr->backup_router) {
915         server->server_type = SILC_BACKUP_ROUTER;
916         server->backup_router = TRUE;
917         server->id_entry->server_type = SILC_BACKUP_ROUTER;
918         break;
919       }
920       ptr = ptr->next;
921     }
922   }
923
924   if (server->server_type != SILC_ROUTER) {
925     server->stat.servers = 1;
926     server->stat.cell_servers = 1;
927   } else {
928     server->stat.routers = 1;
929   }
930
931   /* If we are normal server we'll retrieve network statisticial information
932      once in a while from the router. */
933   if (server->server_type != SILC_ROUTER)
934     silc_schedule_task_add_timeout(server->schedule, silc_server_get_stats,
935                                    server, 10, 0);
936
937   /* Start packet engine */
938   server->packet_engine =
939     silc_packet_engine_start(server->rng, server->server_type == SILC_ROUTER,
940                              &silc_server_stream_cbs, server);
941   if (!server->packet_engine)
942     goto err;
943
944   /* Register client entry expiration timeout */
945   silc_schedule_task_add_timeout(server->schedule,
946                                  silc_server_purge_expired_clients, server,
947                                  120, 0);
948
949   /* Initialize HTTP server */
950   silc_server_http_init(server);
951
952   SILC_LOG_DEBUG(("Server initialized"));
953
954   /* We are done here, return succesfully */
955   return TRUE;
956
957  err:
958   silc_server_config_unref(&server->config_ref);
959   return FALSE;
960 }
961
962 /* Task callback to close a socket connection after rehash */
963
964 SILC_TASK_CALLBACK(silc_server_rehash_close_connection)
965 {
966   SilcServer server = app_context;
967   SilcPacketStream sock = context;
968   SilcIDListData idata = silc_packet_get_context(sock);
969   const char *hostname;
970   SilcUInt16 port;
971
972   silc_socket_stream_get_info(silc_packet_stream_get_stream(sock),
973                               NULL, &hostname, NULL, &port);
974
975   SILC_LOG_INFO(("Connection %s:%d [%s] is unconfigured",
976                  hostname, port, SILC_CONNTYPE_STRING(idata->conn_type)));
977   silc_schedule_task_del_by_context(server->schedule, sock);
978   silc_server_disconnect_remote(server, sock,
979                                 SILC_STATUS_ERR_BANNED_FROM_SERVER,
980                                 "This connection is removed from "
981                                 "configuration");
982   silc_server_free_sock_user_data(server, sock, NULL);
983 }
984
985 /* This function basically reads the config file again and switches the config
986    object pointed by the server object. After that, we have to fix various
987    things such as the server_name and the listening ports.
988    Keep in mind that we no longer have the root privileges at this point. */
989
990 SilcBool silc_server_rehash(SilcServer server)
991 {
992   SilcServerConfig newconfig;
993
994   SILC_LOG_INFO(("Rehashing server"));
995
996   /* Reset the logging system */
997   silc_log_quick(TRUE);
998   silc_log_flush_all();
999
1000   /* Start the main rehash phase (read again the config file) */
1001   newconfig = silc_server_config_alloc(server->config_file, server);
1002   if (!newconfig) {
1003     SILC_LOG_ERROR(("Rehash FAILED."));
1004     return FALSE;
1005   }
1006
1007   /* Fix the server_name field */
1008   if (strcmp(server->server_name, newconfig->server_info->server_name)) {
1009     silc_free(server->server_name);
1010
1011     /* Check server name */
1012     server->server_name =
1013       silc_identifier_check(newconfig->server_info->server_name,
1014                             strlen(newconfig->server_info->server_name),
1015                             SILC_STRING_LOCALE, 256, NULL);
1016     if (!server->server_name) {
1017       SILC_LOG_ERROR(("Malformed server name string '%s'",
1018                       server->config->server_info->server_name));
1019       return FALSE;
1020     }
1021
1022     /* Update the idcache list with a fresh pointer */
1023     silc_free(server->id_entry->server_name);
1024     server->id_entry->server_name = strdup(server->server_name);
1025     silc_idcache_update_by_context(server->local_list->servers,
1026                                    server->id_entry, NULL,
1027                                    strdup(server->id_entry->server_name),
1028                                    TRUE);
1029   }
1030
1031   /* Set logging */
1032   silc_server_config_setlogfiles(server);
1033
1034   /* Change new key pair if necessary */
1035   if (newconfig->server_info->public_key &&
1036       !silc_pkcs_public_key_compare(server->public_key,
1037                                     newconfig->server_info->public_key)) {
1038     silc_pkcs_public_key_free(server->public_key);
1039     silc_pkcs_private_key_free(server->private_key);
1040     server->public_key = newconfig->server_info->public_key;
1041     server->private_key = newconfig->server_info->private_key;
1042     newconfig->server_info->public_key = NULL;
1043     newconfig->server_info->private_key = NULL;
1044   }
1045
1046   /* Check for unconfigured server and router connections and close
1047      connections that were unconfigured. */
1048
1049   if (server->config->routers) {
1050     SilcServerConfigRouter *ptr;
1051     SilcServerConfigRouter *newptr;
1052     SilcBool found;
1053
1054     for (ptr = server->config->routers; ptr; ptr = ptr->next) {
1055       found = FALSE;
1056
1057       /* Check whether new config has this one too */
1058       for (newptr = newconfig->routers; newptr; newptr = newptr->next) {
1059         if (silc_string_compare(newptr->host, ptr->host) &&
1060             newptr->port == ptr->port &&
1061             newptr->initiator == ptr->initiator) {
1062           found = TRUE;
1063           break;
1064         }
1065       }
1066
1067       if (!found && ptr->host) {
1068         /* Remove this connection */
1069         SilcPacketStream sock;
1070         sock = silc_server_find_socket_by_host(server, SILC_CONN_ROUTER,
1071                                                ptr->host, ptr->port);
1072         if (sock)
1073           silc_schedule_task_add_timeout(server->schedule,
1074                                          silc_server_rehash_close_connection,
1075                                          sock, 0, 1);
1076       }
1077     }
1078   }
1079
1080   if (server->config->servers) {
1081     SilcServerConfigServer *ptr;
1082     SilcServerConfigServer *newptr;
1083     SilcBool found;
1084
1085     for (ptr = server->config->servers; ptr; ptr = ptr->next) {
1086       found = FALSE;
1087
1088       /* Check whether new config has this one too */
1089       for (newptr = newconfig->servers; newptr; newptr = newptr->next) {
1090         if (silc_string_compare(newptr->host, ptr->host)) {
1091           found = TRUE;
1092           break;
1093         }
1094       }
1095
1096       if (!found && ptr->host) {
1097         /* Remove this connection */
1098         SilcPacketStream sock;
1099         sock = silc_server_find_socket_by_host(server, SILC_CONN_SERVER,
1100                                                ptr->host, 0);
1101         if (sock)
1102           silc_schedule_task_add_timeout(server->schedule,
1103                                          silc_server_rehash_close_connection,
1104                                          sock, 0, 1);
1105       }
1106     }
1107   }
1108
1109   if (server->config->clients) {
1110     SilcServerConfigClient *ptr;
1111     SilcServerConfigClient *newptr;
1112     SilcBool found;
1113
1114     for (ptr = server->config->clients; ptr; ptr = ptr->next) {
1115       found = FALSE;
1116
1117       /* Check whether new config has this one too */
1118       for (newptr = newconfig->clients; newptr; newptr = newptr->next) {
1119         if (silc_string_compare(newptr->host, ptr->host)) {
1120           found = TRUE;
1121           break;
1122         }
1123       }
1124
1125       if (!found && ptr->host) {
1126         /* Remove this connection */
1127         SilcPacketStream sock;
1128         sock = silc_server_find_socket_by_host(server, SILC_CONN_CLIENT,
1129                                                ptr->host, 0);
1130         if (sock)
1131           silc_schedule_task_add_timeout(server->schedule,
1132                                          silc_server_rehash_close_connection,
1133                                          sock, 0, 1);
1134       }
1135     }
1136   }
1137
1138   /* Create connections after rehash */
1139   silc_server_create_connections(server);
1140
1141   /* Check whether our router status has changed */
1142   if (newconfig->servers) {
1143     SilcServerConfigServer *ptr = newconfig->servers;
1144
1145     server->server_type = SILC_ROUTER;
1146     while (ptr) {
1147       if (ptr->backup_router) {
1148         server->server_type = SILC_BACKUP_ROUTER;
1149         server->backup_router = TRUE;
1150         server->id_entry->server_type = SILC_BACKUP_ROUTER;
1151         break;
1152       }
1153       ptr = ptr->next;
1154     }
1155   }
1156
1157   /* Our old config is gone now. We'll unreference our reference made in
1158      silc_server_init and then destroy it since we are destroying it
1159      underneath the application (layer which called silc_server_init). */
1160   silc_server_config_unref(&server->config_ref);
1161   silc_server_config_destroy(server->config);
1162
1163   /* Take new config context */
1164   server->config = newconfig;
1165   silc_server_config_ref(&server->config_ref, server->config, server->config);
1166
1167 #ifdef SILC_DEBUG
1168   /* Set debugging on if configured */
1169   if (server->config->debug_string) {
1170     silc_log_debug(TRUE);
1171     silc_log_set_debug_string(server->config->debug_string);
1172   }
1173 #endif /* SILC_DEBUG */
1174
1175   SILC_LOG_DEBUG(("Server rehashed"));
1176
1177   return TRUE;
1178 }
1179
1180 /* The heart of the server. This runs the scheduler thus runs the server.
1181    When this returns the server has been stopped and the program will
1182    be terminated. */
1183
1184 void silc_server_run(SilcServer server)
1185 {
1186   SILC_LOG_INFO(("SILC Server started"));
1187
1188   /* Start the scheduler, the heart of the SILC server. When this returns
1189      the program will be terminated. */
1190   silc_schedule(server->schedule);
1191 }
1192
1193 /* Stops the SILC server. This function is used to shutdown the server.
1194    This is usually called after the scheduler has returned. After stopping
1195    the server one should call silc_server_free. */
1196
1197 void silc_server_stop(SilcServer server)
1198 {
1199   SilcDList list;
1200   SilcPacketStream ps;
1201   SilcNetListener listener;
1202
1203   SILC_LOG_INFO(("SILC Server shutting down"));
1204
1205   server->server_shutdown = TRUE;
1206
1207   /* Close all connections */
1208   if (server->packet_engine) {
1209     list = silc_packet_engine_get_streams(server->packet_engine);
1210
1211     silc_dlist_start(list);
1212     while ((ps = silc_dlist_get(list))) {
1213       SilcIDListData idata = silc_packet_get_context(ps);
1214
1215       if (!silc_packet_stream_is_valid(ps))
1216         continue;
1217
1218       if (idata)
1219         idata->status &= ~SILC_IDLIST_STATUS_DISABLED;
1220
1221       silc_server_disconnect_remote(server, ps, SILC_STATUS_OK,
1222                                     "Server is shutting down");
1223       silc_server_free_sock_user_data(server, ps,
1224                                       "Server is shutting down");
1225     }
1226     silc_packet_engine_free_streams_list(list);
1227   }
1228
1229   /* We are not connected to network anymore */
1230   server->standalone = TRUE;
1231
1232   silc_dlist_start(server->listeners);
1233   while ((listener = silc_dlist_get(server->listeners)))
1234     silc_net_close_listener(listener);
1235
1236   silc_server_http_uninit(server);
1237
1238   /* Cancel any possible retry timeouts */
1239   silc_schedule_task_del_by_callback(server->schedule,
1240                                      silc_server_connect_router);
1241   silc_schedule_task_del_by_callback(server->schedule,
1242                                      silc_server_connect_to_router_retry);
1243   silc_schedule_task_del_by_callback(server->schedule,
1244                                      silc_server_connect_to_router);
1245
1246   silc_schedule_stop(server->schedule);
1247
1248   SILC_LOG_DEBUG(("Server stopped"));
1249 }
1250
1251 /* Purge expired client entries from the server */
1252
1253 SILC_TASK_CALLBACK(silc_server_purge_expired_clients)
1254 {
1255   SilcServer server = context;
1256   SilcClientEntry client;
1257   SilcIDList id_list;
1258   SilcUInt64 curtime = silc_time();
1259
1260   SILC_LOG_DEBUG(("Expire timeout"));
1261
1262   silc_dlist_start(server->expired_clients);
1263   while ((client = silc_dlist_get(server->expired_clients))) {
1264     if (client->data.status & SILC_IDLIST_STATUS_REGISTERED)
1265       continue;
1266
1267     /* For unregistered clients the created timestamp is actually
1268        unregistered timestamp.  Make sure client remains in history
1269        at least 500 seconds. */
1270     if (curtime - client->data.created < 500)
1271       continue;
1272
1273     id_list = (client->data.status & SILC_IDLIST_STATUS_LOCAL ?
1274                server->local_list : server->global_list);
1275
1276     silc_idlist_del_data(client);
1277     silc_idlist_del_client(id_list, client);
1278     silc_dlist_del(server->expired_clients, client);
1279   }
1280
1281   silc_schedule_task_add_timeout(server->schedule,
1282                                  silc_server_purge_expired_clients, server,
1283                                  120, 0);
1284 }
1285
1286
1287 /******************************* Connecting *********************************/
1288
1289 /* Free connection context */
1290
1291 void silc_server_connection_free(SilcServerConnection sconn)
1292 {
1293   SILC_LOG_DEBUG(("Free connection %p", sconn));
1294   silc_dlist_del(sconn->server->conns, sconn);
1295   silc_server_config_unref(&sconn->conn);
1296   silc_free(sconn->remote_host);
1297   silc_free(sconn->backup_replace_ip);
1298   silc_free(sconn);
1299 }
1300
1301 /* Creates connection to a remote router. */
1302
1303 void silc_server_create_connection(SilcServer server,
1304                                    SilcBool reconnect,
1305                                    SilcBool dynamic,
1306                                    const char *remote_host, SilcUInt32 port,
1307                                    SilcServerConnectCallback callback,
1308                                    void *context)
1309 {
1310   SilcServerConnection sconn;
1311
1312   /* Allocate connection object for hold connection specific stuff. */
1313   sconn = silc_calloc(1, sizeof(*sconn));
1314   if (!sconn)
1315     return;
1316   sconn->remote_host = strdup(remote_host);
1317   sconn->remote_port = port;
1318   sconn->no_reconnect = reconnect == FALSE;
1319   sconn->callback = callback;
1320   sconn->callback_context = context;
1321   sconn->no_conf = dynamic;
1322   sconn->server = server;
1323
1324   SILC_LOG_DEBUG(("Created connection %p", sconn));
1325
1326   silc_schedule_task_add_timeout(server->schedule, silc_server_connect_router,
1327                                  sconn, 0, 0);
1328 }
1329
1330 /* Connection authentication completion callback */
1331
1332 static void
1333 silc_server_ke_auth_compl(SilcConnAuth connauth, SilcBool success,
1334                           void *context)
1335 {
1336   SilcServerConnection sconn = context;
1337   SilcUnknownEntry entry = silc_packet_get_context(sconn->sock);
1338   SilcServer server = entry->server;
1339   SilcServerConfigServer *conn;
1340   SilcServerConfigConnParams *param;
1341   SilcIDListData idata;
1342   SilcServerEntry id_entry = NULL;
1343   unsigned char id[32];
1344   SilcUInt32 id_len;
1345   SilcID remote_id;
1346   const char *ip;
1347
1348   SILC_LOG_DEBUG(("Connection %p authentication completed", sconn));
1349
1350   entry->op = NULL;
1351
1352   if (success == FALSE) {
1353     /* Authentication failed */
1354     /* XXX retry connecting */
1355
1356     silc_server_disconnect_remote(server, sconn->sock,
1357                                   SILC_STATUS_ERR_AUTH_FAILED, NULL);
1358     if (sconn->callback)
1359       (*sconn->callback)(server, NULL, sconn->callback_context);
1360     silc_server_connection_free(sconn);
1361     return;
1362   }
1363
1364   /* XXX For now remote is router always */
1365   entry->data.conn_type = SILC_CONN_ROUTER;
1366
1367   SILC_LOG_INFO(("Connected to %s %s",
1368                  SILC_CONNTYPE_STRING(entry->data.conn_type),
1369                  sconn->remote_host));
1370
1371   /* Create the actual entry for remote entity */
1372   switch (entry->data.conn_type) {
1373   case SILC_CONN_SERVER:
1374     SILC_LOG_DEBUG(("Remote is SILC server"));
1375
1376     /* Add new server.  The server must register itself to us before it
1377        becomes registered to SILC network. */
1378     id_entry = silc_idlist_add_server(server->local_list,
1379                                       strdup(sconn->remote_host),
1380                                       SILC_SERVER, NULL, NULL, sconn->sock);
1381     if (!id_entry) {
1382       silc_server_disconnect_remote(server, sconn->sock,
1383                                     SILC_STATUS_ERR_RESOURCE_LIMIT, NULL);
1384       if (sconn->callback)
1385         (*sconn->callback)(server, NULL, sconn->callback_context);
1386       silc_server_connection_free(sconn);
1387       silc_free(entry);
1388       return;
1389     }
1390
1391     /* Statistics */
1392     server->stat.my_servers++;
1393     if (server->server_type == SILC_ROUTER)
1394       server->stat.servers++;
1395     SILC_LOG_DEBUG(("my_servers %d", server->stat.my_servers));
1396
1397     silc_idlist_add_data(id_entry, (SilcIDListData)entry);
1398     break;
1399
1400   case SILC_CONN_ROUTER:
1401     SILC_LOG_DEBUG(("Remote is SILC router"));
1402
1403     /* Register to network */
1404     silc_id_id2str(server->id, SILC_ID_SERVER, id, sizeof(id), &id_len);
1405     if (!silc_packet_send_va(sconn->sock, SILC_PACKET_NEW_SERVER, 0,
1406                              SILC_STR_UI_SHORT(id_len),
1407                              SILC_STR_DATA(id, id_len),
1408                              SILC_STR_UI_SHORT(strlen(server->server_name)),
1409                              SILC_STR_DATA(server->server_name,
1410                                            strlen(server->server_name)),
1411                              SILC_STR_END)) {
1412       silc_server_disconnect_remote(server, sconn->sock,
1413                                     SILC_STATUS_ERR_RESOURCE_LIMIT, NULL);
1414       if (sconn->callback)
1415         (*sconn->callback)(server, NULL, sconn->callback_context);
1416       silc_server_connection_free(sconn);
1417       silc_free(entry);
1418       return;
1419     }
1420
1421     /* Get remote ID */
1422     silc_packet_get_ids(sconn->sock, NULL, NULL, NULL, &remote_id);
1423
1424     /* Check that we do not have this ID already */
1425     id_entry = silc_idlist_find_server_by_id(server->local_list,
1426                                              &remote_id.u.server_id,
1427                                              TRUE, NULL);
1428     if (id_entry) {
1429       silc_idcache_del_by_context(server->local_list->servers, id_entry, NULL);
1430     } else {
1431       id_entry = silc_idlist_find_server_by_id(server->global_list,
1432                                                &remote_id.u.server_id,
1433                                                TRUE, NULL);
1434       if (id_entry)
1435         silc_idcache_del_by_context(server->global_list->servers, id_entry,
1436                                     NULL);
1437     }
1438
1439     SILC_LOG_DEBUG(("New server id(%s)",
1440                     silc_id_render(&remote_id.u.server_id, SILC_ID_SERVER)));
1441
1442     /* Add the connected router to global server list.  Router is sent
1443        as NULL since it's local to us. */
1444     id_entry = silc_idlist_add_server(server->global_list,
1445                                       strdup(sconn->remote_host),
1446                                       SILC_ROUTER,
1447                                       silc_id_dup(&remote_id.u.server_id,
1448                                                   SILC_ID_SERVER),
1449                                       NULL, sconn->sock);
1450     if (!id_entry) {
1451       silc_server_disconnect_remote(server, sconn->sock,
1452                                     SILC_STATUS_ERR_RESOURCE_LIMIT, NULL);
1453       if (sconn->callback)
1454         (*sconn->callback)(server, NULL, sconn->callback_context);
1455       silc_server_connection_free(sconn);
1456       silc_free(entry);
1457       return;
1458     }
1459
1460     /* Registered */
1461     silc_idlist_add_data(id_entry, (SilcIDListData)entry);
1462     idata = (SilcIDListData)id_entry;
1463     idata->status |= (SILC_IDLIST_STATUS_REGISTERED |
1464                       SILC_IDLIST_STATUS_LOCAL);
1465     idata->sconn = sconn;
1466
1467     /* Statistics */
1468     server->stat.my_routers++;
1469     if (server->server_type == SILC_ROUTER)
1470       server->stat.routers++;
1471     SILC_LOG_DEBUG(("my_routers %d", server->stat.my_routers));
1472
1473     if (!sconn->backup) {
1474       /* Mark this router our primary router if we're still standalone */
1475       if (server->standalone) {
1476         SILC_LOG_DEBUG(("This connection is our primary router"));
1477         server->id_entry->router = id_entry;
1478         server->router = id_entry;
1479         server->router->server_type = SILC_ROUTER;
1480         server->standalone = FALSE;
1481         server->backup_primary = FALSE;
1482
1483         /* Announce data if we are not backup router (unless not as primary
1484            currently).  Backup router announces later at the end of
1485            resuming protocol. */
1486         if (server->backup_router && server->server_type == SILC_ROUTER) {
1487           SILC_LOG_DEBUG(("Announce data after resume protocol"));
1488         } else {
1489           /* If we are router then announce our possible servers.  Backup
1490              router announces also global servers. */
1491           if (server->server_type == SILC_ROUTER)
1492             silc_server_announce_servers(server,
1493                                          server->backup_router ? TRUE : FALSE,
1494                                          0, SILC_PRIMARY_ROUTE(server));
1495
1496           /* Announce our clients and channels to the router */
1497           silc_server_announce_clients(server, 0, SILC_PRIMARY_ROUTE(server));
1498           silc_server_announce_channels(server, 0, SILC_PRIMARY_ROUTE(server));
1499         }
1500
1501         /* If we are backup router then this primary router is whom we are
1502            backing up. */
1503         if (server->server_type == SILC_BACKUP_ROUTER) {
1504           silc_socket_stream_get_info(silc_packet_stream_get_stream(sconn->
1505                                                                     sock),
1506                                       NULL, NULL, &ip, NULL);
1507           silc_server_backup_add(server, server->id_entry, ip,
1508                                  sconn->remote_port, TRUE);
1509         }
1510 #if 0
1511       } else {
1512         /* We already have primary router.  Disconnect this connection */
1513         SILC_LOG_DEBUG(("We already have primary router, disconnect"));
1514         silc_idlist_del_server(server->global_list, id_entry);
1515         silc_server_disconnect_remote(server, sconn->sock,
1516                                       SILC_STATUS_ERR_RESOURCE_LIMIT, NULL);
1517         if (sconn->callback)
1518           (*sconn->callback)(server, NULL, sconn->callback_context);
1519         silc_server_connection_free(sconn);
1520         silc_free(entry);
1521         return;
1522 #endif /* 0 */
1523       }
1524     } else {
1525       /* Add this server to be our backup router */
1526       id_entry->server_type = SILC_BACKUP_ROUTER;
1527       silc_server_backup_add(server, id_entry, sconn->backup_replace_ip,
1528                              sconn->backup_replace_port, FALSE);
1529     }
1530
1531     break;
1532
1533   default:
1534     silc_server_disconnect_remote(server, sconn->sock,
1535                                   SILC_STATUS_ERR_AUTH_FAILED, NULL);
1536     if (sconn->callback)
1537       (*sconn->callback)(server, NULL, sconn->callback_context);
1538     silc_server_connection_free(sconn);
1539     silc_free(entry);
1540     return;
1541   }
1542
1543   SILC_LOG_DEBUG(("Connection established, sock %p", sconn->sock));
1544
1545   conn = sconn->conn.ref_ptr;
1546   param = &server->config->param;
1547   if (conn && conn->param)
1548     param = conn->param;
1549
1550   /* Register rekey timeout */
1551   sconn->rekey_timeout = param->key_exchange_rekey;
1552   silc_schedule_task_add_timeout(server->schedule, silc_server_do_rekey,
1553                                  sconn->sock, sconn->rekey_timeout, 0);
1554
1555   /* Set the entry as packet stream context */
1556   silc_packet_set_context(sconn->sock, id_entry);
1557
1558   /* Call the completion callback to indicate that we've connected to
1559      the router */
1560   if (sconn && sconn->callback)
1561     (*sconn->callback)(server, id_entry, sconn->callback_context);
1562
1563   if (sconn == server->router_conn)
1564     server->router_conn = NULL;
1565
1566   silc_free(entry);
1567 }
1568
1569 /* SKE completion callback */
1570
1571 static void silc_server_ke_completed(SilcSKE ske, SilcSKEStatus status,
1572                                      SilcSKESecurityProperties prop,
1573                                      SilcSKEKeyMaterial keymat,
1574                                      SilcSKERekeyMaterial rekey,
1575                                      void *context)
1576 {
1577   SilcPacketStream sock = context;
1578   SilcUnknownEntry entry = silc_packet_get_context(sock);
1579   SilcServerConnection sconn = silc_ske_get_context(ske);
1580   SilcServer server = entry->server;
1581   SilcServerConfigRouter *conn = sconn->conn.ref_ptr;
1582   SilcAuthMethod auth_meth = SILC_AUTH_NONE;
1583   void *auth_data = NULL;
1584   SilcUInt32 auth_data_len = 0;
1585   SilcConnAuth connauth;
1586   SilcCipher send_key, receive_key;
1587   SilcHmac hmac_send, hmac_receive;
1588   SilcHash hash;
1589
1590   SILC_LOG_DEBUG(("Connection %p, SKE completed", sconn));
1591
1592   entry->op = NULL;
1593
1594   if (status != SILC_SKE_STATUS_OK) {
1595     /* SKE failed */
1596     SILC_LOG_ERROR(("Error (%s) during Key Exchange protocol with %s (%s)",
1597                     silc_ske_map_status(status), entry->hostname, entry->ip));
1598
1599     /* XXX retry connecting */
1600     silc_ske_free(ske);
1601     silc_server_disconnect_remote(server, sconn->sock,
1602                                   SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1603     if (sconn->callback)
1604       (*sconn->callback)(server, NULL, sconn->callback_context);
1605     silc_server_connection_free(sconn);
1606     return;
1607   }
1608
1609   SILC_LOG_DEBUG(("Setting keys into use"));
1610
1611   /* Set the keys into use.  The data will be encrypted after this. */
1612   if (!silc_ske_set_keys(ske, keymat, prop, &send_key, &receive_key,
1613                          &hmac_send, &hmac_receive, &hash)) {
1614
1615     /* XXX retry connecting */
1616
1617     /* Error setting keys */
1618     silc_ske_free(ske);
1619     silc_server_disconnect_remote(server, sconn->sock,
1620                                   SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
1621     if (sconn->callback)
1622       (*sconn->callback)(server, NULL, sconn->callback_context);
1623     silc_server_connection_free(sconn);
1624     return;
1625   }
1626   silc_packet_set_keys(sconn->sock, send_key, receive_key, hmac_send,
1627                        hmac_receive, FALSE);
1628
1629   SILC_LOG_DEBUG(("Starting connection authentication"));
1630
1631   connauth = silc_connauth_alloc(server->schedule, ske,
1632                                  server->config->conn_auth_timeout);
1633   if (!connauth) {
1634     /* XXX retry connecting */
1635
1636     /** Error allocating auth protocol */
1637     silc_ske_free(ske);
1638     silc_server_disconnect_remote(server, sconn->sock,
1639                                   SILC_STATUS_ERR_RESOURCE_LIMIT, NULL);
1640     if (sconn->callback)
1641       (*sconn->callback)(server, NULL, sconn->callback_context);
1642     silc_server_connection_free(sconn);
1643     return;
1644   }
1645
1646   /* Get authentication method */
1647   if (conn) {
1648     if (conn->passphrase) {
1649       if (conn->publickeys && !server->config->prefer_passphrase_auth) {
1650         auth_meth = SILC_AUTH_PUBLIC_KEY;
1651         auth_data = server->private_key;
1652       } else {
1653         auth_meth = SILC_AUTH_PASSWORD;
1654         auth_data = conn->passphrase;
1655         auth_data_len = conn->passphrase_len;
1656       }
1657     } else {
1658       auth_meth = SILC_AUTH_PUBLIC_KEY;
1659       auth_data = server->private_key;
1660     }
1661   }
1662
1663   entry->data.rekey = rekey;
1664
1665   /* Start connection authentication */
1666   entry->op =
1667     silc_connauth_initiator(connauth, server->server_type == SILC_SERVER ?
1668                             SILC_CONN_SERVER : SILC_CONN_ROUTER, auth_meth,
1669                             auth_data, auth_data_len,
1670                             silc_server_ke_auth_compl, sconn);
1671 }
1672
1673 /* Function that is called when the network connection to a router has
1674    been established.  This will continue with the key exchange protocol
1675    with the remote router. */
1676
1677 void silc_server_start_key_exchange(SilcServerConnection sconn)
1678 {
1679   SilcServer server = sconn->server;
1680   SilcServerConfigRouter *conn = sconn->conn.ref_ptr;
1681   SilcUnknownEntry entry;
1682   SilcSKEParamsStruct params;
1683   SilcSKE ske;
1684
1685   /* Cancel any possible retry timeouts */
1686   silc_schedule_task_del_by_context(server->schedule, sconn);
1687
1688   /* Create packet stream */
1689   sconn->sock = silc_packet_stream_create(server->packet_engine,
1690                                           server->schedule, sconn->stream);
1691   if (!sconn->sock) {
1692     SILC_LOG_ERROR(("Cannot connect: cannot create packet stream"));
1693     silc_stream_destroy(sconn->stream);
1694     if (sconn->callback)
1695       (*sconn->callback)(server, NULL, sconn->callback_context);
1696     silc_server_connection_free(sconn);
1697     return;
1698   }
1699   server->stat.conn_num++;
1700
1701   /* Set source ID to packet stream */
1702   if (!silc_packet_set_ids(sconn->sock, SILC_ID_SERVER, server->id,
1703                            0, NULL)) {
1704     silc_packet_stream_destroy(sconn->sock);
1705     if (sconn->callback)
1706       (*sconn->callback)(server, NULL, sconn->callback_context);
1707     silc_server_connection_free(sconn);
1708     return;
1709   }
1710
1711   /* Create entry for remote entity */
1712   entry = silc_calloc(1, sizeof(*entry));
1713   if (!entry) {
1714     silc_packet_stream_destroy(sconn->sock);
1715     silc_server_connection_free(sconn);
1716     return;
1717   }
1718   entry->server = server;
1719   silc_packet_set_context(sconn->sock, entry);
1720
1721   /* Set Key Exchange flags from configuration, but fall back to global
1722      settings too. */
1723   memset(&params, 0, sizeof(params));
1724   SILC_GET_SKE_FLAGS(conn, params.flags);
1725   if (server->config->param.key_exchange_pfs)
1726     params.flags |= SILC_SKE_SP_FLAG_PFS;
1727
1728   /* Start SILC Key Exchange protocol */
1729   SILC_LOG_DEBUG(("Starting key exchange protocol, connection %p", sconn));
1730   ske = silc_ske_alloc(server->rng, server->schedule, server->repository,
1731                        server->public_key, server->private_key, sconn);
1732   if (!ske) {
1733     silc_free(entry);
1734     silc_packet_stream_destroy(sconn->sock);
1735     if (sconn->callback)
1736       (*sconn->callback)(server, NULL, sconn->callback_context);
1737     silc_server_connection_free(sconn);
1738     return;
1739   }
1740   silc_ske_set_callbacks(ske, silc_server_verify_key,
1741                          silc_server_ke_completed, sconn->sock);
1742
1743   /* Start key exchange protocol */
1744   params.version = silc_version_string;
1745   params.timeout_secs = server->config->key_exchange_timeout;
1746   entry->op = silc_ske_initiator(ske, sconn->sock, &params, NULL);
1747 }
1748
1749 /* Timeout callback that will be called to retry connecting to remote
1750    router. This is used by both normal and router server. This will wait
1751    before retrying the connecting. The timeout is generated by exponential
1752    backoff algorithm. */
1753
1754 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
1755 {
1756   SilcServerConnection sconn = context;
1757   SilcServer server = sconn->server;
1758   SilcServerConfigRouter *conn = sconn->conn.ref_ptr;
1759   SilcServerConfigConnParams *param =
1760                 (conn->param ? conn->param : &server->config->param);
1761
1762   SILC_LOG_INFO(("Retrying connecting to %s:%d", sconn->remote_host,
1763                  sconn->remote_port));
1764
1765   /* Calculate next timeout */
1766   if (sconn->retry_count >= 1) {
1767     sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
1768     if (sconn->retry_timeout > param->reconnect_interval_max)
1769       sconn->retry_timeout = param->reconnect_interval_max;
1770   } else {
1771     sconn->retry_timeout = param->reconnect_interval;
1772   }
1773   sconn->retry_count++;
1774   sconn->retry_timeout = sconn->retry_timeout +
1775     (silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER);
1776
1777   /* If we've reached max retry count, give up. */
1778   if ((sconn->retry_count > param->reconnect_count) &&
1779       !param->reconnect_keep_trying) {
1780     SILC_LOG_ERROR(("Could not connect, giving up"));
1781
1782     if (sconn->callback)
1783       (*sconn->callback)(server, NULL, sconn->callback_context);
1784     silc_server_connection_free(sconn);
1785     return;
1786   }
1787
1788   SILC_LOG_DEBUG(("Retrying connecting %d seconds", sconn->retry_timeout));
1789
1790   /* We will lookup a fresh pointer later */
1791   silc_server_config_unref(&sconn->conn);
1792
1793   /* Wait before retrying */
1794   silc_schedule_task_del_by_context(server->schedule, sconn);
1795   silc_schedule_task_add_timeout(server->schedule, silc_server_connect_router,
1796                                  sconn, sconn->retry_timeout, 0);
1797 }
1798
1799 /* Callback for async connection to remote router */
1800
1801 static void silc_server_connection_established(SilcNetStatus status,
1802                                                SilcStream stream,
1803                                                void *context)
1804 {
1805   SilcServerConnection sconn = context;
1806   SilcServer server = sconn->server;
1807
1808   silc_schedule_task_del_by_context(server->schedule, sconn);
1809   sconn->op = NULL;
1810
1811   switch (status) {
1812   case SILC_NET_OK:
1813     SILC_LOG_DEBUG(("Connection %p to %s:%d established", sconn,
1814                     sconn->remote_host, sconn->remote_port));
1815
1816     /* Continue with key exchange protocol */
1817     sconn->stream = stream;
1818     silc_server_start_key_exchange(sconn);
1819     break;
1820
1821   case SILC_NET_UNKNOWN_IP:
1822   case SILC_NET_UNKNOWN_HOST:
1823     SILC_LOG_ERROR(("Could not connect to %s:%d: %s",
1824                     sconn->remote_host, sconn->remote_port,
1825                     silc_net_get_error_string(status)));
1826
1827     if (sconn->callback)
1828       (*sconn->callback)(server, NULL, sconn->callback_context);
1829     silc_server_connection_free(sconn);
1830     break;
1831
1832   default:
1833     SILC_LOG_ERROR(("Could not connect to %s:%d: %s",
1834                     sconn->remote_host, sconn->remote_port,
1835                     silc_net_get_error_string(status)));
1836     if (!sconn->no_reconnect) {
1837       silc_schedule_task_add_timeout(sconn->server->schedule,
1838                                      silc_server_connect_to_router_retry,
1839                                      sconn, 1, 0);
1840       silc_dlist_del(server->conns, sconn);
1841     } else {
1842       if (sconn->callback)
1843         (*sconn->callback)(server, NULL, sconn->callback_context);
1844       silc_server_connection_free(sconn);
1845     }
1846     break;
1847   }
1848 }
1849
1850 /* Generic routine to use connect to a router. */
1851
1852 SILC_TASK_CALLBACK(silc_server_connect_router)
1853 {
1854   SilcServerConnection sconn = context;
1855   SilcServer server = sconn->server;
1856   SilcServerConfigRouter *rconn;
1857
1858   silc_schedule_task_del_by_context(server->schedule, sconn);
1859
1860   /* Don't connect if we are shutting down. */
1861   if (server->server_shutdown) {
1862     if (sconn->callback)
1863       (*sconn->callback)(server, NULL, sconn->callback_context);
1864     silc_server_connection_free(sconn);
1865     return;
1866   }
1867
1868   SILC_LOG_INFO(("Connecting to the %s %s on port %d",
1869                  (sconn->backup ? "backup router" : "router"),
1870                  sconn->remote_host, sconn->remote_port));
1871
1872   if (!sconn->no_conf) {
1873     /* Find connection configuration */
1874     rconn = silc_server_config_find_router_conn(server, sconn->remote_host,
1875                                                 sconn->remote_port);
1876     if (!rconn) {
1877       SILC_LOG_INFO(("Unconfigured %s connection %s:%d, cannot connect",
1878                      (sconn->backup ? "backup router" : "router"),
1879                      sconn->remote_host, sconn->remote_port));
1880       silc_server_connection_free(sconn);
1881       return;
1882     }
1883     silc_server_config_ref(&sconn->conn, server->config, (void *)rconn);
1884   }
1885
1886   /* Connect to remote host */
1887   sconn->op =
1888     silc_net_tcp_connect((!server->config->server_info->primary ? NULL :
1889                           server->config->server_info->primary->server_ip),
1890                          sconn->remote_host, sconn->remote_port,
1891                          server->schedule, silc_server_connection_established,
1892                          sconn);
1893   if (!sconn->op) {
1894     SILC_LOG_ERROR(("Could not connect to router %s:%d",
1895                     sconn->remote_host, sconn->remote_port));
1896     silc_server_connection_free(sconn);
1897     return;
1898   }
1899
1900   /* Add to connection list */
1901   silc_dlist_add(server->conns, sconn);
1902 }
1903
1904 /* This function connects to our primary router or if we are a router this
1905    establishes all our primary routes. This is called at the start of the
1906    server to do authentication and key exchange with our router - called
1907    from schedule. */
1908
1909 SILC_TASK_CALLBACK(silc_server_connect_to_router)
1910 {
1911   SilcServer server = context;
1912   SilcServerConnection sconn;
1913   SilcServerConfigRouter *ptr;
1914
1915   /* Don't connect if we are shutting down. */
1916   if (server->server_shutdown)
1917     return;
1918
1919   SILC_LOG_DEBUG(("We are %s",
1920                   (server->server_type == SILC_SERVER ?
1921                    "normal server" : server->server_type == SILC_ROUTER ?
1922                    "router" : "backup router/normal server")));
1923
1924   if (!server->config->routers) {
1925     /* There wasn't a configured router, we will continue but we don't
1926        have a connection to outside world.  We will be standalone server. */
1927     SILC_LOG_DEBUG(("No router(s), we are standalone"));
1928     server->standalone = TRUE;
1929     return;
1930   }
1931
1932   /* Cancel any possible retry timeouts */
1933   silc_schedule_task_del_by_callback(server->schedule,
1934                                      silc_server_connect_router);
1935   silc_schedule_task_del_by_callback(server->schedule,
1936                                      silc_server_connect_to_router_retry);
1937
1938   /* Create the connections to all our routes */
1939   for (ptr = server->config->routers; ptr; ptr = ptr->next) {
1940
1941     SILC_LOG_DEBUG(("%s connection [%s] %s:%d",
1942                     ptr->backup_router ? "Backup router" : "Router",
1943                     ptr->initiator ? "Initiator" : "Responder",
1944                     ptr->host, ptr->port));
1945
1946     if (server->server_type == SILC_ROUTER && ptr->backup_router &&
1947         ptr->initiator == FALSE && !server->backup_router &&
1948         !silc_server_config_get_backup_router(server))
1949       server->wait_backup = TRUE;
1950
1951     if (!ptr->initiator)
1952       continue;
1953     if (ptr->dynamic_connection)
1954       continue;
1955
1956     /* Check whether we are connecting or connected to this host already */
1957     if (silc_server_num_sockets_by_remote(server,
1958                                           silc_net_is_ip(ptr->host) ?
1959                                           ptr->host : NULL,
1960                                           silc_net_is_ip(ptr->host) ?
1961                                           NULL : ptr->host, ptr->port,
1962                                           SILC_CONN_ROUTER)) {
1963       SILC_LOG_DEBUG(("We are already connected to %s:%d",
1964                       ptr->host, ptr->port));
1965
1966       /* If we don't have primary router and this connection is our
1967          primary router we are in desync.  Reconnect to the primary. */
1968       if (server->standalone && !server->router) {
1969         /* XXX */
1970         SilcPacketStream sock;
1971         SilcServerConfigRouter *primary =
1972           silc_server_config_get_primary_router(server);
1973         if (primary != ptr)
1974           continue;
1975         sock = silc_server_find_socket_by_host(server, SILC_CONN_ROUTER,
1976                                                ptr->host, ptr->port);
1977         if (!sock)
1978           continue;
1979         server->backup_noswitch = TRUE;
1980         silc_server_free_sock_user_data(server, sock, NULL);
1981         silc_server_disconnect_remote(server, sock, 0, NULL);
1982         server->backup_noswitch = FALSE;
1983         SILC_LOG_DEBUG(("Reconnecting to primary router"));
1984       } else {
1985         continue;
1986       }
1987     }
1988
1989     /* Allocate connection object for hold connection specific stuff. */
1990     sconn = silc_calloc(1, sizeof(*sconn));
1991     if (!sconn)
1992       continue;
1993     sconn->server = server;
1994     sconn->remote_host = strdup(ptr->host);
1995     sconn->remote_port = ptr->port;
1996     sconn->backup = ptr->backup_router;
1997     if (sconn->backup) {
1998       sconn->backup_replace_ip = strdup(ptr->backup_replace_ip);
1999       sconn->backup_replace_port = ptr->backup_replace_port;
2000     }
2001
2002     SILC_LOG_DEBUG(("Created connection %p", sconn));
2003
2004     if (!server->router_conn && !sconn->backup)
2005       server->router_conn = sconn;
2006
2007     /* Connect */
2008     silc_server_connect_router(server->schedule, server, SILC_TASK_EXPIRE,
2009                                0, sconn);
2010   }
2011 }
2012
2013
2014 /************************ Accepting new connection **************************/
2015
2016 /* After this is called, server don't wait for backup router anymore.
2017    This gets called automatically even after we have backup router
2018    connection established. */
2019
2020 SILC_TASK_CALLBACK(silc_server_backup_router_wait)
2021 {
2022   SilcServer server = context;
2023   server->wait_backup = FALSE;
2024 }
2025
2026 /* Authentication data callback */
2027
2028 static SilcBool
2029 silc_server_accept_get_auth(SilcConnAuth connauth,
2030                             SilcConnectionType conn_type,
2031                             unsigned char **passphrase,
2032                             SilcUInt32 *passphrase_len,
2033                             SilcSKR *repository,
2034                             void *context)
2035 {
2036   SilcPacketStream sock = context;
2037   SilcUnknownEntry entry = silc_packet_get_context(sock);
2038   SilcServer server = entry->server;
2039
2040   SILC_LOG_DEBUG(("Remote connection type %d", conn_type));
2041
2042   /* Remote end is client */
2043   if (conn_type == SILC_CONN_CLIENT) {
2044     SilcServerConfigClient *cconfig = entry->cconfig.ref_ptr;
2045     if (!cconfig)
2046       return FALSE;
2047
2048     *passphrase = cconfig->passphrase;
2049     *passphrase_len = cconfig->passphrase_len;
2050     if (cconfig->publickeys)
2051       *repository = server->repository;
2052
2053     if (cconfig->publickeys) {
2054       if (server->config->prefer_passphrase_auth) {
2055         *repository = NULL;
2056       } else {
2057         *passphrase = NULL;
2058         *passphrase_len = 0;
2059       }
2060     }
2061
2062     entry->conn_type = conn_type;
2063     return TRUE;
2064   }
2065
2066   /* Remote end is server */
2067   if (conn_type == SILC_CONN_SERVER) {
2068     SilcServerConfigServer *sconfig;
2069
2070     /* If we are normal server, don't accept the connection */
2071     if (server->server_type == SILC_SERVER)
2072       return FALSE;
2073
2074     sconfig = entry->sconfig.ref_ptr;
2075     if (!sconfig)
2076       return FALSE;
2077
2078     *passphrase = sconfig->passphrase;
2079     *passphrase_len = sconfig->passphrase_len;
2080     if (sconfig->publickeys)
2081       *repository = server->repository;
2082
2083     if (sconfig->publickeys) {
2084       if (server->config->prefer_passphrase_auth) {
2085         *repository = NULL;
2086       } else {
2087         *passphrase = NULL;
2088         *passphrase_len = 0;
2089       }
2090     }
2091
2092     entry->conn_type = conn_type;
2093     return TRUE;
2094   }
2095
2096   /* Remote end is router */
2097   if (conn_type == SILC_CONN_ROUTER) {
2098     SilcServerConfigRouter *rconfig = entry->rconfig.ref_ptr;
2099     if (!rconfig)
2100       return FALSE;
2101
2102     *passphrase = rconfig->passphrase;
2103     *passphrase_len = rconfig->passphrase_len;
2104     if (rconfig->publickeys)
2105       *repository = server->repository;
2106
2107     if (rconfig->publickeys) {
2108       if (server->config->prefer_passphrase_auth) {
2109         *repository = NULL;
2110       } else {
2111         *passphrase = NULL;
2112         *passphrase_len = 0;
2113       }
2114     }
2115
2116     entry->conn_type = conn_type;
2117     return TRUE;
2118   }
2119
2120   return FALSE;
2121 }
2122
2123 /* Authentication completion callback. */
2124
2125 static void
2126 silc_server_accept_auth_compl(SilcConnAuth connauth, SilcBool success,
2127                               void *context)
2128 {
2129   SilcPacketStream sock = context;
2130   SilcUnknownEntry entry = silc_packet_get_context(sock);
2131   SilcIDListData idata = (SilcIDListData)entry;
2132   SilcServer server = entry->server;
2133   SilcServerConfigConnParams *param = &server->config->param;
2134   SilcServerConnection sconn;
2135   void *id_entry;
2136   const char *hostname, *ip;
2137   SilcUInt16 port;
2138
2139   entry->op = NULL;
2140   silc_socket_stream_get_info(silc_packet_stream_get_stream(sock),
2141                               NULL, &hostname, &ip, &port);
2142
2143   if (success == FALSE) {
2144     /* Authentication failed */
2145     SILC_LOG_INFO(("Authentication failed for %s (%s) [%s]", entry->hostname,
2146                    entry->ip, SILC_CONNTYPE_STRING(entry->data.conn_type)));
2147     server->stat.auth_failures++;
2148     silc_server_disconnect_remote(server, sock,
2149                                   SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
2150     goto out;
2151   }
2152
2153   SILC_LOG_DEBUG(("Checking whether connection is allowed"));
2154
2155   switch (entry->conn_type) {
2156   case SILC_CONN_CLIENT:
2157     {
2158       SilcClientEntry client;
2159       SilcServerConfigClient *conn = entry->cconfig.ref_ptr;
2160
2161       /* Verify whether this connection is after all allowed to connect */
2162       if (!silc_server_connection_allowed(server, sock, entry->conn_type,
2163                                           &server->config->param,
2164                                           conn->param,
2165                                           silc_connauth_get_ske(connauth))) {
2166         server->stat.auth_failures++;
2167         goto out;
2168       }
2169
2170       /* If we are primary router and we have backup router configured
2171          but it has not connected to use yet, do not accept any other
2172          connection. */
2173       if (server->wait_backup && server->server_type == SILC_ROUTER &&
2174           !server->backup_router) {
2175         SilcServerConfigRouter *router;
2176         router = silc_server_config_get_backup_router(server);
2177         if (router && strcmp(server->config->server_info->primary->server_ip,
2178                              entry->ip) &&
2179             silc_server_find_socket_by_host(server,
2180                                             SILC_CONN_SERVER,
2181                                             router->backup_replace_ip, 0)) {
2182           SILC_LOG_INFO(("Will not accept connections because we do "
2183                          "not have backup router connection established"));
2184           silc_server_disconnect_remote(server, sock,
2185                                         SILC_STATUS_ERR_PERM_DENIED,
2186                                         "We do not have connection to backup "
2187                                         "router established, try later");
2188           server->stat.auth_failures++;
2189
2190           /* From here on, wait 20 seconds for the backup router to appear. */
2191           silc_schedule_task_add_timeout(server->schedule,
2192                                          silc_server_backup_router_wait,
2193                                          (void *)server, 20, 0);
2194           goto out;
2195         }
2196       }
2197
2198       SILC_LOG_DEBUG(("Remote host is client"));
2199       SILC_LOG_INFO(("Connection %s (%s) is client", entry->hostname,
2200                      entry->ip));
2201
2202       /* Add the client to the client ID cache. The nickname and Client ID
2203          and other information is created after we have received NEW_CLIENT
2204          packet from client. */
2205       client = silc_idlist_add_client(server->local_list,
2206                                       NULL, NULL, NULL, NULL, NULL, sock);
2207       if (!client) {
2208         SILC_LOG_ERROR(("Could not add new client to cache"));
2209         server->stat.auth_failures++;
2210         silc_server_disconnect_remote(server, sock,
2211                                       SILC_STATUS_ERR_AUTH_FAILED, NULL);
2212         goto out;
2213       }
2214       entry->data.status |= SILC_IDLIST_STATUS_LOCAL;
2215       entry->data.conn_type = SILC_CONN_CLIENT;
2216
2217       /* Statistics */
2218       server->stat.my_clients++;
2219       server->stat.clients++;
2220       server->stat.cell_clients++;
2221
2222       /* Get connection parameters */
2223       if (conn->param) {
2224         param = conn->param;
2225
2226         if (!param->keepalive_secs)
2227           param->keepalive_secs = server->config->param.keepalive_secs;
2228
2229         if (!param->qos && server->config->param.qos) {
2230           param->qos = server->config->param.qos;
2231           param->qos_rate_limit = server->config->param.qos_rate_limit;
2232           param->qos_bytes_limit = server->config->param.qos_bytes_limit;
2233           param->qos_limit_sec = server->config->param.qos_limit_sec;
2234           param->qos_limit_usec = server->config->param.qos_limit_usec;
2235         }
2236
2237         /* Check if to be anonymous connection */
2238         if (param->anonymous)
2239           client->mode |= SILC_UMODE_ANONYMOUS;
2240       }
2241
2242       /* Add public key to repository */
2243       SILC_LOG_DEBUG(("Add client public key to repository"));
2244       if (!silc_server_get_public_key_by_client(server, client, NULL))
2245         silc_skr_add_public_key_simple(server->repository,
2246                                        entry->data.public_key,
2247                                        SILC_SKR_USAGE_IDENTIFICATION, client,
2248                                        NULL);
2249
2250       id_entry = (void *)client;
2251       break;
2252     }
2253
2254   case SILC_CONN_SERVER:
2255   case SILC_CONN_ROUTER:
2256     {
2257       SilcServerEntry new_server;
2258       SilcBool initiator = FALSE;
2259       SilcBool backup_local = FALSE;
2260       SilcBool backup_router = FALSE;
2261       char *backup_replace_ip = NULL;
2262       SilcUInt16 backup_replace_port = 0;
2263       SilcServerConfigServer *srvconn = entry->sconfig.ref_ptr;
2264       SilcServerConfigRouter *rconn = entry->rconfig.ref_ptr;
2265
2266       /* If we are backup router and this is incoming server connection
2267          and we do not have connection to primary router, do not allow
2268          the connection. */
2269       if (server->server_type == SILC_BACKUP_ROUTER &&
2270           entry->conn_type == SILC_CONN_SERVER &&
2271           !SILC_PRIMARY_ROUTE(server)) {
2272         SILC_LOG_INFO(("Will not accept server connection because we do "
2273                        "not have primary router connection established"));
2274         silc_server_disconnect_remote(server, sock,
2275                                       SILC_STATUS_ERR_PERM_DENIED,
2276                                       "We do not have connection to primary "
2277                                       "router established, try later");
2278         server->stat.auth_failures++;
2279         goto out;
2280       }
2281
2282       if (entry->conn_type == SILC_CONN_ROUTER) {
2283         /* Verify whether this connection is after all allowed to connect */
2284         if (!silc_server_connection_allowed(server, sock,
2285                                             entry->conn_type,
2286                                             &server->config->param,
2287                                             rconn ? rconn->param : NULL,
2288                                             silc_connauth_get_ske(connauth))) {
2289           server->stat.auth_failures++;
2290           goto out;
2291         }
2292
2293         if (rconn) {
2294           if (rconn->param) {
2295             param = rconn->param;
2296
2297             if (!param->keepalive_secs)
2298               param->keepalive_secs = server->config->param.keepalive_secs;
2299
2300             if (!param->qos && server->config->param.qos) {
2301               param->qos = server->config->param.qos;
2302               param->qos_rate_limit = server->config->param.qos_rate_limit;
2303               param->qos_bytes_limit = server->config->param.qos_bytes_limit;
2304               param->qos_limit_sec = server->config->param.qos_limit_sec;
2305               param->qos_limit_usec = server->config->param.qos_limit_usec;
2306             }
2307           }
2308
2309           initiator = rconn->initiator;
2310           backup_local = rconn->backup_local;
2311           backup_router = rconn->backup_router;
2312           backup_replace_ip = rconn->backup_replace_ip;
2313           backup_replace_port = rconn->backup_replace_port;
2314         }
2315       }
2316
2317       if (entry->conn_type == SILC_CONN_SERVER) {
2318         /* Verify whether this connection is after all allowed to connect */
2319         if (!silc_server_connection_allowed(server, sock,
2320                                             entry->conn_type,
2321                                             &server->config->param,
2322                                             srvconn ? srvconn->param : NULL,
2323                                             silc_connauth_get_ske(connauth))) {
2324           server->stat.auth_failures++;
2325           goto out;
2326         }
2327         if (srvconn) {
2328           if (srvconn->param) {
2329             param = srvconn->param;
2330
2331             if (!param->keepalive_secs)
2332               param->keepalive_secs = server->config->param.keepalive_secs;
2333
2334             if (!param->qos && server->config->param.qos) {
2335               param->qos = server->config->param.qos;
2336               param->qos_rate_limit = server->config->param.qos_rate_limit;
2337               param->qos_bytes_limit = server->config->param.qos_bytes_limit;
2338               param->qos_limit_sec = server->config->param.qos_limit_sec;
2339               param->qos_limit_usec = server->config->param.qos_limit_usec;
2340             }
2341           }
2342
2343           backup_router = srvconn->backup_router;
2344         }
2345       }
2346
2347       /* If we are primary router and we have backup router configured
2348          but it has not connected to use yet, do not accept any other
2349          connection. */
2350       if (server->wait_backup && server->server_type == SILC_ROUTER &&
2351           !server->backup_router && !backup_router) {
2352         SilcServerConfigRouter *router;
2353         router = silc_server_config_get_backup_router(server);
2354         if (router && strcmp(server->config->server_info->primary->server_ip,
2355                              ip) &&
2356             silc_server_find_socket_by_host(server,
2357                                             SILC_CONN_SERVER,
2358                                             router->backup_replace_ip, 0)) {
2359           SILC_LOG_INFO(("Will not accept connections because we do "
2360                          "not have backup router connection established"));
2361           silc_server_disconnect_remote(server, sock,
2362                                         SILC_STATUS_ERR_PERM_DENIED,
2363                                         "We do not have connection to backup "
2364                                         "router established, try later");
2365           server->stat.auth_failures++;
2366
2367           /* From here on, wait 20 seconds for the backup router to appear. */
2368           silc_schedule_task_add_timeout(server->schedule,
2369                                          silc_server_backup_router_wait,
2370                                          (void *)server, 20, 0);
2371           goto out;
2372         }
2373       }
2374
2375       SILC_LOG_DEBUG(("Remote host is %s",
2376                       entry->conn_type == SILC_CONN_SERVER ?
2377                       "server" : (backup_router ?
2378                                   "backup router" : "router")));
2379       SILC_LOG_INFO(("Connection %s (%s) is %s", entry->hostname,
2380                      entry->ip, entry->conn_type == SILC_CONN_SERVER ?
2381                      "server" : (backup_router ?
2382                                  "backup router" : "router")));
2383
2384       /* Add the server into server cache. The server name and Server ID
2385          is updated after we have received NEW_SERVER packet from the
2386          server. We mark ourselves as router for this server if we really
2387          are router. */
2388       new_server =
2389         silc_idlist_add_server((entry->conn_type == SILC_CONN_SERVER ?
2390                                 server->local_list : (backup_router ?
2391                                                       server->local_list :
2392                                                       server->global_list)),
2393                                NULL,
2394                                (entry->conn_type == SILC_CONN_SERVER ?
2395                                 SILC_SERVER : SILC_ROUTER),
2396                                NULL,
2397                                (entry->conn_type == SILC_CONN_SERVER ?
2398                                 server->id_entry : (backup_router ?
2399                                                     server->id_entry : NULL)),
2400                                sock);
2401       if (!new_server) {
2402         SILC_LOG_ERROR(("Could not add new server to cache"));
2403         silc_server_disconnect_remote(server, sock,
2404                                       SILC_STATUS_ERR_AUTH_FAILED, NULL);
2405         server->stat.auth_failures++;
2406         goto out;
2407       }
2408       entry->data.status |= SILC_IDLIST_STATUS_LOCAL;
2409       entry->data.conn_type = entry->conn_type;
2410
2411       id_entry = (void *)new_server;
2412
2413       /* If the incoming connection is router and marked as backup router
2414          then add it to be one of our backups */
2415       if (entry->data.conn_type == SILC_CONN_ROUTER && backup_router) {
2416         /* Change it back to SERVER type since that's what it really is. */
2417         if (backup_local)
2418           entry->data.conn_type = SILC_CONN_SERVER;
2419         new_server->server_type = SILC_BACKUP_ROUTER;
2420
2421         SILC_SERVER_SEND_OPERS(server, FALSE, TRUE, SILC_NOTIFY_TYPE_NONE,
2422                                ("Backup router %s is now online",
2423                                 entry->hostname));
2424
2425         /* Remove the backup waiting with timeout */
2426         silc_schedule_task_add_timeout(server->schedule,
2427                                        silc_server_backup_router_wait,
2428                                        (void *)server, 10, 0);
2429       }
2430
2431       /* Statistics */
2432       if (entry->data.conn_type == SILC_CONN_SERVER) {
2433         server->stat.my_servers++;
2434         server->stat.servers++;
2435         SILC_LOG_DEBUG(("my_servers %d", server->stat.my_servers));
2436       } else {
2437         server->stat.my_routers++;
2438         server->stat.routers++;
2439         SILC_LOG_DEBUG(("my_routers %d", server->stat.my_routers));
2440       }
2441
2442       /* Check whether this connection is to be our primary router connection
2443          if we do not already have the primary route. */
2444       if (!backup_router &&
2445           server->standalone && entry->data.conn_type == SILC_CONN_ROUTER) {
2446         if (silc_server_config_is_primary_route(server) && !initiator)
2447           break;
2448
2449         SILC_LOG_DEBUG(("We are not standalone server anymore"));
2450         server->standalone = FALSE;
2451         if (!server->id_entry->router) {
2452           server->id_entry->router = id_entry;
2453           server->router = id_entry;
2454         }
2455       }
2456
2457       break;
2458     }
2459
2460   default:
2461     goto out;
2462     break;
2463   }
2464
2465   /* Add connection to server->conns so that we know we have connection
2466      to this peer. */
2467   sconn = silc_calloc(1, sizeof(*sconn));
2468   sconn->server = server;
2469   sconn->sock = sock;
2470   sconn->remote_host = strdup(hostname);
2471   sconn->remote_port = port;
2472   silc_dlist_add(server->conns, sconn);
2473   idata->sconn = sconn;
2474   idata->last_receive = time(NULL);
2475
2476   /* Add the common data structure to the ID entry. */
2477   silc_idlist_add_data(id_entry, (SilcIDListData)entry);
2478   silc_packet_set_context(sock, id_entry);
2479
2480   /* Connection has been fully established now. Everything is ok. */
2481   SILC_LOG_DEBUG(("New connection %p authenticated", sconn));
2482
2483   /* Perform Quality of Service */
2484   if (param->qos)
2485     silc_socket_stream_set_qos(silc_packet_stream_get_stream(sock),
2486                                param->qos_rate_limit, param->qos_bytes_limit,
2487                                param->qos_limit_sec, param->qos_limit_usec);
2488
2489   silc_server_config_unref(&entry->cconfig);
2490   silc_server_config_unref(&entry->sconfig);
2491   silc_server_config_unref(&entry->rconfig);
2492   silc_free(entry);
2493
2494  out:
2495   silc_ske_free(silc_connauth_get_ske(connauth));
2496   silc_connauth_free(connauth);
2497 }
2498
2499 /* SKE completion callback.  We set the new keys into use here. */
2500
2501 static void
2502 silc_server_accept_completed(SilcSKE ske, SilcSKEStatus status,
2503                              SilcSKESecurityProperties prop,
2504                              SilcSKEKeyMaterial keymat,
2505                              SilcSKERekeyMaterial rekey,
2506                              void *context)
2507 {
2508   SilcPacketStream sock = context;
2509   SilcUnknownEntry entry = silc_packet_get_context(sock);
2510   SilcIDListData idata = (SilcIDListData)entry;
2511   SilcServer server = entry->server;
2512   SilcConnAuth connauth;
2513   SilcCipher send_key, receive_key;
2514   SilcHmac hmac_send, hmac_receive;
2515   SilcHash hash;
2516   unsigned char *pk;
2517   SilcUInt32 pk_len;
2518
2519   entry->op = NULL;
2520
2521   if (status != SILC_SKE_STATUS_OK) {
2522     /* SKE failed */
2523     SILC_LOG_ERROR(("Error (%s) during Key Exchange protocol with %s (%s)",
2524                     silc_ske_map_status(status), entry->hostname, entry->ip));
2525     silc_ske_free(ske);
2526     silc_server_disconnect_remote(server, sock,
2527                                   SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
2528     return;
2529   }
2530
2531   SILC_LOG_DEBUG(("Setting keys into use"));
2532
2533   /* Set the keys into use.  The data will be encrypted after this. */
2534   if (!silc_ske_set_keys(ske, keymat, prop, &send_key, &receive_key,
2535                          &hmac_send, &hmac_receive, &hash)) {
2536     /* Error setting keys */
2537     silc_ske_free(ske);
2538     silc_server_disconnect_remote(server, sock,
2539                                   SILC_STATUS_ERR_KEY_EXCHANGE_FAILED, NULL);
2540     return;
2541   }
2542   silc_packet_set_keys(sock, send_key, receive_key, hmac_send,
2543                        hmac_receive, FALSE);
2544
2545   idata->rekey = rekey;
2546   idata->public_key = silc_pkcs_public_key_copy(prop->public_key);
2547   pk = silc_pkcs_public_key_encode(idata->public_key, &pk_len);
2548   silc_hash_make(server->sha1hash, pk, pk_len, idata->fingerprint);
2549
2550   silc_hash_alloc(silc_hash_get_name(prop->hash), &idata->hash);
2551
2552   SILC_LOG_DEBUG(("Starting connection authentication"));
2553   server->stat.auth_attempts++;
2554
2555   connauth = silc_connauth_alloc(server->schedule, ske,
2556                                  server->config->conn_auth_timeout);
2557   if (!connauth) {
2558     /** Error allocating auth protocol */
2559     silc_ske_free(ske);
2560     silc_server_disconnect_remote(server, sock,
2561                                   SILC_STATUS_ERR_RESOURCE_LIMIT, NULL);
2562     return;
2563   }
2564
2565   /* Start connection authentication */
2566   entry->op =
2567     silc_connauth_responder(connauth, silc_server_accept_get_auth,
2568                             silc_server_accept_auth_compl, sock);
2569 }
2570
2571 /* Accept new TCP connection */
2572
2573 static void silc_server_accept_new_connection(SilcNetStatus status,
2574                                               SilcStream stream,
2575                                               void *context)
2576 {
2577   SilcServer server = context;
2578   SilcPacketStream packet_stream;
2579   SilcServerConfigClient *cconfig = NULL;
2580   SilcServerConfigServer *sconfig = NULL;
2581   SilcServerConfigRouter *rconfig = NULL;
2582   SilcServerConfigDeny *deny;
2583   SilcUnknownEntry entry;
2584   SilcSKE ske;
2585   SilcSKEParamsStruct params;
2586   char *hostname, *ip;
2587   SilcUInt16 port;
2588
2589   SILC_LOG_DEBUG(("Accepting new connection"));
2590
2591   /* Check for maximum allowed connections */
2592   server->stat.conn_attempts++;
2593   if (silc_dlist_count(server->conns) >
2594       server->config->param.connections_max) {
2595     SILC_LOG_ERROR(("Refusing connection, server is full"));
2596     server->stat.conn_failures++;
2597     silc_stream_destroy(stream);
2598     return;
2599   }
2600
2601   /* Get hostname, IP and port */
2602   if (!silc_socket_stream_get_info(stream, NULL, (const char **)&hostname,
2603                                    (const char **)&ip, &port)) {
2604     /* Bad socket stream */
2605     server->stat.conn_failures++;
2606     silc_stream_destroy(stream);
2607     return;
2608   }
2609
2610   /* Create packet stream */
2611   packet_stream = silc_packet_stream_create(server->packet_engine,
2612                                             server->schedule, stream);
2613   if (!packet_stream) {
2614     SILC_LOG_ERROR(("Refusing connection, cannot create packet stream"));
2615     server->stat.conn_failures++;
2616     silc_stream_destroy(stream);
2617     return;
2618   }
2619   server->stat.conn_num++;
2620
2621   /* Set source ID to packet stream */
2622   if (!silc_packet_set_ids(packet_stream, SILC_ID_SERVER, server->id,
2623                            0, NULL)) {
2624     /* Out of memory */
2625     server->stat.conn_failures++;
2626     silc_packet_stream_destroy(packet_stream);
2627     return;
2628   }
2629
2630   /* Check whether this connection is denied to connect to us. */
2631   deny = silc_server_config_find_denied(server, ip);
2632   if (!deny)
2633     deny = silc_server_config_find_denied(server, hostname);
2634   if (deny) {
2635     /* The connection is denied */
2636     SILC_LOG_INFO(("Connection %s (%s) is denied", hostname, ip));
2637     silc_server_disconnect_remote(server, packet_stream,
2638                                   SILC_STATUS_ERR_BANNED_FROM_SERVER,
2639                                   deny->reason);
2640     return;
2641   }
2642
2643   /* Check whether we have configured this sort of connection at all. We
2644      have to check all configurations since we don't know what type of
2645      connection this is. */
2646   if (!(cconfig = silc_server_config_find_client(server, ip)))
2647     cconfig = silc_server_config_find_client(server, hostname);
2648   if (!(sconfig = silc_server_config_find_server_conn(server, ip)))
2649     sconfig = silc_server_config_find_server_conn(server, hostname);
2650   if (server->server_type == SILC_ROUTER)
2651     if (!(rconfig = silc_server_config_find_router_conn(server, ip, port)))
2652       rconfig = silc_server_config_find_router_conn(server, hostname, port);
2653   if (!cconfig && !sconfig && !rconfig) {
2654     SILC_LOG_INFO(("Connection %s (%s) is not allowed", hostname, ip));
2655     server->stat.conn_failures++;
2656     silc_server_disconnect_remote(server, packet_stream,
2657                                   SILC_STATUS_ERR_BANNED_FROM_SERVER, NULL);
2658     return;
2659   }
2660
2661   /* The connection is allowed */
2662   entry = silc_calloc(1, sizeof(*entry));
2663   if (!entry) {
2664     server->stat.conn_failures++;
2665     silc_server_disconnect_remote(server, packet_stream,
2666                                   SILC_STATUS_ERR_RESOURCE_LIMIT, NULL);
2667     return;
2668   }
2669   entry->hostname = hostname;
2670   entry->ip = ip;
2671   entry->port = port;
2672   entry->server = server;
2673   entry->data.conn_type = SILC_CONN_UNKNOWN;
2674   silc_packet_set_context(packet_stream, entry);
2675
2676   silc_server_config_ref(&entry->cconfig, server->config, cconfig);
2677   silc_server_config_ref(&entry->sconfig, server->config, sconfig);
2678   silc_server_config_ref(&entry->rconfig, server->config, rconfig);
2679
2680   /* Take flags for key exchange. Since we do not know what type of connection
2681      this is, we go through all found configurations and use the global ones
2682      as well. This will result always into strictest key exchange flags. */
2683   memset(&params, 0, sizeof(params));
2684   SILC_GET_SKE_FLAGS(cconfig, params.flags);
2685   SILC_GET_SKE_FLAGS(sconfig, params.flags);
2686   SILC_GET_SKE_FLAGS(rconfig, params.flags);
2687   if (server->config->param.key_exchange_pfs)
2688     params.flags |= SILC_SKE_SP_FLAG_PFS;
2689
2690   SILC_LOG_INFO(("Incoming connection %s (%s)", hostname, ip));
2691   server->stat.conn_attempts++;
2692
2693   /* Start SILC Key Exchange protocol */
2694   SILC_LOG_DEBUG(("Starting key exchange protocol"));
2695   ske = silc_ske_alloc(server->rng, server->schedule, server->repository,
2696                        server->public_key, server->private_key,
2697                        packet_stream);
2698   if (!ske) {
2699     server->stat.conn_failures++;
2700     silc_server_disconnect_remote(server, packet_stream,
2701                                   SILC_STATUS_ERR_RESOURCE_LIMIT, NULL);
2702     return;
2703   }
2704   silc_ske_set_callbacks(ske, silc_server_verify_key,
2705                          silc_server_accept_completed, packet_stream);
2706
2707   /* Start key exchange protocol */
2708   params.version = silc_version_string;
2709   params.timeout_secs = server->config->key_exchange_timeout;
2710   entry->op = silc_ske_responder(ske, packet_stream, &params);
2711 }
2712
2713
2714 /********************************** Rekey ***********************************/
2715
2716 /* Initiator rekey completion callback */
2717
2718 static void silc_server_rekey_completion(SilcSKE ske,
2719                                          SilcSKEStatus status,
2720                                          const SilcSKESecurityProperties prop,
2721                                          const SilcSKEKeyMaterial keymat,
2722                                          SilcSKERekeyMaterial rekey,
2723                                          void *context)
2724 {
2725   SilcPacketStream sock = context;
2726   SilcIDListData idata = silc_packet_get_context(sock);
2727   SilcServer server = idata->sconn->server;
2728
2729   idata->sconn->op = NULL;
2730   if (status != SILC_SKE_STATUS_OK) {
2731     SILC_LOG_ERROR(("Error during rekey protocol with %s",
2732                     idata->sconn->remote_host));
2733     return;
2734   }
2735
2736   SILC_LOG_DEBUG(("Rekey protocol completed with %s:%d [%s]",
2737                   idata->sconn->remote_host, idata->sconn->remote_port,
2738                   SILC_CONNTYPE_STRING(idata->conn_type)));
2739
2740   /* Save rekey data for next rekey */
2741   idata->rekey = rekey;
2742
2743   /* Register new rekey timeout */
2744   silc_schedule_task_add_timeout(server->schedule, silc_server_do_rekey,
2745                                  sock, idata->sconn->rekey_timeout, 0);
2746 }
2747
2748 /* Rekey callback.  Start rekey as initiator */
2749
2750 SILC_TASK_CALLBACK(silc_server_do_rekey)
2751 {
2752   SilcServer server = app_context;
2753   SilcPacketStream sock = context;
2754   SilcIDListData idata = silc_packet_get_context(sock);
2755   SilcSKE ske;
2756
2757   SILC_LOG_DEBUG(("Perform rekey, sock %p", sock));
2758
2759   /* Do not execute rekey with disabled connections */
2760   if (idata->status & SILC_IDLIST_STATUS_DISABLED)
2761     return;
2762
2763   /* If another protocol is active do not start rekey */
2764   if (idata->sconn->op) {
2765     SILC_LOG_DEBUG(("Waiting for other protocol to finish before rekeying"));
2766     silc_schedule_task_add_timeout(server->schedule, silc_server_do_rekey,
2767                                    sock, 60, 0);
2768     return;
2769   }
2770
2771   SILC_LOG_DEBUG(("Executing rekey protocol with %s:%d [%s]",
2772                   idata->sconn->remote_host, idata->sconn->remote_port,
2773                   SILC_CONNTYPE_STRING(idata->conn_type)));
2774
2775   /* Allocate SKE */
2776   ske = silc_ske_alloc(server->rng, server->schedule, NULL,
2777                        server->public_key, NULL, sock);
2778   if (!ske)
2779     return;
2780
2781   /* Set SKE callbacks */
2782   silc_ske_set_callbacks(ske, NULL, silc_server_rekey_completion, sock);
2783
2784   /* Perform rekey */
2785   idata->sconn->op = silc_ske_rekey_initiator(ske, sock, idata->rekey);
2786 }
2787
2788 /* Responder rekey completion callback */
2789
2790 static void
2791 silc_server_rekey_resp_completion(SilcSKE ske,
2792                                   SilcSKEStatus status,
2793                                   const SilcSKESecurityProperties prop,
2794                                   const SilcSKEKeyMaterial keymat,
2795                                   SilcSKERekeyMaterial rekey,
2796                                   void *context)
2797 {
2798   SilcPacketStream sock = context;
2799   SilcIDListData idata = silc_packet_get_context(sock);
2800
2801   idata->sconn->op = NULL;
2802   if (status != SILC_SKE_STATUS_OK) {
2803     SILC_LOG_ERROR(("Error during rekey protocol with %s",
2804                     idata->sconn->remote_host));
2805     return;
2806   }
2807
2808   SILC_LOG_DEBUG(("Rekey protocol completed with %s:%d [%s]",
2809                   idata->sconn->remote_host, idata->sconn->remote_port,
2810                   SILC_CONNTYPE_STRING(idata->conn_type)));
2811
2812   /* Save rekey data for next rekey */
2813   idata->rekey = rekey;
2814 }
2815
2816 /* Start rekey as responder */
2817
2818 static void silc_server_rekey(SilcServer server, SilcPacketStream sock,
2819                               SilcPacket packet)
2820 {
2821   SilcIDListData idata = silc_packet_get_context(sock);
2822   SilcSKE ske;
2823
2824   SILC_LOG_DEBUG(("Executing rekey protocol with %s:%d [%s]",
2825                   idata->sconn->remote_host, idata->sconn->remote_port,
2826                   SILC_CONNTYPE_STRING(idata->conn_type)));
2827
2828   /* Allocate SKE */
2829   ske = silc_ske_alloc(server->rng, server->schedule, NULL,
2830                        server->public_key, NULL, sock);
2831   if (!ske) {
2832     silc_packet_free(packet);
2833     return;
2834   }
2835
2836   /* Set SKE callbacks */
2837   silc_ske_set_callbacks(ske, NULL, silc_server_rekey_resp_completion, sock);
2838
2839   /* Perform rekey */
2840   idata->sconn->op = silc_ske_rekey_responder(ske, sock, idata->rekey,
2841                                               packet);
2842 }
2843
2844
2845 /****************************** Disconnection *******************************/
2846
2847 /* Destroys packet stream. */
2848
2849 SILC_TASK_CALLBACK(silc_server_close_connection_final)
2850 {
2851   silc_packet_stream_unref(context);
2852 }
2853
2854 /* Closes connection to socket connection */
2855
2856 void silc_server_close_connection(SilcServer server,
2857                                   SilcPacketStream sock)
2858 {
2859   SilcIDListData idata = silc_packet_get_context(sock);
2860   char tmp[128];
2861   const char *hostname;
2862   SilcUInt16 port;
2863
2864   if (!silc_packet_stream_is_valid(sock))
2865     return;
2866
2867   memset(tmp, 0, sizeof(tmp));
2868   //  silc_socket_get_error(sock, tmp, sizeof(tmp));
2869   silc_socket_stream_get_info(silc_packet_stream_get_stream(sock),
2870                               NULL, &hostname, NULL, &port);
2871   SILC_LOG_INFO(("Closing connection %s:%d [%s] %s", hostname, port,
2872                  idata ? SILC_CONNTYPE_STRING(idata->conn_type) : "",
2873                  tmp[0] ? tmp : ""));
2874
2875   //  silc_socket_set_qos(sock, 0, 0, 0, 0, NULL);
2876
2877   if (idata && idata->sconn) {
2878     silc_server_connection_free(idata->sconn);
2879     idata->sconn = NULL;
2880   }
2881
2882   /* Take a reference and then destroy the stream.  The last reference
2883      is released later in a timeout callback. */
2884   silc_packet_stream_ref(sock);
2885   silc_packet_stream_destroy(sock);
2886
2887   /* Close connection with timeout */
2888   server->stat.conn_num--;
2889   silc_schedule_task_del_by_all(server->schedule, 0,
2890                                 silc_server_close_connection_final, sock);
2891   silc_schedule_task_add_timeout(server->schedule,
2892                                  silc_server_close_connection_final,
2893                                  sock, 0, 1);
2894 }
2895
2896 /* Sends disconnect message to remote connection and disconnects the
2897    connection. */
2898
2899 void silc_server_disconnect_remote(SilcServer server,
2900                                    SilcPacketStream sock,
2901                                    SilcStatus status, ...)
2902 {
2903   unsigned char buf[512];
2904   va_list ap;
2905   char *cp;
2906
2907   if (!sock)
2908     return;
2909
2910   SILC_LOG_DEBUG(("Disconnecting remote host"));
2911
2912   va_start(ap, status);
2913   cp = va_arg(ap, char *);
2914   if (cp)
2915     silc_vsnprintf(buf, sizeof(buf), cp, ap);
2916   va_end(ap);
2917
2918   /* Send SILC_PACKET_DISCONNECT */
2919   silc_packet_send_va(sock, SILC_PACKET_DISCONNECT, 0,
2920                       SILC_STR_UI_CHAR(status),
2921                       SILC_STR_UI8_STRING(cp ? buf : NULL),
2922                       SILC_STR_END);
2923
2924   /* Close connection */
2925   silc_server_close_connection(server, sock);
2926 }
2927
2928 /* Frees client data and notifies about client's signoff. */
2929
2930 void silc_server_free_client_data(SilcServer server,
2931                                   SilcPacketStream sock,
2932                                   SilcClientEntry client,
2933                                   int notify,
2934                                   const char *signoff)
2935 {
2936   SILC_LOG_DEBUG(("Freeing client %p data", client));
2937
2938   if (client->id) {
2939     /* Check if anyone is watching this nickname */
2940     if (server->server_type == SILC_ROUTER)
2941       silc_server_check_watcher_list(server, client, NULL,
2942                                      SILC_NOTIFY_TYPE_SIGNOFF);
2943
2944     /* Send SIGNOFF notify to routers. */
2945     if (notify)
2946       silc_server_send_notify_signoff(server, SILC_PRIMARY_ROUTE(server),
2947                                       SILC_BROADCAST(server), client->id,
2948                                       signoff);
2949   }
2950
2951   /* Remove client from all channels */
2952   if (notify)
2953     silc_server_remove_from_channels(server, NULL, client,
2954                                      TRUE, (char *)signoff, TRUE, FALSE);
2955   else
2956     silc_server_remove_from_channels(server, NULL, client,
2957                                      FALSE, NULL, FALSE, FALSE);
2958
2959   /* Remove this client from watcher list if it is */
2960   silc_server_del_from_watcher_list(server, client);
2961
2962   /* Remove client's public key from repository, this will free it too. */
2963   if (client->data.public_key) {
2964     silc_skr_del_public_key(server->repository, client->data.public_key,
2965                             client);
2966     client->data.public_key = NULL;
2967   }
2968
2969   /* Update statistics */
2970   server->stat.my_clients--;
2971   server->stat.clients--;
2972   if (server->stat.cell_clients)
2973     server->stat.cell_clients--;
2974   SILC_OPER_STATS_UPDATE(client, server, SILC_UMODE_SERVER_OPERATOR);
2975   SILC_OPER_STATS_UPDATE(client, router, SILC_UMODE_ROUTER_OPERATOR);
2976   silc_schedule_task_del_by_context(server->schedule, client);
2977
2978   if (client->data.sconn)
2979     silc_server_connection_free(client->data.sconn);
2980
2981   /* We will not delete the client entry right away. We will take it
2982      into history (for WHOWAS command) for 5 minutes, unless we're
2983      shutting down server. */
2984   if (!server->server_shutdown) {
2985     client->data.status &= ~SILC_IDLIST_STATUS_REGISTERED;
2986     client->mode = 0;
2987     client->router = NULL;
2988     client->connection = NULL;
2989     client->data.created = silc_time();
2990     silc_dlist_add(server->expired_clients, client);
2991   } else {
2992     /* Delete directly since we're shutting down server */
2993     SILC_LOG_DEBUG(("Delete client directly"));
2994     silc_idlist_del_data(client);
2995     silc_idlist_del_client(server->local_list, client);
2996   }
2997 }
2998
2999 /* Frees user_data pointer from socket connection object. This also sends
3000    appropriate notify packets to the network to inform about leaving
3001    entities. */
3002
3003 void silc_server_free_sock_user_data(SilcServer server,
3004                                      SilcPacketStream sock,
3005                                      const char *signoff_message)
3006 {
3007   SilcIDListData idata = silc_packet_get_context(sock);
3008   const char *ip;
3009   SilcUInt16 port;
3010
3011   SILC_LOG_DEBUG(("Start"));
3012
3013   if (!idata)
3014     return;
3015
3016   silc_schedule_task_del_by_context(server->schedule, sock);
3017
3018   /* Cancel active protocols */
3019   if (idata) {
3020     if (idata->sconn && idata->sconn->op) {
3021       SILC_LOG_DEBUG(("Abort active protocol"));
3022       silc_async_abort(idata->sconn->op, NULL, NULL);
3023     }
3024     if (idata->conn_type == SILC_CONN_UNKNOWN &&
3025         ((SilcUnknownEntry)idata)->op) {
3026       SILC_LOG_DEBUG(("Abort active protocol"));
3027       silc_async_abort(((SilcUnknownEntry)idata)->op, NULL, NULL);
3028     }
3029   }
3030
3031   switch (idata->conn_type) {
3032   case SILC_CONN_CLIENT:
3033     {
3034       SilcClientEntry client_entry = (SilcClientEntry)idata;
3035       silc_server_free_client_data(server, sock, client_entry, TRUE,
3036                                    signoff_message);
3037       silc_packet_set_context(sock, NULL);
3038       break;
3039     }
3040
3041   case SILC_CONN_SERVER:
3042   case SILC_CONN_ROUTER:
3043     {
3044       SilcServerEntry user_data = (SilcServerEntry)idata;
3045       SilcServerEntry backup_router = NULL;
3046
3047       SILC_LOG_DEBUG(("Freeing server %p data", user_data));
3048
3049       if (user_data->id)
3050         backup_router = silc_server_backup_get(server, user_data->id);
3051
3052       if (!server->backup_router && server->server_type == SILC_ROUTER &&
3053           backup_router == server->id_entry &&
3054           idata->conn_type != SILC_CONN_ROUTER)
3055         backup_router = NULL;
3056
3057       if (server->server_shutdown || server->backup_noswitch)
3058         backup_router = NULL;
3059
3060       silc_socket_stream_get_info(silc_packet_stream_get_stream(sock),
3061                                   NULL, NULL, &ip, &port);
3062
3063       /* If this was our primary router connection then we're lost to
3064          the outside world. */
3065       if (server->router == user_data) {
3066         /* Check whether we have a backup router connection */
3067         if (!backup_router || backup_router == user_data) {
3068           if (!server->no_reconnect)
3069             silc_server_create_connections(server);
3070           server->id_entry->router = NULL;
3071           server->router = NULL;
3072           server->standalone = TRUE;
3073           server->backup_primary = FALSE;
3074           backup_router = NULL;
3075         } else {
3076           if (server->id_entry != backup_router) {
3077             SILC_LOG_INFO(("New primary router is backup router %s",
3078                            backup_router->server_name));
3079             server->id_entry->router = backup_router;
3080             server->router = backup_router;
3081             server->router_connect = time(0);
3082             server->backup_primary = TRUE;
3083             backup_router->data.status &= ~SILC_IDLIST_STATUS_DISABLED;
3084
3085             /* Send START_USE to backup router to indicate we have switched */
3086             silc_server_backup_send_start_use(server,
3087                                               backup_router->connection,
3088                                               FALSE);
3089           } else {
3090             SILC_LOG_INFO(("We are now new primary router in this cell"));
3091             server->id_entry->router = NULL;
3092             server->router = NULL;
3093             server->standalone = TRUE;
3094           }
3095
3096           /* We stop here to take a breath */
3097           sleep(2);
3098
3099           if (server->backup_router) {
3100             server->server_type = SILC_ROUTER;
3101
3102             /* We'll need to constantly try to reconnect to the primary
3103                router so that we'll see when it comes back online. */
3104             silc_server_create_connection(server, FALSE, FALSE, ip, port,
3105                                          silc_server_backup_connected,
3106                                          NULL);
3107           }
3108
3109           /* Mark this connection as replaced */
3110           silc_server_backup_replaced_add(server, user_data->id,
3111                                           backup_router);
3112         }
3113       } else if (backup_router) {
3114         SILC_LOG_INFO(("Enabling the use of backup router %s",
3115                        backup_router->server_name));
3116
3117         /* Mark this connection as replaced */
3118         silc_server_backup_replaced_add(server, user_data->id,
3119                                         backup_router);
3120       } else if (server->server_type == SILC_SERVER &&
3121                  idata->conn_type == SILC_CONN_ROUTER) {
3122         /* Reconnect to the router (backup) */
3123         if (!server->no_reconnect)
3124           silc_server_create_connections(server);
3125       }
3126
3127       if (user_data->server_name)
3128         SILC_SERVER_SEND_OPERS(server, FALSE, TRUE, SILC_NOTIFY_TYPE_NONE,
3129                                ("Server %s signoff", user_data->server_name));
3130
3131       if (!backup_router) {
3132         /* Remove all servers that are originated from this server, and
3133            remove the clients of those servers too. */
3134         silc_server_remove_servers_by_server(server, user_data, TRUE);
3135
3136 #if 0
3137         /* Remove the clients that this server owns as they will become
3138            invalid now too.  For backup router the server is actually
3139            coming from the primary router, so mark that as the owner
3140            of this entry. */
3141         if (server->server_type == SILC_BACKUP_ROUTER &&
3142             sock->type == SILC_CONN_SERVER)
3143           silc_server_remove_clients_by_server(server, server->router,
3144                                                user_data, TRUE);
3145         else
3146 #endif
3147           silc_server_remove_clients_by_server(server, user_data,
3148                                                user_data, TRUE);
3149
3150         /* Remove channels owned by this server */
3151         if (server->server_type == SILC_SERVER)
3152           silc_server_remove_channels_by_server(server, user_data);
3153       } else {
3154         /* Enable local server connections that may be disabled */
3155         silc_server_local_servers_toggle_enabled(server, TRUE);
3156
3157         /* Update the client entries of this server to the new backup
3158            router.  If we are the backup router we also resolve the real
3159            servers for the clients.  After updating is over this also
3160            removes the clients that this server explicitly owns. */
3161         silc_server_update_clients_by_server(server, user_data,
3162                                              backup_router, TRUE);
3163
3164         /* If we are router and just lost our primary router (now standlaone)
3165            we remove everything that was behind it, since we don't know
3166            any better. */
3167         if (server->server_type == SILC_ROUTER && server->standalone)
3168           /* Remove all servers that are originated from this server, and
3169              remove the clients of those servers too. */
3170           silc_server_remove_servers_by_server(server, user_data, TRUE);
3171
3172         /* Finally remove the clients that are explicitly owned by this
3173            server.  They go down with the server. */
3174         silc_server_remove_clients_by_server(server, user_data,
3175                                              user_data, TRUE);
3176
3177         /* Update our server cache to use the new backup router too. */
3178         silc_server_update_servers_by_server(server, user_data, backup_router);
3179         if (server->server_type == SILC_SERVER)
3180           silc_server_update_channels_by_server(server, user_data,
3181                                                 backup_router);
3182
3183         /* Send notify about primary router going down to local operators */
3184         if (server->backup_router)
3185           SILC_SERVER_SEND_OPERS(server, FALSE, TRUE,
3186                                  SILC_NOTIFY_TYPE_NONE,
3187                                  ("%s switched to backup router %s "
3188                                   "(we are primary router now)",
3189                                   server->server_name, server->server_name));
3190         else if (server->router)
3191           SILC_SERVER_SEND_OPERS(server, FALSE, TRUE,
3192                                  SILC_NOTIFY_TYPE_NONE,
3193                                  ("%s switched to backup router %s",
3194                                   server->server_name,
3195                                   server->router->server_name));
3196       }
3197       server->backup_noswitch = FALSE;
3198
3199       if (idata->sconn)
3200         silc_server_connection_free(idata->sconn);
3201
3202       /* Statistics */
3203       if (idata->conn_type == SILC_CONN_SERVER) {
3204         server->stat.my_servers--;
3205         server->stat.servers--;
3206         SILC_LOG_DEBUG(("my_servers %d", server->stat.my_servers));
3207       } else if (idata->conn_type == SILC_CONN_ROUTER) {
3208         server->stat.my_routers--;
3209         server->stat.routers--;
3210         SILC_LOG_DEBUG(("my_routers %d", server->stat.my_routers));
3211       }
3212       if (server->server_type == SILC_ROUTER)
3213         server->stat.cell_servers--;
3214
3215       /* Free the server entry */
3216       silc_server_backup_del(server, user_data);
3217       silc_server_backup_replaced_del(server, user_data);
3218       silc_idlist_del_data(user_data);
3219       if (!silc_idlist_del_server(server->local_list, user_data))
3220         silc_idlist_del_server(server->global_list, user_data);
3221
3222       if (backup_router && backup_router != server->id_entry) {
3223         /* Announce all of our stuff that was created about 5 minutes ago.
3224            The backup router knows all the other stuff already. */
3225         if (server->server_type == SILC_ROUTER)
3226           silc_server_announce_servers(server, FALSE, time(0) - 300,
3227                                        backup_router->connection);
3228
3229         /* Announce our clients and channels to the router */
3230         silc_server_announce_clients(server, time(0) - 300,
3231                                      backup_router->connection);
3232         silc_server_announce_channels(server, time(0) - 300,
3233                                       backup_router->connection);
3234       }
3235
3236       silc_packet_set_context(sock, NULL);
3237       break;
3238     }
3239
3240   default:
3241     {
3242       SilcUnknownEntry entry = (SilcUnknownEntry)idata;
3243
3244       SILC_LOG_DEBUG(("Freeing unknown connection data"));
3245
3246       if (idata->sconn)
3247         silc_server_connection_free(idata->sconn);
3248       silc_idlist_del_data(idata);
3249       silc_free(entry);
3250       silc_packet_set_context(sock, NULL);
3251       break;
3252     }
3253   }
3254 }
3255
3256 /* Removes client from all channels it has joined. This is used when client
3257    connection is disconnected. If the client on a channel is last, the
3258    channel is removed as well. This sends the SIGNOFF notify types. */
3259
3260 void silc_server_remove_from_channels(SilcServer server,
3261                                       SilcPacketStream sock,
3262                                       SilcClientEntry client,
3263                                       SilcBool notify,
3264                                       const char *signoff_message,
3265                                       SilcBool keygen,
3266                                       SilcBool killed)
3267 {
3268   SilcChannelEntry channel;
3269   SilcChannelClientEntry chl;
3270   SilcHashTableList htl;
3271   SilcBuffer clidp = NULL;
3272
3273   if (!client)
3274     return;
3275
3276   if (notify && !client->id)
3277     notify = FALSE;
3278
3279   SILC_LOG_DEBUG(("Removing client %s from joined channels",
3280                   notify ? silc_id_render(client->id, SILC_ID_CLIENT) : ""));
3281
3282   if (notify) {
3283     clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3284     if (!clidp)
3285       notify = FALSE;
3286   }
3287
3288   /* Remove the client from all channels. The client is removed from
3289      the channels' user list. */
3290   silc_hash_table_list(client->channels, &htl);
3291   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
3292     channel = chl->channel;
3293
3294     /* Remove channel if this is last client leaving the channel, unless
3295        the channel is permanent. */
3296     if (server->server_type != SILC_SERVER &&
3297         silc_hash_table_count(channel->user_list) < 2) {
3298       silc_server_channel_delete(server, channel);
3299       continue;
3300     }
3301
3302     silc_hash_table_del(client->channels, channel);
3303     silc_hash_table_del(channel->user_list, client);
3304     channel->user_count--;
3305
3306     /* If there is no global users on the channel anymore mark the channel
3307        as local channel. Do not check if the removed client is local client. */
3308     if (server->server_type == SILC_SERVER && channel->global_users &&
3309         chl->client->router && !silc_server_channel_has_global(channel))
3310       channel->global_users = FALSE;
3311
3312     memset(chl, 'A', sizeof(*chl));
3313     silc_free(chl);
3314
3315     /* Update statistics */
3316     if (SILC_IS_LOCAL(client))
3317       server->stat.my_chanclients--;
3318     if (server->server_type == SILC_ROUTER) {
3319       server->stat.cell_chanclients--;
3320       server->stat.chanclients--;
3321     }
3322
3323     /* If there is not at least one local user on the channel then we don't
3324        need the channel entry anymore, we can remove it safely, unless the
3325        channel is permanent channel */
3326     if (server->server_type == SILC_SERVER &&
3327         !silc_server_channel_has_local(channel)) {
3328       /* Notify about leaving client if this channel has global users. */
3329       if (notify && channel->global_users)
3330         silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3331                                            SILC_NOTIFY_TYPE_SIGNOFF,
3332                                            signoff_message ? 2 : 1,
3333                                            clidp->data, silc_buffer_len(clidp),
3334                                            signoff_message, signoff_message ?
3335                                            strlen(signoff_message) : 0);
3336
3337       silc_schedule_task_del_by_context(server->schedule, channel->rekey);
3338       silc_server_channel_delete(server, channel);
3339       continue;
3340     }
3341
3342     /* Send notify to channel about client leaving SILC and channel too */
3343     if (notify)
3344       silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3345                                          SILC_NOTIFY_TYPE_SIGNOFF,
3346                                          signoff_message ? 2 : 1,
3347                                          clidp->data, silc_buffer_len(clidp),
3348                                          signoff_message, signoff_message ?
3349                                          strlen(signoff_message) : 0);
3350
3351     if (killed && clidp) {
3352       /* Remove the client from channel's invite list */
3353       if (channel->invite_list &&
3354           silc_hash_table_count(channel->invite_list)) {
3355         SilcBuffer ab;
3356         SilcArgumentPayload iargs;
3357         ab = silc_argument_payload_encode_one(NULL, clidp->data,
3358                                               silc_buffer_len(clidp), 3);
3359         iargs = silc_argument_payload_parse(ab->data, silc_buffer_len(ab), 1);
3360         silc_server_inviteban_process(server, channel->invite_list, 1, iargs);
3361         silc_buffer_free(ab);
3362         silc_argument_payload_free(iargs);
3363       }
3364     }
3365
3366     /* Don't create keys if we are shutting down */
3367     if (server->server_shutdown)
3368       continue;
3369
3370     /* Re-generate channel key if needed */
3371     if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
3372       if (!silc_server_create_channel_key(server, channel, 0))
3373         continue;
3374
3375       /* Send the channel key to the channel. The key of course is not sent
3376          to the client who was removed from the channel. */
3377       silc_server_send_channel_key(server, client->connection, channel,
3378                                    server->server_type == SILC_ROUTER ?
3379                                    FALSE : !server->standalone);
3380     }
3381   }
3382
3383   silc_hash_table_list_reset(&htl);
3384   if (clidp)
3385     silc_buffer_free(clidp);
3386 }
3387
3388 /* Removes client from one channel. This is used for example when client
3389    calls LEAVE command to remove itself from the channel. Returns TRUE
3390    if channel still exists and FALSE if the channel is removed when
3391    last client leaves the channel. If `notify' is FALSE notify messages
3392    are not sent. */
3393
3394 SilcBool silc_server_remove_from_one_channel(SilcServer server,
3395                                          SilcPacketStream sock,
3396                                          SilcChannelEntry channel,
3397                                          SilcClientEntry client,
3398                                          SilcBool notify)
3399 {
3400   SilcChannelClientEntry chl;
3401   SilcBuffer clidp;
3402
3403   SILC_LOG_DEBUG(("Removing %s from channel %s",
3404                   silc_id_render(client->id, SILC_ID_CLIENT),
3405                   channel->channel_name));
3406
3407   /* Get the entry to the channel, if this client is not on the channel
3408      then return Ok. */
3409   if (!silc_hash_table_find(client->channels, channel, NULL, (void *)&chl))
3410     return TRUE;
3411
3412   /* Remove channel if this is last client leaving the channel, unless
3413      the channel is permanent. */
3414   if (server->server_type != SILC_SERVER &&
3415       silc_hash_table_count(channel->user_list) < 2) {
3416     silc_server_channel_delete(server, channel);
3417     return FALSE;
3418   }
3419
3420   silc_hash_table_del(client->channels, channel);
3421   silc_hash_table_del(channel->user_list, client);
3422   channel->user_count--;
3423
3424   /* If there is no global users on the channel anymore mark the channel
3425      as local channel. Do not check if the client is local client. */
3426   if (server->server_type == SILC_SERVER && channel->global_users &&
3427       chl->client->router && !silc_server_channel_has_global(channel))
3428     channel->global_users = FALSE;
3429
3430   memset(chl, 'O', sizeof(*chl));
3431   silc_free(chl);
3432
3433   /* Update statistics */
3434   if (SILC_IS_LOCAL(client))
3435     server->stat.my_chanclients--;
3436   if (server->server_type == SILC_ROUTER) {
3437     server->stat.cell_chanclients--;
3438     server->stat.chanclients--;
3439   }
3440
3441   clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3442   if (!clidp)
3443     notify = FALSE;
3444
3445   /* If there is not at least one local user on the channel then we don't
3446      need the channel entry anymore, we can remove it safely, unless the
3447      channel is permanent channel */
3448   if (server->server_type == SILC_SERVER &&
3449       !silc_server_channel_has_local(channel)) {
3450     /* Notify about leaving client if this channel has global users. */
3451     if (notify && channel->global_users)
3452       silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3453                                          SILC_NOTIFY_TYPE_LEAVE, 1,
3454                                          clidp->data, silc_buffer_len(clidp));
3455
3456     silc_schedule_task_del_by_context(server->schedule, channel->rekey);
3457     silc_server_channel_delete(server, channel);
3458     silc_buffer_free(clidp);
3459     return FALSE;
3460   }
3461
3462   /* Send notify to channel about client leaving the channel */
3463   if (notify)
3464     silc_server_send_notify_to_channel(server, NULL, channel, FALSE, TRUE,
3465                                        SILC_NOTIFY_TYPE_LEAVE, 1,
3466                                        clidp->data, silc_buffer_len(clidp));
3467
3468   silc_buffer_free(clidp);
3469   return TRUE;
3470 }
3471
3472 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
3473    function may be used only by router. In real SILC network all channels
3474    are created by routers thus this function is never used by normal
3475    server. */
3476
3477 SilcChannelEntry silc_server_create_new_channel(SilcServer server,
3478                                                 SilcServerID *router_id,
3479                                                 char *cipher,
3480                                                 char *hmac,
3481                                                 char *channel_name,
3482                                                 int broadcast)
3483 {
3484   SilcChannelID *channel_id;
3485   SilcChannelEntry entry;
3486   SilcCipher send_key, receive_key;
3487   SilcHmac newhmac;
3488
3489   SILC_LOG_DEBUG(("Creating new channel %s", channel_name));
3490
3491   if (!cipher)
3492     cipher = SILC_DEFAULT_CIPHER;
3493   if (!hmac)
3494     hmac = SILC_DEFAULT_HMAC;
3495
3496   /* Allocate cipher */
3497   if (!silc_cipher_alloc(cipher, &send_key))
3498     return NULL;
3499   if (!silc_cipher_alloc(cipher, &receive_key)) {
3500     silc_cipher_free(send_key);
3501     return NULL;
3502   }
3503
3504   /* Allocate hmac */
3505   if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3506     silc_cipher_free(send_key);
3507     silc_cipher_free(receive_key);
3508     return NULL;
3509   }
3510
3511   channel_name = strdup(channel_name);
3512
3513   /* Create the channel ID */
3514   if (!silc_id_create_channel_id(server, router_id, server->rng,
3515                                  &channel_id)) {
3516     silc_free(channel_name);
3517     silc_cipher_free(send_key);
3518     silc_cipher_free(receive_key);
3519     silc_hmac_free(newhmac);
3520     return NULL;
3521   }
3522
3523   /* Create the channel */
3524   entry = silc_idlist_add_channel(server->local_list, channel_name,
3525                                   SILC_CHANNEL_MODE_NONE, channel_id,
3526                                   NULL, send_key, receive_key, newhmac);
3527   if (!entry) {
3528     silc_free(channel_name);
3529     silc_cipher_free(send_key);
3530     silc_cipher_free(receive_key);
3531     silc_hmac_free(newhmac);
3532     silc_free(channel_id);
3533     return NULL;
3534   }
3535
3536   entry->cipher = strdup(cipher);
3537   entry->hmac_name = strdup(hmac);
3538
3539   /* Now create the actual key material */
3540   if (!silc_server_create_channel_key(server, entry,
3541                                       silc_cipher_get_key_len(send_key) / 8)) {
3542     silc_idlist_del_channel(server->local_list, entry);
3543     return NULL;
3544   }
3545
3546   /* Notify other routers about the new channel. We send the packet
3547      to our primary route. */
3548   if (broadcast)
3549     silc_server_send_new_channel(server, SILC_PRIMARY_ROUTE(server), TRUE,
3550                                  channel_name, entry->id,
3551                                  silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3552                                  entry->mode);
3553
3554   /* Distribute to backup routers */
3555   if (broadcast && server->server_type == SILC_ROUTER) {
3556     SilcBuffer packet;
3557     unsigned char cid[32];
3558     SilcUInt32 name_len = strlen(channel_name);
3559     SilcUInt32 id_len;
3560
3561     silc_id_id2str(entry->id, SILC_ID_CHANNEL, cid, sizeof(cid), &id_len);
3562     packet = silc_channel_payload_encode(channel_name, name_len,
3563                                          cid, id_len, entry->mode);
3564     silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
3565                             packet->data, silc_buffer_len(packet), FALSE,
3566                             TRUE);
3567     silc_buffer_free(packet);
3568   }
3569
3570   server->stat.my_channels++;
3571   if (server->server_type == SILC_ROUTER) {
3572     server->stat.channels++;
3573     server->stat.cell_channels++;
3574     entry->users_resolved = TRUE;
3575   }
3576
3577   return entry;
3578 }
3579
3580 /* Same as above but creates the channel with Channel ID `channel_id. */
3581
3582 SilcChannelEntry
3583 silc_server_create_new_channel_with_id(SilcServer server,
3584                                        char *cipher,
3585                                        char *hmac,
3586                                        char *channel_name,
3587                                        SilcChannelID *channel_id,
3588                                        int broadcast)
3589 {
3590   SilcChannelEntry entry;
3591   SilcCipher send_key, receive_key;
3592   SilcHmac newhmac;
3593
3594   SILC_LOG_DEBUG(("Creating new channel %s", channel_name));
3595
3596   if (!cipher)
3597     cipher = SILC_DEFAULT_CIPHER;
3598   if (!hmac)
3599     hmac = SILC_DEFAULT_HMAC;
3600
3601   /* Allocate cipher */
3602   if (!silc_cipher_alloc(cipher, &send_key))
3603     return NULL;
3604   if (!silc_cipher_alloc(cipher, &receive_key)) {
3605     silc_cipher_free(send_key);
3606     return NULL;
3607   }
3608
3609   /* Allocate hmac */
3610   if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
3611     silc_cipher_free(send_key);
3612     silc_cipher_free(receive_key);
3613     return NULL;
3614   }
3615
3616   channel_name = strdup(channel_name);
3617
3618   /* Create the channel */
3619   entry = silc_idlist_add_channel(server->local_list, channel_name,
3620                                   SILC_CHANNEL_MODE_NONE, channel_id,
3621                                   NULL, send_key, receive_key, newhmac);
3622   if (!entry) {
3623     silc_cipher_free(send_key);
3624     silc_cipher_free(receive_key);
3625     silc_hmac_free(newhmac);
3626     silc_free(channel_name);
3627     return NULL;
3628   }
3629
3630   /* Now create the actual key material */
3631   if (!silc_server_create_channel_key(server, entry,
3632                                       silc_cipher_get_key_len(send_key) / 8)) {
3633     silc_idlist_del_channel(server->local_list, entry);
3634     return NULL;
3635   }
3636
3637   /* Notify other routers about the new channel. We send the packet
3638      to our primary route. */
3639   if (broadcast)
3640     silc_server_send_new_channel(server, SILC_PRIMARY_ROUTE(server), TRUE,
3641                                  channel_name, entry->id,
3642                                  silc_id_get_len(entry->id, SILC_ID_CHANNEL),
3643                                  entry->mode);
3644
3645   /* Distribute to backup routers */
3646   if (broadcast && server->server_type == SILC_ROUTER) {
3647     SilcBuffer packet;
3648     unsigned char cid[32];
3649     SilcUInt32 name_len = strlen(channel_name);
3650     SilcUInt32 id_len;
3651
3652     silc_id_id2str(entry->id, SILC_ID_CHANNEL, cid, sizeof(cid), &id_len);
3653     packet = silc_channel_payload_encode(channel_name, name_len,
3654                                          cid, id_len, entry->mode);
3655     silc_server_backup_send(server, NULL, SILC_PACKET_NEW_CHANNEL, 0,
3656                             packet->data, silc_buffer_len(packet), FALSE,
3657                             TRUE);
3658     silc_buffer_free(packet);
3659   }
3660
3661   server->stat.my_channels++;
3662   if (server->server_type == SILC_ROUTER) {
3663     server->stat.channels++;
3664     server->stat.cell_channels++;
3665     entry->users_resolved = TRUE;
3666   }
3667
3668   return entry;
3669 }
3670
3671 /* Channel's key re-key timeout callback. */
3672
3673 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
3674 {
3675   SilcServer server = app_context;
3676   SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
3677
3678   rekey->task = NULL;
3679
3680   /* Return now if we are shutting down */
3681   if (server->server_shutdown)
3682     return;
3683
3684   if (!silc_server_create_channel_key(server, rekey->channel, rekey->key_len))
3685     return;
3686
3687   silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
3688 }
3689
3690 /* Generates new channel key. This is used to create the initial channel key
3691    but also to re-generate new key for channel. If `key_len' is provided
3692    it is the bytes of the key length. */
3693
3694 SilcBool silc_server_create_channel_key(SilcServer server,
3695                                         SilcChannelEntry channel,
3696                                         SilcUInt32 key_len)
3697 {
3698   int i;
3699   unsigned char channel_key[32], hash[SILC_HASH_MAXLEN];
3700   SilcUInt32 len;
3701
3702   if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
3703     SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
3704     return TRUE;
3705   }
3706
3707   SILC_LOG_DEBUG(("Generating channel %s key", channel->channel_name));
3708
3709   if (!channel->send_key)
3710     if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->send_key)) {
3711       channel->send_key = NULL;
3712       return FALSE;
3713     }
3714   if (!channel->receive_key)
3715     if (!silc_cipher_alloc(SILC_DEFAULT_CIPHER, &channel->receive_key)) {
3716       silc_cipher_free(channel->send_key);
3717       channel->send_key = channel->receive_key = NULL;
3718       return FALSE;
3719     }
3720
3721   if (key_len)
3722     len = key_len;
3723   else if (channel->key_len)
3724     len = channel->key_len / 8;
3725   else
3726     len = silc_cipher_get_key_len(channel->send_key) / 8;
3727
3728   /* Create channel key */
3729   for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
3730
3731   /* Set the key */
3732   silc_cipher_set_key(channel->send_key, channel_key, len * 8, TRUE);
3733   silc_cipher_set_key(channel->receive_key, channel_key, len * 8, FALSE);
3734
3735   /* Remove old key if exists */
3736   if (channel->key) {
3737     memset(channel->key, 0, channel->key_len / 8);
3738     silc_free(channel->key);
3739   }
3740
3741   /* Save the key */
3742   channel->key_len = len * 8;
3743   channel->key = silc_memdup(channel_key, len);
3744   memset(channel_key, 0, sizeof(channel_key));
3745
3746   /* Generate HMAC key from the channel key data and set it */
3747   if (!channel->hmac)
3748     if (!silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac)) {
3749       memset(channel->key, 0, channel->key_len / 8);
3750       silc_free(channel->key);
3751       silc_cipher_free(channel->send_key);
3752       silc_cipher_free(channel->receive_key);
3753       channel->send_key = channel->receive_key = NULL;
3754       return FALSE;
3755     }
3756   silc_hash_make(silc_hmac_get_hash(channel->hmac), channel->key, len, hash);
3757   silc_hmac_set_key(channel->hmac, hash,
3758                     silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3759   memset(hash, 0, sizeof(hash));
3760
3761   if (server->server_type == SILC_ROUTER) {
3762     if (!channel->rekey)
3763       channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3764     channel->rekey->channel = channel;
3765     channel->rekey->key_len = key_len;
3766     if (channel->rekey->task)
3767       silc_schedule_task_del(server->schedule, channel->rekey->task);
3768
3769     channel->rekey->task =
3770       silc_schedule_task_add_timeout(server->schedule,
3771                                      silc_server_channel_key_rekey,
3772                                      (void *)channel->rekey,
3773                                      server->config->channel_rekey_secs, 0);
3774   }
3775
3776   return TRUE;
3777 }
3778
3779 /* Saves the channel key found in the encoded `key_payload' buffer. This
3780    function is used when we receive Channel Key Payload and also when we're
3781    processing JOIN command reply. Returns entry to the channel. */
3782
3783 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
3784                                               SilcBuffer key_payload,
3785                                               SilcChannelEntry channel)
3786 {
3787   SilcChannelKeyPayload payload = NULL;
3788   SilcChannelID id;
3789   unsigned char *tmp, hash[SILC_HASH_MAXLEN];
3790   SilcUInt32 tmp_len;
3791   char *cipher;
3792
3793   /* Decode channel key payload */
3794   payload = silc_channel_key_payload_parse(key_payload->data,
3795                                            silc_buffer_len(key_payload));
3796   if (!payload) {
3797     SILC_LOG_ERROR(("Bad channel key payload received, dropped"));
3798     channel = NULL;
3799     goto out;
3800   }
3801
3802   /* Get the channel entry */
3803   if (!channel) {
3804
3805     /* Get channel ID */
3806     tmp = silc_channel_key_get_id(payload, &tmp_len);
3807     if (!silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL, &id, sizeof(id))) {
3808       channel = NULL;
3809       goto out;
3810     }
3811
3812     channel = silc_idlist_find_channel_by_id(server->local_list, &id, NULL);
3813     if (!channel) {
3814       channel = silc_idlist_find_channel_by_id(server->global_list, &id, NULL);
3815       if (!channel) {
3816         if (server->server_type == SILC_ROUTER)
3817           SILC_LOG_ERROR(("Received key for non-existent channel %s",
3818                           silc_id_render(&id, SILC_ID_CHANNEL)));
3819         goto out;
3820       }
3821     }
3822   }
3823
3824   SILC_LOG_DEBUG(("Saving new channel %s key", channel->channel_name));
3825
3826   tmp = silc_channel_key_get_key(payload, &tmp_len);
3827   if (!tmp) {
3828     channel = NULL;
3829     goto out;
3830   }
3831
3832   cipher = silc_channel_key_get_cipher(payload, NULL);
3833   if (!cipher) {
3834     channel = NULL;
3835     goto out;
3836   }
3837
3838   /* Remove old key if exists */
3839   if (channel->key) {
3840     memset(channel->key, 0, channel->key_len / 8);
3841     silc_free(channel->key);
3842     silc_cipher_free(channel->send_key);
3843     silc_cipher_free(channel->receive_key);
3844   }
3845
3846   /* Create new cipher */
3847   if (!silc_cipher_alloc(cipher, &channel->send_key)) {
3848     channel->send_key = NULL;
3849     channel = NULL;
3850     goto out;
3851   }
3852   if (!silc_cipher_alloc(cipher, &channel->receive_key)) {
3853     silc_cipher_free(channel->send_key);
3854     channel->send_key = channel->receive_key = NULL;
3855     channel = NULL;
3856     goto out;
3857   }
3858
3859   if (channel->cipher)
3860     silc_free(channel->cipher);
3861   channel->cipher = strdup(cipher);
3862
3863   /* Save the key */
3864   channel->key_len = tmp_len * 8;
3865   channel->key = silc_memdup(tmp, tmp_len);
3866   silc_cipher_set_key(channel->send_key, tmp, channel->key_len, TRUE);
3867   silc_cipher_set_key(channel->receive_key, tmp, channel->key_len, FALSE);
3868
3869   /* Generate HMAC key from the channel key data and set it */
3870   if (!channel->hmac)
3871     if (!silc_hmac_alloc(SILC_DEFAULT_HMAC, NULL, &channel->hmac)) {
3872       memset(channel->key, 0, channel->key_len / 8);
3873       silc_free(channel->key);
3874       silc_cipher_free(channel->send_key);
3875       silc_cipher_free(channel->receive_key);
3876       channel->send_key = channel->receive_key = NULL;
3877       return FALSE;
3878     }
3879   silc_hash_make(silc_hmac_get_hash(channel->hmac), tmp, tmp_len, hash);
3880   silc_hmac_set_key(channel->hmac, hash,
3881                     silc_hash_len(silc_hmac_get_hash(channel->hmac)));
3882
3883   memset(hash, 0, sizeof(hash));
3884   memset(tmp, 0, tmp_len);
3885
3886   if (server->server_type == SILC_ROUTER) {
3887     if (!channel->rekey)
3888       channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3889     channel->rekey->channel = channel;
3890     if (channel->rekey->task)
3891       silc_schedule_task_del(server->schedule, channel->rekey->task);
3892
3893     channel->rekey->task =
3894       silc_schedule_task_add_timeout(server->schedule,
3895                                      silc_server_channel_key_rekey,
3896                                      (void *)channel->rekey,
3897                                      server->config->channel_rekey_secs, 0);
3898   }
3899
3900  out:
3901   if (payload)
3902     silc_channel_key_payload_free(payload);
3903
3904   return channel;
3905 }
3906
3907 /* Returns assembled of all servers in the given ID list. The packet's
3908    form is dictated by the New ID payload. */
3909
3910 static void silc_server_announce_get_servers(SilcServer server,
3911                                              SilcServerEntry remote,
3912                                              SilcIDList id_list,
3913                                              SilcBuffer *servers,
3914                                              unsigned long creation_time)
3915 {
3916   SilcList list;
3917   SilcIDCacheEntry id_cache;
3918   SilcServerEntry entry;
3919   SilcBuffer idp;
3920
3921   /* Go through all clients in the list */
3922   if (silc_idcache_get_all(id_list->servers, &list)) {
3923     silc_list_start(list);
3924     while ((id_cache = silc_list_get(list))) {
3925       entry = (SilcServerEntry)id_cache->context;
3926
3927       /* Do not announce the one we've sending our announcements and
3928          do not announce ourself. Also check the creation time if it's
3929          provided. */
3930       if ((entry == remote) || (entry == server->id_entry) ||
3931           (creation_time && entry->data.created < creation_time))
3932         continue;
3933
3934       idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
3935
3936       *servers = silc_buffer_realloc(*servers,
3937                                      (*servers ?
3938                                       silc_buffer_truelen((*servers)) +
3939                                       silc_buffer_len(idp) :
3940                                       silc_buffer_len(idp)));
3941       silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
3942       silc_buffer_put(*servers, idp->data, silc_buffer_len(idp));
3943       silc_buffer_pull(*servers, silc_buffer_len(idp));
3944       silc_buffer_free(idp);
3945     }
3946   }
3947 }
3948
3949 static SilcBuffer
3950 silc_server_announce_encode_notify(SilcNotifyType notify, SilcUInt32 argc, ...)
3951 {
3952   va_list ap;
3953   SilcBuffer p;
3954
3955   va_start(ap, argc);
3956   p = silc_notify_payload_encode(notify, argc, ap);
3957   va_end(ap);
3958
3959   return p;
3960 }
3961
3962 /* This function is used by router to announce existing servers to our
3963    primary router when we've connected to it. If `creation_time' is non-zero
3964    then only the servers that has been created after the `creation_time'
3965    will be announced. */
3966
3967 void silc_server_announce_servers(SilcServer server, SilcBool global,
3968                                   unsigned long creation_time,
3969                                   SilcPacketStream remote)
3970 {
3971   SilcBuffer servers = NULL;
3972
3973   SILC_LOG_DEBUG(("Announcing servers"));
3974
3975   /* Get servers in local list */
3976   silc_server_announce_get_servers(server, silc_packet_get_context(remote),
3977                                    server->local_list, &servers,
3978                                    creation_time);
3979
3980   if (global)
3981     /* Get servers in global list */
3982     silc_server_announce_get_servers(server, silc_packet_get_context(remote),
3983                                      server->global_list, &servers,
3984                                      creation_time);
3985
3986   if (servers) {
3987     silc_buffer_push(servers, servers->data - servers->head);
3988     SILC_LOG_HEXDUMP(("servers"), servers->data, silc_buffer_len(servers));
3989
3990     /* Send the packet */
3991     silc_server_packet_send(server, remote,
3992                             SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3993                             servers->data, silc_buffer_len(servers));
3994
3995     silc_buffer_free(servers);
3996   }
3997 }
3998
3999 /* Returns assembled packet of all clients in the given ID list. The
4000    packet's form is dictated by the New ID Payload. */
4001
4002 static void silc_server_announce_get_clients(SilcServer server,
4003                                              SilcIDList id_list,
4004                                              SilcBuffer *clients,
4005                                              SilcBuffer *umodes,
4006                                              unsigned long creation_time)
4007 {
4008   SilcList list;
4009   SilcIDCacheEntry id_cache;
4010   SilcClientEntry client;
4011   SilcBuffer idp;
4012   SilcBuffer tmp;
4013   unsigned char mode[4];
4014
4015   /* Go through all clients in the list */
4016   if (silc_idcache_get_all(id_list->clients, &list)) {
4017     silc_list_start(list);
4018     while ((id_cache = silc_list_get(list))) {
4019       client = (SilcClientEntry)id_cache->context;
4020
4021       if (creation_time && client->data.created < creation_time)
4022         continue;
4023       if (!(client->data.status & SILC_IDLIST_STATUS_REGISTERED))
4024         continue;
4025       if (!client->connection && !client->router)
4026         continue;
4027
4028       SILC_LOG_DEBUG(("Announce Client ID %s",
4029                       silc_id_render(client->id, SILC_ID_CLIENT)));
4030
4031       idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
4032
4033       *clients = silc_buffer_realloc(*clients,
4034                                      (*clients ?
4035                                       silc_buffer_truelen((*clients)) +
4036                                       silc_buffer_len(idp) :
4037                                       silc_buffer_len(idp)));
4038       silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
4039       silc_buffer_put(*clients, idp->data, silc_buffer_len(idp));
4040       silc_buffer_pull(*clients, silc_buffer_len(idp));
4041
4042       SILC_PUT32_MSB(client->mode, mode);
4043       tmp =
4044         silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_UMODE_CHANGE,
4045                                            2, idp->data, silc_buffer_len(idp),
4046                                            mode, 4);
4047       *umodes = silc_buffer_realloc(*umodes,
4048                                     (*umodes ?
4049                                      silc_buffer_truelen((*umodes)) +
4050                                      silc_buffer_len(tmp) :
4051                                      silc_buffer_len(tmp)));
4052       silc_buffer_pull_tail(*umodes, ((*umodes)->end - (*umodes)->data));
4053       silc_buffer_put(*umodes, tmp->data, silc_buffer_len(tmp));
4054       silc_buffer_pull(*umodes, silc_buffer_len(tmp));
4055       silc_buffer_free(tmp);
4056
4057       silc_buffer_free(idp);
4058     }
4059   }
4060 }
4061
4062 /* This function is used to announce our existing clients to our router
4063    when we've connected to it. If `creation_time' is non-zero then only
4064    the clients that has been created after the `creation_time' will be
4065    announced. */
4066
4067 void silc_server_announce_clients(SilcServer server,
4068                                   unsigned long creation_time,
4069                                   SilcPacketStream remote)
4070 {
4071   SilcBuffer clients = NULL;
4072   SilcBuffer umodes = NULL;
4073
4074   SILC_LOG_DEBUG(("Announcing clients"));
4075
4076   /* Get clients in local list */
4077   silc_server_announce_get_clients(server, server->local_list,
4078                                    &clients, &umodes, creation_time);
4079
4080   /* As router we announce our global list as well */
4081   if (server->server_type == SILC_ROUTER)
4082     silc_server_announce_get_clients(server, server->global_list,
4083                                      &clients, &umodes, creation_time);
4084
4085   if (clients) {
4086     silc_buffer_push(clients, clients->data - clients->head);
4087     SILC_LOG_HEXDUMP(("clients"), clients->data, silc_buffer_len(clients));
4088
4089     /* Send the packet */
4090     silc_server_packet_send(server, remote,
4091                             SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
4092                             clients->data, silc_buffer_len(clients));
4093
4094     silc_buffer_free(clients);
4095   }
4096
4097   if (umodes) {
4098     silc_buffer_push(umodes, umodes->data - umodes->head);
4099     SILC_LOG_HEXDUMP(("umodes"), umodes->data, silc_buffer_len(umodes));
4100
4101     /* Send the packet */
4102     silc_server_packet_send(server, remote,
4103                             SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4104                             umodes->data, silc_buffer_len(umodes));
4105
4106     silc_buffer_free(umodes);
4107   }
4108 }
4109
4110 /* Returns channel's topic for announcing it */
4111
4112 void silc_server_announce_get_channel_topic(SilcServer server,
4113                                             SilcChannelEntry channel,
4114                                             SilcBuffer *topic)
4115 {
4116   SilcBuffer chidp;
4117
4118   if (channel->topic) {
4119     chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
4120     *topic = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_TOPIC_SET, 2,
4121                                                 chidp->data,
4122                                                 silc_buffer_len(chidp),
4123                                                 channel->topic,
4124                                                 strlen(channel->topic));
4125     silc_buffer_free(chidp);
4126   }
4127 }
4128
4129 /* Returns channel's invite and ban lists */
4130
4131 void silc_server_announce_get_inviteban(SilcServer server,
4132                                         SilcChannelEntry channel,
4133                                         SilcBuffer *invite,
4134                                         SilcBuffer *ban)
4135 {
4136   SilcBuffer list, idp, idp2, tmp2;
4137   SilcUInt32 type;
4138   SilcHashTableList htl;
4139   const unsigned char a[1] = { 0x03 };
4140
4141   idp = silc_id_payload_encode((void *)channel->id, SILC_ID_CHANNEL);
4142
4143   /* Encode invite list */
4144   if (channel->invite_list && silc_hash_table_count(channel->invite_list)) {
4145     list = silc_buffer_alloc_size(2);
4146     type = silc_hash_table_count(channel->invite_list);
4147     SILC_PUT16_MSB(type, list->data);
4148     silc_hash_table_list(channel->invite_list, &htl);
4149     while (silc_hash_table_get(&htl, (void *)&type, (void *)&tmp2))
4150       list = silc_argument_payload_encode_one(list, tmp2->data, silc_buffer_len(tmp2),
4151                                               type);
4152     silc_hash_table_list_reset(&htl);
4153
4154     idp2 = silc_id_payload_encode(server->id, SILC_ID_SERVER);
4155     *invite =
4156       silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_INVITE, 5,
4157                                          idp->data, silc_buffer_len(idp),
4158                                          channel->channel_name,
4159                                          strlen(channel->channel_name),
4160                                          idp2->data, silc_buffer_len(idp2),
4161                                          a, 1,
4162                                          list->data, silc_buffer_len(list));
4163     silc_buffer_free(idp2);
4164     silc_buffer_free(list);
4165   }
4166
4167   /* Encode ban list */
4168   if (channel->ban_list && silc_hash_table_count(channel->ban_list)) {
4169     list = silc_buffer_alloc_size(2);
4170     type = silc_hash_table_count(channel->ban_list);
4171     SILC_PUT16_MSB(type, list->data);
4172     silc_hash_table_list(channel->ban_list, &htl);
4173     while (silc_hash_table_get(&htl, (void *)&type, (void *)&tmp2))
4174       list = silc_argument_payload_encode_one(list, tmp2->data, silc_buffer_len(tmp2),
4175                                               type);
4176     silc_hash_table_list_reset(&htl);
4177
4178     *ban =
4179       silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_BAN, 3,
4180                                          idp->data, silc_buffer_len(idp),
4181                                          a, 1,
4182                                          list->data, silc_buffer_len(list));
4183     silc_buffer_free(list);
4184   }
4185
4186   silc_buffer_free(idp);
4187 }
4188
4189 /* Returns assembled packets for channel users of the `channel'. */
4190
4191 void silc_server_announce_get_channel_users(SilcServer server,
4192                                             SilcChannelEntry channel,
4193                                             SilcBuffer *channel_modes,
4194                                             SilcBuffer *channel_users,
4195                                             SilcBuffer *channel_users_modes)
4196 {
4197   SilcChannelClientEntry chl;
4198   SilcHashTableList htl;
4199   SilcBuffer chidp, clidp, csidp;
4200   SilcBuffer tmp, fkey = NULL, chpklist;
4201   int len;
4202   unsigned char mode[4], ulimit[4];
4203   char *hmac;
4204
4205   SILC_LOG_DEBUG(("Start"));
4206
4207   chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
4208   csidp = silc_id_payload_encode(server->id, SILC_ID_SERVER);
4209   chpklist = silc_server_get_channel_pk_list(server, channel, TRUE, FALSE);
4210
4211   /* CMODE notify */
4212   SILC_PUT32_MSB(channel->mode, mode);
4213   if (channel->mode & SILC_CHANNEL_MODE_ULIMIT)
4214     SILC_PUT32_MSB(channel->user_limit, ulimit);
4215   hmac = channel->hmac ? (char *)silc_hmac_get_name(channel->hmac) : NULL;
4216   if (channel->founder_key)
4217     fkey = silc_public_key_payload_encode(channel->founder_key);
4218   tmp =
4219     silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CMODE_CHANGE,
4220                                        8, csidp->data,
4221                                        silc_buffer_len(csidp),
4222                                        mode, sizeof(mode),
4223                                        NULL, 0,
4224                                        hmac, hmac ? strlen(hmac) : 0,
4225                                        channel->passphrase,
4226                                        channel->passphrase ?
4227                                        strlen(channel->passphrase) : 0,
4228                                        fkey ? fkey->data : NULL,
4229                                        fkey ? silc_buffer_len(fkey) : 0,
4230                                        chpklist ? chpklist->data : NULL,
4231                                        chpklist ?
4232                                        silc_buffer_len(chpklist) : 0,
4233                                        (channel->mode &
4234                                         SILC_CHANNEL_MODE_ULIMIT ?
4235                                         ulimit : NULL),
4236                                        (channel->mode &
4237                                         SILC_CHANNEL_MODE_ULIMIT ?
4238                                         sizeof(ulimit) : 0));
4239   len = silc_buffer_len(tmp);
4240   *channel_modes =
4241     silc_buffer_realloc(*channel_modes,
4242                         (*channel_modes ?
4243                          silc_buffer_truelen((*channel_modes)) + len : len));
4244   silc_buffer_pull_tail(*channel_modes,
4245                         ((*channel_modes)->end -
4246                          (*channel_modes)->data));
4247   silc_buffer_put(*channel_modes, tmp->data, silc_buffer_len(tmp));
4248   silc_buffer_pull(*channel_modes, len);
4249   silc_buffer_free(tmp);
4250   silc_buffer_free(fkey);
4251   fkey = NULL;
4252
4253   /* Now find all users on the channel */
4254   silc_hash_table_list(channel->user_list, &htl);
4255   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4256     clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
4257
4258     SILC_LOG_DEBUG(("JOIN Client %s", silc_id_render(chl->client->id,
4259                                                      SILC_ID_CLIENT)));
4260
4261     /* JOIN Notify */
4262     tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
4263                                              clidp->data,
4264                                              silc_buffer_len(clidp),
4265                                              chidp->data,
4266                                              silc_buffer_len(chidp));
4267     len = silc_buffer_len(tmp);
4268     *channel_users =
4269       silc_buffer_realloc(*channel_users,
4270                           (*channel_users ?
4271                            silc_buffer_truelen((*channel_users)) + len : len));
4272     silc_buffer_pull_tail(*channel_users,
4273                           ((*channel_users)->end -
4274                            (*channel_users)->data));
4275
4276     silc_buffer_put(*channel_users, tmp->data, silc_buffer_len(tmp));
4277     silc_buffer_pull(*channel_users, len);
4278     silc_buffer_free(tmp);
4279
4280     /* CUMODE notify for mode change on the channel */
4281     SILC_PUT32_MSB(chl->mode, mode);
4282     if (chl->mode & SILC_CHANNEL_UMODE_CHANFO && channel->founder_key)
4283       fkey = silc_public_key_payload_encode(channel->founder_key);
4284     tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
4285                                              4, csidp->data,
4286                                              silc_buffer_len(csidp),
4287                                              mode, sizeof(mode),
4288                                              clidp->data,
4289                                              silc_buffer_len(clidp),
4290                                              fkey ? fkey->data : NULL,
4291                                              fkey ? silc_buffer_len(fkey) : 0);
4292     len = silc_buffer_len(tmp);
4293     *channel_users_modes =
4294       silc_buffer_realloc(*channel_users_modes,
4295                           (*channel_users_modes ?
4296                            silc_buffer_truelen((*channel_users_modes)) +
4297                            len : len));
4298     silc_buffer_pull_tail(*channel_users_modes,
4299                           ((*channel_users_modes)->end -
4300                            (*channel_users_modes)->data));
4301
4302     silc_buffer_put(*channel_users_modes, tmp->data, silc_buffer_len(tmp));
4303     silc_buffer_pull(*channel_users_modes, len);
4304     silc_buffer_free(tmp);
4305     silc_buffer_free(fkey);
4306     fkey = NULL;
4307     silc_buffer_free(clidp);
4308   }
4309   silc_hash_table_list_reset(&htl);
4310   silc_buffer_free(chidp);
4311   silc_buffer_free(csidp);
4312 }
4313
4314 /* Returns assembled packets for all channels and users on those channels
4315    from the given ID List. The packets are in the form dictated by the
4316    New Channel and New Channel User payloads. */
4317
4318 void silc_server_announce_get_channels(SilcServer server,
4319                                        SilcIDList id_list,
4320                                        SilcBuffer *channels,
4321                                        SilcBuffer **channel_modes,
4322                                        SilcBuffer *channel_users,
4323                                        SilcBuffer **channel_users_modes,
4324                                        SilcUInt32 *channel_users_modes_c,
4325                                        SilcBuffer **channel_topics,
4326                                        SilcBuffer **channel_invites,
4327                                        SilcBuffer **channel_bans,
4328                                        SilcChannelID ***channel_ids,
4329                                        unsigned long creation_time)
4330 {
4331   SilcList list;
4332   SilcIDCacheEntry id_cache;
4333   SilcChannelEntry channel;
4334   unsigned char cid[32];
4335   SilcUInt32 id_len;
4336   SilcUInt16 name_len;
4337   int len;
4338   int i = *channel_users_modes_c;
4339   SilcBool announce;
4340
4341   SILC_LOG_DEBUG(("Start"));
4342
4343   /* Go through all channels in the list */
4344   if (silc_idcache_get_all(id_list->channels, &list)) {
4345     silc_list_start(list);
4346     while ((id_cache = silc_list_get(list))) {
4347       channel = (SilcChannelEntry)id_cache->context;
4348
4349       if (creation_time && channel->created < creation_time)
4350         announce = FALSE;
4351       else
4352         announce = TRUE;
4353
4354       SILC_LOG_DEBUG(("Announce Channel ID %s",
4355                       silc_id_render(channel->id, SILC_ID_CHANNEL)));
4356
4357       silc_id_id2str(channel->id, SILC_ID_CHANNEL, cid, sizeof(cid), &id_len);
4358       name_len = strlen(channel->channel_name);
4359
4360       if (announce) {
4361         len = 4 + name_len + id_len + 4;
4362         *channels =
4363           silc_buffer_realloc(*channels,
4364                               (*channels ?
4365                                silc_buffer_truelen((*channels)) +
4366                                len : len));
4367         silc_buffer_pull_tail(*channels,
4368                               ((*channels)->end - (*channels)->data));
4369         silc_buffer_format(*channels,
4370                            SILC_STR_UI_SHORT(name_len),
4371                            SILC_STR_UI_XNSTRING(channel->channel_name,
4372                                                 name_len),
4373                            SILC_STR_UI_SHORT(id_len),
4374                              SILC_STR_UI_XNSTRING(cid, id_len),
4375                            SILC_STR_UI_INT(channel->mode),
4376                            SILC_STR_END);
4377         silc_buffer_pull(*channels, len);
4378       }
4379
4380       if (creation_time && channel->updated < creation_time)
4381         announce = FALSE;
4382       else
4383         announce = TRUE;
4384
4385       if (announce) {
4386         /* Channel user modes */
4387         *channel_users_modes = silc_realloc(*channel_users_modes,
4388                                             sizeof(**channel_users_modes) *
4389                                             (i + 1));
4390         (*channel_users_modes)[i] = NULL;
4391         *channel_modes = silc_realloc(*channel_modes,
4392                                       sizeof(**channel_modes) * (i + 1));
4393         (*channel_modes)[i] = NULL;
4394         *channel_ids = silc_realloc(*channel_ids,
4395                                       sizeof(**channel_ids) * (i + 1));
4396         (*channel_ids)[i] = NULL;
4397         silc_server_announce_get_channel_users(server, channel,
4398                                                &(*channel_modes)[i],
4399                                                channel_users,
4400                                                &(*channel_users_modes)[i]);
4401         (*channel_ids)[i] = channel->id;
4402
4403         /* Channel's topic */
4404         *channel_topics = silc_realloc(*channel_topics,
4405                                        sizeof(**channel_topics) * (i + 1));
4406         (*channel_topics)[i] = NULL;
4407         silc_server_announce_get_channel_topic(server, channel,
4408                                                &(*channel_topics)[i]);
4409
4410         /* Channel's invite and ban list */
4411         *channel_invites = silc_realloc(*channel_invites,
4412                                         sizeof(**channel_invites) * (i + 1));
4413         (*channel_invites)[i] = NULL;
4414         *channel_bans = silc_realloc(*channel_bans,
4415                                      sizeof(**channel_bans) * (i + 1));
4416         (*channel_bans)[i] = NULL;
4417         silc_server_announce_get_inviteban(server, channel,
4418                                            &(*channel_invites)[i],
4419                                            &(*channel_bans)[i]);
4420
4421         (*channel_users_modes_c)++;
4422
4423         i++;
4424       }
4425     }
4426   }
4427 }
4428
4429 /* This function is used to announce our existing channels to our router
4430    when we've connected to it. This also announces the users on the
4431    channels to the router. If the `creation_time' is non-zero only the
4432    channels that was created after the `creation_time' are announced.
4433    Note that the channel users are still announced even if the `creation_time'
4434    was provided. */
4435
4436 void silc_server_announce_channels(SilcServer server,
4437                                    unsigned long creation_time,
4438                                    SilcPacketStream remote)
4439 {
4440   SilcBuffer channels = NULL, *channel_modes = NULL, channel_users = NULL;
4441   SilcBuffer *channel_users_modes = NULL;
4442   SilcBuffer *channel_topics = NULL;
4443   SilcBuffer *channel_invites = NULL;
4444   SilcBuffer *channel_bans = NULL;
4445   SilcUInt32 channel_users_modes_c = 0;
4446   SilcChannelID **channel_ids = NULL;
4447
4448   SILC_LOG_DEBUG(("Announcing channels and channel users"));
4449
4450   /* Get channels and channel users in local list */
4451   silc_server_announce_get_channels(server, server->local_list,
4452                                     &channels, &channel_modes,
4453                                     &channel_users,
4454                                     &channel_users_modes,
4455                                     &channel_users_modes_c,
4456                                     &channel_topics,
4457                                     &channel_invites,
4458                                     &channel_bans,
4459                                     &channel_ids, creation_time);
4460
4461   /* Get channels and channel users in global list */
4462   if (server->server_type != SILC_SERVER)
4463     silc_server_announce_get_channels(server, server->global_list,
4464                                       &channels, &channel_modes,
4465                                       &channel_users,
4466                                       &channel_users_modes,
4467                                       &channel_users_modes_c,
4468                                       &channel_topics,
4469                                       &channel_invites,
4470                                       &channel_bans,
4471                                       &channel_ids, creation_time);
4472
4473   if (channels) {
4474     silc_buffer_push(channels, channels->data - channels->head);
4475     SILC_LOG_HEXDUMP(("channels"), channels->data, silc_buffer_len(channels));
4476
4477     /* Send the packet */
4478     silc_server_packet_send(server, remote,
4479                             SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
4480                             channels->data, silc_buffer_len(channels));
4481
4482     silc_buffer_free(channels);
4483   }
4484
4485   if (channel_users) {
4486     silc_buffer_push(channel_users, channel_users->data - channel_users->head);
4487     SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
4488                      silc_buffer_len(channel_users));
4489
4490     /* Send the packet */
4491     silc_server_packet_send(server, remote,
4492                             SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4493                             channel_users->data, silc_buffer_len(channel_users));
4494
4495     silc_buffer_free(channel_users);
4496   }
4497
4498   if (channel_modes) {
4499     int i;
4500
4501     for (i = 0; i < channel_users_modes_c; i++) {
4502       if (!channel_modes[i])
4503         continue;
4504       silc_buffer_push(channel_modes[i],
4505                        channel_modes[i]->data -
4506                        channel_modes[i]->head);
4507       SILC_LOG_HEXDUMP(("channel modes"), channel_modes[i]->data,
4508                        silc_buffer_len(channel_modes[i]));
4509       silc_server_packet_send_dest(server, remote,
4510                                    SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4511                                    channel_ids[i], SILC_ID_CHANNEL,
4512                                    channel_modes[i]->data,
4513                                    silc_buffer_len(channel_modes[i]));
4514       silc_buffer_free(channel_modes[i]);
4515     }
4516     silc_free(channel_modes);
4517   }
4518
4519   if (channel_users_modes) {
4520     int i;
4521
4522     for (i = 0; i < channel_users_modes_c; i++) {
4523       if (!channel_users_modes[i])
4524         continue;
4525       silc_buffer_push(channel_users_modes[i],
4526                        channel_users_modes[i]->data -
4527                        channel_users_modes[i]->head);
4528       SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
4529                        silc_buffer_len(channel_users_modes[i]));
4530       silc_server_packet_send_dest(server, remote,
4531                                    SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4532                                    channel_ids[i], SILC_ID_CHANNEL,
4533                                    channel_users_modes[i]->data,
4534                                    silc_buffer_len(channel_users_modes[i]));
4535       silc_buffer_free(channel_users_modes[i]);
4536     }
4537     silc_free(channel_users_modes);
4538   }
4539
4540   if (channel_topics) {
4541     int i;
4542
4543     for (i = 0; i < channel_users_modes_c; i++) {
4544       if (!channel_topics[i])
4545         continue;
4546
4547       silc_buffer_push(channel_topics[i],
4548                        channel_topics[i]->data -
4549                        channel_topics[i]->head);
4550       SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
4551                        silc_buffer_len(channel_topics[i]));
4552       silc_server_packet_send_dest(server, remote,
4553                                    SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4554                                    channel_ids[i], SILC_ID_CHANNEL,
4555                                    channel_topics[i]->data,
4556                                    silc_buffer_len(channel_topics[i]));
4557       silc_buffer_free(channel_topics[i]);
4558     }
4559     silc_free(channel_topics);
4560   }
4561
4562   if (channel_invites) {
4563     int i;
4564
4565     for (i = 0; i < channel_users_modes_c; i++) {
4566       if (!channel_invites[i])
4567         continue;
4568
4569       silc_buffer_push(channel_invites[i],
4570                        channel_invites[i]->data -
4571                        channel_invites[i]->head);
4572       SILC_LOG_HEXDUMP(("channel invite list"), channel_invites[i]->data,
4573                        silc_buffer_len(channel_invites[i]));
4574       silc_server_packet_send_dest(server, remote,
4575                                    SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4576                                    channel_ids[i], SILC_ID_CHANNEL,
4577                                    channel_invites[i]->data,
4578                                    silc_buffer_len(channel_invites[i]));
4579       silc_buffer_free(channel_invites[i]);
4580     }
4581     silc_free(channel_invites);
4582   }
4583
4584   if (channel_bans) {
4585     int i;
4586
4587     for (i = 0; i < channel_users_modes_c; i++) {
4588       if (!channel_bans[i])
4589         continue;
4590
4591       silc_buffer_push(channel_bans[i],
4592                        channel_bans[i]->data -
4593                        channel_bans[i]->head);
4594       SILC_LOG_HEXDUMP(("channel ban list"), channel_bans[i]->data,
4595                        silc_buffer_len(channel_bans[i]));
4596       silc_server_packet_send_dest(server, remote,
4597                                    SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4598                                    channel_ids[i], SILC_ID_CHANNEL,
4599                                    channel_bans[i]->data,
4600                                    silc_buffer_len(channel_bans[i]));
4601       silc_buffer_free(channel_bans[i]);
4602     }
4603     silc_free(channel_bans);
4604   }
4605
4606   silc_free(channel_ids);
4607 }
4608
4609 /* Announces WATCH list. */
4610
4611 void silc_server_announce_watches(SilcServer server,
4612                                   SilcPacketStream remote)
4613 {
4614   SilcHashTableList htl;
4615   SilcBuffer buffer, idp, args, pkp;
4616   SilcClientEntry client;
4617   void *key;
4618
4619   SILC_LOG_DEBUG(("Announcing watch list"));
4620
4621   /* XXX because way we save the nicks (hash) we cannot announce them. */
4622
4623   /* XXX we should send all public keys in one command if client is
4624      watching more than one key */
4625   silc_hash_table_list(server->watcher_list_pk, &htl);
4626   while (silc_hash_table_get(&htl, &key, (void *)&client)) {
4627     if (!client || !client->id)
4628       continue;
4629
4630     server->stat.commands_sent++;
4631
4632     idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
4633     args = silc_buffer_alloc_size(2);
4634     silc_buffer_format(args,
4635                        SILC_STR_UI_SHORT(1),
4636                        SILC_STR_END);
4637     pkp = silc_public_key_payload_encode(key);
4638     args = silc_argument_payload_encode_one(args, pkp->data,
4639                                             silc_buffer_len(pkp), 0x00);
4640     buffer = silc_command_payload_encode_va(SILC_COMMAND_WATCH,
4641                                             ++server->cmd_ident, 2,
4642                                             1, idp->data, silc_buffer_len(idp),
4643                                             4, args->data,
4644                                             silc_buffer_len(args));
4645
4646     /* Send command */
4647     silc_server_packet_send(server, remote, SILC_PACKET_COMMAND, 0,
4648                             buffer->data, silc_buffer_len(buffer));
4649
4650     silc_buffer_free(pkp);
4651     silc_buffer_free(args);
4652     silc_buffer_free(idp);
4653     silc_buffer_free(buffer);
4654   }
4655   silc_hash_table_list_reset(&htl);
4656 }
4657
4658 /* Assembles user list and users mode list from the `channel'. */
4659
4660 SilcBool silc_server_get_users_on_channel(SilcServer server,
4661                                           SilcChannelEntry channel,
4662                                           SilcBuffer *user_list,
4663                                           SilcBuffer *mode_list,
4664                                           SilcUInt32 *user_count)
4665 {
4666   SilcChannelClientEntry chl;
4667   SilcHashTableList htl;
4668   SilcBuffer client_id_list;
4669   SilcBuffer client_mode_list;
4670   SilcBuffer idp;
4671   SilcUInt32 list_count = 0, len = 0;
4672
4673   if (!silc_hash_table_count(channel->user_list))
4674     return FALSE;
4675
4676   silc_hash_table_list(channel->user_list, &htl);
4677   while (silc_hash_table_get(&htl, NULL, (void *)&chl))
4678     len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
4679   silc_hash_table_list_reset(&htl);
4680
4681   client_id_list = silc_buffer_alloc(len);
4682   client_mode_list =
4683     silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
4684   silc_buffer_pull_tail(client_id_list, silc_buffer_truelen(client_id_list));
4685   silc_buffer_pull_tail(client_mode_list,
4686                         silc_buffer_truelen(client_mode_list));
4687
4688   silc_hash_table_list(channel->user_list, &htl);
4689   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4690     /* Client ID */
4691     idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
4692     silc_buffer_put(client_id_list, idp->data, silc_buffer_len(idp));
4693     silc_buffer_pull(client_id_list, silc_buffer_len(idp));
4694     silc_buffer_free(idp);
4695
4696     /* Client's mode on channel */
4697     SILC_PUT32_MSB(chl->mode, client_mode_list->data);
4698     silc_buffer_pull(client_mode_list, 4);
4699
4700     list_count++;
4701   }
4702   silc_hash_table_list_reset(&htl);
4703   silc_buffer_push(client_id_list,
4704                    client_id_list->data - client_id_list->head);
4705   silc_buffer_push(client_mode_list,
4706                    client_mode_list->data - client_mode_list->head);
4707
4708   *user_list = client_id_list;
4709   *mode_list = client_mode_list;
4710   *user_count = list_count;
4711   return TRUE;
4712 }
4713
4714 /* Saves users and their modes to the `channel'. */
4715
4716 void silc_server_save_users_on_channel(SilcServer server,
4717                                        SilcPacketStream sock,
4718                                        SilcChannelEntry channel,
4719                                        SilcClientID *noadd,
4720                                        SilcBuffer user_list,
4721                                        SilcBuffer mode_list,
4722                                        SilcUInt32 user_count)
4723 {
4724   int i;
4725   SilcUInt16 idp_len;
4726   SilcUInt32 mode;
4727   SilcID id;
4728   SilcClientEntry client;
4729   SilcIDCacheEntry cache;
4730   SilcChannelClientEntry chl;
4731
4732   SILC_LOG_DEBUG(("Saving %d users on %s channel", user_count,
4733                   channel->channel_name));
4734
4735   for (i = 0; i < user_count; i++) {
4736     /* Client ID */
4737     SILC_GET16_MSB(idp_len, user_list->data + 2);
4738     idp_len += 4;
4739     if (!silc_id_payload_parse_id(user_list->data, idp_len, &id))
4740       continue;
4741     silc_buffer_pull(user_list, idp_len);
4742
4743     /* Mode */
4744     SILC_GET32_MSB(mode, mode_list->data);
4745     silc_buffer_pull(mode_list, 4);
4746
4747     if (noadd && SILC_ID_CLIENT_COMPARE(&id.u.client_id, noadd))
4748       continue;
4749
4750     cache = NULL;
4751
4752     /* Check if we have this client cached already. */
4753     client = silc_idlist_find_client_by_id(server->local_list,
4754                                            &id.u.client_id,
4755                                            server->server_type, &cache);
4756     if (!client)
4757       client = silc_idlist_find_client_by_id(server->global_list,
4758                                              &id.u.client_id,
4759                                              server->server_type, &cache);
4760     if (!client) {
4761       /* If router did not find such Client ID in its lists then this must
4762          be bogus client or some router in the net is buggy. */
4763       if (server->server_type != SILC_SERVER)
4764         continue;
4765
4766       /* We don't have that client anywhere, add it. The client is added
4767          to global list since server didn't have it in the lists so it must be
4768          global. */
4769       client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
4770                                       silc_id_dup(&id.u.client_id,
4771                                                   SILC_ID_CLIENT),
4772                                       silc_packet_get_context(sock),
4773                                       NULL);
4774       if (!client) {
4775         SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
4776         continue;
4777       }
4778
4779       client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
4780     }
4781
4782     if (!(client->data.status & SILC_IDLIST_STATUS_REGISTERED)) {
4783       SILC_LOG_ERROR(("Attempting to add unregistered client to channel ",
4784                       "%s", channel->channel_name));
4785       continue;
4786     }
4787
4788     if (!silc_server_client_on_channel(client, channel, &chl)) {
4789       /* Client was not on the channel, add it. */
4790       chl = silc_calloc(1, sizeof(*chl));
4791       chl->client = client;
4792       chl->mode = mode;
4793       chl->channel = channel;
4794       silc_hash_table_add(channel->user_list, chl->client, chl);
4795       silc_hash_table_add(client->channels, chl->channel, chl);
4796       channel->user_count++;
4797     } else {
4798       /* Update mode */
4799       chl->mode = mode;
4800     }
4801   }
4802 }
4803
4804 /* Saves channels and channels user modes to the `client'.  Removes
4805    the client from those channels that are not sent in the list but
4806    it has joined. */
4807
4808 void silc_server_save_user_channels(SilcServer server,
4809                                     SilcPacketStream sock,
4810                                     SilcClientEntry client,
4811                                     SilcBuffer channels,
4812                                     SilcBuffer channels_user_modes)
4813 {
4814   SilcDList ch;
4815   SilcUInt32 *chumodes;
4816   SilcChannelPayload entry;
4817   SilcChannelEntry channel;
4818   SilcChannelID channel_id;
4819   SilcChannelClientEntry chl;
4820   SilcHashTable ht = NULL;
4821   SilcHashTableList htl;
4822   char *name;
4823   int i = 0;
4824
4825   if (!channels || !channels_user_modes ||
4826       !(client->data.status & SILC_IDLIST_STATUS_REGISTERED))
4827     goto out;
4828
4829   ch = silc_channel_payload_parse_list(channels->data,
4830                                        silc_buffer_len(channels));
4831   if (ch && silc_get_mode_list(channels_user_modes, silc_dlist_count(ch),
4832                                &chumodes)) {
4833     ht = silc_hash_table_alloc(0, silc_hash_ptr, NULL, NULL,
4834                                NULL, NULL, NULL, TRUE);
4835     silc_dlist_start(ch);
4836     while ((entry = silc_dlist_get(ch)) != SILC_LIST_END) {
4837       /* Check if we have this channel, and add it if we don't have it.
4838          Also add the client on the channel unless it is there already. */
4839       if (!silc_channel_get_id_parse(entry, &channel_id))
4840         continue;
4841       channel = silc_idlist_find_channel_by_id(server->local_list,
4842                                                &channel_id, NULL);
4843       if (!channel)
4844         channel = silc_idlist_find_channel_by_id(server->global_list,
4845                                                  &channel_id, NULL);
4846       if (!channel) {
4847         if (server->server_type != SILC_SERVER) {
4848           i++;
4849           continue;
4850         }
4851
4852         /* We don't have that channel anywhere, add it. */
4853         name = silc_channel_get_name(entry, NULL);
4854         channel = silc_idlist_add_channel(server->global_list, strdup(name), 0,
4855                                           silc_id_dup(&channel_id,
4856                                                       SILC_ID_CHANNEL),
4857                                           server->router, NULL, NULL, 0);
4858         if (!channel) {
4859           i++;
4860           continue;
4861         }
4862       }
4863
4864       channel->mode = silc_channel_get_mode(entry);
4865
4866       /* Add the client on the channel */
4867       if (!silc_server_client_on_channel(client, channel, &chl)) {
4868         chl = silc_calloc(1, sizeof(*chl));
4869         chl->client = client;
4870         chl->mode = chumodes[i++];
4871         chl->channel = channel;
4872         silc_hash_table_add(channel->user_list, chl->client, chl);
4873         silc_hash_table_add(client->channels, chl->channel, chl);
4874         channel->user_count++;
4875       } else {
4876         /* Update mode */
4877         chl->mode = chumodes[i++];
4878       }
4879
4880       silc_hash_table_add(ht, channel, channel);
4881     }
4882     silc_channel_payload_list_free(ch);
4883     silc_free(chumodes);
4884   }
4885
4886  out:
4887   /* Go through the list again and remove client from channels that
4888      are no part of the list. */
4889   if (ht) {
4890     silc_hash_table_list(client->channels, &htl);
4891     while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4892       if (!silc_hash_table_find(ht, chl->channel, NULL, NULL)) {
4893         silc_hash_table_del(chl->channel->user_list, chl->client);
4894         silc_hash_table_del(chl->client->channels, chl->channel);
4895         silc_free(chl);
4896       }
4897     }
4898     silc_hash_table_list_reset(&htl);
4899     silc_hash_table_free(ht);
4900   } else {
4901     silc_hash_table_list(client->channels, &htl);
4902     while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4903       silc_hash_table_del(chl->channel->user_list, chl->client);
4904       silc_hash_table_del(chl->client->channels, chl->channel);
4905       silc_free(chl);
4906     }
4907     silc_hash_table_list_reset(&htl);
4908   }
4909 }
4910
4911 /* Lookups route to the client indicated by the `id_data'. The connection
4912    object and internal data object is returned. Returns NULL if route
4913    could not be found to the client. If the `client_id' is specified then
4914    it is used and the `id_data' is ignored. */
4915
4916 SilcPacketStream
4917 silc_server_get_client_route(SilcServer server,
4918                              unsigned char *id_data,
4919                              SilcUInt32 id_len,
4920                              SilcClientID *client_id,
4921                              SilcIDListData *idata,
4922                              SilcClientEntry *client_entry)
4923 {
4924   SilcClientID *id, clid;
4925   SilcClientEntry client;
4926
4927   SILC_LOG_DEBUG(("Start"));
4928
4929   if (client_entry)
4930     *client_entry = NULL;
4931
4932   /* Decode destination Client ID */
4933   if (!client_id) {
4934     if (!silc_id_str2id(id_data, id_len, SILC_ID_CLIENT, &clid, sizeof(clid)))
4935       return NULL;
4936     id = silc_id_dup(&clid, SILC_ID_CLIENT);
4937   } else {
4938     id = silc_id_dup(client_id, SILC_ID_CLIENT);
4939   }
4940
4941   /* If the destination belongs to our server we don't have to route
4942      the packet anywhere but to send it to the local destination. */
4943   client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
4944   if (client) {
4945     silc_free(id);
4946
4947     /* If we are router and the client has router then the client is in
4948        our cell but not directly connected to us. */
4949     if (server->server_type == SILC_ROUTER && client->router) {
4950       /* We are of course in this case the client's router thus the route
4951          to the client is the server who owns the client. So, we will send
4952          the packet to that server. */
4953       if (idata)
4954         *idata = (SilcIDListData)client->router;
4955       return client->router->connection;
4956     }
4957
4958     /* Seems that client really is directly connected to us */
4959     if (idata)
4960       *idata = (SilcIDListData)client;
4961     if (client_entry)
4962       *client_entry = client;
4963     return client->connection;
4964   }
4965
4966   /* Destination belongs to someone not in this server. If we are normal
4967      server our action is to send the packet to our router. */
4968   if (server->server_type != SILC_ROUTER && !server->standalone) {
4969     silc_free(id);
4970     if (idata)
4971       *idata = (SilcIDListData)server->router;
4972     return SILC_PRIMARY_ROUTE(server);
4973   }
4974
4975   /* We are router and we will perform route lookup for the destination
4976      and send the packet to fastest route. */
4977   if (server->server_type == SILC_ROUTER && !server->standalone) {
4978     /* Check first that the ID is valid */
4979     client = silc_idlist_find_client_by_id(server->global_list, id,
4980                                            TRUE, NULL);
4981     if (client) {
4982       SilcPacketStream dst_sock;
4983
4984       dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
4985
4986       silc_free(id);
4987       if (idata && dst_sock)
4988         *idata = silc_packet_get_context(dst_sock);
4989       return dst_sock;
4990     }
4991   }
4992
4993   silc_free(id);
4994   return NULL;
4995 }
4996
4997 /* Encodes and returns channel list of channels the `client' has joined.
4998    Secret channels are not put to the list. */
4999
5000 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
5001                                                SilcClientEntry client,
5002                                                SilcBool get_private,
5003                                                SilcBool get_secret,
5004                                                SilcBuffer *user_mode_list)
5005 {
5006   SilcBuffer buffer = NULL;
5007   SilcChannelEntry channel;
5008   SilcChannelClientEntry chl;
5009   SilcHashTableList htl;
5010   unsigned char cid[32];
5011   SilcUInt32 id_len;
5012   SilcUInt16 name_len;
5013   int len;
5014
5015   if (user_mode_list)
5016     *user_mode_list = NULL;
5017
5018   silc_hash_table_list(client->channels, &htl);
5019   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
5020     channel = chl->channel;
5021
5022     if (channel->mode & SILC_CHANNEL_MODE_SECRET && !get_secret)
5023       continue;
5024     if (channel->mode & SILC_CHANNEL_MODE_PRIVATE && !get_private)
5025       continue;
5026
5027     silc_id_id2str(channel->id, SILC_ID_CHANNEL, cid, sizeof(cid), &id_len);
5028     name_len = strlen(channel->channel_name);
5029
5030     len = 4 + name_len + id_len + 4;
5031     buffer = silc_buffer_realloc(buffer,
5032                                  (buffer ?
5033                                   silc_buffer_truelen(buffer) + len : len));
5034     silc_buffer_pull_tail(buffer, (buffer->end - buffer->data));
5035     silc_buffer_format(buffer,
5036                        SILC_STR_UI_SHORT(name_len),
5037                        SILC_STR_DATA(channel->channel_name, name_len),
5038                        SILC_STR_UI_SHORT(id_len),
5039                        SILC_STR_DATA(cid, id_len),
5040                        SILC_STR_UI_INT(chl->channel->mode),
5041                        SILC_STR_END);
5042     silc_buffer_pull(buffer, len);
5043
5044     if (user_mode_list) {
5045       *user_mode_list =
5046         silc_buffer_realloc(*user_mode_list,
5047                             (*user_mode_list ?
5048                              silc_buffer_truelen((*user_mode_list)) + 4 : 4));
5049       silc_buffer_pull_tail(*user_mode_list, ((*user_mode_list)->end -
5050                                               (*user_mode_list)->data));
5051       SILC_PUT32_MSB(chl->mode, (*user_mode_list)->data);
5052       silc_buffer_pull(*user_mode_list, 4);
5053     }
5054   }
5055   silc_hash_table_list_reset(&htl);
5056
5057   if (buffer)
5058     silc_buffer_push(buffer, buffer->data - buffer->head);
5059   if (user_mode_list && *user_mode_list)
5060     silc_buffer_push(*user_mode_list, ((*user_mode_list)->data -
5061                                        (*user_mode_list)->head));
5062
5063   return buffer;
5064 }
5065
5066 /* Task callback used to retrieve network statistical information from
5067    router server once in a while. */
5068
5069 SILC_TASK_CALLBACK(silc_server_get_stats)
5070 {
5071   SilcServer server = (SilcServer)context;
5072   SilcBuffer idp, packet;
5073
5074   if (!server->standalone) {
5075     SILC_LOG_DEBUG(("Retrieving stats from router"));
5076     server->stat.commands_sent++;
5077     idp = silc_id_payload_encode(server->router->id, SILC_ID_SERVER);
5078     if (idp) {
5079       packet = silc_command_payload_encode_va(SILC_COMMAND_STATS,
5080                                               ++server->cmd_ident, 1,
5081                                               1, idp->data,
5082                                               silc_buffer_len(idp));
5083       silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
5084                               SILC_PACKET_COMMAND, 0, packet->data,
5085                               silc_buffer_len(packet));
5086       silc_buffer_free(packet);
5087       silc_buffer_free(idp);
5088     }
5089   }
5090
5091   silc_schedule_task_add_timeout(server->schedule, silc_server_get_stats,
5092                                  server, 120, 0);
5093 }