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