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