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