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