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