Fixed many 64-bit alignment issues from silcd.
[silc.git] / apps / silcd / server.c
1 /*
2
3   server.c
4
5   Author: Pekka Riikonen <priikone@silcnet.org>
6
7   Copyright (C) 1997 - 2008 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   void *ptype;
4139   SilcHashTableList htl;
4140   const unsigned char a[1] = { 0x03 };
4141
4142   idp = silc_id_payload_encode((void *)channel->id, SILC_ID_CHANNEL);
4143
4144   /* Encode invite list */
4145   if (channel->invite_list && silc_hash_table_count(channel->invite_list)) {
4146     list = silc_buffer_alloc_size(2);
4147     type = silc_hash_table_count(channel->invite_list);
4148     SILC_PUT16_MSB(type, list->data);
4149     silc_hash_table_list(channel->invite_list, &htl);
4150     while (silc_hash_table_get(&htl, (void *)&ptype, (void *)&tmp2))
4151       list = silc_argument_payload_encode_one(list, tmp2->data,
4152                                               silc_buffer_len(tmp2),
4153                                               SILC_PTR_TO_32(ptype));
4154     silc_hash_table_list_reset(&htl);
4155
4156     idp2 = silc_id_payload_encode(server->id, SILC_ID_SERVER);
4157     *invite =
4158       silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_INVITE, 5,
4159                                          idp->data, silc_buffer_len(idp),
4160                                          channel->channel_name,
4161                                          strlen(channel->channel_name),
4162                                          idp2->data, silc_buffer_len(idp2),
4163                                          a, 1,
4164                                          list->data, silc_buffer_len(list));
4165     silc_buffer_free(idp2);
4166     silc_buffer_free(list);
4167   }
4168
4169   /* Encode ban list */
4170   if (channel->ban_list && silc_hash_table_count(channel->ban_list)) {
4171     list = silc_buffer_alloc_size(2);
4172     type = silc_hash_table_count(channel->ban_list);
4173     SILC_PUT16_MSB(type, list->data);
4174     silc_hash_table_list(channel->ban_list, &htl);
4175     while (silc_hash_table_get(&htl, (void *)&ptype, (void *)&tmp2))
4176       list = silc_argument_payload_encode_one(list, tmp2->data,
4177                                               silc_buffer_len(tmp2),
4178                                               SILC_PTR_TO_32(ptype));
4179     silc_hash_table_list_reset(&htl);
4180
4181     *ban =
4182       silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_BAN, 3,
4183                                          idp->data, silc_buffer_len(idp),
4184                                          a, 1,
4185                                          list->data, silc_buffer_len(list));
4186     silc_buffer_free(list);
4187   }
4188
4189   silc_buffer_free(idp);
4190 }
4191
4192 /* Returns assembled packets for channel users of the `channel'. */
4193
4194 void silc_server_announce_get_channel_users(SilcServer server,
4195                                             SilcChannelEntry channel,
4196                                             SilcBuffer *channel_modes,
4197                                             SilcBuffer *channel_users,
4198                                             SilcBuffer *channel_users_modes)
4199 {
4200   SilcChannelClientEntry chl;
4201   SilcHashTableList htl;
4202   SilcBuffer chidp, clidp, csidp;
4203   SilcBuffer tmp, fkey = NULL, chpklist;
4204   int len;
4205   unsigned char mode[4], ulimit[4];
4206   char *hmac;
4207
4208   SILC_LOG_DEBUG(("Start"));
4209
4210   chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
4211   csidp = silc_id_payload_encode(server->id, SILC_ID_SERVER);
4212   chpklist = silc_server_get_channel_pk_list(server, channel, TRUE, FALSE);
4213
4214   /* CMODE notify */
4215   SILC_PUT32_MSB(channel->mode, mode);
4216   if (channel->mode & SILC_CHANNEL_MODE_ULIMIT)
4217     SILC_PUT32_MSB(channel->user_limit, ulimit);
4218   hmac = channel->hmac ? (char *)silc_hmac_get_name(channel->hmac) : NULL;
4219   if (channel->founder_key)
4220     fkey = silc_public_key_payload_encode(channel->founder_key);
4221   tmp =
4222     silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CMODE_CHANGE,
4223                                        8, csidp->data,
4224                                        silc_buffer_len(csidp),
4225                                        mode, sizeof(mode),
4226                                        NULL, 0,
4227                                        hmac, hmac ? strlen(hmac) : 0,
4228                                        channel->passphrase,
4229                                        channel->passphrase ?
4230                                        strlen(channel->passphrase) : 0,
4231                                        fkey ? fkey->data : NULL,
4232                                        fkey ? silc_buffer_len(fkey) : 0,
4233                                        chpklist ? chpklist->data : NULL,
4234                                        chpklist ?
4235                                        silc_buffer_len(chpklist) : 0,
4236                                        (channel->mode &
4237                                         SILC_CHANNEL_MODE_ULIMIT ?
4238                                         ulimit : NULL),
4239                                        (channel->mode &
4240                                         SILC_CHANNEL_MODE_ULIMIT ?
4241                                         sizeof(ulimit) : 0));
4242   len = silc_buffer_len(tmp);
4243   *channel_modes =
4244     silc_buffer_realloc(*channel_modes,
4245                         (*channel_modes ?
4246                          silc_buffer_truelen((*channel_modes)) + len : len));
4247   silc_buffer_pull_tail(*channel_modes,
4248                         ((*channel_modes)->end -
4249                          (*channel_modes)->data));
4250   silc_buffer_put(*channel_modes, tmp->data, silc_buffer_len(tmp));
4251   silc_buffer_pull(*channel_modes, len);
4252   silc_buffer_free(tmp);
4253   silc_buffer_free(fkey);
4254   fkey = NULL;
4255
4256   /* Now find all users on the channel */
4257   silc_hash_table_list(channel->user_list, &htl);
4258   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4259     clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
4260
4261     SILC_LOG_DEBUG(("JOIN Client %s", silc_id_render(chl->client->id,
4262                                                      SILC_ID_CLIENT)));
4263
4264     /* JOIN Notify */
4265     tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_JOIN, 2,
4266                                              clidp->data,
4267                                              silc_buffer_len(clidp),
4268                                              chidp->data,
4269                                              silc_buffer_len(chidp));
4270     len = silc_buffer_len(tmp);
4271     *channel_users =
4272       silc_buffer_realloc(*channel_users,
4273                           (*channel_users ?
4274                            silc_buffer_truelen((*channel_users)) + len : len));
4275     silc_buffer_pull_tail(*channel_users,
4276                           ((*channel_users)->end -
4277                            (*channel_users)->data));
4278
4279     silc_buffer_put(*channel_users, tmp->data, silc_buffer_len(tmp));
4280     silc_buffer_pull(*channel_users, len);
4281     silc_buffer_free(tmp);
4282
4283     /* CUMODE notify for mode change on the channel */
4284     SILC_PUT32_MSB(chl->mode, mode);
4285     if (chl->mode & SILC_CHANNEL_UMODE_CHANFO && channel->founder_key)
4286       fkey = silc_public_key_payload_encode(channel->founder_key);
4287     tmp = silc_server_announce_encode_notify(SILC_NOTIFY_TYPE_CUMODE_CHANGE,
4288                                              4, csidp->data,
4289                                              silc_buffer_len(csidp),
4290                                              mode, sizeof(mode),
4291                                              clidp->data,
4292                                              silc_buffer_len(clidp),
4293                                              fkey ? fkey->data : NULL,
4294                                              fkey ? silc_buffer_len(fkey) : 0);
4295     len = silc_buffer_len(tmp);
4296     *channel_users_modes =
4297       silc_buffer_realloc(*channel_users_modes,
4298                           (*channel_users_modes ?
4299                            silc_buffer_truelen((*channel_users_modes)) +
4300                            len : len));
4301     silc_buffer_pull_tail(*channel_users_modes,
4302                           ((*channel_users_modes)->end -
4303                            (*channel_users_modes)->data));
4304
4305     silc_buffer_put(*channel_users_modes, tmp->data, silc_buffer_len(tmp));
4306     silc_buffer_pull(*channel_users_modes, len);
4307     silc_buffer_free(tmp);
4308     silc_buffer_free(fkey);
4309     fkey = NULL;
4310     silc_buffer_free(clidp);
4311   }
4312   silc_hash_table_list_reset(&htl);
4313   silc_buffer_free(chidp);
4314   silc_buffer_free(csidp);
4315 }
4316
4317 /* Returns assembled packets for all channels and users on those channels
4318    from the given ID List. The packets are in the form dictated by the
4319    New Channel and New Channel User payloads. */
4320
4321 void silc_server_announce_get_channels(SilcServer server,
4322                                        SilcIDList id_list,
4323                                        SilcBuffer *channels,
4324                                        SilcBuffer **channel_modes,
4325                                        SilcBuffer *channel_users,
4326                                        SilcBuffer **channel_users_modes,
4327                                        SilcUInt32 *channel_users_modes_c,
4328                                        SilcBuffer **channel_topics,
4329                                        SilcBuffer **channel_invites,
4330                                        SilcBuffer **channel_bans,
4331                                        SilcChannelID ***channel_ids,
4332                                        unsigned long creation_time)
4333 {
4334   SilcList list;
4335   SilcIDCacheEntry id_cache;
4336   SilcChannelEntry channel;
4337   unsigned char cid[32];
4338   SilcUInt32 id_len;
4339   SilcUInt16 name_len;
4340   int len;
4341   int i = *channel_users_modes_c;
4342   SilcBool announce;
4343
4344   SILC_LOG_DEBUG(("Start"));
4345
4346   /* Go through all channels in the list */
4347   if (silc_idcache_get_all(id_list->channels, &list)) {
4348     silc_list_start(list);
4349     while ((id_cache = silc_list_get(list))) {
4350       channel = (SilcChannelEntry)id_cache->context;
4351
4352       if (creation_time && channel->created < creation_time)
4353         announce = FALSE;
4354       else
4355         announce = TRUE;
4356
4357       SILC_LOG_DEBUG(("Announce Channel ID %s",
4358                       silc_id_render(channel->id, SILC_ID_CHANNEL)));
4359
4360       silc_id_id2str(channel->id, SILC_ID_CHANNEL, cid, sizeof(cid), &id_len);
4361       name_len = strlen(channel->channel_name);
4362
4363       if (announce) {
4364         len = 4 + name_len + id_len + 4;
4365         *channels =
4366           silc_buffer_realloc(*channels,
4367                               (*channels ?
4368                                silc_buffer_truelen((*channels)) +
4369                                len : len));
4370         silc_buffer_pull_tail(*channels,
4371                               ((*channels)->end - (*channels)->data));
4372         silc_buffer_format(*channels,
4373                            SILC_STR_UI_SHORT(name_len),
4374                            SILC_STR_UI_XNSTRING(channel->channel_name,
4375                                                 name_len),
4376                            SILC_STR_UI_SHORT(id_len),
4377                              SILC_STR_UI_XNSTRING(cid, id_len),
4378                            SILC_STR_UI_INT(channel->mode),
4379                            SILC_STR_END);
4380         silc_buffer_pull(*channels, len);
4381       }
4382
4383       if (creation_time && channel->updated < creation_time)
4384         announce = FALSE;
4385       else
4386         announce = TRUE;
4387
4388       if (announce) {
4389         /* Channel user modes */
4390         *channel_users_modes = silc_realloc(*channel_users_modes,
4391                                             sizeof(**channel_users_modes) *
4392                                             (i + 1));
4393         (*channel_users_modes)[i] = NULL;
4394         *channel_modes = silc_realloc(*channel_modes,
4395                                       sizeof(**channel_modes) * (i + 1));
4396         (*channel_modes)[i] = NULL;
4397         *channel_ids = silc_realloc(*channel_ids,
4398                                       sizeof(**channel_ids) * (i + 1));
4399         (*channel_ids)[i] = NULL;
4400         silc_server_announce_get_channel_users(server, channel,
4401                                                &(*channel_modes)[i],
4402                                                channel_users,
4403                                                &(*channel_users_modes)[i]);
4404         (*channel_ids)[i] = channel->id;
4405
4406         /* Channel's topic */
4407         *channel_topics = silc_realloc(*channel_topics,
4408                                        sizeof(**channel_topics) * (i + 1));
4409         (*channel_topics)[i] = NULL;
4410         silc_server_announce_get_channel_topic(server, channel,
4411                                                &(*channel_topics)[i]);
4412
4413         /* Channel's invite and ban list */
4414         *channel_invites = silc_realloc(*channel_invites,
4415                                         sizeof(**channel_invites) * (i + 1));
4416         (*channel_invites)[i] = NULL;
4417         *channel_bans = silc_realloc(*channel_bans,
4418                                      sizeof(**channel_bans) * (i + 1));
4419         (*channel_bans)[i] = NULL;
4420         silc_server_announce_get_inviteban(server, channel,
4421                                            &(*channel_invites)[i],
4422                                            &(*channel_bans)[i]);
4423
4424         (*channel_users_modes_c)++;
4425
4426         i++;
4427       }
4428     }
4429   }
4430 }
4431
4432 /* This function is used to announce our existing channels to our router
4433    when we've connected to it. This also announces the users on the
4434    channels to the router. If the `creation_time' is non-zero only the
4435    channels that was created after the `creation_time' are announced.
4436    Note that the channel users are still announced even if the `creation_time'
4437    was provided. */
4438
4439 void silc_server_announce_channels(SilcServer server,
4440                                    unsigned long creation_time,
4441                                    SilcPacketStream remote)
4442 {
4443   SilcBuffer channels = NULL, *channel_modes = NULL, channel_users = NULL;
4444   SilcBuffer *channel_users_modes = NULL;
4445   SilcBuffer *channel_topics = NULL;
4446   SilcBuffer *channel_invites = NULL;
4447   SilcBuffer *channel_bans = NULL;
4448   SilcUInt32 channel_users_modes_c = 0;
4449   SilcChannelID **channel_ids = NULL;
4450
4451   SILC_LOG_DEBUG(("Announcing channels and channel users"));
4452
4453   /* Get channels and channel users in local list */
4454   silc_server_announce_get_channels(server, server->local_list,
4455                                     &channels, &channel_modes,
4456                                     &channel_users,
4457                                     &channel_users_modes,
4458                                     &channel_users_modes_c,
4459                                     &channel_topics,
4460                                     &channel_invites,
4461                                     &channel_bans,
4462                                     &channel_ids, creation_time);
4463
4464   /* Get channels and channel users in global list */
4465   if (server->server_type != SILC_SERVER)
4466     silc_server_announce_get_channels(server, server->global_list,
4467                                       &channels, &channel_modes,
4468                                       &channel_users,
4469                                       &channel_users_modes,
4470                                       &channel_users_modes_c,
4471                                       &channel_topics,
4472                                       &channel_invites,
4473                                       &channel_bans,
4474                                       &channel_ids, creation_time);
4475
4476   if (channels) {
4477     silc_buffer_push(channels, channels->data - channels->head);
4478     SILC_LOG_HEXDUMP(("channels"), channels->data, silc_buffer_len(channels));
4479
4480     /* Send the packet */
4481     silc_server_packet_send(server, remote,
4482                             SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
4483                             channels->data, silc_buffer_len(channels));
4484
4485     silc_buffer_free(channels);
4486   }
4487
4488   if (channel_users) {
4489     silc_buffer_push(channel_users, channel_users->data - channel_users->head);
4490     SILC_LOG_HEXDUMP(("channel users"), channel_users->data,
4491                      silc_buffer_len(channel_users));
4492
4493     /* Send the packet */
4494     silc_server_packet_send(server, remote,
4495                             SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4496                             channel_users->data, silc_buffer_len(channel_users));
4497
4498     silc_buffer_free(channel_users);
4499   }
4500
4501   if (channel_modes) {
4502     int i;
4503
4504     for (i = 0; i < channel_users_modes_c; i++) {
4505       if (!channel_modes[i])
4506         continue;
4507       silc_buffer_push(channel_modes[i],
4508                        channel_modes[i]->data -
4509                        channel_modes[i]->head);
4510       SILC_LOG_HEXDUMP(("channel modes"), channel_modes[i]->data,
4511                        silc_buffer_len(channel_modes[i]));
4512       silc_server_packet_send_dest(server, remote,
4513                                    SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4514                                    channel_ids[i], SILC_ID_CHANNEL,
4515                                    channel_modes[i]->data,
4516                                    silc_buffer_len(channel_modes[i]));
4517       silc_buffer_free(channel_modes[i]);
4518     }
4519     silc_free(channel_modes);
4520   }
4521
4522   if (channel_users_modes) {
4523     int i;
4524
4525     for (i = 0; i < channel_users_modes_c; i++) {
4526       if (!channel_users_modes[i])
4527         continue;
4528       silc_buffer_push(channel_users_modes[i],
4529                        channel_users_modes[i]->data -
4530                        channel_users_modes[i]->head);
4531       SILC_LOG_HEXDUMP(("channel users modes"), channel_users_modes[i]->data,
4532                        silc_buffer_len(channel_users_modes[i]));
4533       silc_server_packet_send_dest(server, remote,
4534                                    SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4535                                    channel_ids[i], SILC_ID_CHANNEL,
4536                                    channel_users_modes[i]->data,
4537                                    silc_buffer_len(channel_users_modes[i]));
4538       silc_buffer_free(channel_users_modes[i]);
4539     }
4540     silc_free(channel_users_modes);
4541   }
4542
4543   if (channel_topics) {
4544     int i;
4545
4546     for (i = 0; i < channel_users_modes_c; i++) {
4547       if (!channel_topics[i])
4548         continue;
4549
4550       silc_buffer_push(channel_topics[i],
4551                        channel_topics[i]->data -
4552                        channel_topics[i]->head);
4553       SILC_LOG_HEXDUMP(("channel topic"), channel_topics[i]->data,
4554                        silc_buffer_len(channel_topics[i]));
4555       silc_server_packet_send_dest(server, remote,
4556                                    SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4557                                    channel_ids[i], SILC_ID_CHANNEL,
4558                                    channel_topics[i]->data,
4559                                    silc_buffer_len(channel_topics[i]));
4560       silc_buffer_free(channel_topics[i]);
4561     }
4562     silc_free(channel_topics);
4563   }
4564
4565   if (channel_invites) {
4566     int i;
4567
4568     for (i = 0; i < channel_users_modes_c; i++) {
4569       if (!channel_invites[i])
4570         continue;
4571
4572       silc_buffer_push(channel_invites[i],
4573                        channel_invites[i]->data -
4574                        channel_invites[i]->head);
4575       SILC_LOG_HEXDUMP(("channel invite list"), channel_invites[i]->data,
4576                        silc_buffer_len(channel_invites[i]));
4577       silc_server_packet_send_dest(server, remote,
4578                                    SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4579                                    channel_ids[i], SILC_ID_CHANNEL,
4580                                    channel_invites[i]->data,
4581                                    silc_buffer_len(channel_invites[i]));
4582       silc_buffer_free(channel_invites[i]);
4583     }
4584     silc_free(channel_invites);
4585   }
4586
4587   if (channel_bans) {
4588     int i;
4589
4590     for (i = 0; i < channel_users_modes_c; i++) {
4591       if (!channel_bans[i])
4592         continue;
4593
4594       silc_buffer_push(channel_bans[i],
4595                        channel_bans[i]->data -
4596                        channel_bans[i]->head);
4597       SILC_LOG_HEXDUMP(("channel ban list"), channel_bans[i]->data,
4598                        silc_buffer_len(channel_bans[i]));
4599       silc_server_packet_send_dest(server, remote,
4600                                    SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
4601                                    channel_ids[i], SILC_ID_CHANNEL,
4602                                    channel_bans[i]->data,
4603                                    silc_buffer_len(channel_bans[i]));
4604       silc_buffer_free(channel_bans[i]);
4605     }
4606     silc_free(channel_bans);
4607   }
4608
4609   silc_free(channel_ids);
4610 }
4611
4612 /* Announces WATCH list. */
4613
4614 void silc_server_announce_watches(SilcServer server,
4615                                   SilcPacketStream remote)
4616 {
4617   SilcHashTableList htl;
4618   SilcBuffer buffer, idp, args, pkp;
4619   SilcClientEntry client;
4620   void *key;
4621
4622   SILC_LOG_DEBUG(("Announcing watch list"));
4623
4624   /* XXX because way we save the nicks (hash) we cannot announce them. */
4625
4626   /* XXX we should send all public keys in one command if client is
4627      watching more than one key */
4628   silc_hash_table_list(server->watcher_list_pk, &htl);
4629   while (silc_hash_table_get(&htl, &key, (void *)&client)) {
4630     if (!client || !client->id)
4631       continue;
4632
4633     server->stat.commands_sent++;
4634
4635     idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
4636     args = silc_buffer_alloc_size(2);
4637     silc_buffer_format(args,
4638                        SILC_STR_UI_SHORT(1),
4639                        SILC_STR_END);
4640     pkp = silc_public_key_payload_encode(key);
4641     args = silc_argument_payload_encode_one(args, pkp->data,
4642                                             silc_buffer_len(pkp), 0x00);
4643     buffer = silc_command_payload_encode_va(SILC_COMMAND_WATCH,
4644                                             ++server->cmd_ident, 2,
4645                                             1, idp->data, silc_buffer_len(idp),
4646                                             4, args->data,
4647                                             silc_buffer_len(args));
4648
4649     /* Send command */
4650     silc_server_packet_send(server, remote, SILC_PACKET_COMMAND, 0,
4651                             buffer->data, silc_buffer_len(buffer));
4652
4653     silc_buffer_free(pkp);
4654     silc_buffer_free(args);
4655     silc_buffer_free(idp);
4656     silc_buffer_free(buffer);
4657   }
4658   silc_hash_table_list_reset(&htl);
4659 }
4660
4661 /* Assembles user list and users mode list from the `channel'. */
4662
4663 SilcBool silc_server_get_users_on_channel(SilcServer server,
4664                                           SilcChannelEntry channel,
4665                                           SilcBuffer *user_list,
4666                                           SilcBuffer *mode_list,
4667                                           SilcUInt32 *user_count)
4668 {
4669   SilcChannelClientEntry chl;
4670   SilcHashTableList htl;
4671   SilcBuffer client_id_list;
4672   SilcBuffer client_mode_list;
4673   SilcBuffer idp;
4674   SilcUInt32 list_count = 0, len = 0;
4675
4676   if (!silc_hash_table_count(channel->user_list))
4677     return FALSE;
4678
4679   silc_hash_table_list(channel->user_list, &htl);
4680   while (silc_hash_table_get(&htl, NULL, (void *)&chl))
4681     len += (silc_id_get_len(chl->client->id, SILC_ID_CLIENT) + 4);
4682   silc_hash_table_list_reset(&htl);
4683
4684   client_id_list = silc_buffer_alloc(len);
4685   client_mode_list =
4686     silc_buffer_alloc(4 * silc_hash_table_count(channel->user_list));
4687   silc_buffer_pull_tail(client_id_list, silc_buffer_truelen(client_id_list));
4688   silc_buffer_pull_tail(client_mode_list,
4689                         silc_buffer_truelen(client_mode_list));
4690
4691   silc_hash_table_list(channel->user_list, &htl);
4692   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4693     /* Client ID */
4694     idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
4695     silc_buffer_put(client_id_list, idp->data, silc_buffer_len(idp));
4696     silc_buffer_pull(client_id_list, silc_buffer_len(idp));
4697     silc_buffer_free(idp);
4698
4699     /* Client's mode on channel */
4700     SILC_PUT32_MSB(chl->mode, client_mode_list->data);
4701     silc_buffer_pull(client_mode_list, 4);
4702
4703     list_count++;
4704   }
4705   silc_hash_table_list_reset(&htl);
4706   silc_buffer_push(client_id_list,
4707                    client_id_list->data - client_id_list->head);
4708   silc_buffer_push(client_mode_list,
4709                    client_mode_list->data - client_mode_list->head);
4710
4711   *user_list = client_id_list;
4712   *mode_list = client_mode_list;
4713   *user_count = list_count;
4714   return TRUE;
4715 }
4716
4717 /* Saves users and their modes to the `channel'. */
4718
4719 void silc_server_save_users_on_channel(SilcServer server,
4720                                        SilcPacketStream sock,
4721                                        SilcChannelEntry channel,
4722                                        SilcClientID *noadd,
4723                                        SilcBuffer user_list,
4724                                        SilcBuffer mode_list,
4725                                        SilcUInt32 user_count)
4726 {
4727   int i;
4728   SilcUInt16 idp_len;
4729   SilcUInt32 mode;
4730   SilcID id;
4731   SilcClientEntry client;
4732   SilcIDCacheEntry cache;
4733   SilcChannelClientEntry chl;
4734
4735   SILC_LOG_DEBUG(("Saving %d users on %s channel", user_count,
4736                   channel->channel_name));
4737
4738   for (i = 0; i < user_count; i++) {
4739     /* Client ID */
4740     SILC_GET16_MSB(idp_len, user_list->data + 2);
4741     idp_len += 4;
4742     if (!silc_id_payload_parse_id(user_list->data, idp_len, &id))
4743       continue;
4744     silc_buffer_pull(user_list, idp_len);
4745
4746     /* Mode */
4747     SILC_GET32_MSB(mode, mode_list->data);
4748     silc_buffer_pull(mode_list, 4);
4749
4750     if (noadd && SILC_ID_CLIENT_COMPARE(&id.u.client_id, noadd))
4751       continue;
4752
4753     cache = NULL;
4754
4755     /* Check if we have this client cached already. */
4756     client = silc_idlist_find_client_by_id(server->local_list,
4757                                            &id.u.client_id,
4758                                            server->server_type, &cache);
4759     if (!client)
4760       client = silc_idlist_find_client_by_id(server->global_list,
4761                                              &id.u.client_id,
4762                                              server->server_type, &cache);
4763     if (!client) {
4764       /* If router did not find such Client ID in its lists then this must
4765          be bogus client or some router in the net is buggy. */
4766       if (server->server_type != SILC_SERVER)
4767         continue;
4768
4769       /* We don't have that client anywhere, add it. The client is added
4770          to global list since server didn't have it in the lists so it must be
4771          global. */
4772       client = silc_idlist_add_client(server->global_list, NULL, NULL, NULL,
4773                                       silc_id_dup(&id.u.client_id,
4774                                                   SILC_ID_CLIENT),
4775                                       silc_packet_get_context(sock),
4776                                       NULL);
4777       if (!client) {
4778         SILC_LOG_ERROR(("Could not add new client to the ID Cache"));
4779         continue;
4780       }
4781
4782       client->data.status |= SILC_IDLIST_STATUS_REGISTERED;
4783     }
4784
4785     if (!(client->data.status & SILC_IDLIST_STATUS_REGISTERED)) {
4786       SILC_LOG_ERROR(("Attempting to add unregistered client to channel ",
4787                       "%s", channel->channel_name));
4788       continue;
4789     }
4790
4791     if (!silc_server_client_on_channel(client, channel, &chl)) {
4792       /* Client was not on the channel, add it. */
4793       chl = silc_calloc(1, sizeof(*chl));
4794       chl->client = client;
4795       chl->mode = mode;
4796       chl->channel = channel;
4797       silc_hash_table_add(channel->user_list, chl->client, chl);
4798       silc_hash_table_add(client->channels, chl->channel, chl);
4799       channel->user_count++;
4800     } else {
4801       /* Update mode */
4802       chl->mode = mode;
4803     }
4804   }
4805 }
4806
4807 /* Saves channels and channels user modes to the `client'.  Removes
4808    the client from those channels that are not sent in the list but
4809    it has joined. */
4810
4811 void silc_server_save_user_channels(SilcServer server,
4812                                     SilcPacketStream sock,
4813                                     SilcClientEntry client,
4814                                     SilcBuffer channels,
4815                                     SilcBuffer channels_user_modes)
4816 {
4817   SilcDList ch;
4818   SilcUInt32 *chumodes;
4819   SilcChannelPayload entry;
4820   SilcChannelEntry channel;
4821   SilcChannelID channel_id;
4822   SilcChannelClientEntry chl;
4823   SilcHashTable ht = NULL;
4824   SilcHashTableList htl;
4825   char *name;
4826   int i = 0;
4827
4828   if (!channels || !channels_user_modes ||
4829       !(client->data.status & SILC_IDLIST_STATUS_REGISTERED))
4830     goto out;
4831
4832   ch = silc_channel_payload_parse_list(channels->data,
4833                                        silc_buffer_len(channels));
4834   if (ch && silc_get_mode_list(channels_user_modes, silc_dlist_count(ch),
4835                                &chumodes)) {
4836     ht = silc_hash_table_alloc(0, silc_hash_ptr, NULL, NULL,
4837                                NULL, NULL, NULL, TRUE);
4838     silc_dlist_start(ch);
4839     while ((entry = silc_dlist_get(ch)) != SILC_LIST_END) {
4840       /* Check if we have this channel, and add it if we don't have it.
4841          Also add the client on the channel unless it is there already. */
4842       if (!silc_channel_get_id_parse(entry, &channel_id))
4843         continue;
4844       channel = silc_idlist_find_channel_by_id(server->local_list,
4845                                                &channel_id, NULL);
4846       if (!channel)
4847         channel = silc_idlist_find_channel_by_id(server->global_list,
4848                                                  &channel_id, NULL);
4849       if (!channel) {
4850         if (server->server_type != SILC_SERVER) {
4851           i++;
4852           continue;
4853         }
4854
4855         /* We don't have that channel anywhere, add it. */
4856         name = silc_channel_get_name(entry, NULL);
4857         channel = silc_idlist_add_channel(server->global_list, strdup(name), 0,
4858                                           silc_id_dup(&channel_id,
4859                                                       SILC_ID_CHANNEL),
4860                                           server->router, NULL, NULL, 0);
4861         if (!channel) {
4862           i++;
4863           continue;
4864         }
4865       }
4866
4867       channel->mode = silc_channel_get_mode(entry);
4868
4869       /* Add the client on the channel */
4870       if (!silc_server_client_on_channel(client, channel, &chl)) {
4871         chl = silc_calloc(1, sizeof(*chl));
4872         chl->client = client;
4873         chl->mode = chumodes[i++];
4874         chl->channel = channel;
4875         silc_hash_table_add(channel->user_list, chl->client, chl);
4876         silc_hash_table_add(client->channels, chl->channel, chl);
4877         channel->user_count++;
4878       } else {
4879         /* Update mode */
4880         chl->mode = chumodes[i++];
4881       }
4882
4883       silc_hash_table_add(ht, channel, channel);
4884     }
4885     silc_channel_payload_list_free(ch);
4886     silc_free(chumodes);
4887   }
4888
4889  out:
4890   /* Go through the list again and remove client from channels that
4891      are no part of the list. */
4892   if (ht) {
4893     silc_hash_table_list(client->channels, &htl);
4894     while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4895       if (!silc_hash_table_find(ht, chl->channel, NULL, NULL)) {
4896         silc_hash_table_del(chl->channel->user_list, chl->client);
4897         silc_hash_table_del(chl->client->channels, chl->channel);
4898         silc_free(chl);
4899       }
4900     }
4901     silc_hash_table_list_reset(&htl);
4902     silc_hash_table_free(ht);
4903   } else {
4904     silc_hash_table_list(client->channels, &htl);
4905     while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
4906       silc_hash_table_del(chl->channel->user_list, chl->client);
4907       silc_hash_table_del(chl->client->channels, chl->channel);
4908       silc_free(chl);
4909     }
4910     silc_hash_table_list_reset(&htl);
4911   }
4912 }
4913
4914 /* Lookups route to the client indicated by the `id_data'. The connection
4915    object and internal data object is returned. Returns NULL if route
4916    could not be found to the client. If the `client_id' is specified then
4917    it is used and the `id_data' is ignored. */
4918
4919 SilcPacketStream
4920 silc_server_get_client_route(SilcServer server,
4921                              unsigned char *id_data,
4922                              SilcUInt32 id_len,
4923                              SilcClientID *client_id,
4924                              SilcIDListData *idata,
4925                              SilcClientEntry *client_entry)
4926 {
4927   SilcClientID *id, clid;
4928   SilcClientEntry client;
4929
4930   SILC_LOG_DEBUG(("Start"));
4931
4932   if (client_entry)
4933     *client_entry = NULL;
4934
4935   /* Decode destination Client ID */
4936   if (!client_id) {
4937     if (!silc_id_str2id(id_data, id_len, SILC_ID_CLIENT, &clid, sizeof(clid)))
4938       return NULL;
4939     id = silc_id_dup(&clid, SILC_ID_CLIENT);
4940   } else {
4941     id = silc_id_dup(client_id, SILC_ID_CLIENT);
4942   }
4943
4944   /* If the destination belongs to our server we don't have to route
4945      the packet anywhere but to send it to the local destination. */
4946   client = silc_idlist_find_client_by_id(server->local_list, id, TRUE, NULL);
4947   if (client) {
4948     silc_free(id);
4949
4950     /* If we are router and the client has router then the client is in
4951        our cell but not directly connected to us. */
4952     if (server->server_type == SILC_ROUTER && client->router) {
4953       /* We are of course in this case the client's router thus the route
4954          to the client is the server who owns the client. So, we will send
4955          the packet to that server. */
4956       if (idata)
4957         *idata = (SilcIDListData)client->router;
4958       return client->router->connection;
4959     }
4960
4961     /* Seems that client really is directly connected to us */
4962     if (idata)
4963       *idata = (SilcIDListData)client;
4964     if (client_entry)
4965       *client_entry = client;
4966     return client->connection;
4967   }
4968
4969   /* Destination belongs to someone not in this server. If we are normal
4970      server our action is to send the packet to our router. */
4971   if (server->server_type != SILC_ROUTER && !server->standalone) {
4972     silc_free(id);
4973     if (idata)
4974       *idata = (SilcIDListData)server->router;
4975     return SILC_PRIMARY_ROUTE(server);
4976   }
4977
4978   /* We are router and we will perform route lookup for the destination
4979      and send the packet to fastest route. */
4980   if (server->server_type == SILC_ROUTER && !server->standalone) {
4981     /* Check first that the ID is valid */
4982     client = silc_idlist_find_client_by_id(server->global_list, id,
4983                                            TRUE, NULL);
4984     if (client) {
4985       SilcPacketStream dst_sock;
4986
4987       dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
4988
4989       silc_free(id);
4990       if (idata && dst_sock)
4991         *idata = silc_packet_get_context(dst_sock);
4992       return dst_sock;
4993     }
4994   }
4995
4996   silc_free(id);
4997   return NULL;
4998 }
4999
5000 /* Encodes and returns channel list of channels the `client' has joined.
5001    Secret channels are not put to the list. */
5002
5003 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
5004                                                SilcClientEntry client,
5005                                                SilcBool get_private,
5006                                                SilcBool get_secret,
5007                                                SilcBuffer *user_mode_list)
5008 {
5009   SilcBuffer buffer = NULL;
5010   SilcChannelEntry channel;
5011   SilcChannelClientEntry chl;
5012   SilcHashTableList htl;
5013   unsigned char cid[32];
5014   SilcUInt32 id_len;
5015   SilcUInt16 name_len;
5016   int len;
5017
5018   if (user_mode_list)
5019     *user_mode_list = NULL;
5020
5021   silc_hash_table_list(client->channels, &htl);
5022   while (silc_hash_table_get(&htl, NULL, (void *)&chl)) {
5023     channel = chl->channel;
5024
5025     if (channel->mode & SILC_CHANNEL_MODE_SECRET && !get_secret)
5026       continue;
5027     if (channel->mode & SILC_CHANNEL_MODE_PRIVATE && !get_private)
5028       continue;
5029
5030     silc_id_id2str(channel->id, SILC_ID_CHANNEL, cid, sizeof(cid), &id_len);
5031     name_len = strlen(channel->channel_name);
5032
5033     len = 4 + name_len + id_len + 4;
5034     buffer = silc_buffer_realloc(buffer,
5035                                  (buffer ?
5036                                   silc_buffer_truelen(buffer) + len : len));
5037     silc_buffer_pull_tail(buffer, (buffer->end - buffer->data));
5038     silc_buffer_format(buffer,
5039                        SILC_STR_UI_SHORT(name_len),
5040                        SILC_STR_DATA(channel->channel_name, name_len),
5041                        SILC_STR_UI_SHORT(id_len),
5042                        SILC_STR_DATA(cid, id_len),
5043                        SILC_STR_UI_INT(chl->channel->mode),
5044                        SILC_STR_END);
5045     silc_buffer_pull(buffer, len);
5046
5047     if (user_mode_list) {
5048       *user_mode_list =
5049         silc_buffer_realloc(*user_mode_list,
5050                             (*user_mode_list ?
5051                              silc_buffer_truelen((*user_mode_list)) + 4 : 4));
5052       silc_buffer_pull_tail(*user_mode_list, ((*user_mode_list)->end -
5053                                               (*user_mode_list)->data));
5054       SILC_PUT32_MSB(chl->mode, (*user_mode_list)->data);
5055       silc_buffer_pull(*user_mode_list, 4);
5056     }
5057   }
5058   silc_hash_table_list_reset(&htl);
5059
5060   if (buffer)
5061     silc_buffer_push(buffer, buffer->data - buffer->head);
5062   if (user_mode_list && *user_mode_list)
5063     silc_buffer_push(*user_mode_list, ((*user_mode_list)->data -
5064                                        (*user_mode_list)->head));
5065
5066   return buffer;
5067 }
5068
5069 /* Task callback used to retrieve network statistical information from
5070    router server once in a while. */
5071
5072 SILC_TASK_CALLBACK(silc_server_get_stats)
5073 {
5074   SilcServer server = (SilcServer)context;
5075   SilcBuffer idp, packet;
5076
5077   if (!server->standalone) {
5078     SILC_LOG_DEBUG(("Retrieving stats from router"));
5079     server->stat.commands_sent++;
5080     idp = silc_id_payload_encode(server->router->id, SILC_ID_SERVER);
5081     if (idp) {
5082       packet = silc_command_payload_encode_va(SILC_COMMAND_STATS,
5083                                               ++server->cmd_ident, 1,
5084                                               1, idp->data,
5085                                               silc_buffer_len(idp));
5086       silc_server_packet_send(server, SILC_PRIMARY_ROUTE(server),
5087                               SILC_PACKET_COMMAND, 0, packet->data,
5088                               silc_buffer_len(packet));
5089       silc_buffer_free(packet);
5090       silc_buffer_free(idp);
5091     }
5092   }
5093
5094   silc_schedule_task_add_timeout(server->schedule, silc_server_get_stats,
5095                                  server, 120, 0);
5096 }