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 SILC_TASK_CALLBACK(silc_server_failure_callback);
42 SILC_TASK_CALLBACK(silc_server_rekey_callback);
43
44 /* Allocates a new SILC server object. This has to be done before the server
45    can be used. After allocation one must call silc_server_init to initialize
46    the server. The new allocated server object is returned to the new_server
47    argument. */
48
49 int silc_server_alloc(SilcServer *new_server)
50 {
51   SilcServer server;
52
53   SILC_LOG_DEBUG(("Allocating new server object"));
54
55   server = silc_calloc(1, sizeof(*server));
56   server->server_type = SILC_SERVER;
57   server->standalone = TRUE;
58   server->local_list = silc_calloc(1, sizeof(*server->local_list));
59   server->global_list = silc_calloc(1, sizeof(*server->global_list));
60   server->pending_commands = silc_dlist_init();
61 #ifdef SILC_SIM
62   server->sim = silc_dlist_init();
63 #endif
64
65   *new_server = server;
66
67   return TRUE;
68 }
69
70 /* Free's the SILC server object. This is called at the very end before
71    the program ends. */
72
73 void silc_server_free(SilcServer server)
74 {
75   if (server) {
76 #ifdef SILC_SIM
77     SilcSimContext *sim;
78 #endif
79
80     if (server->local_list)
81       silc_free(server->local_list);
82     if (server->global_list)
83       silc_free(server->global_list);
84     if (server->rng)
85       silc_rng_free(server->rng);
86
87 #ifdef SILC_SIM
88     while ((sim = silc_dlist_get(server->sim)) != SILC_LIST_END) {
89       silc_dlist_del(server->sim, sim);
90       silc_sim_free(sim);
91     }
92     silc_dlist_uninit(server->sim);
93 #endif
94
95     if (server->params)
96       silc_free(server->params);
97
98     if (server->pending_commands)
99       silc_dlist_uninit(server->pending_commands);
100
101     silc_free(server);
102   }
103 }
104
105 /* Initializes the entire SILC server. This is called always before running
106    the server. This is called only once at the initialization of the program.
107    This binds the server to its listenning port. After this function returns 
108    one should call silc_server_run to start the server. This returns TRUE 
109    when everything is ok to run the server. Configuration file must be
110    read and parsed before calling this. */
111
112 int silc_server_init(SilcServer server)
113 {
114   int *sock = NULL, sock_count = 0, i;
115   SilcServerID *id;
116   SilcServerEntry id_entry;
117   SilcIDListPurge purge;
118
119   SILC_LOG_DEBUG(("Initializing server"));
120   assert(server);
121   assert(server->config);
122
123   /* Set public and private keys */
124   if (!server->config->server_keys ||
125       !server->config->server_keys->public_key || 
126       !server->config->server_keys->private_key) {
127     SILC_LOG_ERROR(("Server public key and/or private key does not exist"));
128     return FALSE;
129   }
130   server->public_key = server->config->server_keys->public_key;
131   server->private_key = server->config->server_keys->private_key;
132
133   /* XXX After server is made as Silc Server Library this can be given
134      as argument, for now this is hard coded */
135   server->params = silc_calloc(1, sizeof(*server->params));
136   server->params->retry_count = SILC_SERVER_RETRY_COUNT;
137   server->params->retry_interval_min = SILC_SERVER_RETRY_INTERVAL_MIN;
138   server->params->retry_interval_max = SILC_SERVER_RETRY_INTERVAL_MAX;
139   server->params->retry_keep_trying = FALSE;
140   server->params->protocol_timeout = 60;
141   server->params->require_reverse_mapping = FALSE;
142
143   /* Set log files where log message should be saved. */
144   server->config->server = server;
145   silc_server_config_setlogfiles(server->config);
146  
147   /* Register all configured ciphers, PKCS and hash functions. */
148   silc_server_config_register_ciphers(server->config);
149   silc_server_config_register_pkcs(server->config);
150   silc_server_config_register_hashfuncs(server->config);
151   silc_server_config_register_hmacs(server->config);
152
153   /* Initialize random number generator for the server. */
154   server->rng = silc_rng_alloc();
155   silc_rng_init(server->rng);
156   silc_rng_global_init(server->rng);
157
158   /* Initialize hash functions for server to use */
159   silc_hash_alloc("md5", &server->md5hash);
160   silc_hash_alloc("sha1", &server->sha1hash);
161
162   /* Initialize none cipher */
163   silc_cipher_alloc("none", &server->none_cipher);
164
165   /* Create a listening server. Note that our server can listen on
166      multiple ports. All listeners are created here and now. */
167   /* XXX Still check this whether to use server_info or listen_port. */
168   sock_count = 0;
169   while(server->config->listen_port) {
170     int tmp;
171
172     tmp = silc_net_create_server(server->config->listen_port->port,
173                                  server->config->listen_port->host);
174     if (tmp < 0)
175       goto err0;
176
177     sock = silc_realloc(sock, (sizeof(int *) * (sock_count + 1)));
178     sock[sock_count] = tmp;
179     server->config->listen_port = server->config->listen_port->next;
180     sock_count++;
181   }
182
183   /* Initialize ID caches */
184   server->local_list->clients = 
185     silc_idcache_alloc(0, silc_idlist_client_destructor);
186   server->local_list->servers = silc_idcache_alloc(0, NULL);
187   server->local_list->channels = silc_idcache_alloc(0, NULL);
188
189   /* These are allocated for normal server as well as these hold some 
190      global information that the server has fetched from its router. For 
191      router these are used as they are supposed to be used on router. */
192   server->global_list->clients = 
193     silc_idcache_alloc(0, silc_idlist_client_destructor);
194   server->global_list->servers = silc_idcache_alloc(0, NULL);
195   server->global_list->channels = silc_idcache_alloc(0, NULL);
196
197   /* Allocate the entire socket list that is used in server. Eventually 
198      all connections will have entry in this table (it is a table of 
199      pointers to the actual object that is allocated individually 
200      later). */
201   server->sockets = silc_calloc(SILC_SERVER_MAX_CONNECTIONS,
202                                 sizeof(*server->sockets));
203
204   for (i = 0; i < sock_count; i++) {
205     SilcSocketConnection newsocket = NULL;
206
207     /* Set socket to non-blocking mode */
208     silc_net_set_socket_nonblock(sock[i]);
209     server->sock = sock[i];
210     
211     /* Create a Server ID for the server. */
212     silc_id_create_server_id(sock[i], server->rng, &id);
213     if (!id) {
214       goto err0;
215     }
216     
217     server->id = id;
218     server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
219     server->id_string_len = silc_id_get_len(SILC_ID_SERVER);
220     server->id_type = SILC_ID_SERVER;
221     server->server_name = server->config->server_info->server_name;
222
223     /* Add ourselves to the server list. We don't have a router yet 
224        beacuse we haven't established a route yet. It will be done later. 
225        For now, NULL is sent as router. This allocates new entry to
226        the ID list. */
227     id_entry = 
228       silc_idlist_add_server(server->local_list,
229                              server->config->server_info->server_name,
230                              server->server_type, server->id, NULL, NULL);
231     if (!id_entry) {
232       SILC_LOG_ERROR(("Could not add ourselves to cache"));
233       goto err0;
234     }
235     
236     /* Add ourselves also to the socket table. The entry allocated above
237        is sent as argument for fast referencing in the future. */
238     silc_socket_alloc(sock[i], SILC_SOCKET_TYPE_SERVER, id_entry, 
239                       &newsocket);
240
241     server->sockets[sock[i]] = newsocket;
242     
243     /* Perform name and address lookups to resolve the listenning address
244        and port. */
245     if (!silc_net_check_local_by_sock(sock[i], &newsocket->hostname, 
246                                      &newsocket->ip)) {
247       if ((server->params->require_reverse_mapping && !newsocket->hostname) ||
248           !newsocket->ip) {
249         SILC_LOG_ERROR(("IP/DNS lookup failed for local host %s",
250                         newsocket->hostname ? newsocket->hostname :
251                         newsocket->ip ? newsocket->ip : ""));
252         server->stat.conn_failures++;
253         goto err0;
254       }
255       if (!newsocket->hostname)
256         newsocket->hostname = strdup(newsocket->ip);
257     }
258     newsocket->port = silc_net_get_local_port(sock[i]);
259
260     /* Put the allocated socket pointer also to the entry allocated above 
261        for fast back-referencing to the socket list. */
262     id_entry->connection = (void *)server->sockets[sock[i]];
263     server->id_entry = id_entry;
264   }
265
266   /* Register the task queues. In SILC we have by default three task queues. 
267      One task queue for non-timeout tasks which perform different kind of 
268      I/O on file descriptors, timeout task queue for timeout tasks, and,
269      generic non-timeout task queue whose tasks apply to all connections. */
270   silc_task_queue_alloc(&server->io_queue, TRUE);
271   if (!server->io_queue) {
272     goto err0;
273   }
274   silc_task_queue_alloc(&server->timeout_queue, TRUE);
275   if (!server->timeout_queue) {
276     goto err1;
277   }
278   silc_task_queue_alloc(&server->generic_queue, TRUE);
279   if (!server->generic_queue) {
280     goto err1;
281   }
282
283   /* Register protocols */
284   silc_server_protocols_register();
285
286   /* Initialize the scheduler */
287   silc_schedule_init(&server->io_queue, &server->timeout_queue, 
288                      &server->generic_queue, 
289                      SILC_SERVER_MAX_CONNECTIONS);
290   
291   /* Add the first task to the queue. This is task that is executed by
292      timeout. It expires as soon as the caller calls silc_server_run. This
293      task performs authentication protocol and key exchange with our
294      primary router. */
295   silc_task_register(server->timeout_queue, sock[0], 
296                      silc_server_connect_to_router,
297                      (void *)server, 0, 1,
298                      SILC_TASK_TIMEOUT,
299                      SILC_TASK_PRI_NORMAL);
300
301   /* Add listener task to the queue. This task receives new connections to the 
302      server. This task remains on the queue until the end of the program. */
303   silc_task_register(server->io_queue, sock[0],
304                      silc_server_accept_new_connection,
305                      (void *)server, 0, 0, 
306                      SILC_TASK_FD,
307                      SILC_TASK_PRI_NORMAL);
308   server->listenning = TRUE;
309
310   /* If server connections has been configured then we must be router as
311      normal server cannot have server connections, only router connections. */
312   if (server->config->servers)
313     server->server_type = SILC_ROUTER;
314
315   /* Register the ID Cache purge task. This periodically purges the ID cache
316      and removes the expired cache entries. */
317
318   /* Clients local list */
319   purge = silc_calloc(1, sizeof(*purge));
320   purge->cache = server->local_list->clients;
321   purge->timeout_queue = server->timeout_queue;
322   silc_task_register(purge->timeout_queue, 0, 
323                      silc_idlist_purge,
324                      (void *)purge, 600, 0,
325                      SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
326
327   /* Clients global list */
328   purge = silc_calloc(1, sizeof(*purge));
329   purge->cache = server->global_list->clients;
330   purge->timeout_queue = server->timeout_queue;
331   silc_task_register(purge->timeout_queue, 0, 
332                      silc_idlist_purge,
333                      (void *)purge, 300, 0,
334                      SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
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   SILC_LOG_INFO(("Connecting to the router %s on port %d", 
537                  sconn->remote_host, sconn->remote_port));
538
539   /* Connect to remote host */
540   sock = silc_net_create_connection(sconn->remote_port, 
541                                     sconn->remote_host);
542   if (sock < 0) {
543     SILC_LOG_ERROR(("Could not connect to router"));
544     silc_task_register(server->timeout_queue, fd, 
545                        silc_server_connect_to_router_retry,
546                        context, 0, 1, SILC_TASK_TIMEOUT, 
547                        SILC_TASK_PRI_NORMAL);
548     return;
549   }
550
551   /* Set socket options */
552   silc_net_set_socket_nonblock(sock);
553   silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
554
555   /* Create socket connection for the connection. Even though we
556      know that we are connecting to a router we will mark the socket
557      to be unknown connection until we have executed authentication
558      protocol. */
559   silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
560   server->sockets[sock] = newsocket;
561   newsocket->hostname = strdup(sconn->remote_host);
562   newsocket->ip = strdup(sconn->remote_host);
563   newsocket->port = sconn->remote_port;
564   sconn->sock = newsocket;
565
566   /* Allocate internal protocol context. This is sent as context
567      to the protocol. */
568   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
569   proto_ctx->server = (void *)server;
570   proto_ctx->context = (void *)sconn;
571   proto_ctx->sock = newsocket;
572   proto_ctx->rng = server->rng;
573   proto_ctx->responder = FALSE;
574       
575   /* Perform key exchange protocol. silc_server_connect_to_router_second
576      will be called after the protocol is finished. */
577   silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE, 
578                       &protocol, proto_ctx,
579                       silc_server_connect_to_router_second);
580   newsocket->protocol = protocol;
581       
582   /* Register a timeout task that will be executed if the protocol
583      is not executed within set limit. */
584   proto_ctx->timeout_task = 
585     silc_task_register(server->timeout_queue, sock, 
586                        silc_server_timeout_remote,
587                        server, server->params->protocol_timeout,
588                        server->params->protocol_timeout_usec,
589                        SILC_TASK_TIMEOUT,
590                        SILC_TASK_PRI_LOW);
591
592   /* Register the connection for network input and output. This sets
593      that scheduler will listen for incoming packets for this connection 
594      and sets that outgoing packets may be sent to this connection as 
595      well. However, this doesn't set the scheduler for outgoing traffic,
596      it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
597      later when outgoing data is available. */
598   context = (void *)server;
599   SILC_REGISTER_CONNECTION_FOR_IO(sock);
600   
601   /* Run the protocol */
602   protocol->execute(server->timeout_queue, 0, protocol, sock, 0, 0);
603 }
604   
605 /* This function connects to our primary router or if we are a router this
606    establishes all our primary routes. This is called at the start of the
607    server to do authentication and key exchange with our router - called
608    from schedule. */
609
610 SILC_TASK_CALLBACK(silc_server_connect_to_router)
611 {
612   SilcServer server = (SilcServer)context;
613   SilcServerConnection sconn;
614
615   SILC_LOG_DEBUG(("Connecting to router(s)"));
616
617   /* If we are normal SILC server we need to connect to our cell's
618      router. */
619   if (server->server_type == SILC_SERVER) {
620     SILC_LOG_DEBUG(("We are normal server"));
621
622     /* Create connection to the router, if configured. */
623     if (server->config->routers) {
624
625       /* Allocate connection object for hold connection specific stuff. */
626       sconn = silc_calloc(1, sizeof(*sconn));
627       sconn->server = server;
628       sconn->remote_host = strdup(server->config->routers->host);
629       sconn->remote_port = server->config->routers->port;
630
631       silc_task_register(server->timeout_queue, fd, 
632                          silc_server_connect_router,
633                          (void *)sconn, 0, 1, SILC_TASK_TIMEOUT, 
634                          SILC_TASK_PRI_NORMAL);
635       return;
636     }
637   }
638
639   /* If we are a SILC router we need to establish all of our primary
640      routes. */
641   if (server->server_type == SILC_ROUTER) {
642     SilcServerConfigSectionServerConnection *ptr;
643
644     SILC_LOG_DEBUG(("We are router"));
645
646     /* Create the connections to all our routes */
647     ptr = server->config->routers;
648     while (ptr) {
649
650       SILC_LOG_DEBUG(("Router connection [%s] %s:%d",
651                       ptr->initiator ? "Initiator" : "Responder",
652                       ptr->host, ptr->port));
653
654       if (ptr->initiator) {
655         /* Allocate connection object for hold connection specific stuff. */
656         sconn = silc_calloc(1, sizeof(*sconn));
657         sconn->server = server;
658         sconn->remote_host = strdup(ptr->host);
659         sconn->remote_port = ptr->port;
660
661         silc_task_register(server->timeout_queue, fd, 
662                            silc_server_connect_router,
663                            (void *)sconn, 0, 1, SILC_TASK_TIMEOUT, 
664                            SILC_TASK_PRI_NORMAL);
665       }
666
667       if (!ptr->next)
668         return;
669
670       ptr = ptr->next;
671     }
672   }
673
674   SILC_LOG_DEBUG(("No router(s), server will be standalone"));
675   
676   /* There wasn't a configured router, we will continue but we don't
677      have a connection to outside world.  We will be standalone server. */
678   server->standalone = TRUE;
679 }
680
681 /* Second part of connecting to router(s). Key exchange protocol has been
682    executed and now we will execute authentication protocol. */
683
684 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
685 {
686   SilcProtocol protocol = (SilcProtocol)context;
687   SilcServerKEInternalContext *ctx = 
688     (SilcServerKEInternalContext *)protocol->context;
689   SilcServer server = (SilcServer)ctx->server;
690   SilcServerConnection sconn = (SilcServerConnection)ctx->context;
691   SilcSocketConnection sock = server->sockets[fd];
692   SilcServerConnAuthInternalContext *proto_ctx;
693   SilcServerConfigSectionServerConnection *conn = NULL;
694
695   SILC_LOG_DEBUG(("Start"));
696
697   if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
698       protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
699     /* Error occured during protocol */
700     silc_protocol_free(protocol);
701     sock->protocol = NULL;
702     silc_ske_free_key_material(ctx->keymat);
703     if (ctx->packet)
704       silc_packet_context_free(ctx->packet);
705     if (ctx->ske)
706       silc_ske_free(ctx->ske);
707     if (ctx->dest_id)
708       silc_free(ctx->dest_id);
709     silc_free(ctx);
710     silc_task_unregister_by_callback(server->timeout_queue,
711                                      silc_server_failure_callback);
712     silc_server_disconnect_remote(server, sock, "Server closed connection: "
713                                   "Key exchange failed");
714     return;
715   }
716   
717   /* We now have the key material as the result of the key exchange
718      protocol. Take the key material into use. Free the raw key material
719      as soon as we've set them into use. */
720   if (!silc_server_protocol_ke_set_keys(ctx->ske, ctx->sock, ctx->keymat,
721                                         ctx->ske->prop->cipher,
722                                         ctx->ske->prop->pkcs,
723                                         ctx->ske->prop->hash,
724                                         ctx->ske->prop->hmac,
725                                         ctx->ske->prop->group,
726                                         ctx->responder)) {
727     silc_protocol_free(protocol);
728     sock->protocol = NULL;
729     silc_ske_free_key_material(ctx->keymat);
730     if (ctx->packet)
731       silc_packet_context_free(ctx->packet);
732     if (ctx->ske)
733       silc_ske_free(ctx->ske);
734     if (ctx->dest_id)
735       silc_free(ctx->dest_id);
736     silc_free(ctx);
737     silc_task_unregister_by_callback(server->timeout_queue,
738                                      silc_server_failure_callback);
739     silc_server_disconnect_remote(server, sock, "Server closed connection: "
740                                   "Key exchange failed");
741     return;
742   }    
743   silc_ske_free_key_material(ctx->keymat);
744
745   /* Allocate internal context for the authentication protocol. This
746      is sent as context for the protocol. */
747   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
748   proto_ctx->server = (void *)server;
749   proto_ctx->context = (void *)sconn;
750   proto_ctx->sock = sock;
751   proto_ctx->ske = ctx->ske;       /* Save SKE object from previous protocol */
752   proto_ctx->dest_id_type = ctx->dest_id_type;
753   proto_ctx->dest_id = ctx->dest_id;
754
755   /* Resolve the authentication method used in this connection. Check if 
756      we find a match from user configured connections */
757   conn = silc_server_config_find_router_conn(server->config,
758                                              sock->hostname,
759                                              sock->port);
760   if (conn) {
761     /* Match found. Use the configured authentication method */
762     proto_ctx->auth_meth = conn->auth_meth;
763     if (conn->auth_data) {
764       proto_ctx->auth_data = strdup(conn->auth_data);
765       proto_ctx->auth_data_len = strlen(conn->auth_data);
766     }
767   } else {
768     SILC_LOG_ERROR(("Could not find connection data for %s (%s) on port",
769                     sock->hostname, sock->ip, sock->port));
770     silc_protocol_free(protocol);
771     sock->protocol = NULL;
772     if (ctx->packet)
773       silc_packet_context_free(ctx->packet);
774     if (ctx->ske)
775       silc_ske_free(ctx->ske);
776     if (ctx->dest_id)
777       silc_free(ctx->dest_id);
778     silc_free(ctx);
779     silc_task_unregister_by_callback(server->timeout_queue,
780                                      silc_server_failure_callback);
781     silc_server_disconnect_remote(server, sock, "Server closed connection: "
782                                   "Key exchange failed");
783     return;
784   }
785
786   /* Free old protocol as it is finished now */
787   silc_protocol_free(protocol);
788   if (ctx->packet)
789     silc_packet_context_free(ctx->packet);
790   silc_free(ctx);
791   sock->protocol = NULL;
792
793   /* Allocate the authentication protocol. This is allocated here
794      but we won't start it yet. We will be receiving party of this
795      protocol thus we will wait that connecting party will make
796      their first move. */
797   silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH, 
798                       &sock->protocol, proto_ctx, 
799                       silc_server_connect_to_router_final);
800
801   /* Register timeout task. If the protocol is not executed inside
802      this timelimit the connection will be terminated. Currently
803      this is 15 seconds and is hard coded limit (XXX). */
804   proto_ctx->timeout_task = 
805     silc_task_register(server->timeout_queue, sock->sock, 
806                        silc_server_timeout_remote,
807                        (void *)server, 15, 0,
808                        SILC_TASK_TIMEOUT,
809                        SILC_TASK_PRI_LOW);
810
811   /* Run the protocol */
812   sock->protocol->execute(server->timeout_queue, 0, 
813                           sock->protocol, sock->sock, 0, 0);
814 }
815
816 /* Finalizes the connection to router. Registers a server task to the
817    queue so that we can accept new connections. */
818
819 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
820 {
821   SilcProtocol protocol = (SilcProtocol)context;
822   SilcServerConnAuthInternalContext *ctx = 
823     (SilcServerConnAuthInternalContext *)protocol->context;
824   SilcServer server = (SilcServer)ctx->server;
825   SilcServerConnection sconn = (SilcServerConnection)ctx->context;
826   SilcSocketConnection sock = ctx->sock;
827   SilcServerEntry id_entry;
828   SilcBuffer packet;
829   SilcServerHBContext hb_context;
830   unsigned char *id_string;
831   SilcIDListData idata;
832
833   SILC_LOG_DEBUG(("Start"));
834
835   if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
836       protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
837     /* Error occured during protocol */
838     if (ctx->dest_id)
839       silc_free(ctx->dest_id);
840     silc_server_disconnect_remote(server, sock, "Server closed connection: "
841                                   "Authentication failed");
842     goto out;
843   }
844
845   /* Add a task to the queue. This task receives new connections to the 
846      server. This task remains on the queue until the end of the program. */
847   if (!server->listenning) {
848     silc_task_register(server->io_queue, server->sock, 
849                        silc_server_accept_new_connection,
850                        (void *)server, 0, 0, 
851                        SILC_TASK_FD,
852                        SILC_TASK_PRI_NORMAL);
853     server->listenning = TRUE;
854   }
855
856   /* Send NEW_SERVER packet to the router. We will become registered
857      to the SILC network after sending this packet. */
858   id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
859   packet = silc_buffer_alloc(2 + 2 + SILC_ID_SERVER_LEN + 
860                              strlen(server->server_name));
861   silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
862   silc_buffer_format(packet,
863                      SILC_STR_UI_SHORT(SILC_ID_SERVER_LEN),
864                      SILC_STR_UI_XNSTRING(id_string, SILC_ID_SERVER_LEN),
865                      SILC_STR_UI_SHORT(strlen(server->server_name)),
866                      SILC_STR_UI_XNSTRING(server->server_name,
867                                           strlen(server->server_name)),
868                      SILC_STR_END);
869
870   /* Send the packet */
871   silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
872                           packet->data, packet->len, TRUE);
873   silc_buffer_free(packet);
874   silc_free(id_string);
875
876   SILC_LOG_DEBUG(("Connected to router %s", sock->hostname));
877
878   /* Add the connected router to local server list */
879   server->standalone = FALSE;
880   id_entry = silc_idlist_add_server(server->local_list, strdup(sock->hostname),
881                                     SILC_ROUTER, ctx->dest_id, NULL, sock);
882   if (!id_entry) {
883     if (ctx->dest_id)
884       silc_free(ctx->dest_id);
885     silc_server_disconnect_remote(server, sock, "Server closed connection: "
886                                   "Authentication failed");
887     goto out;
888   }
889
890   silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
891   silc_free(sock->user_data);
892   sock->user_data = (void *)id_entry;
893   sock->type = SILC_SOCKET_TYPE_ROUTER;
894   server->id_entry->router = id_entry;
895   server->router = id_entry;
896   idata = (SilcIDListData)sock->user_data;
897   idata->registered = TRUE;
898
899   /* Perform keepalive. The `hb_context' will be freed automatically
900      when finally calling the silc_socket_free function. XXX hardcoded 
901      timeout!! */
902   hb_context = silc_calloc(1, sizeof(*hb_context));
903   hb_context->server = server;
904   silc_socket_set_heartbeat(sock, 600, hb_context,
905                             silc_server_perform_heartbeat,
906                             server->timeout_queue);
907
908   /* Register re-key timeout */
909   idata->rekey->timeout = 3600; /* XXX hardcoded */
910   idata->rekey->context = (void *)server;
911   silc_task_register(server->timeout_queue, sock->sock, 
912                      silc_server_rekey_callback,
913                      (void *)sock, idata->rekey->timeout, 0,
914                      SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
915
916   /* If we are router then announce our possible servers. */
917   if (server->server_type == SILC_ROUTER)
918     silc_server_announce_servers(server);
919
920   /* Announce our clients and channels to the router */
921   silc_server_announce_clients(server);
922   silc_server_announce_channels(server);
923
924  out:
925   /* Free the temporary connection data context */
926   if (sconn) {
927     silc_free(sconn->remote_host);
928     silc_free(sconn);
929   }
930
931   /* Free the protocol object */
932   silc_protocol_free(protocol);
933   if (ctx->packet)
934     silc_packet_context_free(ctx->packet);
935   if (ctx->ske)
936     silc_ske_free(ctx->ske);
937   silc_free(ctx);
938   sock->protocol = NULL;
939 }
940
941 /* Accepts new connections to the server. Accepting new connections are
942    done in three parts to make it async. */
943
944 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
945 {
946   SilcServer server = (SilcServer)context;
947   SilcSocketConnection newsocket;
948   SilcServerKEInternalContext *proto_ctx;
949   int sock, port;
950   void *config;
951
952   SILC_LOG_DEBUG(("Accepting new connection"));
953
954   server->stat.conn_attempts++;
955
956   sock = silc_net_accept_connection(server->sock);
957   if (sock < 0) {
958     SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
959     server->stat.conn_failures++;
960     return;
961   }
962
963   /* Check max connections */
964   if (sock > SILC_SERVER_MAX_CONNECTIONS) {
965     SILC_LOG_ERROR(("Refusing connection, server is full"));
966     server->stat.conn_failures++;
967     return;
968   }
969
970   /* Set socket options */
971   silc_net_set_socket_nonblock(sock);
972   silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
973
974   /* We don't create a ID yet, since we don't know what type of connection
975      this is yet. But, we do add the connection to the socket table. */
976   silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
977   server->sockets[sock] = newsocket;
978
979   /* XXX This MUST be done async as this will block the entire server
980      process. Either we have to do our own resolver stuff or in the future
981      we can use threads. */
982   /* Perform name and address lookups for the remote host. */
983   if (!silc_net_check_host_by_sock(sock, &newsocket->hostname, 
984                                    &newsocket->ip)) {
985     if ((server->params->require_reverse_mapping && !newsocket->hostname) ||
986         !newsocket->ip) {
987       SILC_LOG_ERROR(("IP/DNS lookup failed %s",
988                       newsocket->hostname ? newsocket->hostname :
989                       newsocket->ip ? newsocket->ip : ""));
990       server->stat.conn_failures++;
991       return;
992     }
993     if (!newsocket->hostname)
994       newsocket->hostname = strdup(newsocket->ip);
995   }
996   newsocket->port = silc_net_get_remote_port(sock);
997
998   /* Register the connection for network input and output. This sets
999      that scheduler will listen for incoming packets for this connection 
1000      and sets that outgoing packets may be sent to this connection as well.
1001      However, this doesn't set the scheduler for outgoing traffic, it
1002      will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
1003      later when outgoing data is available. */
1004   SILC_REGISTER_CONNECTION_FOR_IO(sock);
1005
1006   /* Check whether we have configred this sort of connection at all. We
1007      have to check all configurations since we don't know what type of
1008      connection this is. */
1009   port = server->sockets[fd]->port; /* Listenning port */
1010   if (!(config = silc_server_config_find_client_conn(server->config,
1011                                                      newsocket->ip, port)))
1012     if (!(config = silc_server_config_find_client_conn(server->config,
1013                                                        newsocket->hostname, 
1014                                                        port)))
1015       if (!(config = silc_server_config_find_server_conn(server->config,
1016                                                          newsocket->ip, 
1017                                                          port)))
1018         if (!(config = silc_server_config_find_server_conn(server->config,
1019                                                            newsocket->hostname,
1020                                                            port)))
1021           if (!(config = 
1022                 silc_server_config_find_router_conn(server->config,
1023                                                     newsocket->ip, port)))
1024             if (!(config = 
1025                   silc_server_config_find_router_conn(server->config,
1026                                                       newsocket->hostname, 
1027                                                       port))) {
1028               silc_server_disconnect_remote(server, newsocket, 
1029                                             "Server closed connection: "
1030                                             "Connection refused");
1031               server->stat.conn_failures++;
1032               return;
1033             }
1034
1035   /* The connection is allowed */
1036
1037   SILC_LOG_INFO(("Incoming connection from %s (%s)", newsocket->hostname,
1038                  newsocket->ip));
1039
1040   /* Allocate internal context for key exchange protocol. This is
1041      sent as context for the protocol. */
1042   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1043   proto_ctx->server = context;
1044   proto_ctx->sock = newsocket;
1045   proto_ctx->rng = server->rng;
1046   proto_ctx->responder = TRUE;
1047   proto_ctx->config = config;
1048
1049   /* Prepare the connection for key exchange protocol. We allocate the
1050      protocol but will not start it yet. The connector will be the
1051      initiator of the protocol thus we will wait for initiation from 
1052      there before we start the protocol. */
1053   server->stat.auth_attempts++;
1054   silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE, 
1055                       &newsocket->protocol, proto_ctx, 
1056                       silc_server_accept_new_connection_second);
1057
1058   /* Register a timeout task that will be executed if the connector
1059      will not start the key exchange protocol within 60 seconds. For
1060      now, this is a hard coded limit. After 60 secs the connection will
1061      be closed if the key exchange protocol has not been started. */
1062   proto_ctx->timeout_task = 
1063     silc_task_register(server->timeout_queue, newsocket->sock, 
1064                        silc_server_timeout_remote,
1065                        context, 60, 0,
1066                        SILC_TASK_TIMEOUT,
1067                        SILC_TASK_PRI_LOW);
1068 }
1069
1070 /* Second part of accepting new connection. Key exchange protocol has been
1071    performed and now it is time to do little connection authentication
1072    protocol to figure out whether this connection is client or server
1073    and whether it has right to access this server (especially server
1074    connections needs to be authenticated). */
1075
1076 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
1077 {
1078   SilcProtocol protocol = (SilcProtocol)context;
1079   SilcServerKEInternalContext *ctx = 
1080     (SilcServerKEInternalContext *)protocol->context;
1081   SilcServer server = (SilcServer)ctx->server;
1082   SilcSocketConnection sock = server->sockets[fd];
1083   SilcServerConnAuthInternalContext *proto_ctx;
1084
1085   SILC_LOG_DEBUG(("Start"));
1086
1087   if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1088       protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1089     /* Error occured during protocol */
1090     silc_protocol_free(protocol);
1091     sock->protocol = NULL;
1092     silc_ske_free_key_material(ctx->keymat);
1093     if (ctx->packet)
1094       silc_packet_context_free(ctx->packet);
1095     if (ctx->ske)
1096       silc_ske_free(ctx->ske);
1097     if (ctx->dest_id)
1098       silc_free(ctx->dest_id);
1099     silc_free(ctx);
1100     silc_task_unregister_by_callback(server->timeout_queue,
1101                                      silc_server_failure_callback);
1102     silc_server_disconnect_remote(server, sock, "Server closed connection: "
1103                                   "Key exchange failed");
1104     server->stat.auth_failures++;
1105     return;
1106   }
1107
1108   /* We now have the key material as the result of the key exchange
1109      protocol. Take the key material into use. Free the raw key material
1110      as soon as we've set them into use. */
1111   if (!silc_server_protocol_ke_set_keys(ctx->ske, ctx->sock, ctx->keymat,
1112                                         ctx->ske->prop->cipher,
1113                                         ctx->ske->prop->pkcs,
1114                                         ctx->ske->prop->hash,
1115                                         ctx->ske->prop->hmac,
1116                                         ctx->ske->prop->group,
1117                                         ctx->responder)) {
1118     silc_protocol_free(protocol);
1119     sock->protocol = NULL;
1120     silc_ske_free_key_material(ctx->keymat);
1121     if (ctx->packet)
1122       silc_packet_context_free(ctx->packet);
1123     if (ctx->ske)
1124       silc_ske_free(ctx->ske);
1125     if (ctx->dest_id)
1126       silc_free(ctx->dest_id);
1127     silc_free(ctx);
1128     silc_task_unregister_by_callback(server->timeout_queue,
1129                                      silc_server_failure_callback);
1130     silc_server_disconnect_remote(server, sock, "Server closed connection: "
1131                                   "Key exchange failed");
1132     server->stat.auth_failures++;
1133     return;
1134   }    
1135   silc_ske_free_key_material(ctx->keymat);
1136
1137   /* Allocate internal context for the authentication protocol. This
1138      is sent as context for the protocol. */
1139   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
1140   proto_ctx->server = (void *)server;
1141   proto_ctx->sock = sock;
1142   proto_ctx->ske = ctx->ske;    /* Save SKE object from previous protocol */
1143   proto_ctx->responder = TRUE;
1144   proto_ctx->dest_id_type = ctx->dest_id_type;
1145   proto_ctx->dest_id = ctx->dest_id;
1146   proto_ctx->config = ctx->config;
1147
1148   /* Free old protocol as it is finished now */
1149   silc_protocol_free(protocol);
1150   if (ctx->packet)
1151     silc_packet_context_free(ctx->packet);
1152   silc_free(ctx);
1153   sock->protocol = NULL;
1154
1155   /* Allocate the authentication protocol. This is allocated here
1156      but we won't start it yet. We will be receiving party of this
1157      protocol thus we will wait that connecting party will make
1158      their first move. */
1159   silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH, 
1160                       &sock->protocol, proto_ctx, 
1161                       silc_server_accept_new_connection_final);
1162
1163   /* Register timeout task. If the protocol is not executed inside
1164      this timelimit the connection will be terminated. Currently
1165      this is 60 seconds and is hard coded limit (XXX). */
1166   proto_ctx->timeout_task = 
1167     silc_task_register(server->timeout_queue, sock->sock, 
1168                        silc_server_timeout_remote,
1169                        (void *)server, 60, 0,
1170                        SILC_TASK_TIMEOUT,
1171                        SILC_TASK_PRI_LOW);
1172 }
1173
1174 /* Final part of accepting new connection. The connection has now
1175    been authenticated and keys has been exchanged. We also know whether
1176    this is client or server connection. */
1177
1178 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
1179 {
1180   SilcProtocol protocol = (SilcProtocol)context;
1181   SilcServerConnAuthInternalContext *ctx = 
1182     (SilcServerConnAuthInternalContext *)protocol->context;
1183   SilcServer server = (SilcServer)ctx->server;
1184   SilcSocketConnection sock = ctx->sock;
1185   SilcServerHBContext hb_context;
1186   void *id_entry = NULL;
1187
1188   SILC_LOG_DEBUG(("Start"));
1189
1190   if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
1191       protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
1192     /* Error occured during protocol */
1193     silc_protocol_free(protocol);
1194     sock->protocol = NULL;
1195     if (ctx->packet)
1196       silc_packet_context_free(ctx->packet);
1197     if (ctx->ske)
1198       silc_ske_free(ctx->ske);
1199     if (ctx->dest_id)
1200       silc_free(ctx->dest_id);
1201     silc_free(ctx);
1202     if (sock)
1203       sock->protocol = NULL;
1204     silc_task_unregister_by_callback(server->timeout_queue,
1205                                      silc_server_failure_callback);
1206     silc_server_disconnect_remote(server, sock, "Server closed connection: "
1207                                   "Authentication failed");
1208     server->stat.auth_failures++;
1209     return;
1210   }
1211
1212   sock->type = ctx->conn_type;
1213   switch(sock->type) {
1214   case SILC_SOCKET_TYPE_CLIENT:
1215     {
1216       SilcClientEntry client;
1217
1218       SILC_LOG_DEBUG(("Remote host is client"));
1219       SILC_LOG_INFO(("Connection from %s (%s) is client", sock->hostname,
1220                      sock->ip));
1221
1222       /* Add the client to the client ID cache. The nickname and Client ID
1223          and other information is created after we have received NEW_CLIENT
1224          packet from client. */
1225       client = silc_idlist_add_client(server->local_list, 
1226                                       NULL, 0, NULL, NULL, NULL, NULL, sock);
1227       if (!client) {
1228         SILC_LOG_ERROR(("Could not add new client to cache"));
1229         silc_free(sock->user_data);
1230         break;
1231       }
1232
1233       /* Statistics */
1234       server->stat.my_clients++;
1235       server->stat.clients++;
1236       if (server->server_type == SILC_ROUTER)
1237         server->stat.cell_clients++;
1238
1239       id_entry = (void *)client;
1240       break;
1241     }
1242   case SILC_SOCKET_TYPE_SERVER:
1243   case SILC_SOCKET_TYPE_ROUTER:
1244     {
1245       SilcServerEntry new_server;
1246       SilcServerConfigSectionServerConnection *conn = ctx->config;
1247
1248       SILC_LOG_DEBUG(("Remote host is %s", 
1249                       sock->type == SILC_SOCKET_TYPE_SERVER ? 
1250                       "server" : "router"));
1251       SILC_LOG_INFO(("Connection from %s (%s) is %s", sock->hostname,
1252                      sock->ip, sock->type == SILC_SOCKET_TYPE_SERVER ? 
1253                      "server" : "router"));
1254
1255       /* Add the server into server cache. The server name and Server ID
1256          is updated after we have received NEW_SERVER packet from the
1257          server. We mark ourselves as router for this server if we really
1258          are router. */
1259       new_server = 
1260         silc_idlist_add_server(server->local_list, NULL,
1261                                sock->type == SILC_SOCKET_TYPE_SERVER ?
1262                                SILC_SERVER : SILC_ROUTER, NULL, 
1263                                sock->type == SILC_SOCKET_TYPE_SERVER ?
1264                                server->id_entry : NULL, sock);
1265       if (!new_server) {
1266         SILC_LOG_ERROR(("Could not add new server to cache"));
1267         silc_free(sock->user_data);
1268         break;
1269       }
1270
1271       /* Statistics */
1272       if (sock->type == SILC_SOCKET_TYPE_SERVER)
1273         server->stat.my_servers++;
1274       else
1275         server->stat.my_routers++;
1276       server->stat.servers++;
1277
1278       id_entry = (void *)new_server;
1279
1280       /* Check whether this connection is to be our primary router connection
1281          if we dont' already have the primary route. */
1282       if (server->standalone && sock->type == SILC_SOCKET_TYPE_ROUTER) {
1283         if (silc_server_config_is_primary_route(server->config) &&
1284             !conn->initiator)
1285           break;
1286
1287         SILC_LOG_DEBUG(("We are not standalone server anymore"));
1288         server->standalone = FALSE;
1289         if (!server->id_entry->router) {
1290           server->id_entry->router = id_entry;
1291           server->router = id_entry;
1292         }
1293       }
1294
1295       break;
1296     }
1297   default:
1298     break;
1299   }
1300
1301   /* Add the common data structure to the ID entry. */
1302   if (id_entry)
1303     silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1304       
1305   /* Add to sockets internal pointer for fast referencing */
1306   silc_free(sock->user_data);
1307   sock->user_data = id_entry;
1308
1309   /* Connection has been fully established now. Everything is ok. */
1310   SILC_LOG_DEBUG(("New connection authenticated"));
1311
1312   /* Perform keepalive. The `hb_context' will be freed automatically
1313      when finally calling the silc_socket_free function. XXX hardcoded 
1314      timeout!! */
1315   hb_context = silc_calloc(1, sizeof(*hb_context));
1316   hb_context->server = server;
1317   silc_socket_set_heartbeat(sock, 600, hb_context,
1318                             silc_server_perform_heartbeat,
1319                             server->timeout_queue);
1320
1321   silc_task_unregister_by_callback(server->timeout_queue,
1322                                    silc_server_failure_callback);
1323   silc_protocol_free(protocol);
1324   if (ctx->packet)
1325     silc_packet_context_free(ctx->packet);
1326   if (ctx->ske)
1327     silc_ske_free(ctx->ske);
1328   if (ctx->dest_id)
1329     silc_free(ctx->dest_id);
1330   silc_free(ctx);
1331   sock->protocol = NULL;
1332 }
1333
1334 /* This function is used to read packets from network and send packets to
1335    network. This is usually a generic task. */
1336
1337 SILC_TASK_CALLBACK(silc_server_packet_process)
1338 {
1339   SilcServer server = (SilcServer)context;
1340   SilcSocketConnection sock = server->sockets[fd];
1341   SilcIDListData idata;
1342   SilcCipher cipher = NULL;
1343   SilcHmac hmac = NULL;
1344   int ret;
1345
1346   if (!sock)
1347     return;
1348
1349   SILC_LOG_DEBUG(("Processing packet"));
1350
1351   /* Packet sending */
1352
1353   if (type == SILC_TASK_WRITE) {
1354     /* Do not send data to disconnected connection */
1355     if (SILC_IS_DISCONNECTED(sock))
1356       return;
1357
1358     server->stat.packets_sent++;
1359
1360     if (sock->outbuf->data - sock->outbuf->head)
1361      silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
1362
1363     /* Send the packet */
1364     ret = silc_packet_send(sock, TRUE);
1365
1366     /* If returned -2 could not write to connection now, will do
1367        it later. */
1368     if (ret == -2)
1369       return;
1370
1371     if (ret == -1)
1372       return;
1373     
1374     /* The packet has been sent and now it is time to set the connection
1375        back to only for input. When there is again some outgoing data 
1376        available for this connection it will be set for output as well. 
1377        This call clears the output setting and sets it only for input. */
1378     SILC_SET_CONNECTION_FOR_INPUT(fd);
1379     SILC_UNSET_OUTBUF_PENDING(sock);
1380
1381     silc_buffer_clear(sock->outbuf);
1382     return;
1383   }
1384
1385   /* Packet receiving */
1386
1387   /* Read some data from connection */
1388   ret = silc_packet_receive(sock);
1389   if (ret < 0)
1390     return;
1391     
1392   /* EOF */
1393   if (ret == 0) {
1394     SILC_LOG_DEBUG(("Read EOF"));
1395       
1396     /* If connection is disconnecting already we will finally
1397        close the connection */
1398     if (SILC_IS_DISCONNECTING(sock)) {
1399       if (sock->user_data)
1400         silc_server_free_sock_user_data(server, sock);
1401       silc_server_close_connection(server, sock);
1402       return;
1403     }
1404       
1405     SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1406     SILC_SET_DISCONNECTING(sock);
1407
1408     /* If the closed connection was our primary router connection the
1409        start re-connecting phase. */
1410     if (!server->standalone && sock->type == SILC_SOCKET_TYPE_ROUTER && 
1411         sock == server->router->connection)
1412       silc_task_register(server->timeout_queue, 0, 
1413                          silc_server_connect_to_router,
1414                          context, 1, 0,
1415                          SILC_TASK_TIMEOUT,
1416                          SILC_TASK_PRI_NORMAL);
1417
1418     if (sock->user_data)
1419       silc_server_free_sock_user_data(server, sock);
1420     silc_server_close_connection(server, sock);
1421     return;
1422   }
1423
1424   /* If connection is disconnecting or disconnected we will ignore
1425      what we read. */
1426   if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1427     SILC_LOG_DEBUG(("Ignoring read data from disonnected connection"));
1428     return;
1429   }
1430
1431   server->stat.packets_received++;
1432
1433   /* Get keys and stuff from ID entry */
1434   idata = (SilcIDListData)sock->user_data;
1435   if (idata) {
1436     idata->last_receive = time(NULL);
1437     cipher = idata->receive_key;
1438     hmac = idata->hmac_receive;
1439   }
1440  
1441   /* Process the packet. This will call the parser that will then
1442      decrypt and parse the packet. */
1443   silc_packet_receive_process(sock, cipher, hmac, silc_server_packet_parse, 
1444                               server);
1445 }
1446
1447 /* Callback function that the silc_packet_decrypt will call to make the
1448    decision whether the packet is normal or special packet. We will 
1449    return TRUE if it is normal and FALSE if it is special */
1450
1451 static int silc_server_packet_decrypt_check(SilcPacketType packet_type,
1452                                             SilcBuffer buffer,
1453                                             SilcPacketContext *packet,
1454                                             void *context)
1455 {
1456   SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1457   SilcServer server = (SilcServer)parse_ctx->context;
1458
1459   /* Packet is normal packet, if: 
1460
1461      1) packet is private message packet and does not have private key set
1462      2) is other packet than channel message packet
1463      3) is channel message packet and remote is router and we are router 
1464
1465      all other packets are special packets 
1466   */
1467
1468   if (packet_type == SILC_PACKET_PRIVATE_MESSAGE &&
1469       (buffer->data[2] & SILC_PACKET_FLAG_PRIVMSG_KEY))
1470     return FALSE;
1471
1472   if (packet_type != SILC_PACKET_CHANNEL_MESSAGE || 
1473       (packet_type == SILC_PACKET_CHANNEL_MESSAGE &&
1474        parse_ctx->sock->type == SILC_SOCKET_TYPE_ROUTER &&
1475        server->server_type == SILC_ROUTER))
1476     return TRUE;
1477
1478   return FALSE;
1479 }
1480   
1481 /* Parses whole packet, received earlier. */
1482
1483 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1484 {
1485   SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1486   SilcServer server = (SilcServer)parse_ctx->context;
1487   SilcSocketConnection sock = parse_ctx->sock;
1488   SilcPacketContext *packet = parse_ctx->packet;
1489   SilcIDListData idata = (SilcIDListData)sock->user_data;
1490   int ret;
1491
1492   SILC_LOG_DEBUG(("Start"));
1493
1494   /* Decrypt the received packet */
1495   ret = silc_packet_decrypt(idata ? idata->receive_key : NULL, 
1496                             idata ? idata->hmac_receive : NULL, 
1497                             packet->buffer, packet,
1498                             silc_server_packet_decrypt_check, parse_ctx);
1499   if (ret < 0)
1500     goto out;
1501
1502   if (ret == 0) {
1503     /* Parse the packet. Packet type is returned. */
1504     ret = silc_packet_parse(packet);
1505   } else {
1506     /* Parse the packet header in special way as this is "special"
1507        packet type. */
1508     ret = silc_packet_parse_special(packet);
1509   }
1510
1511   if (ret == SILC_PACKET_NONE)
1512     goto out;
1513
1514   /* Check that the the current client ID is same as in the client's packet. */
1515   if (sock->type == SILC_SOCKET_TYPE_CLIENT) {
1516     SilcClientEntry client = (SilcClientEntry)sock->user_data;
1517     if (client && client->id) {
1518       void *id = silc_id_str2id(packet->src_id, packet->src_id_len,
1519                                 packet->src_id_type);
1520       if (SILC_ID_CLIENT_COMPARE(client->id, id)) {
1521         silc_free(id);
1522         goto out;
1523       }
1524       silc_free(id);
1525     }
1526   }
1527
1528   if (server->server_type == SILC_ROUTER) {
1529     /* Route the packet if it is not destined to us. Other ID types but
1530        server are handled separately after processing them. */
1531     if (!(packet->flags & SILC_PACKET_FLAG_BROADCAST) &&
1532         packet->dst_id_type == SILC_ID_SERVER && 
1533         sock->type != SILC_SOCKET_TYPE_CLIENT &&
1534         SILC_ID_SERVER_COMPARE(packet->dst_id, server->id_string)) {
1535       
1536       /* Route the packet to fastest route for the destination ID */
1537       void *id = silc_id_str2id(packet->dst_id, packet->dst_id_len, 
1538                                 packet->dst_id_type);
1539       if (!id)
1540         goto out;
1541       silc_server_packet_route(server,
1542                                silc_server_route_get(server, id,
1543                                                      packet->dst_id_type),
1544                                packet);
1545       silc_free(id);
1546       goto out;
1547     }
1548   }
1549
1550   /* Parse the incoming packet type */
1551   silc_server_packet_parse_type(server, sock, packet);
1552
1553   if (server->server_type == SILC_ROUTER) {
1554     /* Broadcast packet if it is marked as broadcast packet and it is
1555        originated from router and we are router. */
1556     if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
1557         packet->flags & SILC_PACKET_FLAG_BROADCAST &&
1558         !server->standalone) {
1559       silc_server_packet_broadcast(server, server->router->connection, packet);
1560     }
1561   }
1562
1563  out:
1564   /*  silc_buffer_clear(sock->inbuf); */
1565   silc_packet_context_free(packet);
1566   silc_free(parse_ctx);
1567 }
1568
1569 /* Parser callback called by silc_packet_receive_process. This merely
1570    registers timeout that will handle the actual parsing when appropriate. */
1571
1572 void silc_server_packet_parse(SilcPacketParserContext *parser_context)
1573 {
1574   SilcServer server = (SilcServer)parser_context->context;
1575   SilcSocketConnection sock = parser_context->sock;
1576
1577   switch (sock->type) {
1578   case SILC_SOCKET_TYPE_UNKNOWN:
1579   case SILC_SOCKET_TYPE_CLIENT:
1580     /* Parse the packet with timeout */
1581     silc_task_register(server->timeout_queue, sock->sock,
1582                        silc_server_packet_parse_real,
1583                        (void *)parser_context, 0, 100000,
1584                        SILC_TASK_TIMEOUT,
1585                        SILC_TASK_PRI_NORMAL);
1586     break;
1587   case SILC_SOCKET_TYPE_SERVER:
1588   case SILC_SOCKET_TYPE_ROUTER:
1589     /* Packets from servers are parsed as soon as possible */
1590     silc_task_register(server->timeout_queue, sock->sock,
1591                        silc_server_packet_parse_real,
1592                        (void *)parser_context, 0, 1,
1593                        SILC_TASK_TIMEOUT,
1594                        SILC_TASK_PRI_NORMAL);
1595     break;
1596   default:
1597     return;
1598   }
1599 }
1600
1601 /* Parses the packet type and calls what ever routines the packet type
1602    requires. This is done for all incoming packets. */
1603
1604 void silc_server_packet_parse_type(SilcServer server, 
1605                                    SilcSocketConnection sock,
1606                                    SilcPacketContext *packet)
1607 {
1608   SilcPacketType type = packet->type;
1609
1610   SILC_LOG_DEBUG(("Parsing packet type %d", type));
1611
1612   /* Parse the packet type */
1613   switch(type) {
1614   case SILC_PACKET_DISCONNECT:
1615     SILC_LOG_DEBUG(("Disconnect packet"));
1616     if (packet->flags & SILC_PACKET_FLAG_LIST)
1617       break;
1618     break;
1619
1620   case SILC_PACKET_SUCCESS:
1621     /*
1622      * Success received for something. For now we can have only
1623      * one protocol for connection executing at once hence this
1624      * success message is for whatever protocol is executing currently.
1625      */
1626     SILC_LOG_DEBUG(("Success packet"));
1627     if (packet->flags & SILC_PACKET_FLAG_LIST)
1628       break;
1629     if (sock->protocol) {
1630       sock->protocol->execute(server->timeout_queue, 0,
1631                               sock->protocol, sock->sock, 0, 0);
1632     }
1633     break;
1634
1635   case SILC_PACKET_FAILURE:
1636     /*
1637      * Failure received for something. For now we can have only
1638      * one protocol for connection executing at once hence this
1639      * failure message is for whatever protocol is executing currently.
1640      */
1641     SILC_LOG_DEBUG(("Failure packet"));
1642     if (packet->flags & SILC_PACKET_FLAG_LIST)
1643       break;
1644     if (sock->protocol) {
1645       SilcServerFailureContext f;
1646       f = silc_calloc(1, sizeof(*f));
1647       f->server = server;
1648       f->sock = sock;
1649       
1650       /* We will wait 5 seconds to process this failure packet */
1651       silc_task_register(server->timeout_queue, sock->sock,
1652                          silc_server_failure_callback, (void *)f, 5, 0,
1653                          SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
1654     }
1655     break;
1656
1657   case SILC_PACKET_REJECT:
1658     SILC_LOG_DEBUG(("Reject packet"));
1659     if (packet->flags & SILC_PACKET_FLAG_LIST)
1660       break;
1661     return;
1662     break;
1663
1664   case SILC_PACKET_NOTIFY:
1665     /*
1666      * Received notify packet. Server can receive notify packets from
1667      * router. Server then relays the notify messages to clients if needed.
1668      */
1669     SILC_LOG_DEBUG(("Notify packet"));
1670     if (packet->flags & SILC_PACKET_FLAG_LIST)
1671       silc_server_notify_list(server, sock, packet);
1672     else
1673       silc_server_notify(server, sock, packet);
1674     break;
1675
1676     /* 
1677      * Channel packets
1678      */
1679   case SILC_PACKET_CHANNEL_MESSAGE:
1680     /*
1681      * Received channel message. Channel messages are special packets
1682      * (although probably most common ones) thus they are handled
1683      * specially.
1684      */
1685     SILC_LOG_DEBUG(("Channel Message packet"));
1686     if (packet->flags & SILC_PACKET_FLAG_LIST)
1687       break;
1688     silc_server_channel_message(server, sock, packet);
1689     break;
1690
1691   case SILC_PACKET_CHANNEL_KEY:
1692     /*
1693      * Received key for channel. As channels are created by the router
1694      * the keys are as well. We will distribute the key to all of our
1695      * locally connected clients on the particular channel. Router
1696      * never receives this channel and thus is ignored.
1697      */
1698     SILC_LOG_DEBUG(("Channel Key packet"));
1699     if (packet->flags & SILC_PACKET_FLAG_LIST)
1700       break;
1701     silc_server_channel_key(server, sock, packet);
1702     break;
1703
1704     /*
1705      * Command packets
1706      */
1707   case SILC_PACKET_COMMAND:
1708     /*
1709      * Recived command. Processes the command request and allocates the
1710      * command context and calls the command.
1711      */
1712     SILC_LOG_DEBUG(("Command packet"));
1713     if (packet->flags & SILC_PACKET_FLAG_LIST)
1714       break;
1715     silc_server_command_process(server, sock, packet);
1716     break;
1717
1718   case SILC_PACKET_COMMAND_REPLY:
1719     /*
1720      * Received command reply packet. Received command reply to command. It
1721      * may be reply to command sent by us or reply to command sent by client
1722      * that we've routed further.
1723      */
1724     SILC_LOG_DEBUG(("Command Reply packet"));
1725     if (packet->flags & SILC_PACKET_FLAG_LIST)
1726       break;
1727     silc_server_command_reply(server, sock, packet);
1728     break;
1729
1730     /*
1731      * Private Message packets
1732      */
1733   case SILC_PACKET_PRIVATE_MESSAGE:
1734     /*
1735      * Received private message packet. The packet is coming from either
1736      * client or server.
1737      */
1738     SILC_LOG_DEBUG(("Private Message packet"));
1739     if (packet->flags & SILC_PACKET_FLAG_LIST)
1740       break;
1741     silc_server_private_message(server, sock, packet);
1742     break;
1743
1744   case SILC_PACKET_PRIVATE_MESSAGE_KEY:
1745     /*
1746      * Private message key packet.
1747      */
1748     if (packet->flags & SILC_PACKET_FLAG_LIST)
1749       break;
1750     silc_server_private_message_key(server, sock, packet);
1751     break;
1752
1753     /*
1754      * Key Exchange protocol packets
1755      */
1756   case SILC_PACKET_KEY_EXCHANGE:
1757     SILC_LOG_DEBUG(("KE packet"));
1758     if (packet->flags & SILC_PACKET_FLAG_LIST)
1759       break;
1760
1761     if (sock->protocol && sock->protocol->protocol &&
1762         sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1763
1764       SilcServerKEInternalContext *proto_ctx = 
1765         (SilcServerKEInternalContext *)sock->protocol->context;
1766
1767       proto_ctx->packet = silc_packet_context_dup(packet);
1768
1769       /* Let the protocol handle the packet */
1770       sock->protocol->execute(server->timeout_queue, 0, 
1771                               sock->protocol, sock->sock, 0, 100000);
1772     } else {
1773       SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
1774                       "protocol active, packet dropped."));
1775
1776       /* XXX Trigger KE protocol?? Rekey actually, maybe. */
1777     }
1778     break;
1779
1780   case SILC_PACKET_KEY_EXCHANGE_1:
1781     SILC_LOG_DEBUG(("KE 1 packet"));
1782     if (packet->flags & SILC_PACKET_FLAG_LIST)
1783       break;
1784
1785     if (sock->protocol && sock->protocol->protocol &&
1786         (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1787          sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
1788
1789       if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
1790         SilcServerRekeyInternalContext *proto_ctx = 
1791           (SilcServerRekeyInternalContext *)sock->protocol->context;
1792         
1793         if (proto_ctx->packet)
1794           silc_packet_context_free(proto_ctx->packet);
1795         
1796         proto_ctx->packet = silc_packet_context_dup(packet);
1797
1798         /* Let the protocol handle the packet */
1799         sock->protocol->execute(server->timeout_queue, 0, 
1800                                 sock->protocol, sock->sock, 0, 0);
1801       } else {
1802         SilcServerKEInternalContext *proto_ctx = 
1803           (SilcServerKEInternalContext *)sock->protocol->context;
1804         
1805         if (proto_ctx->packet)
1806           silc_packet_context_free(proto_ctx->packet);
1807         
1808         proto_ctx->packet = silc_packet_context_dup(packet);
1809         proto_ctx->dest_id_type = packet->src_id_type;
1810         proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1811                                             packet->src_id_type);
1812         if (!proto_ctx->dest_id)
1813           break;
1814
1815         /* Let the protocol handle the packet */
1816         sock->protocol->execute(server->timeout_queue, 0, 
1817                                 sock->protocol, sock->sock,
1818                                 0, 100000);
1819       }
1820     } else {
1821       SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
1822                       "protocol active, packet dropped."));
1823     }
1824     break;
1825
1826   case SILC_PACKET_KEY_EXCHANGE_2:
1827     SILC_LOG_DEBUG(("KE 2 packet"));
1828     if (packet->flags & SILC_PACKET_FLAG_LIST)
1829       break;
1830
1831     if (sock->protocol && sock->protocol->protocol &&
1832         (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_KEY_EXCHANGE ||
1833          sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY)) {
1834
1835       if (sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
1836         SilcServerRekeyInternalContext *proto_ctx = 
1837           (SilcServerRekeyInternalContext *)sock->protocol->context;
1838         
1839         if (proto_ctx->packet)
1840           silc_packet_context_free(proto_ctx->packet);
1841         
1842         proto_ctx->packet = silc_packet_context_dup(packet);
1843
1844         /* Let the protocol handle the packet */
1845         sock->protocol->execute(server->timeout_queue, 0, 
1846                                 sock->protocol, sock->sock, 0, 0);
1847       } else {
1848         SilcServerKEInternalContext *proto_ctx = 
1849           (SilcServerKEInternalContext *)sock->protocol->context;
1850         
1851         if (proto_ctx->packet)
1852           silc_packet_context_free(proto_ctx->packet);
1853         
1854         proto_ctx->packet = silc_packet_context_dup(packet);
1855         proto_ctx->dest_id_type = packet->src_id_type;
1856         proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_len,
1857                                             packet->src_id_type);
1858         if (!proto_ctx->dest_id)
1859           break;
1860
1861         /* Let the protocol handle the packet */
1862         sock->protocol->execute(server->timeout_queue, 0, 
1863                                 sock->protocol, sock->sock,
1864                                 0, 100000);
1865       }
1866     } else {
1867       SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
1868                       "protocol active, packet dropped."));
1869     }
1870     break;
1871
1872   case SILC_PACKET_CONNECTION_AUTH_REQUEST:
1873     /*
1874      * Connection authentication request packet. When we receive this packet
1875      * we will send to the other end information about our mandatory
1876      * authentication method for the connection. This packet maybe received
1877      * at any time. 
1878      */
1879     SILC_LOG_DEBUG(("Connection authentication request packet"));
1880     if (packet->flags & SILC_PACKET_FLAG_LIST)
1881       break;
1882     silc_server_connection_auth_request(server, sock, packet);
1883     break;
1884
1885     /*
1886      * Connection Authentication protocol packets
1887      */
1888   case SILC_PACKET_CONNECTION_AUTH:
1889     /* Start of the authentication protocol. We receive here the 
1890        authentication data and will verify it. */
1891     SILC_LOG_DEBUG(("Connection auth packet"));
1892     if (packet->flags & SILC_PACKET_FLAG_LIST)
1893       break;
1894
1895     if (sock->protocol && sock->protocol->protocol->type 
1896         == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
1897
1898       SilcServerConnAuthInternalContext *proto_ctx = 
1899         (SilcServerConnAuthInternalContext *)sock->protocol->context;
1900
1901       proto_ctx->packet = silc_packet_context_dup(packet);
1902
1903       /* Let the protocol handle the packet */
1904       sock->protocol->execute(server->timeout_queue, 0, 
1905                               sock->protocol, sock->sock, 0, 0);
1906     } else {
1907       SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
1908                       "protocol active, packet dropped."));
1909     }
1910     break;
1911
1912   case SILC_PACKET_NEW_ID:
1913     /*
1914      * Received New ID packet. This includes some new ID that has been
1915      * created. It may be for client, server or channel. This is the way
1916      * to distribute information about new registered entities in the
1917      * SILC network.
1918      */
1919     SILC_LOG_DEBUG(("New ID packet"));
1920     if (packet->flags & SILC_PACKET_FLAG_LIST)
1921       silc_server_new_id_list(server, sock, packet);
1922     else
1923       silc_server_new_id(server, sock, packet);
1924     break;
1925
1926   case SILC_PACKET_NEW_CLIENT:
1927     /*
1928      * Received new client packet. This includes client information that
1929      * we will use to create initial client ID. After creating new
1930      * ID we will send it to the client.
1931      */
1932     SILC_LOG_DEBUG(("New Client packet"));
1933     if (packet->flags & SILC_PACKET_FLAG_LIST)
1934       break;
1935     silc_server_new_client(server, sock, packet);
1936     break;
1937
1938   case SILC_PACKET_NEW_SERVER:
1939     /*
1940      * Received new server packet. This includes Server ID and some other
1941      * information that we may save. This is received after server has 
1942      * connected to us.
1943      */
1944     SILC_LOG_DEBUG(("New Server packet"));
1945     if (packet->flags & SILC_PACKET_FLAG_LIST)
1946       break;
1947     silc_server_new_server(server, sock, packet);
1948     break;
1949
1950   case SILC_PACKET_NEW_CHANNEL:
1951     /*
1952      * Received new channel packet. Information about new channel in the
1953      * network are distributed using this packet.
1954      */
1955     SILC_LOG_DEBUG(("New Channel packet"));
1956     if (packet->flags & SILC_PACKET_FLAG_LIST)
1957       silc_server_new_channel_list(server, sock, packet);
1958     else
1959       silc_server_new_channel(server, sock, packet);
1960     break;
1961
1962   case SILC_PACKET_HEARTBEAT:
1963     /*
1964      * Received heartbeat.
1965      */
1966     SILC_LOG_DEBUG(("Heartbeat packet"));
1967     if (packet->flags & SILC_PACKET_FLAG_LIST)
1968       break;
1969     break;
1970
1971   case SILC_PACKET_KEY_AGREEMENT:
1972     /*
1973      * Received heartbeat.
1974      */
1975     SILC_LOG_DEBUG(("Key agreement packet"));
1976     if (packet->flags & SILC_PACKET_FLAG_LIST)
1977       break;
1978     silc_server_key_agreement(server, sock, packet);
1979     break;
1980
1981   case SILC_PACKET_REKEY:
1982     /*
1983      * Received re-key packet. The sender wants to regenerate the session
1984      * keys.
1985      */
1986     SILC_LOG_DEBUG(("Re-key packet"));
1987     if (packet->flags & SILC_PACKET_FLAG_LIST)
1988       break;
1989     silc_server_rekey(server, sock, packet);
1990     break;
1991
1992   case SILC_PACKET_REKEY_DONE:
1993     /*
1994      * The re-key is done.
1995      */
1996     SILC_LOG_DEBUG(("Re-key done packet"));
1997     if (packet->flags & SILC_PACKET_FLAG_LIST)
1998       break;
1999
2000     if (sock->protocol && sock->protocol->protocol &&
2001         sock->protocol->protocol->type == SILC_PROTOCOL_SERVER_REKEY) {
2002
2003       SilcServerRekeyInternalContext *proto_ctx = 
2004         (SilcServerRekeyInternalContext *)sock->protocol->context;
2005
2006       if (proto_ctx->packet)
2007         silc_packet_context_free(proto_ctx->packet);
2008
2009       proto_ctx->packet = silc_packet_context_dup(packet);
2010
2011       /* Let the protocol handle the packet */
2012       sock->protocol->execute(server->timeout_queue, 0, 
2013                               sock->protocol, sock->sock, 0, 0);
2014     } else {
2015       SILC_LOG_ERROR(("Received Re-key done packet but no re-key "
2016                       "protocol active, packet dropped."));
2017     }
2018     break;
2019
2020   default:
2021     SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
2022     break;
2023   }
2024   
2025 }
2026
2027 /* Creates connection to a remote router. */
2028
2029 void silc_server_create_connection(SilcServer server,
2030                                    char *remote_host, uint32 port)
2031 {
2032   SilcServerConnection sconn;
2033
2034   /* Allocate connection object for hold connection specific stuff. */
2035   sconn = silc_calloc(1, sizeof(*sconn));
2036   sconn->server = server;
2037   sconn->remote_host = strdup(remote_host);
2038   sconn->remote_port = port;
2039
2040   silc_task_register(server->timeout_queue, 0, 
2041                      silc_server_connect_router,
2042                      (void *)sconn, 0, 1, SILC_TASK_TIMEOUT, 
2043                      SILC_TASK_PRI_NORMAL);
2044 }
2045
2046 SILC_TASK_CALLBACK(silc_server_close_connection_final)
2047 {
2048   silc_socket_free((SilcSocketConnection)context);
2049 }
2050
2051 /* Closes connection to socket connection */
2052
2053 void silc_server_close_connection(SilcServer server,
2054                                   SilcSocketConnection sock)
2055 {
2056   SILC_LOG_INFO(("Closing connection %s:%d [%s] (%d)", sock->hostname,
2057                  sock->port,  
2058                  (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2059                   sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2060                   sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2061                   "Router"), sock->sock));
2062
2063   /* We won't listen for this connection anymore */
2064   silc_schedule_unset_listen_fd(sock->sock);
2065
2066   /* Unregister all tasks */
2067   silc_task_unregister_by_fd(server->io_queue, sock->sock);
2068   silc_task_unregister_by_fd(server->timeout_queue, sock->sock);
2069
2070   /* Close the actual connection */
2071   silc_net_close_connection(sock->sock);
2072   server->sockets[sock->sock] = NULL;
2073
2074   silc_task_register(server->timeout_queue, 0, 
2075                      silc_server_close_connection_final,
2076                      (void *)sock, 0, 1, SILC_TASK_TIMEOUT, 
2077                      SILC_TASK_PRI_NORMAL);
2078 }
2079
2080 /* Sends disconnect message to remote connection and disconnects the 
2081    connection. */
2082
2083 void silc_server_disconnect_remote(SilcServer server,
2084                                    SilcSocketConnection sock,
2085                                    const char *fmt, ...)
2086 {
2087   va_list ap;
2088   unsigned char buf[4096];
2089
2090   if (!sock)
2091     return;
2092
2093   memset(buf, 0, sizeof(buf));
2094   va_start(ap, fmt);
2095   vsprintf(buf, fmt, ap);
2096   va_end(ap);
2097
2098   SILC_LOG_DEBUG(("Disconnecting remote host"));
2099
2100   SILC_LOG_INFO(("Disconnecting %s:%d [%s]", sock->hostname,
2101                   sock->port,
2102                   (sock->type == SILC_SOCKET_TYPE_UNKNOWN ? "Unknown" :
2103                    sock->type == SILC_SOCKET_TYPE_CLIENT ? "Client" :
2104                    sock->type == SILC_SOCKET_TYPE_SERVER ? "Server" :
2105                    "Router")));
2106
2107   /* Notify remote end that the conversation is over. The notify message
2108      is tried to be sent immediately. */
2109   silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,  
2110                           buf, strlen(buf), TRUE);
2111
2112   /* Mark the connection to be disconnected */
2113   SILC_SET_DISCONNECTED(sock);
2114   silc_server_close_connection(server, sock);
2115 }
2116
2117 typedef struct {
2118   SilcServer server;
2119   SilcClientEntry client;
2120 } *FreeClientInternal;
2121
2122 SILC_TASK_CALLBACK(silc_server_free_client_data_timeout)
2123 {
2124   FreeClientInternal i = (FreeClientInternal)context;
2125
2126   silc_idlist_del_data(i->client);
2127   silc_idcache_purge_by_context(i->server->local_list->clients, i->client);
2128   silc_free(i);
2129 }
2130
2131 /* Frees client data and notifies about client's signoff. */
2132
2133 void silc_server_free_client_data(SilcServer server, 
2134                                   SilcSocketConnection sock,
2135                                   SilcClientEntry client, 
2136                                   int notify,
2137                                   char *signoff)
2138 {
2139   FreeClientInternal i = silc_calloc(1, sizeof(*i));
2140
2141   /* If there is pending outgoing data for the client then purge it
2142      to the network before removing the client entry. */
2143   if (sock && SILC_IS_OUTBUF_PENDING(sock) && 
2144       (SILC_IS_DISCONNECTED(sock) == FALSE)) {
2145     server->stat.packets_sent++;
2146
2147     if (sock->outbuf->data - sock->outbuf->head)
2148      silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
2149
2150     silc_packet_send(sock, TRUE);
2151
2152     SILC_SET_CONNECTION_FOR_INPUT(sock->sock);
2153     SILC_UNSET_OUTBUF_PENDING(sock);
2154     silc_buffer_clear(sock->outbuf);
2155   }
2156
2157   /* Send SIGNOFF notify to routers. */
2158   if (notify && !server->standalone && server->router)
2159     silc_server_send_notify_signoff(server, server->router->connection,
2160                                     server->server_type == SILC_SERVER ?
2161                                     FALSE : TRUE, client->id, 
2162                                     SILC_ID_CLIENT_LEN, signoff);
2163
2164   /* Remove client from all channels */
2165   if (notify)
2166     silc_server_remove_from_channels(server, NULL, client, 
2167                                      TRUE, signoff, TRUE);
2168   else
2169     silc_server_remove_from_channels(server, NULL, client, 
2170                                      FALSE, NULL, FALSE);
2171
2172   /* We will not delete the client entry right away. We will take it
2173      into history (for WHOWAS command) for 5 minutes */
2174   i->server = server;
2175   i->client = client;
2176   silc_task_register(server->timeout_queue, 0, 
2177                      silc_server_free_client_data_timeout,
2178                      (void *)i, 300, 0,
2179                      SILC_TASK_TIMEOUT, SILC_TASK_PRI_LOW);
2180   client->data.registered = FALSE;
2181
2182   /* Free the client entry and everything in it */
2183   server->stat.my_clients--;
2184   server->stat.clients--;
2185   if (server->server_type == SILC_ROUTER)
2186     server->stat.cell_clients--;
2187 }
2188
2189 /* Frees user_data pointer from socket connection object. This also sends
2190    appropriate notify packets to the network to inform about leaving
2191    entities. */
2192
2193 void silc_server_free_sock_user_data(SilcServer server, 
2194                                      SilcSocketConnection sock)
2195 {
2196   SILC_LOG_DEBUG(("Start"));
2197
2198   switch(sock->type) {
2199   case SILC_SOCKET_TYPE_CLIENT:
2200     {
2201       SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
2202       silc_server_free_client_data(server, sock, user_data, TRUE, NULL);
2203       break;
2204     }
2205   case SILC_SOCKET_TYPE_SERVER:
2206   case SILC_SOCKET_TYPE_ROUTER:
2207     {
2208       SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
2209
2210       /* Free all client entries that this server owns as they will
2211          become invalid now as well. */
2212       silc_server_remove_clients_by_server(server, user_data, TRUE);
2213
2214       /* If this was our primary router connection then we're lost to
2215          the outside world. */
2216       if (server->router == user_data) {
2217         server->id_entry->router = NULL;
2218         server->router = NULL;
2219         server->standalone = TRUE;
2220       }
2221
2222       /* Free the server entry */
2223       silc_idlist_del_data(user_data);
2224       silc_idlist_del_server(server->local_list, user_data);
2225       server->stat.my_servers--;
2226       server->stat.servers--;
2227       if (server->server_type == SILC_ROUTER)
2228         server->stat.cell_servers--;
2229       break;
2230     }
2231   default:
2232     {
2233       SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
2234
2235       silc_idlist_del_data(user_data);
2236       silc_free(user_data);
2237       break;
2238     }
2239   }
2240
2241   sock->user_data = NULL;
2242 }
2243
2244 /* This function is used to remove all client entries by the server `entry'.
2245    This is called when the connection is lost to the server. In this case
2246    we must invalidate all the client entries owned by the server `entry'. 
2247    If the `server_signoff' is TRUE then the SERVER_SIGNOFF notify is
2248    distributed to our local clients. */
2249
2250 int silc_server_remove_clients_by_server(SilcServer server, 
2251                                          SilcServerEntry entry,
2252                                          int server_signoff)
2253 {
2254   SilcIDCacheList list = NULL;
2255   SilcIDCacheEntry id_cache = NULL;
2256   SilcClientEntry client = NULL;
2257   SilcBuffer idp;
2258   SilcClientEntry *clients = NULL;
2259   uint32 clients_c = 0;
2260   unsigned char **argv = NULL;
2261   uint32 *argv_lens = NULL, *argv_types = NULL, argc = 0;
2262   int i;
2263
2264   SILC_LOG_DEBUG(("Start"));
2265
2266   if (server_signoff) {
2267     idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
2268     argv = silc_realloc(argv, sizeof(*argv) * (argc + 1));
2269     argv_lens = silc_realloc(argv_lens,  sizeof(*argv_lens) * (argc + 1));
2270     argv_types = silc_realloc(argv_types, sizeof(*argv_types) * (argc + 1));
2271     argv[argc] = idp->data;
2272     argv_lens[argc] = idp->len;
2273     argv_types[argc] = argc + 1;
2274     argc++;
2275     silc_buffer_free(idp);
2276   }
2277
2278   if (silc_idcache_find_by_id(server->local_list->clients, 
2279                               SILC_ID_CACHE_ANY, SILC_ID_CLIENT, &list)) {
2280
2281     if (silc_idcache_list_first(list, &id_cache)) {
2282       while (id_cache) {
2283         client = (SilcClientEntry)id_cache->context;
2284         if (client->data.registered == FALSE) {
2285           if (!silc_idcache_list_next(list, &id_cache))
2286             break;
2287           else
2288             continue;
2289         }
2290
2291         if (client->router != entry) {
2292           if (server_signoff && client->connection) {
2293             clients = silc_realloc(clients, 
2294                                    sizeof(*clients) * (clients_c + 1));
2295             clients[clients_c] = client;
2296             clients_c++;
2297           }
2298
2299           if (!silc_idcache_list_next(list, &id_cache))
2300             break;
2301           else
2302             continue;
2303         }
2304
2305         if (server_signoff) {
2306           idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2307           argv = silc_realloc(argv, sizeof(*argv) * (argc + 1));
2308           argv_lens = silc_realloc(argv_lens, sizeof(*argv_lens) *
2309                                    (argc + 1));
2310           argv_types = silc_realloc(argv_types, sizeof(*argv_types) *
2311                                     (argc + 1));
2312           argv[argc] = silc_calloc(idp->len, sizeof(*argv[0]));
2313           memcpy(argv[argc], idp->data, idp->len);
2314           argv_lens[argc] = idp->len;
2315           argv_types[argc] = argc + 1;
2316           argc++;
2317           silc_buffer_free(idp);
2318         }
2319
2320         /* Remove the client entry */
2321         silc_server_remove_from_channels(server, NULL, client, FALSE, 
2322                                          NULL, FALSE);
2323         silc_idlist_del_client(server->local_list, client);
2324
2325         if (!silc_idcache_list_next(list, &id_cache))
2326           break;
2327       }
2328     }
2329     silc_idcache_list_free(list);
2330   }
2331   
2332   if (silc_idcache_find_by_id(server->global_list->clients, 
2333                               SILC_ID_CACHE_ANY, SILC_ID_CLIENT, &list)) {
2334
2335     if (silc_idcache_list_first(list, &id_cache)) {
2336       while (id_cache) {
2337         client = (SilcClientEntry)id_cache->context;
2338         if (client->data.registered == FALSE) {
2339           if (!silc_idcache_list_next(list, &id_cache))
2340             break;
2341           else
2342             continue;
2343         }
2344         
2345         if (client->router != entry) {
2346           if (server_signoff && client->connection) {
2347             clients = silc_realloc(clients, 
2348                                    sizeof(*clients) * (clients_c + 1));
2349             clients[clients_c] = client;
2350             clients_c++;
2351           }
2352
2353           if (!silc_idcache_list_next(list, &id_cache))
2354             break;
2355           else
2356             continue;
2357         }
2358
2359         if (server_signoff) {
2360           idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2361           argv = silc_realloc(argv, sizeof(*argv) * (argc + 1));
2362           argv_lens = silc_realloc(argv_lens, sizeof(*argv_lens) *
2363                                    (argc + 1));
2364           argv_types = silc_realloc(argv_types, sizeof(*argv_types) *
2365                                     (argc + 1));
2366           argv[argc] = silc_calloc(idp->len, sizeof(*argv[0]));
2367           memcpy(argv[argc], idp->data, idp->len);
2368           argv_lens[argc] = idp->len;
2369           argv_types[argc] = argc + 1;
2370           argc++;
2371           silc_buffer_free(idp);
2372         }
2373
2374         /* Remove the client entry */
2375         silc_server_remove_from_channels(server, NULL, client, FALSE,
2376                                          NULL, FALSE);
2377         silc_idlist_del_client(server->global_list, client);
2378
2379         if (!silc_idcache_list_next(list, &id_cache))
2380           break;
2381       }
2382     }
2383     silc_idcache_list_free(list);
2384   }
2385
2386   /* Send the SERVER_SIGNOFF notify */
2387   if (server_signoff) {
2388     SilcBuffer args;
2389
2390     /* Send SERVER_SIGNOFF notify to our primary router */
2391     if (!server->standalone && server->router) {
2392       args = silc_argument_payload_encode(1, argv, argv_lens,
2393                                           argv_types);
2394       silc_server_send_notify_args(server, 
2395                                    server->router->connection,
2396                                    server->server_type == SILC_SERVER ? 
2397                                    FALSE : TRUE, 
2398                                    SILC_NOTIFY_TYPE_SERVER_SIGNOFF,
2399                                    argc, args);
2400       silc_buffer_free(args);
2401     }
2402
2403     args = silc_argument_payload_encode(argc, argv, argv_lens,
2404                                         argv_types);
2405     /* Send to local clients */
2406     for (i = 0; i < clients_c; i++) {
2407       silc_server_send_notify_args(server, clients[i]->connection,
2408                                    FALSE, SILC_NOTIFY_TYPE_SERVER_SIGNOFF,
2409                                    argc, args);
2410     }
2411
2412     silc_free(clients);
2413     silc_buffer_free(args);
2414     silc_free(argv);
2415     silc_free(argv_lens);
2416     silc_free(argv_types);
2417   }
2418
2419   return TRUE;
2420 }
2421
2422 /* Checks whether given channel has global users.  If it does this returns
2423    TRUE and FALSE if there is only locally connected clients on the channel. */
2424
2425 int silc_server_channel_has_global(SilcChannelEntry channel)
2426 {
2427   SilcChannelClientEntry chl;
2428
2429   silc_list_start(channel->user_list);
2430   while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2431     if (chl->client->router)
2432       return TRUE;
2433   }
2434
2435   return FALSE;
2436 }
2437
2438 /* Checks whether given channel has locally connected users.  If it does this
2439    returns TRUE and FALSE if there is not one locally connected client. */
2440
2441 int silc_server_channel_has_local(SilcChannelEntry channel)
2442 {
2443   SilcChannelClientEntry chl;
2444
2445   silc_list_start(channel->user_list);
2446   while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2447     if (!chl->client->router)
2448       return TRUE;
2449   }
2450
2451   return FALSE;
2452 }
2453
2454 /* Removes client from all channels it has joined. This is used when client
2455    connection is disconnected. If the client on a channel is last, the
2456    channel is removed as well. This sends the SIGNOFF notify types. */
2457
2458 void silc_server_remove_from_channels(SilcServer server, 
2459                                       SilcSocketConnection sock,
2460                                       SilcClientEntry client,
2461                                       int notify,
2462                                       char *signoff_message,
2463                                       int keygen)
2464 {
2465   SilcChannelEntry channel;
2466   SilcChannelClientEntry chl;
2467   SilcBuffer clidp;
2468
2469   SILC_LOG_DEBUG(("Start"));
2470
2471   if (!client || !client->id)
2472     return;
2473
2474   clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2475
2476   /* Remove the client from all channels. The client is removed from
2477      the channels' user list. */
2478   silc_list_start(client->channels);
2479   while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
2480     channel = chl->channel;
2481
2482     /* Remove channel from client's channel list */
2483     silc_list_del(client->channels, chl);
2484
2485     /* Remove channel if there is no users anymore */
2486     if (server->server_type == SILC_ROUTER &&
2487         silc_list_count(channel->user_list) < 2) {
2488       server->stat.my_channels--;
2489
2490       if (channel->rekey)
2491         silc_task_unregister_by_context(server->timeout_queue, channel->rekey);
2492
2493       if (channel->founder_key) {
2494         /* The founder auth data exists, do not remove the channel entry */
2495         SilcChannelClientEntry chl2;
2496
2497         channel->id = NULL;
2498
2499         silc_list_start(channel->user_list);
2500         while ((chl2 = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2501           silc_list_del(chl2->client->channels, chl2);
2502           silc_list_del(channel->user_list, chl2);
2503           silc_free(chl2);
2504         }
2505         continue;
2506       }
2507
2508       if (!silc_idlist_del_channel(server->local_list, channel))
2509         silc_idlist_del_channel(server->global_list, channel);
2510       continue;
2511     }
2512
2513     /* Remove client from channel's client list */
2514     silc_list_del(channel->user_list, chl);
2515     silc_free(chl);
2516     server->stat.my_chanclients--;
2517
2518     /* If there is no global users on the channel anymore mark the channel
2519        as local channel. */
2520     if (server->server_type == SILC_SERVER &&
2521         !silc_server_channel_has_global(channel))
2522       channel->global_users = FALSE;
2523
2524     /* If there is not at least one local user on the channel then we don't
2525        need the channel entry anymore, we can remove it safely. */
2526     if (server->server_type == SILC_SERVER &&
2527         !silc_server_channel_has_local(channel)) {
2528       /* Notify about leaving client if this channel has global users. */
2529       if (notify && channel->global_users)
2530         silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2531                                            SILC_NOTIFY_TYPE_SIGNOFF, 
2532                                            signoff_message ? 2 : 1,
2533                                            clidp->data, clidp->len,
2534                                            signoff_message, signoff_message ?
2535                                            strlen(signoff_message) : 0);
2536
2537       server->stat.my_channels--;
2538
2539       if (channel->rekey)
2540         silc_task_unregister_by_context(server->timeout_queue, channel->rekey);
2541
2542       if (channel->founder_key) {
2543         /* The founder auth data exists, do not remove the channel entry */
2544         SilcChannelClientEntry chl2;
2545
2546         channel->id = NULL;
2547
2548         silc_list_start(channel->user_list);
2549         while ((chl2 = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2550           silc_list_del(chl2->client->channels, chl2);
2551           silc_list_del(channel->user_list, chl2);
2552           silc_free(chl2);
2553         }
2554         continue;
2555       }
2556
2557       if (!silc_idlist_del_channel(server->local_list, channel))
2558         silc_idlist_del_channel(server->global_list, channel);
2559       continue;
2560     }
2561
2562     /* Send notify to channel about client leaving SILC and thus
2563        the entire channel. */
2564     if (notify)
2565       silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2566                                          SILC_NOTIFY_TYPE_SIGNOFF, 
2567                                          signoff_message ? 2 : 1,
2568                                          clidp->data, clidp->len,
2569                                          signoff_message, signoff_message ?
2570                                          strlen(signoff_message) : 0);
2571
2572     if (keygen && !(channel->mode & SILC_CHANNEL_MODE_PRIVKEY)) {
2573       /* Re-generate channel key */
2574       silc_server_create_channel_key(server, channel, 0);
2575       
2576       /* Send the channel key to the channel. The key of course is not sent
2577          to the client who was removed from the channel. */
2578       silc_server_send_channel_key(server, client->connection, channel, 
2579                                    server->server_type == SILC_ROUTER ? 
2580                                    FALSE : !server->standalone);
2581     }
2582   }
2583
2584   silc_buffer_free(clidp);
2585 }
2586
2587 /* Removes client from one channel. This is used for example when client
2588    calls LEAVE command to remove itself from the channel. Returns TRUE
2589    if channel still exists and FALSE if the channel is removed when
2590    last client leaves the channel. If `notify' is FALSE notify messages
2591    are not sent. */
2592
2593 int silc_server_remove_from_one_channel(SilcServer server, 
2594                                         SilcSocketConnection sock,
2595                                         SilcChannelEntry channel,
2596                                         SilcClientEntry client,
2597                                         int notify)
2598 {
2599   SilcChannelEntry ch;
2600   SilcChannelClientEntry chl;
2601   SilcBuffer clidp;
2602
2603   SILC_LOG_DEBUG(("Start"));
2604
2605   clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
2606
2607   /* Remove the client from the channel. The client is removed from
2608      the channel's user list. */
2609   silc_list_start(client->channels);
2610   while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
2611     if (chl->channel != channel)
2612       continue;
2613
2614     ch = chl->channel;
2615
2616     /* Remove channel from client's channel list */
2617     silc_list_del(client->channels, chl);
2618
2619     /* Remove channel if there is no users anymore */
2620     if (server->server_type == SILC_ROUTER &&
2621         silc_list_count(channel->user_list) < 2) {
2622       if (channel->rekey)
2623         silc_task_unregister_by_context(server->timeout_queue, channel->rekey);
2624       if (!silc_idlist_del_channel(server->local_list, channel))
2625         silc_idlist_del_channel(server->global_list, channel);
2626       silc_buffer_free(clidp);
2627       server->stat.my_channels--;
2628       return FALSE;
2629     }
2630
2631     /* Remove client from channel's client list */
2632     silc_list_del(channel->user_list, chl);
2633     silc_free(chl);
2634     server->stat.my_chanclients--;
2635
2636     /* If there is no global users on the channel anymore mark the channel
2637        as local channel. */
2638     if (server->server_type == SILC_SERVER &&
2639         !silc_server_channel_has_global(channel))
2640       channel->global_users = FALSE;
2641
2642     /* If there is not at least one local user on the channel then we don't
2643        need the channel entry anymore, we can remove it safely. */
2644     if (server->server_type == SILC_SERVER &&
2645         !silc_server_channel_has_local(channel)) {
2646       /* Notify about leaving client if this channel has global users. */
2647       if (notify && channel->global_users)
2648         silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2649                                            SILC_NOTIFY_TYPE_LEAVE, 1,
2650                                            clidp->data, clidp->len);
2651
2652       server->stat.my_channels--;
2653       silc_buffer_free(clidp);
2654
2655       if (channel->rekey)
2656         silc_task_unregister_by_context(server->timeout_queue, channel->rekey);
2657
2658       if (channel->founder_key) {
2659         /* The founder auth data exists, do not remove the channel entry */
2660         SilcChannelClientEntry chl2;
2661
2662         channel->id = NULL;
2663
2664         silc_list_start(channel->user_list);
2665         while ((chl2 = silc_list_get(channel->user_list)) != SILC_LIST_END) {
2666           silc_list_del(chl2->client->channels, chl2);
2667           silc_list_del(channel->user_list, chl2);
2668           silc_free(chl2);
2669         }
2670         return FALSE;
2671       }
2672
2673       if (!silc_idlist_del_channel(server->local_list, channel))
2674         silc_idlist_del_channel(server->global_list, channel);
2675       return FALSE;
2676     }
2677
2678     /* Send notify to channel about client leaving the channel */
2679     if (notify)
2680       silc_server_send_notify_to_channel(server, NULL, channel, FALSE,
2681                                          SILC_NOTIFY_TYPE_LEAVE, 1,
2682                                          clidp->data, clidp->len);
2683     break;
2684   }
2685
2686   silc_buffer_free(clidp);
2687   return TRUE;
2688 }
2689
2690 /* Returns TRUE if the given client is on the channel.  FALSE if not. 
2691    This works because we assure that the user list on the channel is
2692    always in up to date thus we can only check the channel list from 
2693    `client' which is faster than checking the user list from `channel'. */
2694
2695 int silc_server_client_on_channel(SilcClientEntry client,
2696                                   SilcChannelEntry channel)
2697 {
2698   SilcChannelClientEntry chl;
2699
2700   if (!client || !channel)
2701     return FALSE;
2702
2703   silc_list_start(client->channels);
2704   while ((chl = silc_list_get(client->channels)) != SILC_LIST_END)
2705     if (chl->channel == channel)
2706       return TRUE;
2707
2708   return FALSE;
2709 }
2710
2711 /* Timeout callback. This is called if connection is idle or for some
2712    other reason is not responding within some period of time. This 
2713    disconnects the remote end. */
2714
2715 SILC_TASK_CALLBACK(silc_server_timeout_remote)
2716 {
2717   SilcServer server = (SilcServer)context;
2718   SilcSocketConnection sock = server->sockets[fd];
2719
2720   if (!sock)
2721     return;
2722
2723   if (sock->user_data)
2724     silc_server_free_sock_user_data(server, sock);
2725
2726   silc_server_disconnect_remote(server, sock, 
2727                                 "Server closed connection: "
2728                                 "Connection timeout");
2729 }
2730
2731 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
2732    function may be used only by router. In real SILC network all channels
2733    are created by routers thus this function is never used by normal
2734    server. */
2735
2736 SilcChannelEntry silc_server_create_new_channel(SilcServer server, 
2737                                                 SilcServerID *router_id,
2738                                                 char *cipher, 
2739                                                 char *hmac,
2740                                                 char *channel_name,
2741                                                 int broadcast)
2742 {
2743   SilcChannelID *channel_id;
2744   SilcChannelEntry entry;
2745   SilcCipher key;
2746   SilcHmac newhmac;
2747
2748   SILC_LOG_DEBUG(("Creating new channel"));
2749
2750   if (!cipher)
2751     cipher = "aes-256-cbc";
2752   if (!hmac)
2753     hmac = "hmac-sha1-96";
2754
2755   /* Allocate cipher */
2756   if (!silc_cipher_alloc(cipher, &key))
2757     return NULL;
2758
2759   /* Allocate hmac */
2760   if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2761     silc_cipher_free(key);
2762     return NULL;
2763   }
2764
2765   channel_name = strdup(channel_name);
2766
2767   /* Create the channel */
2768   silc_id_create_channel_id(router_id, server->rng, &channel_id);
2769   entry = silc_idlist_add_channel(server->local_list, channel_name, 
2770                                   SILC_CHANNEL_MODE_NONE, channel_id, 
2771                                   NULL, key, newhmac);
2772   if (!entry) {
2773     silc_free(channel_name);
2774     return NULL;
2775   }
2776
2777   entry->cipher = strdup(cipher);
2778   entry->hmac_name = strdup(hmac);
2779
2780   /* Now create the actual key material */
2781   silc_server_create_channel_key(server, entry, 
2782                                  silc_cipher_get_key_len(key) / 8);
2783
2784   /* Notify other routers about the new channel. We send the packet
2785      to our primary route. */
2786   if (broadcast && server->standalone == FALSE)
2787     silc_server_send_new_channel(server, server->router->connection, TRUE, 
2788                                  channel_name, entry->id, SILC_ID_CHANNEL_LEN,
2789                                  entry->mode);
2790
2791   server->stat.my_channels++;
2792
2793   return entry;
2794 }
2795
2796 /* Same as above but creates the channel with Channel ID `channel_id. */
2797
2798 SilcChannelEntry 
2799 silc_server_create_new_channel_with_id(SilcServer server, 
2800                                        char *cipher, 
2801                                        char *hmac,
2802                                        char *channel_name,
2803                                        SilcChannelID *channel_id,
2804                                        int broadcast)
2805 {
2806   SilcChannelEntry entry;
2807   SilcCipher key;
2808   SilcHmac newhmac;
2809
2810   SILC_LOG_DEBUG(("Creating new channel"));
2811
2812   if (!cipher)
2813     cipher = "aes-256-cbc";
2814   if (!hmac)
2815     hmac = "hmac-sha1-96";
2816
2817   /* Allocate cipher */
2818   if (!silc_cipher_alloc(cipher, &key))
2819     return NULL;
2820
2821   /* Allocate hmac */
2822   if (!silc_hmac_alloc(hmac, NULL, &newhmac)) {
2823     silc_cipher_free(key);
2824     return NULL;
2825   }
2826
2827   channel_name = strdup(channel_name);
2828
2829   /* Create the channel */
2830   entry = silc_idlist_add_channel(server->local_list, channel_name, 
2831                                   SILC_CHANNEL_MODE_NONE, channel_id, 
2832                                   NULL, key, newhmac);
2833   if (!entry) {
2834     silc_free(channel_name);
2835     return NULL;
2836   }
2837
2838   /* Now create the actual key material */
2839   silc_server_create_channel_key(server, entry, 
2840                                  silc_cipher_get_key_len(key) / 8);
2841
2842   /* Notify other routers about the new channel. We send the packet
2843      to our primary route. */
2844   if (broadcast && server->standalone == FALSE)
2845     silc_server_send_new_channel(server, server->router->connection, TRUE, 
2846                                  channel_name, entry->id, SILC_ID_CHANNEL_LEN,
2847                                  entry->mode);
2848
2849   server->stat.my_channels++;
2850
2851   return entry;
2852 }
2853
2854 /* Channel's key re-key timeout callback. */
2855
2856 SILC_TASK_CALLBACK(silc_server_channel_key_rekey)
2857 {
2858   SilcServerChannelRekey rekey = (SilcServerChannelRekey)context;
2859   SilcServer server = (SilcServer)rekey->context;
2860
2861   silc_server_create_channel_key(server, rekey->channel, rekey->key_len);
2862   silc_server_send_channel_key(server, NULL, rekey->channel, FALSE);
2863
2864   silc_task_register(server->timeout_queue, 0, 
2865                      silc_server_channel_key_rekey,
2866                      (void *)rekey, 3600, 0,
2867                      SILC_TASK_TIMEOUT,
2868                      SILC_TASK_PRI_NORMAL);
2869 }
2870
2871 /* Generates new channel key. This is used to create the initial channel key
2872    but also to re-generate new key for channel. If `key_len' is provided
2873    it is the bytes of the key length. */
2874
2875 void silc_server_create_channel_key(SilcServer server, 
2876                                     SilcChannelEntry channel,
2877                                     uint32 key_len)
2878 {
2879   int i;
2880   unsigned char channel_key[32], hash[32];
2881   uint32 len;
2882
2883   SILC_LOG_DEBUG(("Generating channel key"));
2884
2885   if (channel->mode & SILC_CHANNEL_MODE_PRIVKEY) {
2886     SILC_LOG_DEBUG(("Channel has private keys, will not generate new key"));
2887     return;
2888   }
2889
2890   if (!channel->channel_key)
2891     if (!silc_cipher_alloc("aes-256-cbc", &channel->channel_key))
2892       return;
2893
2894   if (key_len)
2895     len = key_len;
2896   else if (channel->key_len)
2897     len = channel->key_len / 8;
2898   else
2899     len = silc_cipher_get_key_len(channel->channel_key) / 8;
2900
2901   /* Create channel key */
2902   for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
2903   
2904   /* Set the key */
2905   silc_cipher_set_key(channel->channel_key, channel_key, len * 8);
2906
2907   /* Remove old key if exists */
2908   if (channel->key) {
2909     memset(channel->key, 0, channel->key_len / 8);
2910     silc_free(channel->key);
2911   }
2912
2913   /* Save the key */
2914   channel->key_len = len * 8;
2915   channel->key = silc_calloc(len, sizeof(*channel->key));
2916   memcpy(channel->key, channel_key, len);
2917   memset(channel_key, 0, sizeof(channel_key));
2918
2919   /* Generate HMAC key from the channel key data and set it */
2920   if (!channel->hmac)
2921     silc_hmac_alloc("hmac-sha1-96", NULL, &channel->hmac);
2922   silc_hash_make(channel->hmac->hash, channel->key, len, hash);
2923   silc_hmac_set_key(channel->hmac, hash, silc_hash_len(channel->hmac->hash));
2924   memset(hash, 0, sizeof(hash));
2925
2926   if (server->server_type == SILC_ROUTER) {
2927     if (!channel->rekey)
2928       channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
2929     channel->rekey->context = (void *)server;
2930     channel->rekey->channel = channel;
2931     channel->rekey->key_len = key_len;
2932
2933     silc_task_unregister_by_callback(server->timeout_queue,
2934                                      silc_server_channel_key_rekey);
2935     silc_task_register(server->timeout_queue, 0, 
2936                        silc_server_channel_key_rekey,
2937                        (void *)channel->rekey, 3600, 0,
2938                        SILC_TASK_TIMEOUT,
2939                        SILC_TASK_PRI_NORMAL);
2940   }
2941 }
2942
2943 /* Saves the channel key found in the encoded `key_payload' buffer. This 
2944    function is used when we receive Channel Key Payload and also when we're
2945    processing JOIN command reply. Returns entry to the channel. */
2946
2947 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
2948                                               SilcBuffer key_payload,
2949                                               SilcChannelEntry channel)
2950 {
2951   SilcChannelKeyPayload payload = NULL;
2952   SilcChannelID *id = NULL;
2953   unsigned char *tmp, hash[32];
2954   uint32 tmp_len;
2955   char *cipher;
2956
2957   SILC_LOG_DEBUG(("Start"));
2958
2959   /* Decode channel key payload */
2960   payload = silc_channel_key_payload_parse(key_payload);
2961   if (!payload) {
2962     SILC_LOG_ERROR(("Bad channel key payload, dropped"));
2963     channel = NULL;
2964     goto out;
2965   }
2966
2967   /* Get the channel entry */
2968   if (!channel) {
2969
2970     /* Get channel ID */
2971     tmp = silc_channel_key_get_id(payload, &tmp_len);
2972     id = silc_id_str2id(tmp, tmp_len, SILC_ID_CHANNEL);
2973     if (!id) {
2974       channel = NULL;
2975       goto out;
2976     }
2977
2978     channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
2979     if (!channel) {
2980       channel = silc_idlist_find_channel_by_id(server->global_list, id, NULL);
2981       if (!channel) {
2982         SILC_LOG_ERROR(("Received key for non-existent channel"));
2983         goto out;
2984       }
2985     }
2986   }
2987
2988   tmp = silc_channel_key_get_key(payload, &tmp_len);
2989   if (!tmp) {
2990     channel = NULL;
2991     goto out;
2992   }
2993
2994   cipher = silc_channel_key_get_cipher(payload, NULL);
2995   if (!cipher) {
2996     channel = NULL;
2997     goto out;
2998   }
2999
3000   /* Remove old key if exists */
3001   if (channel->key) {
3002     memset(channel->key, 0, channel->key_len / 8);
3003     silc_free(channel->key);
3004     silc_cipher_free(channel->channel_key);
3005   }
3006
3007   /* Create new cipher */
3008   if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
3009     channel = NULL;
3010     goto out;
3011   }
3012
3013   if (channel->cipher)
3014     silc_free(channel->cipher);
3015   channel->cipher = strdup(cipher);
3016
3017   /* Save the key */
3018   channel->key_len = tmp_len * 8;
3019   channel->key = silc_calloc(tmp_len, sizeof(unsigned char));
3020   memcpy(channel->key, tmp, tmp_len);
3021   silc_cipher_set_key(channel->channel_key, tmp, channel->key_len);
3022
3023   /* Generate HMAC key from the channel key data and set it */
3024   if (!channel->hmac)
3025     silc_hmac_alloc("hmac-sha1-96", NULL, &channel->hmac);
3026   silc_hash_make(channel->hmac->hash, tmp, tmp_len, hash);
3027   silc_hmac_set_key(channel->hmac, hash, silc_hash_len(channel->hmac->hash));
3028
3029   memset(hash, 0, sizeof(hash));
3030   memset(tmp, 0, tmp_len);
3031
3032   if (server->server_type == SILC_ROUTER) {
3033     if (!channel->rekey)
3034       channel->rekey = silc_calloc(1, sizeof(*channel->rekey));
3035     channel->rekey->context = (void *)server;
3036     channel->rekey->channel = channel;
3037
3038     silc_task_unregister_by_callback(server->timeout_queue,
3039                                      silc_server_channel_key_rekey);
3040     silc_task_register(server->timeout_queue, 0, 
3041                        silc_server_channel_key_rekey,
3042                        (void *)channel->rekey, 3600, 0,
3043                        SILC_TASK_TIMEOUT,
3044                        SILC_TASK_PRI_NORMAL);
3045   }
3046
3047  out:
3048   if (id)
3049     silc_free(id);
3050   if (payload)
3051     silc_channel_key_payload_free(payload);
3052
3053   return channel;
3054 }
3055
3056 /* Heartbeat callback. This function is set as argument for the
3057    silc_socket_set_heartbeat function. The library will call this function
3058    at the set time interval. */
3059
3060 void silc_server_perform_heartbeat(SilcSocketConnection sock,
3061                                    void *hb_context)
3062 {
3063   SilcServerHBContext hb = (SilcServerHBContext)hb_context;
3064
3065   SILC_LOG_DEBUG(("Sending heartbeat to %s (%s)", sock->hostname,
3066                   sock->ip));
3067
3068   /* Send the heartbeat */
3069   silc_server_send_heartbeat(hb->server, sock);
3070 }
3071
3072 /* Returns assembled of all servers in the given ID list. The packet's
3073    form is dictated by the New ID payload. */
3074
3075 static void silc_server_announce_get_servers(SilcServer server,
3076                                              SilcIDList id_list,
3077                                              SilcBuffer *servers)
3078 {
3079   SilcIDCacheList list;
3080   SilcIDCacheEntry id_cache;
3081   SilcServerEntry entry;
3082   SilcBuffer idp;
3083
3084   /* Go through all clients in the list */
3085   if (silc_idcache_find_by_id(id_list->clients, SILC_ID_CACHE_ANY, 
3086                               SILC_ID_SERVER, &list)) {
3087     if (silc_idcache_list_first(list, &id_cache)) {
3088       while (id_cache) {
3089         entry = (SilcServerEntry)id_cache->context;
3090
3091         idp = silc_id_payload_encode(entry->id, SILC_ID_SERVER);
3092
3093         *servers = silc_buffer_realloc(*servers, 
3094                                        (*servers ? 
3095                                         (*servers)->truelen + idp->len : 
3096                                         idp->len));
3097         silc_buffer_pull_tail(*servers, ((*servers)->end - (*servers)->data));
3098         silc_buffer_put(*servers, idp->data, idp->len);
3099         silc_buffer_pull(*servers, idp->len);
3100         silc_buffer_free(idp);
3101
3102         if (!silc_idcache_list_next(list, &id_cache))
3103           break;
3104       }
3105     }
3106
3107     silc_idcache_list_free(list);
3108   }
3109 }
3110
3111 /* This function is used by router to announce existing servers to our
3112    primary router when we've connected to it. */
3113
3114 void silc_server_announce_servers(SilcServer server)
3115 {
3116   SilcBuffer servers = NULL;
3117
3118   SILC_LOG_DEBUG(("Announcing servers"));
3119
3120   /* Get servers in local list */
3121   silc_server_announce_get_servers(server, server->local_list, &servers);
3122
3123   /* Get servers in global list */
3124   silc_server_announce_get_servers(server, server->global_list, &servers);
3125
3126   if (servers) {
3127     silc_buffer_push(servers, servers->data - servers->head);
3128     SILC_LOG_HEXDUMP(("servers"), servers->data, servers->len);
3129
3130     /* Send the packet */
3131     silc_server_packet_send(server, server->router->connection,
3132                             SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3133                             servers->data, servers->len, TRUE);
3134
3135     silc_buffer_free(servers);
3136   }
3137 }
3138
3139 /* Returns assembled packet of all clients in the given ID list. The
3140    packet's form is dictated by the New ID Payload. */
3141
3142 static void silc_server_announce_get_clients(SilcServer server,
3143                                              SilcIDList id_list,
3144                                              SilcBuffer *clients)
3145 {
3146   SilcIDCacheList list;
3147   SilcIDCacheEntry id_cache;
3148   SilcClientEntry client;
3149   SilcBuffer idp;
3150
3151   /* Go through all clients in the list */
3152   if (silc_idcache_find_by_id(id_list->clients, SILC_ID_CACHE_ANY, 
3153                               SILC_ID_CLIENT, &list)) {
3154     if (silc_idcache_list_first(list, &id_cache)) {
3155       while (id_cache) {
3156         client = (SilcClientEntry)id_cache->context;
3157
3158         idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
3159
3160         *clients = silc_buffer_realloc(*clients, 
3161                                        (*clients ? 
3162                                         (*clients)->truelen + idp->len : 
3163                                         idp->len));
3164         silc_buffer_pull_tail(*clients, ((*clients)->end - (*clients)->data));
3165         silc_buffer_put(*clients, idp->data, idp->len);
3166         silc_buffer_pull(*clients, idp->len);
3167         silc_buffer_free(idp);
3168
3169         if (!silc_idcache_list_next(list, &id_cache))
3170           break;
3171       }
3172     }
3173
3174     silc_idcache_list_free(list);
3175   }
3176 }
3177
3178 /* This function is used to announce our existing clients to our router
3179    when we've connected to it. */
3180
3181 void silc_server_announce_clients(SilcServer server)
3182 {
3183   SilcBuffer clients = NULL;
3184
3185   SILC_LOG_DEBUG(("Announcing clients"));
3186
3187   /* Get clients in local list */
3188   silc_server_announce_get_clients(server, server->local_list,
3189                                    &clients);
3190
3191   /* As router we announce our global list as well */
3192   if (server->server_type == SILC_ROUTER)
3193     silc_server_announce_get_clients(server, server->global_list,
3194                                      &clients);
3195
3196   if (clients) {
3197     silc_buffer_push(clients, clients->data - clients->head);
3198     SILC_LOG_HEXDUMP(("clients"), clients->data, clients->len);
3199
3200     /* Send the packet */
3201     silc_server_packet_send(server, server->router->connection,
3202                             SILC_PACKET_NEW_ID, SILC_PACKET_FLAG_LIST,
3203                             clients->data, clients->len, TRUE);
3204
3205     silc_buffer_free(clients);
3206   }
3207 }
3208
3209 static SilcBuffer 
3210 silc_server_announce_encode_join(uint32 argc, ...)
3211 {
3212   va_list ap;
3213
3214   va_start(ap, argc);
3215   return silc_notify_payload_encode(SILC_NOTIFY_TYPE_JOIN, argc, ap);
3216 }
3217
3218 /* Returns assembled packets for channel users of the `channel'. */
3219
3220 void silc_server_announce_get_channel_users(SilcServer server,
3221                                             SilcChannelEntry channel,
3222                                             SilcBuffer *channel_users)
3223 {
3224   SilcChannelClientEntry chl;
3225   SilcBuffer chidp, clidp;
3226   SilcBuffer tmp;
3227   int len;
3228
3229   SILC_LOG_DEBUG(("Start"));
3230
3231   /* Now find all users on the channel */
3232   chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
3233   silc_list_start(channel->user_list);
3234   while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
3235     clidp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3236     tmp = silc_server_announce_encode_join(2, clidp->data, clidp->len,
3237                                            chidp->data, chidp->len);
3238     len = tmp->len;
3239     *channel_users = 
3240       silc_buffer_realloc(*channel_users, 
3241                           (*channel_users ? 
3242                            (*channel_users)->truelen + len : len));
3243     silc_buffer_pull_tail(*channel_users, 
3244                           ((*channel_users)->end - 
3245                            (*channel_users)->data));
3246     
3247     silc_buffer_put(*channel_users, tmp->data, tmp->len);
3248     silc_buffer_pull(*channel_users, len);
3249     silc_buffer_free(clidp);
3250     silc_buffer_free(tmp);
3251   }
3252   silc_buffer_free(chidp);
3253 }
3254
3255 /* Returns assembled packets for all channels and users on those channels
3256    from the given ID List. The packets are in the form dictated by the
3257    New Channel and New Channel User payloads. */
3258
3259 void silc_server_announce_get_channels(SilcServer server,
3260                                        SilcIDList id_list,
3261                                        SilcBuffer *channels,
3262                                        SilcBuffer *channel_users)
3263 {
3264   SilcIDCacheList list;
3265   SilcIDCacheEntry id_cache;
3266   SilcChannelEntry channel;
3267   unsigned char *cid;
3268   uint16 name_len;
3269   int len;
3270
3271   SILC_LOG_DEBUG(("Start"));
3272
3273   /* Go through all channels in the list */
3274   if (silc_idcache_find_by_id(id_list->channels, SILC_ID_CACHE_ANY, 
3275                               SILC_ID_CHANNEL, &list)) {
3276     if (silc_idcache_list_first(list, &id_cache)) {
3277       while (id_cache) {
3278         channel = (SilcChannelEntry)id_cache->context;
3279         
3280         cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3281         name_len = strlen(channel->channel_name);
3282
3283         len = 4 + name_len + SILC_ID_CHANNEL_LEN + 4;
3284         *channels = 
3285           silc_buffer_realloc(*channels, 
3286                               (*channels ? (*channels)->truelen + len : len));
3287         silc_buffer_pull_tail(*channels, 
3288                               ((*channels)->end - (*channels)->data));
3289         silc_buffer_format(*channels,
3290                            SILC_STR_UI_SHORT(name_len),
3291                            SILC_STR_UI_XNSTRING(channel->channel_name, 
3292                                                 name_len),
3293                            SILC_STR_UI_SHORT(SILC_ID_CHANNEL_LEN),
3294                            SILC_STR_UI_XNSTRING(cid, SILC_ID_CHANNEL_LEN),
3295                            SILC_STR_UI_INT(channel->mode),
3296                            SILC_STR_END);
3297         silc_buffer_pull(*channels, len);
3298
3299         silc_server_announce_get_channel_users(server, channel,
3300                                                channel_users);
3301
3302         silc_free(cid);
3303
3304         if (!silc_idcache_list_next(list, &id_cache))
3305           break;
3306       }
3307     }
3308
3309     silc_idcache_list_free(list);
3310   }
3311 }
3312
3313 /* This function is used to announce our existing channels to our router
3314    when we've connected to it. This also announces the users on the
3315    channels to the router. */
3316
3317 void silc_server_announce_channels(SilcServer server)
3318 {
3319   SilcBuffer channels = NULL, channel_users = NULL;
3320
3321   SILC_LOG_DEBUG(("Announcing channels and channel users"));
3322
3323   /* Get channels and channel users in local list */
3324   silc_server_announce_get_channels(server, server->local_list,
3325                                     &channels, &channel_users);
3326
3327   /* Get channels and channel users in global list */
3328   silc_server_announce_get_channels(server, server->global_list,
3329                                     &channels, &channel_users);
3330
3331   if (channels) {
3332     silc_buffer_push(channels, channels->data - channels->head);
3333     SILC_LOG_HEXDUMP(("channels"), channels->data, channels->len);
3334
3335     /* Send the packet */
3336     silc_server_packet_send(server, server->router->connection,
3337                             SILC_PACKET_NEW_CHANNEL, SILC_PACKET_FLAG_LIST,
3338                             channels->data, channels->len,
3339                             FALSE);
3340
3341     silc_buffer_free(channels);
3342   }
3343
3344   if (channel_users) {
3345     silc_buffer_push(channel_users, channel_users->data - channel_users->head);
3346     SILC_LOG_HEXDUMP(("channel users"), channel_users->data, 
3347                      channel_users->len);
3348
3349     /* Send the packet */
3350     silc_server_packet_send(server, server->router->connection,
3351                             SILC_PACKET_NOTIFY, SILC_PACKET_FLAG_LIST,
3352                             channel_users->data, channel_users->len,
3353                             FALSE);
3354
3355     silc_buffer_free(channel_users);
3356   }
3357 }
3358
3359 /* Failure timeout callback. If this is called then we will immediately
3360    process the received failure. We always process the failure with timeout
3361    since we do not want to blindly trust to received failure packets. 
3362    This won't be called (the timeout is cancelled) if the failure was
3363    bogus (it is bogus if remote does not close the connection after sending
3364    the failure). */
3365
3366 SILC_TASK_CALLBACK(silc_server_failure_callback)
3367 {
3368   SilcServerFailureContext f = (SilcServerFailureContext)context;
3369
3370   if (f->sock->protocol) {
3371     f->sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
3372     f->sock->protocol->execute(f->server->timeout_queue, 0,
3373                                f->sock->protocol, f->sock->sock, 0, 0);
3374   }
3375
3376   silc_free(f);
3377 }
3378
3379 /* Assembles user list and users mode list from the `channel'. */
3380
3381 void silc_server_get_users_on_channel(SilcServer server,
3382                                       SilcChannelEntry channel,
3383                                       SilcBuffer *user_list,
3384                                       SilcBuffer *mode_list,
3385                                       uint32 *user_count)
3386 {
3387   SilcChannelClientEntry chl;
3388   SilcBuffer client_id_list;
3389   SilcBuffer client_mode_list;
3390   SilcBuffer idp;
3391   uint32 list_count = 0;
3392
3393   client_id_list = silc_buffer_alloc((SILC_ID_CLIENT_LEN + 4) * 
3394                                      silc_list_count(channel->user_list));
3395   client_mode_list = silc_buffer_alloc(4 * 
3396                                        silc_list_count(channel->user_list));
3397   silc_buffer_pull_tail(client_id_list, SILC_BUFFER_END(client_id_list));
3398   silc_buffer_pull_tail(client_mode_list, SILC_BUFFER_END(client_mode_list));
3399   silc_list_start(channel->user_list);
3400   while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
3401     /* Client ID */
3402     idp = silc_id_payload_encode(chl->client->id, SILC_ID_CLIENT);
3403     silc_buffer_put(client_id_list, idp->data, idp->len);
3404     silc_buffer_pull(client_id_list, idp->len);
3405     silc_buffer_free(idp);
3406
3407     /* Client's mode on channel */
3408     SILC_PUT32_MSB(chl->mode, client_mode_list->data);
3409     silc_buffer_pull(client_mode_list, 4);
3410
3411     list_count++;
3412   }
3413   silc_buffer_push(client_id_list, 
3414                    client_id_list->data - client_id_list->head);
3415   silc_buffer_push(client_mode_list, 
3416                    client_mode_list->data - client_mode_list->head);
3417
3418   *user_list = client_id_list;
3419   *mode_list = client_mode_list;
3420   *user_count = list_count;
3421 }
3422
3423 /* Saves users and their modes to the `channel'. */
3424
3425 void silc_server_save_users_on_channel(SilcServer server,
3426                                        SilcSocketConnection sock,
3427                                        SilcChannelEntry channel,
3428                                        SilcClientID *noadd,
3429                                        SilcBuffer user_list,
3430                                        SilcBuffer mode_list,
3431                                        uint32 user_count)
3432 {
3433   int i;
3434
3435   /* Cache the received Client ID's and modes. This cache expires
3436      whenever server sends notify message to channel. It means two things;
3437      some user has joined or leaved the channel. XXX TODO! */
3438   for (i = 0; i < user_count; i++) {
3439     uint16 idp_len;
3440     uint32 mode;
3441     SilcClientID *client_id;
3442     SilcClientEntry client;
3443
3444     /* Client ID */
3445     SILC_GET16_MSB(idp_len, user_list->data + 2);
3446     idp_len += 4;
3447     client_id = silc_id_payload_parse_id(user_list->data, idp_len);
3448     silc_buffer_pull(user_list, idp_len);
3449     if (!client_id)
3450       continue;
3451
3452     /* Mode */
3453     SILC_GET32_MSB(mode, mode_list->data);
3454     silc_buffer_pull(mode_list, 4);
3455
3456     if (noadd && !SILC_ID_CLIENT_COMPARE(client_id, noadd)) {
3457       silc_free(client_id);
3458       continue;
3459     }
3460     
3461     /* Check if we have this client cached already. */
3462     client = silc_idlist_find_client_by_id(server->local_list, client_id,
3463                                            NULL);
3464     if (!client)
3465       client = silc_idlist_find_client_by_id(server->global_list, 
3466                                              client_id, NULL);
3467     if (!client) {
3468       /* If router did not find such Client ID in its lists then this must
3469          be bogus client or some router in the net is buggy. */
3470       if (server->server_type == SILC_ROUTER) {
3471         silc_free(client_id);
3472         continue;
3473       }
3474
3475       /* We don't have that client anywhere, add it. The client is added
3476          to global list since server didn't have it in the lists so it must be 
3477          global. */
3478       client = silc_idlist_add_client(server->global_list, NULL, 0, NULL, 
3479                                       NULL, 
3480                                       silc_id_dup(client_id, SILC_ID_CLIENT), 
3481                                       sock->user_data, NULL);
3482       if (!client) {
3483         silc_free(client_id);
3484         continue;
3485       }
3486
3487       client->data.registered = TRUE;
3488     }
3489
3490     silc_free(client_id);
3491
3492     if (!silc_server_client_on_channel(client, channel)) {
3493       /* Client was not on the channel, add it. */
3494       SilcChannelClientEntry chl = silc_calloc(1, sizeof(*chl));
3495       chl->client = client;
3496       chl->mode = mode;
3497       chl->channel = channel;
3498       silc_list_add(channel->user_list, chl);
3499       silc_list_add(client->channels, chl);
3500     }
3501   }
3502 }
3503
3504 /* Lookups route to the client indicated by the `id_data'. The connection
3505    object and internal data object is returned. Returns NULL if route
3506    could not be found to the client. If the `client_id' is specified then
3507    it is used and the `id_data' is ignored. */
3508
3509 SilcSocketConnection silc_server_get_client_route(SilcServer server,
3510                                                   unsigned char *id_data,
3511                                                   uint32 id_len,
3512                                                   SilcClientID *client_id,
3513                                                   SilcIDListData *idata)
3514 {
3515   SilcClientID *id;
3516   SilcClientEntry client;
3517
3518   SILC_LOG_DEBUG(("Start"));
3519
3520   /* Decode destination Client ID */
3521   if (!client_id) {
3522     id = silc_id_str2id(id_data, id_len, SILC_ID_CLIENT);
3523     if (!id) {
3524       SILC_LOG_ERROR(("Could not decode destination Client ID, dropped"));
3525       return NULL;
3526     }
3527   } else {
3528     id = silc_id_dup(client_id, SILC_ID_CLIENT);
3529   }
3530
3531   /* If the destination belongs to our server we don't have to route
3532      the packet anywhere but to send it to the local destination. */
3533   client = silc_idlist_find_client_by_id(server->local_list, id, NULL);
3534   if (client) {
3535     silc_free(id);
3536
3537     if (client && client->data.registered == FALSE)
3538       return NULL;
3539
3540     /* If we are router and the client has router then the client is in
3541        our cell but not directly connected to us. */
3542     if (server->server_type == SILC_ROUTER && client->router) {
3543       /* We are of course in this case the client's router thus the real
3544          "router" of the client is the server who owns the client. Thus
3545          we will send the packet to that server. */
3546       if (idata)
3547         *idata = (SilcIDListData)client->router;
3548       return client->router->connection;
3549     }
3550
3551     /* Seems that client really is directly connected to us */
3552     if (idata)
3553       *idata = (SilcIDListData)client;
3554     return client->connection;
3555   }
3556
3557   /* Destination belongs to someone not in this server. If we are normal
3558      server our action is to send the packet to our router. */
3559   if (server->server_type == SILC_SERVER && !server->standalone) {
3560     silc_free(id);
3561     if (idata)
3562       *idata = (SilcIDListData)server->router;
3563     return server->router->connection;
3564   }
3565
3566   /* We are router and we will perform route lookup for the destination 
3567      and send the packet to fastest route. */
3568   if (server->server_type == SILC_ROUTER && !server->standalone) {
3569     /* Check first that the ID is valid */
3570     client = silc_idlist_find_client_by_id(server->global_list, id, NULL);
3571     if (client) {
3572       SilcSocketConnection dst_sock;
3573
3574       dst_sock = silc_server_route_get(server, id, SILC_ID_CLIENT);
3575
3576       silc_free(id);
3577       if (idata)
3578         *idata = (SilcIDListData)dst_sock->user_data;
3579       return dst_sock;
3580     }
3581   }
3582
3583   silc_free(id);
3584   return NULL;
3585 }
3586
3587 /* Encodes and returns channel list of channels the `client' has joined.
3588    Secret channels are not put to the list. */
3589
3590 SilcBuffer silc_server_get_client_channel_list(SilcServer server,
3591                                                SilcClientEntry client)
3592 {
3593   SilcBuffer buffer = NULL;
3594   SilcChannelEntry channel;
3595   SilcChannelClientEntry chl;
3596   unsigned char *cid;
3597   uint16 name_len;
3598   int len;
3599
3600   silc_list_start(client->channels);
3601   while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
3602     channel = chl->channel;
3603
3604     if (channel->mode & SILC_CHANNEL_MODE_SECRET)
3605       continue;
3606
3607     cid = silc_id_id2str(channel->id, SILC_ID_CHANNEL);
3608     name_len = strlen(channel->channel_name);
3609     
3610     len = 4 + name_len + SILC_ID_CHANNEL_LEN + 4;
3611     buffer = silc_buffer_realloc(buffer, 
3612                                  (buffer ? (buffer)->truelen + len : len));
3613     silc_buffer_pull_tail(buffer, ((buffer)->end - (buffer)->data));
3614     silc_buffer_format(buffer,
3615                        SILC_STR_UI_SHORT(name_len),
3616                        SILC_STR_UI_XNSTRING(channel->channel_name, 
3617                                             name_len),
3618                        SILC_STR_UI_SHORT(SILC_ID_CHANNEL_LEN),
3619                        SILC_STR_UI_XNSTRING(cid, SILC_ID_CHANNEL_LEN),
3620                        SILC_STR_UI_INT(chl->mode), /* Client's mode */
3621                        SILC_STR_END);
3622     silc_buffer_pull(buffer, len);
3623     silc_free(cid);
3624   }
3625
3626   if (buffer)
3627     silc_buffer_push(buffer, buffer->data - buffer->head);
3628
3629   return buffer;
3630 }
3631
3632 /* Finds client entry by Client ID and if it is not found then resolves
3633    it using WHOIS command. */
3634
3635 SilcClientEntry silc_server_get_client_resolve(SilcServer server,
3636                                                SilcClientID *client_id)
3637 {
3638   SilcClientEntry client;
3639
3640   client = silc_idlist_find_client_by_id(server->local_list, client_id, NULL);
3641   if (!client) {
3642     client = silc_idlist_find_client_by_id(server->global_list, 
3643                                            client_id, NULL);
3644     if (!client && server->server_type == SILC_ROUTER)
3645       return NULL;
3646   }
3647
3648   if (!client && server->standalone)
3649     return NULL;
3650
3651   if (!client || !client->nickname || !client->username) {
3652     SilcBuffer buffer, idp;
3653
3654     idp = silc_id_payload_encode(client_id, SILC_ID_CLIENT);
3655     buffer = silc_command_payload_encode_va(SILC_COMMAND_WHOIS,
3656                                             ++server->cmd_ident, 1,
3657                                             3, idp->data, idp->len);
3658     silc_server_packet_send(server, client ? client->router->connection :
3659                             server->router->connection,
3660                             SILC_PACKET_COMMAND, 0,
3661                             buffer->data, buffer->len, FALSE);
3662     silc_buffer_free(idp);
3663     silc_buffer_free(buffer);
3664   }
3665
3666   return client;
3667 }
3668
3669 /* A timeout callback for the re-key. We will be the initiator of the
3670    re-key protocol. */
3671
3672 SILC_TASK_CALLBACK(silc_server_rekey_callback)
3673 {
3674   SilcSocketConnection sock = (SilcSocketConnection)context;
3675   SilcIDListData idata = (SilcIDListData)sock->user_data;
3676   SilcServer server = (SilcServer)idata->rekey->context;
3677   SilcProtocol protocol;
3678   SilcServerRekeyInternalContext *proto_ctx;
3679
3680   SILC_LOG_DEBUG(("Start"));
3681
3682   /* Allocate internal protocol context. This is sent as context
3683      to the protocol. */
3684   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
3685   proto_ctx->server = (void *)server;
3686   proto_ctx->sock = sock;
3687   proto_ctx->responder = FALSE;
3688   proto_ctx->pfs = idata->rekey->pfs;
3689       
3690   /* Perform rekey protocol. Will call the final callback after the
3691      protocol is over. */
3692   silc_protocol_alloc(SILC_PROTOCOL_SERVER_REKEY, 
3693                       &protocol, proto_ctx, silc_server_rekey_final);
3694   sock->protocol = protocol;
3695       
3696   /* Run the protocol */
3697   protocol->execute(server->timeout_queue, 0, protocol, 
3698                     sock->sock, 0, 0);
3699
3700   /* Re-register re-key timeout */
3701   silc_task_register(server->timeout_queue, sock->sock, 
3702                      silc_server_rekey_callback,
3703                      context, idata->rekey->timeout, 0,
3704                      SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
3705 }
3706
3707 /* The final callback for the REKEY protocol. This will actually take the
3708    new key material into use. */
3709
3710 SILC_TASK_CALLBACK_GLOBAL(silc_server_rekey_final)
3711 {
3712   SilcProtocol protocol = (SilcProtocol)context;
3713   SilcServerRekeyInternalContext *ctx =
3714     (SilcServerRekeyInternalContext *)protocol->context;
3715   SilcServer server = (SilcServer)ctx->server;
3716   SilcSocketConnection sock = ctx->sock;
3717
3718   SILC_LOG_DEBUG(("Start"));
3719
3720   if (protocol->state == SILC_PROTOCOL_STATE_ERROR ||
3721       protocol->state == SILC_PROTOCOL_STATE_FAILURE) {
3722     /* Error occured during protocol */
3723     silc_protocol_cancel(server->timeout_queue, protocol);
3724     silc_protocol_free(protocol);
3725     sock->protocol = NULL;
3726     if (ctx->packet)
3727       silc_packet_context_free(ctx->packet);
3728     if (ctx->ske)
3729       silc_ske_free(ctx->ske);
3730     silc_free(ctx);
3731     return;
3732   }
3733
3734   /* Cleanup */
3735   silc_protocol_free(protocol);
3736   sock->protocol = NULL;
3737   if (ctx->packet)
3738     silc_packet_context_free(ctx->packet);
3739   if (ctx->ske)
3740     silc_ske_free(ctx->ske);
3741   silc_free(ctx);
3742 }