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