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