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