updates.
[silc.git] / apps / silcd / server.c
1 /*
2
3   server.c
4
5   Author: Pekka Riikonen <priikone@poseidon.pspt.fi>
6
7   Copyright (C) 1997 - 2001 Pekka Riikonen
8
9   This program is free software; you can redistribute it and/or modify
10   it under the terms of the GNU General Public License as published by
11   the Free Software Foundation; either version 2 of the License, or
12   (at your option) any later version.
13   
14   This program is distributed in the hope that it will be useful,
15   but WITHOUT ANY WARRANTY; without even the implied warranty of
16   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17   GNU General Public License for more details.
18
19 */
20 /*
21  * This is the actual SILC server than handles everything relating to
22  * servicing the SILC connections. This is also a SILC router as a router 
23  * is also normal server.
24  */
25 /* $Id$ */
26
27 #include "serverincludes.h"
28 #include "server_internal.h"
29
30 /* Static prototypes */
31 SILC_TASK_CALLBACK(silc_server_connect_router);
32 SILC_TASK_CALLBACK(silc_server_connect_to_router);
33 SILC_TASK_CALLBACK(silc_server_connect_to_router_second);
34 SILC_TASK_CALLBACK(silc_server_connect_to_router_final);
35 SILC_TASK_CALLBACK(silc_server_accept_new_connection);
36 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second);
37 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final);
38 SILC_TASK_CALLBACK(silc_server_packet_process);
39 SILC_TASK_CALLBACK(silc_server_packet_parse_real);
40 SILC_TASK_CALLBACK(silc_server_timeout_remote);
41
42 /* Allocates a new SILC server object. This has to be done before the server
43    can be used. After allocation one must call silc_server_init to initialize
44    the server. The new allocated server object is returned to the new_server
45    argument. */
46
47 int silc_server_alloc(SilcServer *new_server)
48 {
49   SilcServer server;
50
51   SILC_LOG_DEBUG(("Allocating new server object"));
52
53   server = silc_calloc(1, sizeof(*server));
54   server->server_type = SILC_SERVER;
55   server->standalone = TRUE;
56   server->local_list = silc_calloc(1, sizeof(*server->local_list));
57   server->global_list = silc_calloc(1, sizeof(*server->global_list));
58   server->pending_commands = silc_dlist_init();
59 #ifdef SILC_SIM
60   server->sim = silc_dlist_init();
61 #endif
62
63   *new_server = server;
64
65   return TRUE;
66 }
67
68 /* Free's the SILC server object. This is called at the very end before
69    the program ends. */
70
71 void silc_server_free(SilcServer server)
72 {
73   if (server) {
74 #ifdef SILC_SIM
75     SilcSimContext *sim;
76 #endif
77
78     if (server->local_list)
79       silc_free(server->local_list);
80     if (server->global_list)
81       silc_free(server->global_list);
82     if (server->rng)
83       silc_rng_free(server->rng);
84
85 #ifdef SILC_SIM
86     while ((sim = silc_dlist_get(server->sim)) != SILC_LIST_END) {
87       silc_dlist_del(server->sim, sim);
88       silc_sim_free(sim);
89     }
90     silc_dlist_uninit(server->sim);
91 #endif
92
93     if (server->params)
94       silc_free(server->params);
95
96     if (server->pending_commands)
97       silc_dlist_uninit(server->pending_commands);
98
99     silc_free(server);
100   }
101 }
102
103 /* Initializes the entire SILC server. This is called always before running
104    the server. This is called only once at the initialization of the program.
105    This binds the server to its listenning port. After this function returns 
106    one should call silc_server_run to start the server. This returns TRUE 
107    when everything is ok to run the server. Configuration file must be
108    read and parsed before calling this. */
109
110 int silc_server_init(SilcServer server)
111 {
112   int *sock = NULL, sock_count = 0, i;
113   SilcServerID *id;
114   SilcServerEntry id_entry;
115
116   SILC_LOG_DEBUG(("Initializing server"));
117   assert(server);
118   assert(server->config);
119
120   /* XXX After server is made as Silc Server Library this can be given
121      as argument, for now this is hard coded */
122   server->params = silc_calloc(1, sizeof(*server->params));
123   server->params->retry_count = SILC_SERVER_RETRY_COUNT;
124   server->params->retry_interval_min = SILC_SERVER_RETRY_INTERVAL_MIN;
125   server->params->retry_interval_max = SILC_SERVER_RETRY_INTERVAL_MAX;
126   server->params->retry_keep_trying = FALSE;
127   server->params->protocol_timeout = 60;
128   server->params->require_reverse_mapping = FALSE;
129
130   /* Set log files where log message should be saved. */
131   server->config->server = server;
132   silc_server_config_setlogfiles(server->config);
133  
134   /* Register all configured ciphers, PKCS and hash functions. */
135   silc_server_config_register_ciphers(server->config);
136   silc_server_config_register_pkcs(server->config);
137   silc_server_config_register_hashfuncs(server->config);
138
139   /* Initialize random number generator for the server. */
140   server->rng = silc_rng_alloc();
141   silc_rng_init(server->rng);
142   silc_rng_global_init(server->rng);
143
144   /* Initialize hash functions for server to use */
145   silc_hash_alloc("md5", &server->md5hash);
146   silc_hash_alloc("sha1", &server->sha1hash);
147
148   /* Initialize none cipher */
149   silc_cipher_alloc("none", &server->none_cipher);
150
151   /* XXXXX Generate RSA key pair */
152   {
153     unsigned char *public_key;
154     unsigned char *private_key;
155     unsigned int pk_len, prv_len;
156     struct stat st;
157
158     if (stat("pubkey.pub", &st) < 0 && stat("privkey.prv", &st) < 0) {
159
160       if (silc_pkcs_alloc("rsa", &server->pkcs) == FALSE) {
161         SILC_LOG_ERROR(("Could not create RSA key pair"));
162         goto err0;
163       }
164       
165       if (server->pkcs->pkcs->init(server->pkcs->context, 
166                                    1024, server->rng) == FALSE) {
167         SILC_LOG_ERROR(("Could not generate RSA key pair"));
168         goto err0;
169       }
170       
171       public_key = server->pkcs->pkcs->get_public_key(server->pkcs->context,
172                                                       &pk_len);
173       private_key = server->pkcs->pkcs->get_private_key(server->pkcs->context,
174                                                         &prv_len);
175       
176       SILC_LOG_HEXDUMP(("public key"), public_key, pk_len);
177       SILC_LOG_HEXDUMP(("private key"), private_key, prv_len);
178       
179       server->public_key = 
180         silc_pkcs_public_key_alloc("rsa", "UN=root, HN=dummy",
181                                    public_key, pk_len);
182       server->private_key = 
183         silc_pkcs_private_key_alloc("rsa", private_key, prv_len);
184       
185       /* XXX Save keys */
186       silc_pkcs_save_public_key("pubkey.pub", server->public_key,
187                                 SILC_PKCS_FILE_PEM);
188       silc_pkcs_save_private_key("privkey.prv", server->private_key, NULL,
189                                  SILC_PKCS_FILE_BIN);
190
191       memset(public_key, 0, pk_len);
192       memset(private_key, 0, prv_len);
193       silc_free(public_key);
194       silc_free(private_key);
195     } else {
196       silc_pkcs_load_public_key("pubkey.pub", &server->public_key,
197                                 SILC_PKCS_FILE_PEM);
198       silc_pkcs_load_private_key("privkey.prv", &server->private_key,
199                                  SILC_PKCS_FILE_BIN);
200     }
201   }
202
203   /* Create a listening server. Note that our server can listen on
204      multiple ports. All listeners are created here and now. */
205   /* XXX Still check this whether to use server_info or listen_port. */
206   sock_count = 0;
207   while(server->config->listen_port) {
208     int tmp;
209
210     tmp = silc_net_create_server(server->config->listen_port->port,
211                                  server->config->listen_port->host);
212     if (tmp < 0)
213       goto err0;
214
215     sock = silc_realloc(sock, (sizeof(int *) * (sock_count + 1)));
216     sock[sock_count] = tmp;
217     server->config->listen_port = server->config->listen_port->next;
218     sock_count++;
219   }
220
221   /* Initialize ID caches */
222   server->local_list->clients = silc_idcache_alloc(0);
223   server->local_list->servers = silc_idcache_alloc(0);
224   server->local_list->channels = silc_idcache_alloc(0);
225
226   /* These are allocated for normal server as well as these hold some 
227      global information that the server has fetched from its router. For 
228      router these are used as they are supposed to be used on router. */
229   server->global_list->clients = silc_idcache_alloc(0);
230   server->global_list->servers = silc_idcache_alloc(0);
231   server->global_list->channels = silc_idcache_alloc(0);
232
233   /* Allocate the entire socket list that is used in server. Eventually 
234      all connections will have entry in this table (it is a table of 
235      pointers to the actual object that is allocated individually 
236      later). */
237   server->sockets = silc_calloc(SILC_SERVER_MAX_CONNECTIONS,
238                                 sizeof(*server->sockets));
239
240   for (i = 0; i < sock_count; i++) {
241     SilcSocketConnection newsocket = NULL;
242
243     /* Set socket to non-blocking mode */
244     silc_net_set_socket_nonblock(sock[i]);
245     server->sock = sock[i];
246     
247     /* Create a Server ID for the server. */
248     silc_id_create_server_id(sock[i], server->rng, &id);
249     if (!id) {
250       goto err0;
251     }
252     
253     server->id = id;
254     server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
255     server->id_string_len = silc_id_get_len(SILC_ID_SERVER);
256     server->id_type = SILC_ID_SERVER;
257     server->server_name = server->config->server_info->server_name;
258
259     /* Add ourselves to the server list. We don't have a router yet 
260        beacuse we haven't established a route yet. It will be done later. 
261        For now, NULL is sent as router. This allocates new entry to
262        the ID list. */
263     id_entry = 
264       silc_idlist_add_server(server->local_list,
265                              server->config->server_info->server_name,
266                              server->server_type, server->id, NULL, NULL);
267     if (!id_entry) {
268       SILC_LOG_ERROR(("Could not add ourselves to cache"));
269       goto err0;
270     }
271     
272     /* Add ourselves also to the socket table. The entry allocated above
273        is sent as argument for fast referencing in the future. */
274     silc_socket_alloc(sock[i], SILC_SOCKET_TYPE_SERVER, id_entry, 
275                       &newsocket);
276     if (!newsocket)
277       goto err0;
278
279     server->sockets[sock[i]] = newsocket;
280
281     /* Put the allocated socket pointer also to the entry allocated above 
282        for fast back-referencing to the socket list. */
283     id_entry->connection = (void *)server->sockets[sock[i]];
284     server->id_entry = id_entry;
285   }
286
287   /* Register the task queues. In SILC we have by default three task queues. 
288      One task queue for non-timeout tasks which perform different kind of 
289      I/O on file descriptors, timeout task queue for timeout tasks, and,
290      generic non-timeout task queue whose tasks apply to all connections. */
291   silc_task_queue_alloc(&server->io_queue, TRUE);
292   if (!server->io_queue) {
293     goto err0;
294   }
295   silc_task_queue_alloc(&server->timeout_queue, TRUE);
296   if (!server->timeout_queue) {
297     goto err1;
298   }
299   silc_task_queue_alloc(&server->generic_queue, TRUE);
300   if (!server->generic_queue) {
301     goto err1;
302   }
303
304   /* Register protocols */
305   silc_server_protocols_register();
306
307   /* Initialize the scheduler */
308   silc_schedule_init(&server->io_queue, &server->timeout_queue, 
309                      &server->generic_queue, 
310                      SILC_SERVER_MAX_CONNECTIONS);
311   
312   /* Add the first task to the queue. This is task that is executed by
313      timeout. It expires as soon as the caller calls silc_server_run. This
314      task performs authentication protocol and key exchange with our
315      primary router. */
316   silc_task_register(server->timeout_queue, sock[0], 
317                      silc_server_connect_to_router,
318                      (void *)server, 0, 1,
319                      SILC_TASK_TIMEOUT,
320                      SILC_TASK_PRI_NORMAL);
321
322   /* Add listener task to the queue. This task receives new connections to the 
323      server. This task remains on the queue until the end of the program. */
324   silc_task_register(server->io_queue, sock[0],
325                      silc_server_accept_new_connection,
326                      (void *)server, 0, 0, 
327                      SILC_TASK_FD,
328                      SILC_TASK_PRI_NORMAL);
329   server->listenning = TRUE;
330
331   /* If server connections has been configured then we must be router as
332      normal server cannot have server connections, only router connections. */
333   if (server->config->servers)
334     server->server_type = SILC_ROUTER;
335
336   SILC_LOG_DEBUG(("Server initialized"));
337
338   /* We are done here, return succesfully */
339   return TRUE;
340
341   silc_task_queue_free(server->timeout_queue);
342  err1:
343   silc_task_queue_free(server->io_queue);
344  err0:
345   for (i = 0; i < sock_count; i++)
346     silc_net_close_server(sock[i]);
347
348   return FALSE;
349 }
350
351 /* Fork server to background and set gid+uid to non-root.
352    Silcd will not run as root, so trying to set either user or group to
353    root will cause silcd to exit. */
354
355 void silc_server_daemonise(SilcServer server)
356 {
357   /* Are we executing silcd as root or a regular user? */
358   if (geteuid()==0) {
359     
360     struct passwd *pw;
361     struct group *gr;
362     char *user, *group;
363     
364     if (!server->config->identity || !server->config->identity->user || 
365         !server->config->identity->group) {
366       fprintf(stderr, "Error:"
367        "\tSILC server must not be run as root.  For the security of your\n"
368        "\tsystem it is strongly suggested that you run SILC under dedicated\n"
369        "\tuser account.  Modify the [Identity] configuration section to run\n"
370        "\tthe server as non-root user.\n");
371       exit(1);
372     }
373     
374     /* Get the values given for user and group in configuration file */
375     user=server->config->identity->user;
376     group=server->config->identity->group;
377     
378     /* Check whether the user/group information is text */ 
379     if (atoi(user)!=0 || atoi(group)!=0) {
380       SILC_LOG_DEBUG(("Invalid user and/or group information"));
381       SILC_LOG_DEBUG(("User and/or group given as number"));
382       fprintf(stderr, "Invalid user and/or group information\n");
383       fprintf(stderr, "Please assign them as names, not numbers\n");
384       exit(1);
385     }
386     
387     /* Catch the nasty incident of string "0" returning 0 from atoi */
388     if (strcmp("0", user)==0 || strcmp("0", group)==0) {
389       SILC_LOG_DEBUG(("User and/or group configured to 0. Unacceptable"));
390       fprintf(stderr, "User and/or group configured to 0. Exiting\n");
391       exit(1);
392     }
393     
394     pw=getpwnam(user);
395     gr=getgrnam(group);
396
397     if (!pw) {
398       fprintf(stderr, "No such user %s found\n", user);
399       exit(1);
400     }
401
402     if (!gr) {
403       fprintf(stderr, "No such group %s found\n", group);
404       exit(1);
405     }
406     
407     /* Check whether user and/or group is set to root. If yes, exit
408        immediately. Otherwise, setgid and setuid server to user.group */
409     if (gr->gr_gid==0 || pw->pw_uid==0) {
410       fprintf(stderr, "Error:"
411        "\tSILC server must not be run as root.  For the security of your\n"
412        "\tsystem it is strongly suggested that you run SILC under dedicated\n"
413        "\tuser account.  Modify the [Identity] configuration section to run\n"
414        "\tthe server as non-root user.\n");
415       exit(1);
416     } else {
417       /* Fork server to background, making it a daemon */
418       if (fork()) {
419         SILC_LOG_DEBUG(("Server started as root. Dropping privileges."));
420         SILC_LOG_DEBUG(("Forking SILC server to background"));
421         exit(0);
422       } 
423       setsid();
424       
425       SILC_LOG_DEBUG(("Changing to group %s", group));
426       if(setgid(gr->gr_gid)==0) {
427         SILC_LOG_DEBUG(("Setgid to %s", group));
428       } else {
429         SILC_LOG_DEBUG(("Setgid to %s failed", group));
430         fprintf(stderr, "Tried to setgid %s but no such group. Exiting\n",
431                 group);
432         exit(1);
433       }
434       SILC_LOG_DEBUG(("Changing to user nobody"));
435       if(setuid(pw->pw_uid)==0) {
436         SILC_LOG_DEBUG(("Setuid to %s", user));
437       } else {
438         SILC_LOG_DEBUG(("Setuid to %s failed", user));
439         fprintf(stderr, "Tried to setuid %s but no such user. Exiting\n",
440                 user);
441         exit(1);
442       }
443     }
444   } else {
445     /* Fork server to background, making it a daemon */
446     if (fork()) {
447       SILC_LOG_DEBUG(("Server started as user")); 
448       SILC_LOG_DEBUG(("Forking SILC server to background"));
449       exit(0);
450     }
451     setsid();
452   }
453 }
454
455 /* Stops the SILC server. This function is used to shutdown the server. 
456    This is usually called after the scheduler has returned. After stopping 
457    the server one should call silc_server_free. */
458
459 void silc_server_stop(SilcServer server)
460 {
461   SILC_LOG_DEBUG(("Stopping server"));
462
463   /* Stop the scheduler, although it might be already stopped. This
464      doesn't hurt anyone. This removes all the tasks and task queues,
465      as well. */
466   silc_schedule_stop();
467   silc_schedule_uninit();
468
469   silc_server_protocols_unregister();
470
471   SILC_LOG_DEBUG(("Server stopped"));
472 }
473
474 /* The heart of the server. This runs the scheduler thus runs the server. 
475    When this returns the server has been stopped and the program will
476    be terminated. */
477
478 void silc_server_run(SilcServer server)
479 {
480   SILC_LOG_DEBUG(("Running server"));
481
482   /* Start the scheduler, the heart of the SILC server. When this returns
483      the program will be terminated. */
484   silc_schedule();
485 }
486
487 /* Timeout callback that will be called to retry connecting to remote
488    router. This is used by both normal and router server. This will wait
489    before retrying the connecting. The timeout is generated by exponential
490    backoff algorithm. */
491
492 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
493 {
494   SilcServerConnection sconn = (SilcServerConnection)context;
495   SilcServer server = sconn->server;
496
497   SILC_LOG_INFO(("Retrying connecting to a router"));
498
499   /* Calculate next timeout */
500   if (sconn->retry_count >= 1) {
501     sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
502     if (sconn->retry_timeout > SILC_SERVER_RETRY_INTERVAL_MAX)
503       sconn->retry_timeout = SILC_SERVER_RETRY_INTERVAL_MAX;
504   } else {
505     sconn->retry_timeout = server->params->retry_interval_min;
506   }
507   sconn->retry_count++;
508   sconn->retry_timeout = sconn->retry_timeout +
509     silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
510
511   /* If we've reached max retry count, give up. */
512   if (sconn->retry_count > server->params->retry_count && 
513       server->params->retry_keep_trying == FALSE) {
514     SILC_LOG_ERROR(("Could not connect to router, giving up"));
515     return;
516   }
517
518   /* Wait one before retrying */
519   silc_task_register(server->timeout_queue, fd, silc_server_connect_router,
520                      context, sconn->retry_timeout, 
521                      server->params->retry_interval_min_usec,
522                      SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
523 }
524
525 /* Generic routine to use connect to a router. */
526
527 SILC_TASK_CALLBACK(silc_server_connect_router)
528 {    
529   SilcServerConnection sconn = (SilcServerConnection)context;
530   SilcServer server = sconn->server;
531   SilcSocketConnection newsocket;
532   SilcProtocol protocol;
533   SilcServerKEInternalContext *proto_ctx;
534   int sock;
535
536   /* Connect to remote host */
537   sock = silc_net_create_connection(sconn->remote_port, 
538                                     sconn->remote_host);
539   if (sock < 0) {
540     SILC_LOG_ERROR(("Could not connect to router"));
541     silc_task_register(server->timeout_queue, fd, 
542                        silc_server_connect_to_router_retry,
543                        context, 0, 1, SILC_TASK_TIMEOUT, 
544                        SILC_TASK_PRI_NORMAL);
545     return;
546   }
547
548   /* Set socket options */
549   silc_net_set_socket_nonblock(sock);
550   silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
551
552   /* Create socket connection for the connection. Even though we
553      know that we are connecting to a router we will mark the socket
554      to be unknown connection until we have executed authentication
555      protocol. */
556   silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
557   server->sockets[sock] = newsocket;
558   newsocket->hostname = strdup(sconn->remote_host);
559   newsocket->ip = strdup(sconn->remote_host);
560   newsocket->port = sconn->remote_port;
561   sconn->sock = newsocket;
562
563   /* Allocate internal protocol context. This is sent as context
564      to the protocol. */
565   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
566   proto_ctx->server = (void *)server;
567   proto_ctx->context = (void *)sconn;
568   proto_ctx->sock = newsocket;
569   proto_ctx->rng = server->rng;
570   proto_ctx->responder = FALSE;
571       
572   /* Perform key exchange protocol. silc_server_connect_to_router_second
573      will be called after the protocol is finished. */
574   silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE, 
575                       &protocol, proto_ctx,
576                       silc_server_connect_to_router_second);
577   newsocket->protocol = protocol;
578       
579   /* Register a timeout task that will be executed if the protocol
580      is not executed within set limit. */
581   proto_ctx->timeout_task = 
582     silc_task_register(server->timeout_queue, sock, 
583                        silc_server_timeout_remote,
584                        server, server->params->protocol_timeout,
585                        server->params->protocol_timeout_usec,
586                        SILC_TASK_TIMEOUT,
587                        SILC_TASK_PRI_LOW);
588
589   /* Register the connection for network input and output. This sets
590      that scheduler will listen for incoming packets for this connection 
591      and sets that outgoing packets may be sent to this connection as 
592      well. However, this doesn't set the scheduler for outgoing traffic,
593      it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
594      later when outgoing data is available. */
595   context = (void *)server;
596   SILC_REGISTER_CONNECTION_FOR_IO(sock);
597   
598   /* Run the protocol */
599   protocol->execute(server->timeout_queue, 0, protocol, sock, 0, 0);
600 }
601   
602 /* This function connects to our primary router or if we are a router this
603    establishes all our primary routes. This is called at the start of the
604    server to do authentication and key exchange with our router - called
605    from schedule. */
606
607 SILC_TASK_CALLBACK(silc_server_connect_to_router)
608 {
609   SilcServer server = (SilcServer)context;
610   SilcServerConnection sconn;
611
612   SILC_LOG_DEBUG(("Connecting to router(s)"));
613
614   /* If we are normal SILC server we need to connect to our cell's
615      router. */
616   if (server->server_type == SILC_SERVER) {
617     SILC_LOG_DEBUG(("We are normal server"));
618
619     /* Create connection to the router, if configured. */
620     if (server->config->routers) {
621
622       /* Allocate connection object for hold connection specific stuff. */
623       sconn = silc_calloc(1, sizeof(*sconn));
624       sconn->server = server;
625       sconn->remote_host = strdup(server->config->routers->host);
626       sconn->remote_port = server->config->routers->port;
627
628       silc_task_register(server->timeout_queue, fd, 
629                          silc_server_connect_router,
630                          (void *)sconn, 0, 1, SILC_TASK_TIMEOUT, 
631                          SILC_TASK_PRI_NORMAL);
632       return;
633     }
634   }
635
636   /* If we are a SILC router we need to establish all of our primary
637      routes. */
638   if (server->server_type == SILC_ROUTER) {
639     SilcServerConfigSectionServerConnection *ptr;
640
641     SILC_LOG_DEBUG(("We are router"));
642
643     /* Create the connections to all our routes */
644     ptr = server->config->routers;
645     while (ptr) {
646
647       SILC_LOG_DEBUG(("Router connection [%s] %s:%d",
648                       ptr->initiator ? "Initiator" : "Responder",
649                       ptr->host, ptr->port));
650
651       if (ptr->initiator) {
652         /* Allocate connection object for hold connection specific stuff. */
653         sconn = silc_calloc(1, sizeof(*sconn));
654         sconn->server = server;
655         sconn->remote_host = strdup(ptr->host);
656         sconn->remote_port = ptr->port;
657
658         silc_task_register(server->timeout_queue, fd, 
659                            silc_server_connect_router,
660                            (void *)sconn, 0, 1, SILC_TASK_TIMEOUT, 
661                            SILC_TASK_PRI_NORMAL);
662       }
663
664       if (!ptr->next)
665         return;
666
667       ptr = ptr->next;
668     }
669   }
670
671   SILC_LOG_DEBUG(("No router(s), server will be standalone"));
672   
673   /* There wasn't a configured router, we will continue but we don't
674      have a connection to outside world.  We will be standalone server. */
675   server->standalone = TRUE;
676 }
677
678 /* Second part of connecting to router(s). Key exchange protocol has been
679    executed and now we will execute authentication protocol. */
680
681 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
682 {
683   SilcProtocol protocol = (SilcProtocol)context;
684   SilcServerKEInternalContext *ctx = 
685     (SilcServerKEInternalContext *)protocol->context;
686   SilcServer server = (SilcServer)ctx->server;
687   SilcServerConnection sconn = (SilcServerConnection)ctx->context;
688   SilcSocketConnection sock = NULL;
689   SilcServerConnAuthInternalContext *proto_ctx;
690
691   SILC_LOG_DEBUG(("Start"));
692
693   if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
694     /* Error occured during protocol */
695     silc_protocol_free(protocol);
696     if (ctx->packet)
697       silc_packet_context_free(ctx->packet);
698     if (ctx->ske)
699       silc_ske_free(ctx->ske);
700     if (ctx->dest_id)
701       silc_free(ctx->dest_id);
702     silc_free(ctx);
703     if (sock)
704       sock->protocol = NULL;
705     silc_server_disconnect_remote(server, sock, "Server closed connection: "
706                                   "Key exchange failed");
707     return;
708   }
709   
710   /* Allocate internal context for the authentication protocol. This
711      is sent as context for the protocol. */
712   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
713   proto_ctx->server = (void *)server;
714   proto_ctx->context = (void *)sconn;
715   proto_ctx->sock = sock = server->sockets[fd];
716   proto_ctx->ske = ctx->ske;       /* Save SKE object from previous protocol */
717   proto_ctx->dest_id_type = ctx->dest_id_type;
718   proto_ctx->dest_id = ctx->dest_id;
719
720   /* Resolve the authentication method used in this connection */
721   proto_ctx->auth_meth = SILC_AUTH_PASSWORD;
722   if (server->config->routers) {
723     SilcServerConfigSectionServerConnection *conn = NULL;
724
725     /* Check if we find a match from user configured connections */
726     conn = silc_server_config_find_router_conn(server->config,
727                                                sock->hostname,
728                                                sock->port);
729     if (conn) {
730       /* Match found. Use the configured authentication method */
731       proto_ctx->auth_meth = conn->auth_meth;
732       if (conn->auth_data) {
733         proto_ctx->auth_data = strdup(conn->auth_data);
734         proto_ctx->auth_data_len = strlen(conn->auth_data);
735       }
736     } else {
737       /* No match found. */
738       /* XXX */
739     }
740   } else {
741     /* XXX */
742   }
743
744   /* Free old protocol as it is finished now */
745   silc_protocol_free(protocol);
746   if (ctx->packet)
747     silc_packet_context_free(ctx->packet);
748   silc_free(ctx);
749   sock->protocol = NULL;
750
751   /* Allocate the authentication protocol. This is allocated here
752      but we won't start it yet. We will be receiving party of this
753      protocol thus we will wait that connecting party will make
754      their first move. */
755   silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH, 
756                       &sock->protocol, proto_ctx, 
757                       silc_server_connect_to_router_final);
758
759   /* Register timeout task. If the protocol is not executed inside
760      this timelimit the connection will be terminated. Currently
761      this is 15 seconds and is hard coded limit (XXX). */
762   proto_ctx->timeout_task = 
763     silc_task_register(server->timeout_queue, sock->sock, 
764                        silc_server_timeout_remote,
765                        (void *)server, 15, 0,
766                        SILC_TASK_TIMEOUT,
767                        SILC_TASK_PRI_LOW);
768
769   /* Run the protocol */
770   sock->protocol->execute(server->timeout_queue, 0, 
771                           sock->protocol, sock->sock, 0, 0);
772 }
773
774 /* Finalizes the connection to router. Registers a server task to the
775    queue so that we can accept new connections. */
776
777 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
778 {
779   SilcProtocol protocol = (SilcProtocol)context;
780   SilcServerConnAuthInternalContext *ctx = 
781     (SilcServerConnAuthInternalContext *)protocol->context;
782   SilcServer server = (SilcServer)ctx->server;
783   SilcServerConnection sconn = (SilcServerConnection)ctx->context;
784   SilcSocketConnection sock = ctx->sock;
785   SilcServerEntry id_entry;
786   SilcBuffer packet;
787   SilcServerHBContext hb_context;
788   unsigned char *id_string;
789
790   SILC_LOG_DEBUG(("Start"));
791
792   if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
793     /* Error occured during protocol */
794     if (ctx->dest_id)
795       silc_free(ctx->dest_id);
796     silc_server_disconnect_remote(server, sock, "Server closed connection: "
797                                   "Authentication failed");
798     goto out;
799   }
800
801   /* Add a task to the queue. This task receives new connections to the 
802      server. This task remains on the queue until the end of the program. */
803   if (!server->listenning) {
804     silc_task_register(server->io_queue, server->sock, 
805                        silc_server_accept_new_connection,
806                        (void *)server, 0, 0, 
807                        SILC_TASK_FD,
808                        SILC_TASK_PRI_NORMAL);
809     server->listenning = TRUE;
810   }
811
812   /* Send NEW_SERVER packet to the router. We will become registered
813      to the SILC network after sending this packet. */
814   id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
815   packet = silc_buffer_alloc(2 + 2 + SILC_ID_SERVER_LEN + 
816                              strlen(server->server_name));
817   silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
818   silc_buffer_format(packet,
819                      SILC_STR_UI_SHORT(SILC_ID_SERVER_LEN),
820                      SILC_STR_UI_XNSTRING(id_string, SILC_ID_SERVER_LEN),
821                      SILC_STR_UI_SHORT(strlen(server->server_name)),
822                      SILC_STR_UI_XNSTRING(server->server_name,
823                                           strlen(server->server_name)),
824                      SILC_STR_END);
825
826   /* Send the packet */
827   silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
828                           packet->data, packet->len, TRUE);
829   silc_buffer_free(packet);
830   silc_free(id_string);
831
832   SILC_LOG_DEBUG(("Connected to router %s", sock->hostname));
833
834   /* Add the connected router to local server list */
835   server->standalone = FALSE;
836   id_entry = silc_idlist_add_server(server->local_list, sock->hostname,
837                                     SILC_ROUTER, ctx->dest_id, NULL, sock);
838   if (!id_entry) {
839     if (ctx->dest_id)
840       silc_free(ctx->dest_id);
841     silc_server_disconnect_remote(server, sock, "Server closed connection: "
842                                   "Authentication failed");
843     goto out;
844   }
845
846   silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
847   silc_free(sock->user_data);
848   sock->user_data = (void *)id_entry;
849   sock->type = SILC_SOCKET_TYPE_ROUTER;
850   server->id_entry->router = id_entry;
851   server->router = id_entry;
852   server->router->data.registered = TRUE;
853
854   /* Perform keepalive. The `hb_context' will be freed automatically
855      when finally calling the silc_socket_free function. XXX hardcoded 
856      timeout!! */
857   hb_context = silc_calloc(1, sizeof(*hb_context));
858   hb_context->server = server;
859   silc_socket_set_heartbeat(sock, 600, hb_context,
860                             silc_server_perform_heartbeat,
861                             server->timeout_queue);
862
863   /* If we are router then announce our possible servers. */
864   if (server->server_type == SILC_ROUTER)
865     silc_server_announce_servers(server);
866
867   /* Announce our clients and channels to the router */
868   silc_server_announce_clients(server);
869   silc_server_announce_channels(server);
870
871  out:
872   /* Free the temporary connection data context */
873   if (sconn) {
874     silc_free(sconn->remote_host);
875     silc_free(sconn);
876   }
877
878   /* Free the protocol object */
879   silc_protocol_free(protocol);
880   if (ctx->packet)
881     silc_packet_context_free(ctx->packet);
882   if (ctx->ske)
883     silc_ske_free(ctx->ske);
884   silc_free(ctx);
885   sock->protocol = NULL;
886 }
887
888 /* Accepts new connections to the server. Accepting new connections are
889    done in three parts to make it async. */
890
891 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
892 {
893   SilcServer server = (SilcServer)context;
894   SilcSocketConnection newsocket;
895   SilcServerKEInternalContext *proto_ctx;
896   int sock;
897
898   SILC_LOG_DEBUG(("Accepting new connection"));
899
900   server->stat.conn_attempts++;
901
902   sock = silc_net_accept_connection(server->sock);
903   if (sock < 0) {
904     SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
905     server->stat.conn_failures++;
906     return;
907   }
908
909   /* Check max connections */
910   if (sock > SILC_SERVER_MAX_CONNECTIONS) {
911     if (server->config->redirect) {
912       /* XXX Redirecting connection to somewhere else now?? */
913       /*silc_server_send_notify("Server is full, trying to redirect..."); */
914     } else {
915       SILC_LOG_ERROR(("Refusing connection, server is full"));
916       server->stat.conn_failures++;
917     }
918     return;
919   }
920
921   /* Set socket options */
922   silc_net_set_socket_nonblock(sock);
923   silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
924
925   /* We don't create a ID yet, since we don't know what type of connection
926      this is yet. But, we do add the connection to the socket table. */
927   silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
928   server->sockets[sock] = newsocket;
929
930   /* XXX This MUST be done async as this will block the entire server
931      process. Either we have to do our own resolver stuff or in the future
932      we can use threads. */
933   /* Perform name and address lookups for the remote host. */
934   silc_net_check_host_by_sock(sock, &newsocket->hostname, &newsocket->ip);
935   if ((server->params->require_reverse_mapping && !newsocket->hostname) ||
936       !newsocket->ip) {
937     SILC_LOG_ERROR(("IP/DNS lookup failed"));
938     server->stat.conn_failures++;
939     return;
940   }
941   if (!newsocket->hostname)
942     newsocket->hostname = strdup(newsocket->ip);
943   newsocket->port = silc_net_get_remote_port(sock);
944
945   SILC_LOG_INFO(("Incoming connection from %s (%s)", newsocket->hostname,
946                  newsocket->ip));
947
948   /* Allocate internal context for key exchange protocol. This is
949      sent as context for the protocol. */
950   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
951   proto_ctx->server = context;
952   proto_ctx->sock = newsocket;
953   proto_ctx->rng = server->rng;
954   proto_ctx->responder = TRUE;
955
956   /* Prepare the connection for key exchange protocol. We allocate the
957      protocol but will not start it yet. The connector will be the
958      initiator of the protocol thus we will wait for initiation from 
959      there before we start the protocol. */
960   server->stat.auth_attempts++;
961   silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE, 
962                       &newsocket->protocol, proto_ctx, 
963                       silc_server_accept_new_connection_second);
964
965   /* Register a timeout task that will be executed if the connector
966      will not start the key exchange protocol within 60 seconds. For
967      now, this is a hard coded limit. After 60 secs the connection will
968      be closed if the key exchange protocol has not been started. */
969   proto_ctx->timeout_task = 
970     silc_task_register(server->timeout_queue, newsocket->sock, 
971                        silc_server_timeout_remote,
972                        context, 60, 0,
973                        SILC_TASK_TIMEOUT,
974                        SILC_TASK_PRI_LOW);
975
976   /* Register the connection for network input and output. This sets
977      that scheduler will listen for incoming packets for this connection 
978      and sets that outgoing packets may be sent to this connection as well.
979      However, this doesn't set the scheduler for outgoing traffic, it
980      will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
981      later when outgoing data is available. */
982   SILC_REGISTER_CONNECTION_FOR_IO(sock);
983 }
984
985 /* Second part of accepting new connection. Key exchange protocol has been
986    performed and now it is time to do little connection authentication
987    protocol to figure out whether this connection is client or server
988    and whether it has right to access this server (especially server
989    connections needs to be authenticated). */
990
991 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
992 {
993   SilcProtocol protocol = (SilcProtocol)context;
994   SilcServerKEInternalContext *ctx = 
995     (SilcServerKEInternalContext *)protocol->context;
996   SilcServer server = (SilcServer)ctx->server;
997   SilcSocketConnection sock = NULL;
998   SilcServerConnAuthInternalContext *proto_ctx;
999
1000   SILC_LOG_DEBUG(("Start"));
1001
1002   if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
1003     /* Error occured during protocol */
1004     silc_protocol_free(protocol);
1005     if (ctx->packet)
1006       silc_packet_context_free(ctx->packet);
1007     if (ctx->ske)
1008       silc_ske_free(ctx->ske);
1009     if (ctx->dest_id)
1010       silc_free(ctx->dest_id);
1011     silc_free(ctx);
1012     if (sock)
1013       sock->protocol = NULL;
1014     silc_server_disconnect_remote(server, sock, "Server closed connection: "
1015                                   "Key exchange failed");
1016     server->stat.auth_failures++;
1017     return;
1018   }
1019
1020   /* Allocate internal context for the authentication protocol. This
1021      is sent as context for the protocol. */
1022   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1023   proto_ctx->server = (void *)server;
1024   proto_ctx->sock = sock = server->sockets[fd];
1025   proto_ctx->ske = ctx->ske;    /* Save SKE object from previous protocol */
1026   proto_ctx->responder = TRUE;
1027   proto_ctx->dest_id_type = ctx->dest_id_type;
1028   proto_ctx->dest_id = ctx->dest_id;
1029
1030   /* Free old protocol as it is finished now */
1031   silc_protocol_free(protocol);
1032   if (ctx->packet)
1033     silc_packet_context_free(ctx->packet);
1034   silc_free(ctx);
1035   sock->protocol = NULL;
1036
1037   /* Allocate the authentication protocol. This is allocated here
1038      but we won't start it yet. We will be receiving party of this
1039      protocol thus we will wait that connecting party will make
1040      their first move. */
1041   silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH, 
1042                       &sock->protocol, proto_ctx, 
1043                       silc_server_accept_new_connection_final);
1044
1045   /* Register timeout task. If the protocol is not executed inside
1046      this timelimit the connection will be terminated. Currently
1047      this is 60 seconds and is hard coded limit (XXX). */
1048   proto_ctx->timeout_task = 
1049     silc_task_register(server->timeout_queue, sock->sock, 
1050                        silc_server_timeout_remote,
1051                        (void *)server, 60, 0,
1052                        SILC_TASK_TIMEOUT,
1053                        SILC_TASK_PRI_LOW);
1054 }
1055
1056 /* Final part of accepting new connection. The connection has now
1057    been authenticated and keys has been exchanged. We also know whether
1058    this is client or server connection. */
1059
1060 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1061 {
1062   SilcProtocol protocol = (SilcProtocol)context;
1063   SilcServerConnAuthInternalContext *ctx = 
1064     (SilcServerConnAuthInternalContext *)protocol->context;
1065   SilcServer server = (SilcServer)ctx->server;
1066   SilcSocketConnection sock = ctx->sock;
1067   SilcServerHBContext hb_context;
1068   void *id_entry = NULL;
1069
1070   SILC_LOG_DEBUG(("Start"));
1071
1072   if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
1073     /* Error occured during protocol */
1074     silc_protocol_free(protocol);
1075     if (ctx->packet)
1076       silc_packet_context_free(ctx->packet);
1077     if (ctx->ske)
1078       silc_ske_free(ctx->ske);
1079     if (ctx->dest_id)
1080       silc_free(ctx->dest_id);
1081     silc_free(ctx);
1082     if (sock)
1083       sock->protocol = NULL;
1084     silc_server_disconnect_remote(server, sock, "Server closed connection: "
1085                                   "Authentication failed");
1086     server->stat.auth_failures++;
1087     return;
1088   }
1089
1090   sock->type = ctx->conn_type;
1091   switch(sock->type) {
1092   case SILC_SOCKET_TYPE_CLIENT:
1093     {
1094       SilcClientEntry client;
1095
1096       SILC_LOG_DEBUG(("Remote host is client"));
1097       SILC_LOG_INFO(("Connection from %s (%s) is client", sock->hostname,
1098                      sock->ip));
1099
1100       /* Add the client to the client ID cache. The nickname and Client ID
1101          and other information is created after we have received NEW_CLIENT
1102          packet from client. */
1103       client = silc_idlist_add_client(server->local_list, 
1104                                       NULL, NULL, NULL, NULL, NULL, sock);
1105       if (!client) {
1106         SILC_LOG_ERROR(("Could not add new client to cache"));
1107         silc_free(sock->user_data);
1108         break;
1109       }
1110
1111       /* Statistics */
1112       server->stat.my_clients++;
1113       server->stat.clients++;
1114       if (server->server_type == SILC_ROUTER)
1115         server->stat.cell_clients++;
1116
1117       id_entry = (void *)client;
1118       break;
1119     }
1120   case SILC_SOCKET_TYPE_SERVER:
1121   case SILC_SOCKET_TYPE_ROUTER:
1122     {
1123       SilcServerEntry new_server;
1124
1125       SILC_LOG_DEBUG(("Remote host is %s", 
1126                       sock->type == SILC_SOCKET_TYPE_SERVER ? 
1127                       "server" : "router"));
1128       SILC_LOG_INFO(("Connection from %s (%s) is %s", sock->hostname,
1129                      sock->ip, sock->type == SILC_SOCKET_TYPE_SERVER ? 
1130                      "server" : "router"));
1131
1132       /* Add the server into server cache. The server name and Server ID
1133          is updated after we have received NEW_SERVER packet from the
1134          server. We mark ourselves as router for this server if we really
1135          are router. */
1136       new_server = 
1137         silc_idlist_add_server(server->local_list, NULL,
1138                                sock->type == SILC_SOCKET_TYPE_SERVER ?
1139                                SILC_SERVER : SILC_ROUTER, NULL, 
1140                                sock->type == SILC_SOCKET_TYPE_SERVER ?
1141                                server->id_entry : NULL, sock);
1142       if (!new_server) {
1143         SILC_LOG_ERROR(("Could not add new server to cache"));
1144         silc_free(sock->user_data);
1145         break;
1146       }
1147
1148       /* Statistics */
1149       if (sock->type == SILC_SOCKET_TYPE_SERVER)
1150         server->stat.my_servers++;
1151       else
1152         server->stat.my_routers++;
1153       server->stat.servers++;
1154
1155       id_entry = (void *)new_server;
1156       
1157       /* There is connection to other server now, if it is router then
1158          we will have connection to outside world.  If we are router but
1159          normal server connected to us then we will remain standalone,
1160          if we are standlone. */
1161       if (server->standalone && sock->type == SILC_SOCKET_TYPE_ROUTER) {
1162         SILC_LOG_DEBUG(("We are not standalone server anymore"));
1163         server->standalone = FALSE;
1164         if (!server->id_entry->router) {
1165           server->id_entry->router = id_entry;
1166           server->router = id_entry;
1167         }
1168       }
1169       break;
1170     }
1171   default:
1172     break;
1173   }
1174
1175   /* Add the common data structure to the ID entry. */
1176   if (id_entry)
1177     silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1178       
1179   /* Add to sockets internal pointer for fast referencing */
1180   silc_free(sock->user_data);
1181   sock->user_data = id_entry;
1182
1183   /* Connection has been fully established now. Everything is ok. */
1184   SILC_LOG_DEBUG(("New connection authenticated"));
1185
1186   /* Perform keepalive. The `hb_context' will be freed automatically
1187      when finally calling the silc_socket_free function. XXX hardcoded 
1188      timeout!! */
1189   hb_context = silc_calloc(1, sizeof(*hb_context));
1190   hb_context->server = server;
1191   silc_socket_set_heartbeat(sock, 600, hb_context,
1192                             silc_server_perform_heartbeat,
1193                             server->timeout_queue);
1194
1195   silc_protocol_free(protocol);
1196   if (ctx->packet)
1197     silc_packet_context_free(ctx->packet);
1198   if (ctx->ske)
1199     silc_ske_free(ctx->ske);
1200   if (ctx->dest_id)
1201     silc_free(ctx->dest_id);
1202   silc_free(ctx);
1203   sock->protocol = NULL;
1204 }
1205
1206 /* This function is used to read packets from network and send packets to
1207    network. This is usually a generic task. */
1208
1209 SILC_TASK_CALLBACK(silc_server_packet_process)
1210 {
1211   SilcServer server = (SilcServer)context;
1212   SilcSocketConnection sock = server->sockets[fd];
1213   SilcIDListData idata;
1214   SilcCipher cipher = NULL;
1215   SilcHmac hmac = NULL;
1216   int ret;
1217
1218   if (!sock)
1219     return;
1220
1221   SILC_LOG_DEBUG(("Processing packet"));
1222
1223   /* Packet sending */
1224
1225   if (type == SILC_TASK_WRITE) {
1226     /* Do not send data to disconnected connection */
1227     if (SILC_IS_DISCONNECTED(sock))
1228       return;
1229
1230     server->stat.packets_sent++;
1231
1232     if (sock->outbuf->data - sock->outbuf->head)
1233       silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
1234
1235     ret = silc_server_packet_send_real(server, sock, TRUE);
1236
1237     /* If returned -2 could not write to connection now, will do
1238        it later. */
1239     if (ret == -2)
1240       return;
1241
1242     if (ret == -1)
1243       return;
1244     
1245     /* The packet has been sent and now it is time to set the connection
1246        back to only for input. When there is again some outgoing data 
1247        available for this connection it will be set for output as well. 
1248        This call clears the output setting and sets it only for input. */
1249     SILC_SET_CONNECTION_FOR_INPUT(fd);
1250     SILC_UNSET_OUTBUF_PENDING(sock);
1251
1252     silc_buffer_clear(sock->outbuf);
1253     return;
1254   }
1255
1256   /* Packet receiving */
1257
1258   /* Read some data from connection */
1259   ret = silc_packet_receive(sock);
1260   if (ret < 0)
1261     return;
1262     
1263   /* EOF */
1264   if (ret == 0) {
1265     SILC_LOG_DEBUG(("Read EOF"));
1266       
1267     /* If connection is disconnecting already we will finally
1268        close the connection */
1269     if (SILC_IS_DISCONNECTING(sock)) {
1270       if (sock->user_data)
1271         silc_server_free_sock_user_data(server, sock);
1272       silc_server_close_connection(server, sock);
1273       return;
1274     }
1275       
1276     SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1277     SILC_SET_DISCONNECTING(sock);
1278
1279     /* If the closed connection was our primary router connection the
1280        start re-connecting phase. */
1281     if (!server->standalone && server->server_type == SILC_SERVER && 
1282         sock == server->router->connection)
1283       silc_task_register(server->timeout_queue, 0, 
1284                          silc_server_connect_to_router,
1285                          context, 0, 500000,
1286                          SILC_TASK_TIMEOUT,
1287                          SILC_TASK_PRI_NORMAL);
1288
1289     if (sock->user_data)
1290       silc_server_free_sock_user_data(server, sock);
1291     silc_server_close_connection(server, sock);
1292     return;
1293   }
1294
1295   /* If connection is disconnecting or disconnected we will ignore
1296      what we read. */
1297   if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1298     SILC_LOG_DEBUG(("Ignoring read data from disonnected connection"));
1299     return;
1300   }
1301
1302   server->stat.packets_received++;
1303
1304   /* Get keys and stuff from ID entry */
1305   idata = (SilcIDListData)sock->user_data;
1306   if (idata) {
1307     idata->last_receive = time(NULL);
1308     cipher = idata->receive_key;
1309     hmac = idata->hmac;
1310   }
1311  
1312   /* Process the packet. This will call the parser that will then
1313      decrypt and parse the packet. */
1314   silc_packet_receive_process(sock, cipher, hmac, silc_server_packet_parse, 
1315                               server);
1316 }
1317
1318 /* Parses whole packet, received earlier. */
1319
1320 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1321 {
1322   SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1323   SilcServer server = (SilcServer)parse_ctx->context;
1324   SilcSocketConnection sock = parse_ctx->sock;
1325   SilcPacketContext *packet = parse_ctx->packet;
1326   int ret;
1327
1328   SILC_LOG_DEBUG(("Start"));
1329
1330   /* Decrypt the received packet */
1331   ret = silc_packet_decrypt(parse_ctx->cipher, parse_ctx->hmac, 
1332                             packet->buffer, packet);
1333   if (ret < 0)
1334     goto out;
1335
1336   if (ret == 0) {
1337     /* Parse the packet. Packet type is returned. */
1338     ret = silc_packet_parse(packet);
1339   } else {
1340     /* Parse the packet header in special way as this is "special"
1341        packet type. */
1342     ret = silc_packet_parse_special(packet);
1343   }
1344
1345   if (ret == SILC_PACKET_NONE)
1346     goto out;
1347
1348   if (server->server_type == SILC_ROUTER) {
1349     /* Route the packet if it is not destined to us. Other ID types but
1350        server are handled separately after processing them. */
1351     if (packet->dst_id_type == SILC_ID_SERVER && 
1352         sock->type != SILC_SOCKET_TYPE_CLIENT &&
1353         SILC_ID_SERVER_COMPARE(packet->dst_id, server->id_string)) {
1354       
1355       /* Route the packet to fastest route for the destination ID */
1356       void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len, 
1357                                 packet->dst_id_type);
1358       if (!id)
1359         goto out;
1360       silc_server_packet_route(server,
1361                                silc_server_route_get(server, id,
1362                                                      packet->dst_id_type),
1363                                packet);
1364       silc_free(id);
1365       goto out;
1366     }
1367     
1368     /* Broadcast packet if it is marked as broadcast packet and it is
1369        originated from router and we are router. */
1370     if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
1371         packet->flags & SILC_PACKET_FLAG_BROADCAST) {
1372       silc_server_packet_broadcast(server, server->router->connection, packet);
1373     }
1374   }
1375
1376   /* Parse the incoming packet type */
1377   silc_server_packet_parse_type(server, sock, packet);
1378
1379  out:
1380   silc_buffer_clear(sock->inbuf);
1381   silc_packet_context_free(packet);
1382   silc_free(parse_ctx);
1383 }
1384
1385 /* Parser callback called by silc_packet_receive_process. This merely
1386    registers timeout that will handle the actual parsing when appropriate. */
1387
1388 void silc_server_packet_parse(SilcPacketParserContext *parser_context)
1389 {
1390   SilcServer server = (SilcServer)parser_context->context;
1391   SilcSocketConnection sock = parser_context->sock;
1392
1393   switch (sock->type) {
1394   case SILC_SOCKET_TYPE_CLIENT:
1395   case SILC_SOCKET_TYPE_UNKNOWN:
1396     /* Parse the packet with timeout */
1397     silc_task_register(server->timeout_queue, sock->sock,
1398                        silc_server_packet_parse_real,
1399                        (void *)parser_context, 0, 100000,
1400                        SILC_TASK_TIMEOUT,
1401                        SILC_TASK_PRI_NORMAL);
1402     break;
1403   case SILC_SOCKET_TYPE_SERVER:
1404   case SILC_SOCKET_TYPE_ROUTER:
1405     /* Packets from servers are parsed as soon as possible */
1406     silc_task_register(server->timeout_queue, sock->sock,
1407                        silc_server_packet_parse_real,
1408                        (void *)parser_context, 0, 1,
1409                        SILC_TASK_TIMEOUT,
1410                        SILC_TASK_PRI_NORMAL);
1411     break;
1412   default:
1413     return;
1414   }
1415 }
1416
1417 /* Parses the packet type and calls what ever routines the packet type
1418    requires. This is done for all incoming packets. */
1419
1420 void silc_server_packet_parse_type(SilcServer server, 
1421                                    SilcSocketConnection sock,
1422                                    SilcPacketContext *packet)
1423 {
1424   SilcPacketType type = packet->type;
1425
1426   SILC_LOG_DEBUG(("Parsing packet type %d", type));
1427
1428   /* Parse the packet type */
1429   switch(type) {
1430   case SILC_PACKET_DISCONNECT:
1431     SILC_LOG_DEBUG(("Disconnect packet"));
1432     if (packet->flags & SILC_PACKET_FLAG_LIST)
1433       break;
1434     break;
1435
1436   case SILC_PACKET_SUCCESS:
1437     /*
1438      * Success received for something. For now we can have only
1439      * one protocol for connection executing at once hence this
1440      * success message is for whatever protocol is executing currently.
1441      */
1442     SILC_LOG_DEBUG(("Success packet"));
1443     if (packet->flags & SILC_PACKET_FLAG_LIST)
1444       break;
1445     if (sock->protocol) {
1446       sock->protocol->execute(server->timeout_queue, 0,
1447                               sock->protocol, sock->sock, 0, 0);
1448     }
1449     break;
1450
1451   case SILC_PACKET_FAILURE:
1452     /*
1453      * Failure received for something. For now we can have only
1454      * one protocol for connection executing at once hence this
1455      * failure message is for whatever protocol is executing currently.
1456      */
1457     SILC_LOG_DEBUG(("Failure packet"));
1458     if (packet->flags & SILC_PACKET_FLAG_LIST)
1459       break;
1460     if (sock->protocol) {
1461       /* XXX Audit the failure type */
1462       sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
1463       sock->protocol->execute(server->timeout_queue, 0,
1464                               sock->protocol, sock->sock, 0, 0);
1465     }
1466     break;
1467
1468   case SILC_PACKET_REJECT:
1469     SILC_LOG_DEBUG(("Reject packet"));
1470     if (packet->flags & SILC_PACKET_FLAG_LIST)
1471       break;
1472     return;
1473     break;
1474
1475   case SILC_PACKET_NOTIFY:
1476     /*
1477      * Received notify packet. Server can receive notify packets from
1478      * router. Server then relays the notify messages to clients if needed.
1479      */
1480     SILC_LOG_DEBUG(("Notify packet"));
1481     if (packet->flags & SILC_PACKET_FLAG_LIST)
1482       silc_server_notify_list(server, sock, packet);
1483     else
1484       silc_server_notify(server, sock, packet);
1485     break;
1486
1487     /* 
1488      * Channel packets
1489      */
1490   case SILC_PACKET_CHANNEL_MESSAGE:
1491     /*
1492      * Received channel message. Channel messages are special packets
1493      * (although probably most common ones) thus they are handled
1494      * specially.
1495      */
1496     SILC_LOG_DEBUG(("Channel Message packet"));
1497     if (packet->flags & SILC_PACKET_FLAG_LIST)
1498       break;
1499     silc_server_channel_message(server, sock, packet);
1500     break;
1501
1502   case SILC_PACKET_CHANNEL_KEY:
1503     /*
1504      * Received key for channel. As channels are created by the router
1505      * the keys are as well. We will distribute the key to all of our
1506      * locally connected clients on the particular channel. Router
1507      * never receives this channel and thus is ignored.
1508      */
1509     SILC_LOG_DEBUG(("Channel Key packet"));
1510     if (packet->flags & SILC_PACKET_FLAG_LIST)
1511       break;
1512     silc_server_channel_key(server, sock, packet);
1513     break;
1514
1515     /*
1516      * Command packets
1517      */
1518   case SILC_PACKET_COMMAND:
1519     /*
1520      * Recived command. Processes the command request and allocates the
1521      * command context and calls the command.
1522      */
1523     SILC_LOG_DEBUG(("Command packet"));
1524     if (packet->flags & SILC_PACKET_FLAG_LIST)
1525       break;
1526     silc_server_command_process(server, sock, packet);
1527     break;
1528
1529   case SILC_PACKET_COMMAND_REPLY:
1530     /*
1531      * Received command reply packet. Received command reply to command. It
1532      * may be reply to command sent by us or reply to command sent by client
1533      * that we've routed further.
1534      */
1535     SILC_LOG_DEBUG(("Command Reply packet"));
1536     if (packet->flags & SILC_PACKET_FLAG_LIST)
1537       break;
1538     silc_server_command_reply(server, sock, packet);
1539     break;
1540
1541     /*
1542      * Private Message packets
1543      */
1544   case SILC_PACKET_PRIVATE_MESSAGE:
1545     /*
1546      * Received private message packet. The packet is coming from either
1547      * client or server.
1548      */
1549     SILC_LOG_DEBUG(("Private Message packet"));
1550     if (packet->flags & SILC_PACKET_FLAG_LIST)
1551       break;
1552     silc_server_private_message(server, sock, packet);
1553     break;
1554
1555   case SILC_PACKET_PRIVATE_MESSAGE_KEY:
1556     /*
1557      * Private message key packet.
1558      */
1559     if (packet->flags & SILC_PACKET_FLAG_LIST)
1560       break;
1561     break;
1562
1563     /*
1564      * Key Exchange protocol packets
1565      */
1566   case SILC_PACKET_KEY_EXCHANGE:
1567     SILC_LOG_DEBUG(("KE packet"));
1568     if (packet->flags & SILC_PACKET_FLAG_LIST)
1569       break;
1570
1571     if (sock->protocol && sock->protocol->protocol->type 
1572         == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1573
1574       SilcServerKEInternalContext *proto_ctx = 
1575         (SilcServerKEInternalContext *)sock->protocol->context;
1576
1577       proto_ctx->packet = silc_packet_context_dup(packet);
1578
1579       /* Let the protocol handle the packet */
1580       sock->protocol->execute(server->timeout_queue, 0, 
1581                               sock->protocol, sock->sock, 0, 100000);
1582     } else {
1583       SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
1584                       "protocol active, packet dropped."));
1585
1586       /* XXX Trigger KE protocol?? Rekey actually, maybe. */
1587     }
1588     break;
1589
1590   case SILC_PACKET_KEY_EXCHANGE_1:
1591     SILC_LOG_DEBUG(("KE 1 packet"));
1592     if (packet->flags & SILC_PACKET_FLAG_LIST)
1593       break;
1594
1595     if (sock->protocol && sock->protocol->protocol->type 
1596         == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1597
1598       SilcServerKEInternalContext *proto_ctx = 
1599         (SilcServerKEInternalContext *)sock->protocol->context;
1600
1601       if (proto_ctx->packet)
1602         silc_packet_context_free(proto_ctx->packet);
1603
1604       proto_ctx->packet = silc_packet_context_dup(packet);
1605       proto_ctx->dest_id_type = packet->src_id_type;
1606       proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1607                                           packet->src_id_type);
1608       if (!proto_ctx->dest_id)
1609         break;
1610
1611       /* Let the protocol handle the packet */
1612       sock->protocol->execute(server->timeout_queue, 0, 
1613                               sock->protocol, sock->sock,
1614                               0, 100000);
1615     } else {
1616       SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
1617                       "protocol active, packet dropped."));
1618     }
1619     break;
1620
1621   case SILC_PACKET_KEY_EXCHANGE_2:
1622     SILC_LOG_DEBUG(("KE 2 packet"));
1623     if (packet->flags & SILC_PACKET_FLAG_LIST)
1624       break;
1625
1626     if (sock->protocol && sock->protocol->protocol->type 
1627         == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1628
1629       SilcServerKEInternalContext *proto_ctx = 
1630         (SilcServerKEInternalContext *)sock->protocol->context;
1631
1632       if (proto_ctx->packet)
1633         silc_packet_context_free(proto_ctx->packet);
1634
1635       proto_ctx->packet = silc_packet_context_dup(packet);
1636       proto_ctx->dest_id_type = packet->src_id_type;
1637       proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1638                                           packet->src_id_type);
1639       if (!proto_ctx->dest_id)
1640         break;
1641
1642       /* Let the protocol handle the packet */
1643       sock->protocol->execute(server->timeout_queue, 0, 
1644                               sock->protocol, sock->sock,
1645                               0, 100000);
1646     } else {
1647       SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
1648                       "protocol active, packet dropped."));
1649     }
1650     break;
1651
1652   case SILC_PACKET_CONNECTION_AUTH_REQUEST:
1653     /*
1654      * Connection authentication request packet. When we receive this packet
1655      * we will send to the other end information about our mandatory
1656      * authentication method for the connection. This packet maybe received
1657      * at any time. 
1658      */
1659     SILC_LOG_DEBUG(("Connection authentication request packet"));
1660     if (packet->flags & SILC_PACKET_FLAG_LIST)
1661       break;
1662     break;
1663
1664     /*
1665      * Connection Authentication protocol packets
1666      */
1667   case SILC_PACKET_CONNECTION_AUTH:
1668     /* Start of the authentication protocol. We receive here the 
1669        authentication data and will verify it. */
1670     SILC_LOG_DEBUG(("Connection auth packet"));
1671     if (packet->flags & SILC_PACKET_FLAG_LIST)
1672       break;
1673
1674     if (sock->protocol && sock->protocol->protocol->type 
1675         == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
1676
1677       SilcServerConnAuthInternalContext *proto_ctx = 
1678         (SilcServerConnAuthInternalContext *)sock->protocol->context;
1679
1680       proto_ctx->packet = silc_packet_context_dup(packet);
1681
1682       /* Let the protocol handle the packet */
1683       sock->protocol->execute(server->timeout_queue, 0, 
1684                               sock->protocol, sock->sock, 0, 0);
1685     } else {
1686       SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
1687                       "protocol active, packet dropped."));
1688     }
1689     break;
1690
1691   case SILC_PACKET_NEW_ID:
1692     /*
1693      * Received New ID packet. This includes some new ID that has been
1694      * created. It may be for client, server or channel. This is the way
1695      * to distribute information about new registered entities in the
1696      * SILC network.
1697      */
1698     SILC_LOG_DEBUG(("New ID packet"));
1699     if (packet->flags & SILC_PACKET_FLAG_LIST)
1700       silc_server_new_id_list(server, sock, packet);
1701     else
1702       silc_server_new_id(server, sock, packet);
1703     break;
1704
1705   case SILC_PACKET_NEW_CLIENT:
1706     /*
1707      * Received new client packet. This includes client information that
1708      * we will use to create initial client ID. After creating new
1709      * ID we will send it to the client.
1710      */
1711     SILC_LOG_DEBUG(("New Client packet"));
1712     if (packet->flags & SILC_PACKET_FLAG_LIST)
1713       break;
1714     silc_server_new_client(server, sock, packet);
1715     break;
1716
1717   case SILC_PACKET_NEW_SERVER:
1718     /*
1719      * Received new server packet. This includes Server ID and some other
1720      * information that we may save. This is received after server has 
1721      * connected to us.
1722      */
1723     SILC_LOG_DEBUG(("New Server packet"));
1724     if (packet->flags & SILC_PACKET_FLAG_LIST)
1725       break;
1726     silc_server_new_server(server, sock, packet);
1727     break;
1728
1729   case SILC_PACKET_NEW_CHANNEL:
1730     /*
1731      * Received new channel packet. Information about new channel in the
1732      * network are distributed using this packet.
1733      */
1734     SILC_LOG_DEBUG(("New Channel packet"));
1735     if (packet->flags & SILC_PACKET_FLAG_LIST)
1736       silc_server_new_channel_list(server, sock, packet);
1737     else
1738       silc_server_new_channel(server, sock, packet);
1739     break;
1740
1741   case SILC_PACKET_HEARTBEAT:
1742     /*
1743      * Received heartbeat.
1744      */
1745     SILC_LOG_DEBUG(("Heartbeat packet"));
1746     if (packet->flags & SILC_PACKET_FLAG_LIST)
1747       break;
1748     break;
1749
1750   default:
1751     SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
1752     break;
1753   }
1754   
1755 }
1756
1757 /* Creates connection to a remote router. */
1758
1759 void silc_server_create_connection(SilcServer server,
1760                                    char *remote_host, unsigned int port)
1761 {
1762   SilcServerConnection sconn;
1763
1764   /* Allocate connection object for hold connection specific stuff. */
1765   sconn = silc_calloc(1, sizeof(*sconn));
1766   sconn->server = server;
1767   sconn->remote_host = strdup(remote_host);
1768   sconn->remote_port = port;
1769
1770   silc_task_register(server->timeout_queue, 0, 
1771                      silc_server_connect_router,
1772                      (void *)sconn, 0, 1, SILC_TASK_TIMEOUT, 
1773                      SILC_TASK_PRI_NORMAL);
1774 }
1775
1776 /* Closes connection to socket connection */
1777
1778 void silc_server_close_connection(SilcServer server,
1779                                   SilcSocketConnection sock)
1780 {
1781   SILC_LOG_DEBUG(("Closing connection %d", sock->sock));
1782
1783   /* We won't listen for this connection anymore */
1784   silc_schedule_unset_listen_fd(sock->sock);
1785
1786   /* Unregister all tasks */
1787   silc_task_unregister_by_fd(server->io_queue, sock->sock);
1788   silc_task_unregister_by_fd(server->timeout_queue, sock->sock);
1789
1790   /* Close the actual connection */
1791   silc_net_close_connection(sock->sock);
1792   server->sockets[sock->sock] = NULL;
1793   silc_socket_free(sock);
1794 }
1795
1796 /* Sends disconnect message to remote connection and disconnects the 
1797    connection. */
1798
1799 void silc_server_disconnect_remote(SilcServer server,
1800                                    SilcSocketConnection sock,
1801                                    const char *fmt, ...)
1802 {
1803   va_list ap;
1804   unsigned char buf[4096];
1805
1806   if (!sock)
1807     return;
1808
1809   memset(buf, 0, sizeof(buf));
1810   va_start(ap, fmt);
1811   vsprintf(buf, fmt, ap);
1812   va_end(ap);
1813
1814   SILC_LOG_DEBUG(("Disconnecting remote host"));
1815
1816   SILC_LOG_INFO(("Disconnecting %s:%d [%s]", sock->hostname,
1817                   sock->port,
1818                   (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
1819                    sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
1820                    sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
1821                    "Router")));
1822
1823   /* Notify remote end that the conversation is over. The notify message
1824      is tried to be sent immediately. */
1825   silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,  
1826                           buf, strlen(buf), TRUE);
1827
1828   /* Mark the connection to be disconnected */
1829   SILC_SET_DISCONNECTED(sock);
1830   silc_server_close_connection(server, sock);
1831 }
1832
1833 /* Frees client data and notifies about client's signoff. */
1834
1835 void silc_server_free_client_data(SilcServer server, 
1836                                   SilcSocketConnection sock,
1837                                   SilcClientEntry user_data, char *signoff)
1838 {
1839   /* Send REMOVE_ID packet to routers. */
1840   if (!server->standalone && server->router)
1841     silc_server_send_notify_signoff(server, server->router->connection,
1842                                     server->server_type == SILC_SERVER ?
1843                                     FALSE : TRUE, user_data->id, 
1844                                     SILC_ID_CLIENT_LEN, signoff);
1845
1846   /* Remove client from all channels */
1847   silc_server_remove_from_channels(server, sock, user_data, signoff);
1848
1849   /* XXX must take some info to history before freeing */
1850
1851   /* Free the client entry and everything in it */
1852   silc_idlist_del_data(user_data);
1853   silc_idlist_del_client(server->local_list, user_data);
1854   server->stat.my_clients--;
1855   server->stat.clients--;
1856   if (server->server_type == SILC_ROUTER)
1857     server->stat.cell_clients--;
1858 }
1859
1860 /* Frees user_data pointer from socket connection object. This also sends
1861    appropriate notify packets to the network to inform about leaving
1862    entities. */
1863
1864 void silc_server_free_sock_user_data(SilcServer server, 
1865                                      SilcSocketConnection sock)
1866 {
1867   SILC_LOG_DEBUG(("Start"));
1868
1869   switch(sock->type) {
1870   case SILC_SOCKET_TYPE_CLIENT:
1871     {
1872       SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
1873       silc_server_free_client_data(server, sock, user_data, NULL);
1874       break;
1875     }
1876   case SILC_SOCKET_TYPE_SERVER:
1877   case SILC_SOCKET_TYPE_ROUTER:
1878     {
1879       SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
1880
1881       /* Send REMOVE_ID packet to routers. */
1882       if (!server->standalone && server->router)
1883         silc_server_send_notify_server_signoff(server, 
1884                                                server->router->connection,
1885                                                server->server_type == 
1886                                                SILC_SERVER ?
1887                                                FALSE : TRUE, user_data->id, 
1888                                                SILC_ID_SERVER_LEN);
1889
1890       /* Then also free all client entries that this server owns as
1891          they will become invalid now as well. */
1892       silc_server_remove_clients_by_server(server, user_data);
1893
1894       /* If this was our primary router connection then we're lost to
1895          the outside world. */
1896       if (server->server_type == SILC_SERVER && server->router == user_data) {
1897         server->id_entry->router = NULL;
1898         server->router = NULL;
1899         server->standalone = TRUE;
1900       }
1901
1902       /* Free the server entry */
1903       silc_idlist_del_data(user_data);
1904       silc_idlist_del_server(server->local_list, user_data);
1905       server->stat.my_servers--;
1906       server->stat.servers--;
1907       if (server->server_type == SILC_ROUTER)
1908         server->stat.cell_servers--;
1909       break;
1910     }
1911   default:
1912     {
1913       SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
1914
1915       silc_idlist_del_data(user_data);
1916       silc_free(user_data);
1917       break;
1918     }
1919   }
1920
1921   sock->user_data = NULL;
1922 }
1923
1924 /* This function is used to remove all client entries by the server `entry'.
1925    This is called when the connection is lost to the server. In this case
1926    we must invalidate all the client entries owned by the server `entry'. */
1927
1928 int silc_server_remove_clients_by_server(SilcServer server, 
1929                                          SilcServerEntry entry)
1930 {
1931   SilcIDCacheList list = NULL;
1932   SilcIDCacheEntry id_cache = NULL;
1933   SilcClientEntry client = NULL;
1934
1935   SILC_LOG_DEBUG(("Start"));
1936
1937   if (silc_idcache_find_by_id(server->local_list->clients, 
1938                               SILC_ID_CACHE_ANY, SILC_ID_CLIENT, &list)) {
1939
1940     if (silc_idcache_list_first(list, &id_cache)) {
1941       while (id_cache) {
1942         client = (SilcClientEntry)id_cache->context;
1943         
1944         if (client->router != entry) {
1945           if (!silc_idcache_list_next(list, &id_cache))
1946             break;
1947           else
1948             continue;
1949         }
1950
1951         /* Remove the client entry */
1952         silc_server_remove_from_channels(server, NULL, client, NULL);
1953         silc_idlist_del_client(server->local_list, client);
1954
1955         if (!silc_idcache_list_next(list, &id_cache))
1956           break;
1957       }
1958     }
1959     silc_idcache_list_free(list);
1960   }
1961   
1962   if (silc_idcache_find_by_id(server->global_list->clients, 
1963                               SILC_ID_CACHE_ANY, SILC_ID_CLIENT, &list)) {
1964
1965     if (silc_idcache_list_first(list, &id_cache)) {
1966       while (id_cache) {
1967         client = (SilcClientEntry)id_cache->context;
1968         
1969         if (client->router != entry) {
1970           if (!silc_idcache_list_next(list, &id_cache))
1971             break;
1972           else
1973             continue;
1974         }
1975
1976         /* Remove the client entry */
1977         silc_server_remove_from_channels(server, NULL, client, NULL);
1978         silc_idlist_del_client(server->global_list, client);
1979
1980         if (!silc_idcache_list_next(list, &id_cache))
1981           break;
1982       }
1983     }
1984     silc_idcache_list_free(list);
1985   }
1986   
1987   return TRUE;
1988 }
1989
1990 /* Checks whether given channel has global users.  If it does this returns
1991    TRUE and FALSE if there is only locally connected clients on the channel. */
1992
1993 int silc_server_channel_has_global(SilcChannelEntry channel)
1994 {
1995   SilcChannelClientEntry chl;
1996
1997   silc_list_start(channel->user_list);
1998   while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
1999     if (chl->client->router)
2000       return TRUE;
2001   }
2002
2003   return FALSE;
2004 }
2005
2006 /* Checks whether given channel has locally connected users.  If it does this
2007    returns TRUE and FALSE if there is not one locally connected client. */
2008
2009 int silc_server_channel_has_local(SilcChannelEntry channel)
2010 {
2011   SilcChannelClientEntry chl;
2012
2013   silc_list_start(channel->user_list);
2014   while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2015     if (!chl->client->router)
2016       return TRUE;
2017   }
2018
2019   return FALSE;
2020 }
2021
2022 /* Removes client from all channels it has joined. This is used when client
2023    connection is disconnected. If the client on a channel is last, the
2024    channel is removed as well. This sends the SIGNOFF notify types. */
2025
2026 void silc_server_remove_from_channels(SilcServer server, 
2027                                       SilcSocketConnection sock,
2028                                       SilcClientEntry client,
2029                                       char *signoff_message)
2030 {
2031   SilcChannelEntry channel;
2032   SilcChannelClientEntry chl;
2033   SilcBuffer clidp;
2034
2035   SILC_LOG_DEBUG(("Start"));
2036
2037   if (!client || !client->id)
2038     return;
2039
2040   clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2041
2042   /* Remove the client from all channels. The client is removed from
2043      the channels' user list. */
2044   silc_list_start(client->channels);
2045   while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
2046     channel = chl->channel;
2047
2048     /* Remove channel from client's channel list */
2049     silc_list_del(client->channels, chl);
2050
2051     /* Remove channel if there is no users anymore */
2052     if (server->server_type == SILC_ROUTER &&
2053         silc_list_count(channel->user_list) < 2) {
2054       if (!silc_idlist_del_channel(server->local_list, channel))
2055         silc_idlist_del_channel(server->global_list, channel);
2056       server->stat.my_channels--;
2057       continue;
2058     }
2059
2060     /* Remove client from channel's client list */
2061     silc_list_del(channel->user_list, chl);
2062     silc_free(chl);
2063     server->stat.my_chanclients--;
2064
2065     /* If there is no global users on the channel anymore mark the channel
2066        as local channel. */
2067     if (server->server_type == SILC_SERVER &&
2068         !silc_server_channel_has_global(channel))
2069       channel->global_users = FALSE;
2070
2071     /* If there is not at least one local user on the channel then we don't
2072        need the channel entry anymore, we can remove it safely. */
2073     if (server->server_type == SILC_SERVER &&
2074         !silc_server_channel_has_local(channel)) {
2075       /* Notify about leaving client if this channel has global users. */
2076       if (channel->global_users)
2077         silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2078                                            SILC_NOTIFY_TYPE_SIGNOFF, 
2079                                            signoff_message ? 2 : 1,
2080                                            clidp->data, clidp->len,
2081                                            signoff_message, signoff_message ?
2082                                            strlen(signoff_message) : 0);
2083
2084       if (!silc_idlist_del_channel(server->local_list, channel))
2085         silc_idlist_del_channel(server->global_list, channel);
2086       server->stat.my_channels--;
2087       continue;
2088     }
2089
2090     /* Send notify to channel about client leaving SILC and thus
2091        the entire channel. */
2092     silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2093                                        SILC_NOTIFY_TYPE_SIGNOFF, 
2094                                        signoff_message ? 2 : 1,
2095                                        clidp->data, clidp->len,
2096                                        signoff_message, signoff_message ?
2097                                        strlen(signoff_message) : 0);
2098   }
2099
2100   silc_buffer_free(clidp);
2101 }
2102
2103 /* Removes client from one channel. This is used for example when client
2104    calls LEAVE command to remove itself from the channel. Returns TRUE
2105    if channel still exists and FALSE if the channel is removed when
2106    last client leaves the channel. If `notify' is FALSE notify messages
2107    are not sent. */
2108
2109 int silc_server_remove_from_one_channel(SilcServer server, 
2110                                         SilcSocketConnection sock,
2111                                         SilcChannelEntry channel,
2112                                         SilcClientEntry client,
2113                                         int notify)
2114 {
2115   SilcChannelEntry ch;
2116   SilcChannelClientEntry chl;
2117   SilcBuffer clidp;
2118
2119   SILC_LOG_DEBUG(("Start"));
2120
2121   clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2122
2123   /* Remove the client from the channel. The client is removed from
2124      the channel's user list. */
2125   silc_list_start(client->channels);
2126   while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
2127     if (chl->channel != channel)
2128       continue;
2129
2130     ch = chl->channel;
2131
2132     /* Remove channel from client's channel list */
2133     silc_list_del(client->channels, chl);
2134
2135     /* Remove channel if there is no users anymore */
2136     if (server->server_type == SILC_ROUTER &&
2137         silc_list_count(channel->user_list) < 2) {
2138       if (!silc_idlist_del_channel(server->local_list, channel))
2139         silc_idlist_del_channel(server->global_list, channel);
2140       silc_buffer_free(clidp);
2141       server->stat.my_channels--;
2142       return FALSE;
2143     }
2144
2145     /* Remove client from channel's client list */
2146     silc_list_del(channel->user_list, chl);
2147     silc_free(chl);
2148     server->stat.my_chanclients--;
2149
2150     /* If there is no global users on the channel anymore mark the channel
2151        as local channel. */
2152     if (server->server_type == SILC_SERVER &&
2153         !silc_server_channel_has_global(channel))
2154       channel->global_users = FALSE;
2155
2156     /* If there is not at least one local user on the channel then we don't
2157        need the channel entry anymore, we can remove it safely. */
2158     if (server->server_type == SILC_SERVER &&
2159         !silc_server_channel_has_local(channel)) {
2160       /* Notify about leaving client if this channel has global users. */
2161       if (notify && channel->global_users)
2162         silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2163                                            SILC_NOTIFY_TYPE_LEAVE, 1,
2164                                            clidp->data, clidp->len);
2165
2166       if (!silc_idlist_del_channel(server->local_list, channel))
2167         silc_idlist_del_channel(server->global_list, channel);
2168       silc_buffer_free(clidp);
2169       server->stat.my_channels--;
2170       return FALSE;
2171     }
2172
2173     /* Send notify to channel about client leaving the channel */
2174     if (notify)
2175       silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2176                                          SILC_NOTIFY_TYPE_LEAVE, 1,
2177                                          clidp->data, clidp->len);
2178     break;
2179   }
2180
2181   silc_buffer_free(clidp);
2182   return TRUE;
2183 }
2184
2185 /* Returns TRUE if the given client is on the channel.  FALSE if not. 
2186    This works because we assure that the user list on the channel is
2187    always in up to date thus we can only check the channel list from 
2188    `client' which is faster than checking the user list from `channel'. */
2189
2190 int silc_server_client_on_channel(SilcClientEntry client,
2191                                   SilcChannelEntry channel)
2192 {
2193   SilcChannelClientEntry chl;
2194
2195   if (!client || !channel)
2196     return FALSE;
2197
2198   silc_list_start(client->channels);
2199   while ((chl = silc_list_get(client->channels)) != SILC_LIST_END)
2200     if (chl->channel == channel)
2201       return TRUE;
2202
2203   return FALSE;
2204 }
2205
2206 /* Timeout callback. This is called if connection is idle or for some
2207    other reason is not responding within some period of time. This 
2208    disconnects the remote end. */
2209
2210 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2211 {
2212   SilcServer server = (SilcServer)context;
2213   SilcSocketConnection sock = server->sockets[fd];
2214
2215   if (!sock)
2216     return;
2217
2218   if (sock->user_data)
2219     silc_server_free_sock_user_data(server, sock);
2220
2221   silc_server_disconnect_remote(server, sock, 
2222                                 "Server closed connection: "
2223                                 "Connection timeout");
2224 }
2225
2226 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
2227    function may be used only by router. In real SILC network all channels
2228    are created by routers thus this function is never used by normal
2229    server. */
2230
2231 SilcChannelEntry silc_server_create_new_channel(SilcServer server, 
2232                                                 SilcServerID *router_id,
2233                                                 char *cipher, 
2234                                                 char *channel_name,
2235                                                 int broadcast)
2236 {
2237   SilcChannelID *channel_id;
2238   SilcChannelEntry entry;
2239   SilcCipher key;
2240
2241   SILC_LOG_DEBUG(("Creating new channel"));
2242
2243   if (!cipher)
2244     cipher = "aes-256-cbc";
2245
2246   /* Allocate cipher */
2247   if (!silc_cipher_alloc(cipher, &key))
2248     return NULL;
2249
2250   channel_name = strdup(channel_name);
2251
2252   /* Create the channel */
2253   silc_id_create_channel_id(router_id, server->rng, &channel_id);
2254   entry = silc_idlist_add_channel(server->local_list, channel_name, 
2255                                   SILC_CHANNEL_MODE_NONE, channel_id, 
2256                                   NULL, key);
2257   if (!entry) {
2258     silc_free(channel_name);
2259     return NULL;
2260   }
2261
2262   /* Now create the actual key material */
2263   silc_server_create_channel_key(server, entry, 32);
2264
2265   /* Notify other routers about the new channel. We send the packet
2266      to our primary route. */
2267   if (broadcast && server->standalone == FALSE) {
2268     silc_server_send_new_channel(server, server->router->connection, TRUE, 
2269                                  channel_name, entry->id, SILC_ID_CHANNEL_LEN);
2270   }
2271
2272   server->stat.my_channels++;
2273
2274   return entry;
2275 }
2276
2277 /* Same as above but creates the channel with Channel ID `channel_id. */
2278
2279 SilcChannelEntry 
2280 silc_server_create_new_channel_with_id(SilcServer server, 
2281                                        char *cipher, 
2282                                        char *channel_name,
2283                                        SilcChannelID *channel_id,
2284                                        int broadcast)
2285 {
2286   SilcChannelEntry entry;
2287   SilcCipher key;
2288
2289   SILC_LOG_DEBUG(("Creating new channel"));
2290
2291   if (!cipher)
2292     cipher = "aes-256-cbc";
2293
2294   /* Allocate cipher */
2295   if (!silc_cipher_alloc(cipher, &key))
2296     return NULL;
2297
2298   channel_name = strdup(channel_name);
2299
2300   /* Create the channel */
2301   entry = silc_idlist_add_channel(server->local_list, channel_name, 
2302                                   SILC_CHANNEL_MODE_NONE, channel_id, 
2303                                   NULL, key);
2304   if (!entry) {
2305     silc_free(channel_name);
2306     return NULL;
2307   }
2308
2309   /* Now create the actual key material */
2310   silc_server_create_channel_key(server, entry, 32);
2311
2312   /* Notify other routers about the new channel. We send the packet
2313      to our primary route. */
2314   if (broadcast && server->standalone == FALSE) {
2315     silc_server_send_new_channel(server, server->router->connection, TRUE, 
2316                                  channel_name, entry->id, SILC_ID_CHANNEL_LEN);
2317   }
2318
2319   server->stat.my_channels++;
2320
2321   return entry;
2322 }
2323
2324 /* Generates new channel key. This is used to create the initial channel key
2325    but also to re-generate new key for channel. If `key_len' is provided
2326    it is the bytes of the key length. */
2327
2328 void silc_server_create_channel_key(SilcServer server, 
2329                                     SilcChannelEntry channel,
2330                                     unsigned int key_len)
2331 {
2332   int i;
2333   unsigned char channel_key[32];
2334   unsigned int len;
2335
2336   if (!channel->channel_key)
2337     silc_cipher_alloc("aes-256-cbc", &channel->channel_key);
2338
2339   if (key_len)
2340     len = key_len;
2341   else if (channel->key_len)
2342     len = channel->key_len / 8;
2343   else
2344     len = sizeof(channel_key);
2345
2346   /* Create channel key */
2347   for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
2348   
2349   /* Set the key */
2350   channel->channel_key->cipher->set_key(channel->channel_key->context, 
2351                                         channel_key, len);
2352
2353   /* Remove old key if exists */
2354   if (channel->key) {
2355     memset(channel->key, 0, channel->key_len / 8);
2356     silc_free(channel->key);
2357   }
2358
2359   /* Save the key */
2360   channel->key_len = len * 8;
2361   channel->key = silc_calloc(len, sizeof(*channel->key));
2362   memcpy(channel->key, channel_key, len);
2363   memset(channel_key, 0, sizeof(channel_key));
2364 }
2365
2366 /* Saves the channel key found in the encoded `key_payload' buffer. This 
2367    function is used when we receive Channel Key Payload and also when we're
2368    processing JOIN command reply. Returns entry to the channel. */
2369
2370 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
2371                                               SilcBuffer key_payload,
2372                                               SilcChannelEntry channel)
2373 {
2374   SilcChannelKeyPayload payload = NULL;
2375   SilcChannelID *id = NULL;
2376   unsigned char *tmp;
2377   unsigned int tmp_len;
2378   char *cipher;
2379
2380   /* Decode channel key payload */
2381   payload = silc_channel_key_payload_parse(key_payload);
2382   if (!payload) {
2383     SILC_LOG_ERROR(("Bad channel key payload, dropped"));
2384     channel = NULL;
2385     goto out;
2386   }
2387
2388   /* Get the channel entry */
2389   if (!channel) {
2390
2391     /* Get channel ID */
2392     tmp = silc_channel_key_get_id(payload, &tmp_len);
2393     id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
2394     if (!id) {
2395       channel = NULL;
2396       goto out;
2397     }
2398
2399     channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
2400     if (!channel) {
2401       channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
2402       if (!channel) {
2403         SILC_LOG_ERROR(("Received key for non-existent channel"));
2404         goto out;
2405       }
2406     }
2407   }
2408
2409   tmp = silc_channel_key_get_key(payload, &tmp_len);
2410   if (!tmp) {
2411     channel = NULL;
2412     goto out;
2413   }
2414
2415   cipher = silc_channel_key_get_cipher(payload, NULL);
2416   if (!cipher) {
2417     channel = NULL;
2418     goto out;
2419   }
2420
2421   /* Remove old key if exists */
2422   if (channel->key) {
2423     memset(channel->key, 0, channel->key_len / 8);
2424     silc_free(channel->key);
2425     silc_cipher_free(channel->channel_key);
2426   }
2427
2428   /* Create new cipher */
2429   if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
2430     channel = NULL;
2431     goto out;
2432   }
2433
2434   /* Save the key */
2435   channel->key_len = tmp_len * 8;
2436   channel->key = silc_calloc(tmp_len, sizeof(unsigned char));
2437   memcpy(channel->key, tmp, tmp_len);
2438   channel->channel_key->cipher->set_key(channel->channel_key->context, 
2439                                         tmp, tmp_len);
2440
2441  out:
2442   if (id)
2443     silc_free(id);
2444   if (payload)
2445     silc_channel_key_payload_free(payload);
2446
2447   return channel;
2448 }
2449
2450 /* Heartbeat callback. This function is set as argument for the
2451    silc_socket_set_heartbeat function. The library will call this function
2452    at the set time interval. */
2453
2454 void silc_server_perform_heartbeat(SilcSocketConnection sock,
2455                                    void *hb_context)
2456 {
2457   SilcServerHBContext hb = (SilcServerHBContext)hb_context;
2458
2459   SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname,
2460                   sock->ip));
2461
2462   /* Send the heartbeat */
2463   silc_server_send_heartbeat(hb->server, sock);
2464 }
2465
2466 /* Returns assembled of all servers in the given ID list. The packet's
2467    form is dictated by the New ID payload. */
2468
2469 static void silc_server_announce_get_servers(SilcServer server,
2470                                              SilcIDList id_list,
2471                                              SilcBuffer *servers)
2472 {
2473   SilcIDCacheList list;
2474   SilcIDCacheEntry id_cache;
2475   SilcServerEntry entry;
2476   SilcBuffer idp;
2477
2478   /* Go through all clients in the list */
2479   if (silc_idcache_find_by_id(id_list->clients, SILC_ID_CACHE_ANY, 
2480                               SILC_ID_SERVER, &list)) {
2481     if (silc_idcache_list_first(list, &id_cache)) {
2482       while (id_cache) {
2483         entry = (SilcServerEntry)id_cache->context;
2484
2485         idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
2486
2487         *servers = silc_buffer_realloc(*servers, 
2488                                        (*servers ? 
2489                                         (*servers)->truelen + idp->len : 
2490                                         idp->len));
2491         silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
2492         silc_buffer_put(*servers, idp->data, idp->len);
2493         silc_buffer_pull(*servers, idp->len);
2494         silc_buffer_free(idp);
2495
2496         if (!silc_idcache_list_next(list, &id_cache))
2497           break;
2498       }
2499     }
2500
2501     silc_idcache_list_free(list);
2502   }
2503 }
2504
2505 /* This function is used by router to announce existing servers to our
2506    primary router when we've connected to it. */
2507
2508 void silc_server_announce_servers(SilcServer server)
2509 {
2510   SilcBuffer servers = NULL;
2511
2512   SILC_LOG_DEBUG(("Announcing servers"));
2513
2514   /* Get servers in local list */
2515   silc_server_announce_get_servers(server, server->local_list, &servers);
2516
2517   /* Get servers in global list */
2518   silc_server_announce_get_servers(server, server->global_list, &servers);
2519
2520   if (servers) {
2521     silc_buffer_push(servers, servers->data - servers->head);
2522     SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
2523
2524     /* Send the packet */
2525     silc_server_packet_send(server, server->router->connection,
2526                             SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
2527                             servers->data, servers->len, TRUE);
2528
2529     silc_buffer_free(servers);
2530   }
2531 }
2532
2533 /* Returns assembled packet of all clients in the given ID list. The
2534    packet's form is dictated by the New ID Payload. */
2535
2536 static void silc_server_announce_get_clients(SilcServer server,
2537                                              SilcIDList id_list,
2538                                              SilcBuffer *clients)
2539 {
2540   SilcIDCacheList list;
2541   SilcIDCacheEntry id_cache;
2542   SilcClientEntry client;
2543   SilcBuffer idp;
2544
2545   /* Go through all clients in the list */
2546   if (silc_idcache_find_by_id(id_list->clients, SILC_ID_CACHE_ANY, 
2547                               SILC_ID_CLIENT, &list)) {
2548     if (silc_idcache_list_first(list, &id_cache)) {
2549       while (id_cache) {
2550         client = (SilcClientEntry)id_cache->context;
2551
2552         idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2553
2554         *clients = silc_buffer_realloc(*clients, 
2555                                        (*clients ? 
2556                                         (*clients)->truelen + idp->len : 
2557                                         idp->len));
2558         silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
2559         silc_buffer_put(*clients, idp->data, idp->len);
2560         silc_buffer_pull(*clients, idp->len);
2561         silc_buffer_free(idp);
2562
2563         if (!silc_idcache_list_next(list, &id_cache))
2564           break;
2565       }
2566     }
2567
2568     silc_idcache_list_free(list);
2569   }
2570 }
2571
2572 /* This function is used to announce our existing clients to our router
2573    when we've connected to it. */
2574
2575 void silc_server_announce_clients(SilcServer server)
2576 {
2577   SilcBuffer clients = NULL;
2578
2579   SILC_LOG_DEBUG(("Announcing clients"));
2580
2581   /* Get clients in local list */
2582   silc_server_announce_get_clients(server, server->local_list,
2583                                    &clients);
2584
2585   /* As router we announce our global list as well */
2586   if (server->server_type == SILC_ROUTER)
2587     silc_server_announce_get_clients(server, server->global_list,
2588                                      &clients);
2589
2590   if (clients) {
2591     silc_buffer_push(clients, clients->data - clients->head);
2592     SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
2593
2594     /* Send the packet */
2595     silc_server_packet_send(server, server->router->connection,
2596                             SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
2597                             clients->data, clients->len, TRUE);
2598
2599     silc_buffer_free(clients);
2600   }
2601 }
2602
2603 static SilcBuffer 
2604 silc_server_announce_encode_join(unsigned int argc, ...)
2605 {
2606   va_list ap;
2607
2608   va_start(ap, argc);
2609   return silc_notify_payload_encode(SILC_NOTIFY_TYPE_JOIN, argc, ap);
2610 }
2611
2612 /* Returns assembled packets for all channels and users on those channels
2613    from the given ID List. The packets are in the form dictated by the
2614    New Channel and New Channel User payloads. */
2615
2616 static void silc_server_announce_get_channels(SilcServer server,
2617                                               SilcIDList id_list,
2618                                               SilcBuffer *channels,
2619                                               SilcBuffer *channel_users)
2620 {
2621   SilcIDCacheList list;
2622   SilcIDCacheEntry id_cache;
2623   SilcChannelEntry channel;
2624   SilcChannelClientEntry chl;
2625   SilcBuffer chidp;
2626   unsigned char *cid;
2627   unsigned short name_len;
2628   int len;
2629
2630   /* Go through all channels in the list */
2631   if (silc_idcache_find_by_id(id_list->channels, SILC_ID_CACHE_ANY, 
2632                               SILC_ID_CHANNEL, &list)) {
2633     if (silc_idcache_list_first(list, &id_cache)) {
2634       while (id_cache) {
2635         channel = (SilcChannelEntry)id_cache->context;
2636         
2637         cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
2638         name_len = strlen(channel->channel_name);
2639
2640         len = 4 + name_len + SILC_ID_CHANNEL_LEN;
2641         *channels = 
2642           silc_buffer_realloc(*channels, 
2643                               (*channels ? (*channels)->truelen + len : len));
2644         silc_buffer_pull_tail(*channels, 
2645                               ((*channels)->end - (*channels)->data));
2646         silc_buffer_format(*channels,
2647                            SILC_STR_UI_SHORT(name_len),
2648                            SILC_STR_UI_XNSTRING(channel->channel_name, 
2649                                                 name_len),
2650                            SILC_STR_UI_SHORT(SILC_ID_CHANNEL_LEN),
2651                            SILC_STR_UI_XNSTRING(cid, SILC_ID_CHANNEL_LEN),
2652                            SILC_STR_END);
2653         silc_buffer_pull(*channels, len);
2654
2655         /* Now find all users on the channel */
2656         chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
2657         silc_list_start(channel->user_list);
2658         while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2659           SilcBuffer clidp;
2660           SilcBuffer tmp;
2661
2662           clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
2663
2664           tmp = silc_server_announce_encode_join(2, clidp->data, clidp->len,
2665                                                  chidp->data, chidp->len);
2666           len = tmp->len;
2667           *channel_users = 
2668             silc_buffer_realloc(*channel_users, 
2669                                 (*channel_users ? 
2670                                  (*channel_users)->truelen + len : len));
2671           silc_buffer_pull_tail(*channel_users, 
2672                                 ((*channel_users)->end - 
2673                                  (*channel_users)->data));
2674
2675           silc_buffer_put(*channel_users, tmp->data, tmp->len);
2676           silc_buffer_pull(*channel_users, len);
2677           silc_buffer_free(clidp);
2678           silc_buffer_free(tmp);
2679         }
2680         silc_buffer_free(chidp);
2681
2682         silc_free(cid);
2683
2684         if (!silc_idcache_list_next(list, &id_cache))
2685           break;
2686       }
2687     }
2688
2689     silc_idcache_list_free(list);
2690   }
2691 }
2692
2693 /* This function is used to announce our existing channels to our router
2694    when we've connected to it. This also announces the users on the
2695    channels to the router. */
2696
2697 void silc_server_announce_channels(SilcServer server)
2698 {
2699   SilcBuffer channels = NULL, channel_users = NULL;
2700
2701   SILC_LOG_DEBUG(("Announcing channels and channel users"));
2702
2703   /* Get channels and channel users in local list */
2704   silc_server_announce_get_channels(server, server->local_list,
2705                                     &channels, &channel_users);
2706
2707   /* Get channels and channel users in global list */
2708   silc_server_announce_get_channels(server, server->global_list,
2709                                     &channels, &channel_users);
2710
2711   if (channels) {
2712     silc_buffer_push(channels, channels->data - channels->head);
2713     SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
2714
2715     /* Send the packet */
2716     silc_server_packet_send(server, server->router->connection,
2717                             SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
2718                             channels->data, channels->len,
2719                             FALSE);
2720
2721     silc_buffer_free(channels);
2722   }
2723
2724   if (channel_users) {
2725     silc_buffer_push(channel_users, channel_users->data - channel_users->head);
2726     SILC_LOG_HEXDUMP(("channel users"), channel_users->data, 
2727                      channel_users->len);
2728
2729     /* Send the packet */
2730     silc_server_packet_send(server, server->router->connection,
2731                             SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
2732                             channel_users->data, channel_users->len,
2733                             FALSE);
2734
2735     silc_buffer_free(channel_users);
2736   }
2737 }