updates.
[silc.git] / apps / silcd / server.c
1 /*
2
3   server.c
4
5   Author: Pekka Riikonen <priikone@poseidon.pspt.fi>
6
7   Copyright (C) 1997 - 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 /* $Id$ */
26
27 #include "serverincludes.h"
28 #include "server_internal.h"
29
30 /* Static prototypes */
31 SILC_TASK_CALLBACK(silc_server_connect_router);
32 SILC_TASK_CALLBACK(silc_server_connect_to_router);
33 SILC_TASK_CALLBACK(silc_server_connect_to_router_second);
34 SILC_TASK_CALLBACK(silc_server_connect_to_router_final);
35 SILC_TASK_CALLBACK(silc_server_accept_new_connection);
36 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second);
37 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final);
38 SILC_TASK_CALLBACK(silc_server_packet_process);
39 SILC_TASK_CALLBACK(silc_server_packet_parse_real);
40 SILC_TASK_CALLBACK(silc_server_timeout_remote);
41
42 /* Allocates a new SILC server object. This has to be done before the server
43    can be used. After allocation one must call silc_server_init to initialize
44    the server. The new allocated server object is returned to the new_server
45    argument. */
46
47 int silc_server_alloc(SilcServer *new_server)
48 {
49   SilcServer server;
50
51   SILC_LOG_DEBUG(("Allocating new server object"));
52
53   server = silc_calloc(1, sizeof(*server));
54   server->server_type = SILC_SERVER;
55   server->standalone = TRUE;
56   server->local_list = silc_calloc(1, sizeof(*server->local_list));
57   server->global_list = silc_calloc(1, sizeof(*server->global_list));
58   server->pending_commands = silc_dlist_init();
59 #ifdef SILC_SIM
60   server->sim = silc_dlist_init();
61 #endif
62
63   *new_server = server;
64
65   return TRUE;
66 }
67
68 /* Free's the SILC server object. This is called at the very end before
69    the program ends. */
70
71 void silc_server_free(SilcServer server)
72 {
73   if (server) {
74 #ifdef SILC_SIM
75     SilcSimContext *sim;
76 #endif
77
78     if (server->local_list)
79       silc_free(server->local_list);
80     if (server->global_list)
81       silc_free(server->global_list);
82     if (server->rng)
83       silc_rng_free(server->rng);
84
85 #ifdef SILC_SIM
86     while ((sim = silc_dlist_get(server->sim)) != SILC_LIST_END) {
87       silc_dlist_del(server->sim, sim);
88       silc_sim_free(sim);
89     }
90     silc_dlist_uninit(server->sim);
91 #endif
92
93     if (server->params)
94       silc_free(server->params);
95
96     if (server->pending_commands)
97       silc_dlist_uninit(server->pending_commands);
98
99     silc_math_primegen_uninit(); /* XXX */
100     silc_free(server);
101   }
102 }
103
104 /* Initializes the entire SILC server. This is called always before running
105    the server. This is called only once at the initialization of the program.
106    This binds the server to its listenning port. After this function returns 
107    one should call silc_server_run to start the server. This returns TRUE 
108    when everything is ok to run the server. Configuration file must be
109    read and parsed before calling this. */
110
111 int silc_server_init(SilcServer server)
112 {
113   int *sock = NULL, sock_count = 0, i;
114   SilcServerID *id;
115   SilcServerEntry id_entry;
116
117   SILC_LOG_DEBUG(("Initializing server"));
118   assert(server);
119   assert(server->config);
120
121   /* XXX After server is made as Silc Server Library this can be given
122      as argument, for now this is hard coded */
123   server->params = silc_calloc(1, sizeof(*server->params));
124   server->params->retry_count = SILC_SERVER_RETRY_COUNT;
125   server->params->retry_interval_min = SILC_SERVER_RETRY_INTERVAL_MIN;
126   server->params->retry_interval_max = SILC_SERVER_RETRY_INTERVAL_MAX;
127   server->params->retry_keep_trying = FALSE;
128   server->params->protocol_timeout = 60;
129   server->params->require_reverse_mapping = FALSE;
130
131   /* Set log files where log message should be saved. */
132   server->config->server = server;
133   silc_config_server_setlogfiles(server->config);
134  
135   /* Register all configured ciphers, PKCS and hash functions. */
136   silc_config_server_register_ciphers(server->config);
137   silc_config_server_register_pkcs(server->config);
138   silc_config_server_register_hashfuncs(server->config);
139
140   /* Initialize random number generator for the server. */
141   server->rng = silc_rng_alloc();
142   silc_rng_init(server->rng);
143   silc_math_primegen_init(); /* XXX */
144
145   /* Initialize hash functions for server to use */
146   silc_hash_alloc("md5", &server->md5hash);
147   silc_hash_alloc("sha1", &server->sha1hash);
148
149   /* Initialize none cipher */
150   silc_cipher_alloc("none", &server->none_cipher);
151
152   /* XXXXX Generate RSA key pair */
153   {
154     unsigned char *public_key;
155     unsigned char *private_key;
156     unsigned int pk_len, prv_len;
157     struct stat st;
158
159     if (stat("pubkey.pub", &st) < 0 && stat("privkey.prv", &st) < 0) {
160
161       if (silc_pkcs_alloc("rsa", &server->pkcs) == FALSE) {
162         SILC_LOG_ERROR(("Could not create RSA key pair"));
163         goto err0;
164       }
165       
166       if (server->pkcs->pkcs->init(server->pkcs->context, 
167                                    1024, server->rng) == FALSE) {
168         SILC_LOG_ERROR(("Could not generate RSA key pair"));
169         goto err0;
170       }
171       
172       public_key = server->pkcs->pkcs->get_public_key(server->pkcs->context,
173                                                       &pk_len);
174       private_key = server->pkcs->pkcs->get_private_key(server->pkcs->context,
175                                                         &prv_len);
176       
177       SILC_LOG_HEXDUMP(("public key"), public_key, pk_len);
178       SILC_LOG_HEXDUMP(("private key"), private_key, prv_len);
179       
180       server->public_key = 
181         silc_pkcs_public_key_alloc("rsa", "UN=root, HN=dummy",
182                                    public_key, pk_len);
183       server->private_key = 
184         silc_pkcs_private_key_alloc("rsa", private_key, prv_len);
185       
186       /* XXX Save keys */
187       silc_pkcs_save_public_key("pubkey.pub", server->public_key,
188                                 SILC_PKCS_FILE_PEM);
189       silc_pkcs_save_private_key("privkey.prv", server->private_key, NULL,
190                                  SILC_PKCS_FILE_BIN);
191
192       memset(public_key, 0, pk_len);
193       memset(private_key, 0, prv_len);
194       silc_free(public_key);
195       silc_free(private_key);
196     } else {
197       silc_pkcs_load_public_key("pubkey.pub", &server->public_key,
198                                 SILC_PKCS_FILE_PEM);
199       silc_pkcs_load_private_key("privkey.prv", &server->private_key,
200                                  SILC_PKCS_FILE_BIN);
201     }
202   }
203
204   /* Create a listening server. Note that our server can listen on
205      multiple ports. All listeners are created here and now. */
206   /* XXX Still check this whether to use server_info or listen_port. */
207   sock_count = 0;
208   while(server->config->listen_port) {
209     int tmp;
210
211     tmp = silc_net_create_server(server->config->listen_port->port,
212                                  server->config->listen_port->host);
213     if (tmp < 0)
214       goto err0;
215
216     sock = silc_realloc(sock, (sizeof(int *) * (sock_count + 1)));
217     sock[sock_count] = tmp;
218     server->config->listen_port = server->config->listen_port->next;
219     sock_count++;
220   }
221
222   /* Initialize ID caches */
223   server->local_list->clients = silc_idcache_alloc(0);
224   server->local_list->servers = silc_idcache_alloc(0);
225   server->local_list->channels = silc_idcache_alloc(0);
226
227   /* These are allocated for normal server as well as these hold some 
228      global information that the server has fetched from its router. For 
229      router these are used as they are supposed to be used on router. */
230   server->global_list->clients = silc_idcache_alloc(0);
231   server->global_list->servers = silc_idcache_alloc(0);
232   server->global_list->channels = silc_idcache_alloc(0);
233
234   /* Allocate the entire socket list that is used in server. Eventually 
235      all connections will have entry in this table (it is a table of 
236      pointers to the actual object that is allocated individually 
237      later). */
238   server->sockets = silc_calloc(SILC_SERVER_MAX_CONNECTIONS,
239                                 sizeof(*server->sockets));
240
241   for (i = 0; i < sock_count; i++) {
242     SilcSocketConnection newsocket = NULL;
243
244     /* Set socket to non-blocking mode */
245     silc_net_set_socket_nonblock(sock[i]);
246     server->sock = sock[i];
247     
248     /* Create a Server ID for the server. */
249     silc_id_create_server_id(sock[i], server->rng, &id);
250     if (!id) {
251       goto err0;
252     }
253     
254     server->id = id;
255     server->id_string = silc_id_id2str(id, SILC_ID_SERVER);
256     server->id_string_len = silc_id_get_len(SILC_ID_SERVER);
257     server->id_type = SILC_ID_SERVER;
258     server->server_name = server->config->server_info->server_name;
259
260     /* Add ourselves to the server list. We don't have a router yet 
261        beacuse we haven't established a route yet. It will be done later. 
262        For now, NULL is sent as router. This allocates new entry to
263        the ID list. */
264     id_entry = 
265       silc_idlist_add_server(server->local_list,
266                              server->config->server_info->server_name,
267                              server->server_type, server->id, NULL, NULL);
268     if (!id_entry) {
269       SILC_LOG_ERROR(("Could not add ourselves to cache"));
270       goto err0;
271     }
272     
273     /* Add ourselves also to the socket table. The entry allocated above
274        is sent as argument for fast referencing in the future. */
275     silc_socket_alloc(sock[i], SILC_SOCKET_TYPE_SERVER, id_entry, 
276                       &newsocket);
277     if (!newsocket)
278       goto err0;
279
280     server->sockets[sock[i]] = newsocket;
281
282     /* Put the allocated socket pointer also to the entry allocated above 
283        for fast back-referencing to the socket list. */
284     id_entry->connection = (void *)server->sockets[sock[i]];
285     server->id_entry = id_entry;
286   }
287
288   /* Register the task queues. In SILC we have by default three task queues. 
289      One task queue for non-timeout tasks which perform different kind of 
290      I/O on file descriptors, timeout task queue for timeout tasks, and,
291      generic non-timeout task queue whose tasks apply to all connections. */
292   silc_task_queue_alloc(&server->io_queue, TRUE);
293   if (!server->io_queue) {
294     goto err0;
295   }
296   silc_task_queue_alloc(&server->timeout_queue, TRUE);
297   if (!server->timeout_queue) {
298     goto err1;
299   }
300   silc_task_queue_alloc(&server->generic_queue, TRUE);
301   if (!server->generic_queue) {
302     goto err1;
303   }
304
305   /* Register protocols */
306   silc_server_protocols_register();
307
308   /* Initialize the scheduler */
309   silc_schedule_init(&server->io_queue, &server->timeout_queue, 
310                      &server->generic_queue, 
311                      SILC_SERVER_MAX_CONNECTIONS);
312   
313   /* Add the first task to the queue. This is task that is executed by
314      timeout. It expires as soon as the caller calls silc_server_run. This
315      task performs authentication protocol and key exchange with our
316      primary router. */
317   silc_task_register(server->timeout_queue, sock[0], 
318                      silc_server_connect_to_router,
319                      (void *)server, 0, 1,
320                      SILC_TASK_TIMEOUT,
321                      SILC_TASK_PRI_NORMAL);
322
323   /* Add listener task to the queue. This task receives new connections to the 
324      server. This task remains on the queue until the end of the program. */
325   silc_task_register(server->io_queue, sock[0],
326                      silc_server_accept_new_connection,
327                      (void *)server, 0, 0, 
328                      SILC_TASK_FD,
329                      SILC_TASK_PRI_NORMAL);
330   server->listenning = TRUE;
331
332   /* If server connections has been configured then we must be router as
333      normal server cannot have server connections, only router connections. */
334   if (server->config->servers)
335     server->server_type = SILC_ROUTER;
336
337   SILC_LOG_DEBUG(("Server initialized"));
338
339   /* We are done here, return succesfully */
340   return TRUE;
341
342   silc_task_queue_free(server->timeout_queue);
343  err1:
344   silc_task_queue_free(server->io_queue);
345  err0:
346   for (i = 0; i < sock_count; i++)
347     silc_net_close_server(sock[i]);
348
349   return FALSE;
350 }
351
352 /* Stops the SILC server. This function is used to shutdown the server. 
353    This is usually called after the scheduler has returned. After stopping 
354    the server one should call silc_server_free. */
355
356 void silc_server_stop(SilcServer server)
357 {
358   SILC_LOG_DEBUG(("Stopping server"));
359
360   /* Stop the scheduler, although it might be already stopped. This
361      doesn't hurt anyone. This removes all the tasks and task queues,
362      as well. */
363   silc_schedule_stop();
364   silc_schedule_uninit();
365
366   silc_server_protocols_unregister();
367
368   SILC_LOG_DEBUG(("Server stopped"));
369 }
370
371 /* The heart of the server. This runs the scheduler thus runs the server. 
372    When this returns the server has been stopped and the program will
373    be terminated. */
374
375 void silc_server_run(SilcServer server)
376 {
377   SILC_LOG_DEBUG(("Running server"));
378
379   /* Start the scheduler, the heart of the SILC server. When this returns
380      the program will be terminated. */
381   silc_schedule();
382 }
383
384 /* Timeout callback that will be called to retry connecting to remote
385    router. This is used by both normal and router server. This will wait
386    before retrying the connecting. The timeout is generated by exponential
387    backoff algorithm. */
388
389 SILC_TASK_CALLBACK(silc_server_connect_to_router_retry)
390 {
391   SilcServerConnection sconn = (SilcServerConnection)context;
392   SilcServer server = sconn->server;
393
394   SILC_LOG_INFO(("Retrying connecting to a router"));
395
396   /* Calculate next timeout */
397   if (sconn->retry_count >= 1) {
398     sconn->retry_timeout = sconn->retry_timeout * SILC_SERVER_RETRY_MULTIPLIER;
399     if (sconn->retry_timeout > SILC_SERVER_RETRY_INTERVAL_MAX)
400       sconn->retry_timeout = SILC_SERVER_RETRY_INTERVAL_MAX;
401   } else {
402     sconn->retry_timeout = server->params->retry_interval_min;
403   }
404   sconn->retry_count++;
405   sconn->retry_timeout = sconn->retry_timeout +
406     silc_rng_get_rn32(server->rng) % SILC_SERVER_RETRY_RANDOMIZER;
407
408   /* If we've reached max retry count, give up. */
409   if (sconn->retry_count > server->params->retry_count && 
410       server->params->retry_keep_trying == FALSE) {
411     SILC_LOG_ERROR(("Could not connect to router, giving up"));
412     return;
413   }
414
415   /* Wait one before retrying */
416   silc_task_register(server->timeout_queue, fd, silc_server_connect_router,
417                      context, sconn->retry_timeout, 
418                      server->params->retry_interval_min_usec,
419                      SILC_TASK_TIMEOUT, SILC_TASK_PRI_NORMAL);
420 }
421
422 /* Generic routine to use connect to a router. */
423
424 SILC_TASK_CALLBACK(silc_server_connect_router)
425 {    
426   SilcServerConnection sconn = (SilcServerConnection)context;
427   SilcServer server = sconn->server;
428   SilcSocketConnection newsocket;
429   SilcProtocol protocol;
430   SilcServerKEInternalContext *proto_ctx;
431   int sock;
432
433   /* Connect to remote host */
434   sock = silc_net_create_connection(sconn->remote_port, 
435                                     sconn->remote_host);
436   if (sock < 0) {
437     SILC_LOG_ERROR(("Could not connect to router"));
438     silc_task_register(server->timeout_queue, fd, 
439                        silc_server_connect_to_router_retry,
440                        context, 0, 1, SILC_TASK_TIMEOUT, 
441                        SILC_TASK_PRI_NORMAL);
442     return;
443   }
444
445   /* Set socket options */
446   silc_net_set_socket_nonblock(sock);
447   silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
448
449   /* Create socket connection for the connection. Even though we
450      know that we are connecting to a router we will mark the socket
451      to be unknown connection until we have executed authentication
452      protocol. */
453   silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
454   server->sockets[sock] = newsocket;
455   newsocket->hostname = sconn->remote_host;
456   newsocket->port = sconn->remote_port;
457   sconn->sock = newsocket;
458
459   /* Allocate internal protocol context. This is sent as context
460      to the protocol. */
461   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
462   proto_ctx->server = (void *)server;
463   proto_ctx->context = (void *)sconn;
464   proto_ctx->sock = newsocket;
465   proto_ctx->rng = server->rng;
466   proto_ctx->responder = FALSE;
467       
468   /* Perform key exchange protocol. silc_server_connect_to_router_second
469      will be called after the protocol is finished. */
470   silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE, 
471                       &protocol, proto_ctx,
472                       silc_server_connect_to_router_second);
473   newsocket->protocol = protocol;
474       
475   /* Register a timeout task that will be executed if the protocol
476      is not executed within set limit. */
477   proto_ctx->timeout_task = 
478     silc_task_register(server->timeout_queue, sock, 
479                        silc_server_timeout_remote,
480                        server, server->params->protocol_timeout,
481                        server->params->protocol_timeout_usec,
482                        SILC_TASK_TIMEOUT,
483                        SILC_TASK_PRI_LOW);
484
485   /* Register the connection for network input and output. This sets
486      that scheduler will listen for incoming packets for this connection 
487      and sets that outgoing packets may be sent to this connection as 
488      well. However, this doesn't set the scheduler for outgoing traffic,
489      it will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
490      later when outgoing data is available. */
491   context = (void *)server;
492   SILC_REGISTER_CONNECTION_FOR_IO(sock);
493   
494   /* Run the protocol */
495   protocol->execute(server->timeout_queue, 0, protocol, sock, 0, 0);
496 }
497   
498 /* This function connects to our primary router or if we are a router this
499    establishes all our primary routes. This is called at the start of the
500    server to do authentication and key exchange with our router - called
501    from schedule. */
502
503 SILC_TASK_CALLBACK(silc_server_connect_to_router)
504 {
505   SilcServer server = (SilcServer)context;
506   SilcServerConnection sconn;
507
508   SILC_LOG_DEBUG(("Connecting to router(s)"));
509
510   /* If we are normal SILC server we need to connect to our cell's
511      router. */
512   if (server->server_type == SILC_SERVER) {
513     SILC_LOG_DEBUG(("We are normal server"));
514
515     /* Create connection to the router, if configured. */
516     if (server->config->routers) {
517
518       /* Allocate connection object for hold connection specific stuff. */
519       sconn = silc_calloc(1, sizeof(*sconn));
520       sconn->server = server;
521       sconn->remote_host = server->config->routers->host;
522       sconn->remote_port = server->config->routers->port;
523
524       silc_task_register(server->timeout_queue, fd, 
525                          silc_server_connect_router,
526                          (void *)sconn, 0, 1, SILC_TASK_TIMEOUT, 
527                          SILC_TASK_PRI_NORMAL);
528       return;
529     }
530   }
531
532   /* If we are a SILC router we need to establish all of our primary
533      routes. */
534   if (server->server_type == SILC_ROUTER) {
535     SilcConfigServerSectionServerConnection *ptr;
536
537     SILC_LOG_DEBUG(("We are router"));
538
539     /* Create the connections to all our routes */
540     ptr = server->config->routers;
541     while (ptr) {
542
543       SILC_LOG_DEBUG(("Router connection [%s] %s:%d",
544                       ptr->initiator ? "Initiator" : "Responder",
545                       ptr->host, ptr->port));
546
547       if (ptr->initiator) {
548         /* Allocate connection object for hold connection specific stuff. */
549         sconn = silc_calloc(1, sizeof(*sconn));
550         sconn->server = server;
551         sconn->remote_host = ptr->host;
552         sconn->remote_port = ptr->port;
553
554         silc_task_register(server->timeout_queue, fd, 
555                            silc_server_connect_router,
556                            (void *)sconn, 0, 1, SILC_TASK_TIMEOUT, 
557                            SILC_TASK_PRI_NORMAL);
558       }
559
560       if (!ptr->next)
561         return;
562
563       ptr = ptr->next;
564     }
565   }
566
567   SILC_LOG_DEBUG(("No router(s), server will be standalone"));
568   
569   /* There wasn't a configured router, we will continue but we don't
570      have a connection to outside world.  We will be standalone server. */
571   server->standalone = TRUE;
572 }
573
574 /* Second part of connecting to router(s). Key exchange protocol has been
575    executed and now we will execute authentication protocol. */
576
577 SILC_TASK_CALLBACK(silc_server_connect_to_router_second)
578 {
579   SilcProtocol protocol = (SilcProtocol)context;
580   SilcServerKEInternalContext *ctx = 
581     (SilcServerKEInternalContext *)protocol->context;
582   SilcServer server = (SilcServer)ctx->server;
583   SilcServerConnection sconn = (SilcServerConnection)ctx->context;
584   SilcSocketConnection sock = NULL;
585   SilcServerConnAuthInternalContext *proto_ctx;
586
587   SILC_LOG_DEBUG(("Start"));
588
589   if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
590     /* Error occured during protocol */
591     silc_protocol_free(protocol);
592     if (ctx->packet)
593       silc_packet_context_free(ctx->packet);
594     if (ctx->ske)
595       silc_ske_free(ctx->ske);
596     if (ctx->dest_id)
597       silc_free(ctx->dest_id);
598     silc_free(ctx);
599     sock->protocol = NULL;
600     silc_server_disconnect_remote(server, sock, "Server closed connection: "
601                                   "Key exchange failed");
602     return;
603   }
604   
605   /* Allocate internal context for the authentication protocol. This
606      is sent as context for the protocol. */
607   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
608   proto_ctx->server = (void *)server;
609   proto_ctx->context = (void *)sconn;
610   proto_ctx->sock = sock = server->sockets[fd];
611   proto_ctx->ske = ctx->ske;       /* Save SKE object from previous protocol */
612   proto_ctx->dest_id_type = ctx->dest_id_type;
613   proto_ctx->dest_id = ctx->dest_id;
614
615   /* Resolve the authentication method used in this connection */
616   proto_ctx->auth_meth = SILC_PROTOCOL_CONN_AUTH_PASSWORD;
617   if (server->config->routers) {
618     SilcConfigServerSectionServerConnection *conn = NULL;
619
620     /* Check if we find a match from user configured connections */
621     conn = silc_config_server_find_router_conn(server->config,
622                                                sock->hostname,
623                                                sock->port);
624     if (conn) {
625       /* Match found. Use the configured authentication method */
626       proto_ctx->auth_meth = conn->auth_meth;
627       if (conn->auth_data) {
628         proto_ctx->auth_data = strdup(conn->auth_data);
629         proto_ctx->auth_data_len = strlen(conn->auth_data);
630       }
631     } else {
632       /* No match found. */
633       /* XXX */
634     }
635   } else {
636     /* XXX */
637   }
638
639   /* Free old protocol as it is finished now */
640   silc_protocol_free(protocol);
641   if (ctx->packet)
642     silc_packet_context_free(ctx->packet);
643   silc_free(ctx);
644   sock->protocol = NULL;
645
646   /* Allocate the authentication protocol. This is allocated here
647      but we won't start it yet. We will be receiving party of this
648      protocol thus we will wait that connecting party will make
649      their first move. */
650   silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH, 
651                       &sock->protocol, proto_ctx, 
652                       silc_server_connect_to_router_final);
653
654   /* Register timeout task. If the protocol is not executed inside
655      this timelimit the connection will be terminated. Currently
656      this is 15 seconds and is hard coded limit (XXX). */
657   proto_ctx->timeout_task = 
658     silc_task_register(server->timeout_queue, sock->sock, 
659                        silc_server_timeout_remote,
660                        (void *)server, 15, 0,
661                        SILC_TASK_TIMEOUT,
662                        SILC_TASK_PRI_LOW);
663
664   /* Run the protocol */
665   sock->protocol->execute(server->timeout_queue, 0, 
666                           sock->protocol, sock->sock, 0, 0);
667 }
668
669 /* Finalizes the connection to router. Registers a server task to the
670    queue so that we can accept new connections. */
671
672 SILC_TASK_CALLBACK(silc_server_connect_to_router_final)
673 {
674   SilcProtocol protocol = (SilcProtocol)context;
675   SilcServerConnAuthInternalContext *ctx = 
676     (SilcServerConnAuthInternalContext *)protocol->context;
677   SilcServer server = (SilcServer)ctx->server;
678   SilcServerConnection sconn = (SilcServerConnection)ctx->context;
679   SilcSocketConnection sock = ctx->sock;
680   SilcServerEntry id_entry;
681   SilcBuffer packet;
682   unsigned char *id_string;
683
684   SILC_LOG_DEBUG(("Start"));
685
686   if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
687     /* Error occured during protocol */
688     if (ctx->dest_id)
689       silc_free(ctx->dest_id);
690     silc_server_disconnect_remote(server, sock, "Server closed connection: "
691                                   "Authentication failed");
692     goto out;
693   }
694
695   /* Add a task to the queue. This task receives new connections to the 
696      server. This task remains on the queue until the end of the program. */
697   if (!server->listenning) {
698     silc_task_register(server->io_queue, server->sock, 
699                        silc_server_accept_new_connection,
700                        (void *)server, 0, 0, 
701                        SILC_TASK_FD,
702                        SILC_TASK_PRI_NORMAL);
703     server->listenning = TRUE;
704   }
705
706   /* Send NEW_SERVER packet to the router. We will become registered
707      to the SILC network after sending this packet. */
708   id_string = silc_id_id2str(server->id, SILC_ID_SERVER);
709   packet = silc_buffer_alloc(2 + 2 + SILC_ID_SERVER_LEN + 
710                              strlen(server->server_name));
711   silc_buffer_pull_tail(packet, SILC_BUFFER_END(packet));
712   silc_buffer_format(packet,
713                      SILC_STR_UI_SHORT(SILC_ID_SERVER_LEN),
714                      SILC_STR_UI_XNSTRING(id_string, SILC_ID_SERVER_LEN),
715                      SILC_STR_UI_SHORT(strlen(server->server_name)),
716                      SILC_STR_UI_XNSTRING(server->server_name,
717                                           strlen(server->server_name)),
718                      SILC_STR_END);
719
720   /* Send the packet */
721   silc_server_packet_send(server, ctx->sock, SILC_PACKET_NEW_SERVER, 0,
722                           packet->data, packet->len, TRUE);
723   silc_buffer_free(packet);
724   silc_free(id_string);
725
726   SILC_LOG_DEBUG(("Connected to router %s", sock->hostname));
727
728   /* Add the connected router to local server list */
729   server->standalone = FALSE;
730   id_entry = silc_idlist_add_server(server->local_list, sock->hostname,
731                                     SILC_ROUTER, ctx->dest_id, NULL, sock);
732   if (!id_entry) {
733     if (ctx->dest_id)
734       silc_free(ctx->dest_id);
735     silc_server_disconnect_remote(server, sock, "Server closed connection: "
736                                   "Authentication failed");
737     goto out;
738   }
739
740   silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
741   silc_free(sock->user_data);
742   sock->user_data = (void *)id_entry;
743   sock->type = SILC_SOCKET_TYPE_ROUTER;
744   server->id_entry->router = id_entry;
745   server->router = id_entry;
746   server->router->data.registered = TRUE;
747
748  out:
749   /* Free the temporary connection data context */
750   if (sconn)
751     silc_free(sconn);
752
753   /* Free the protocol object */
754   silc_protocol_free(protocol);
755   if (ctx->packet)
756     silc_packet_context_free(ctx->packet);
757   if (ctx->ske)
758     silc_ske_free(ctx->ske);
759   silc_free(ctx);
760   sock->protocol = NULL;
761 }
762
763 /* Accepts new connections to the server. Accepting new connections are
764    done in three parts to make it async. */
765
766 SILC_TASK_CALLBACK(silc_server_accept_new_connection)
767 {
768   SilcServer server = (SilcServer)context;
769   SilcSocketConnection newsocket;
770   SilcServerKEInternalContext *proto_ctx;
771   int sock;
772
773   SILC_LOG_DEBUG(("Accepting new connection"));
774
775   sock = silc_net_accept_connection(server->sock);
776   if (sock < 0) {
777     SILC_LOG_ERROR(("Could not accept new connection: %s", strerror(errno)));
778     return;
779   }
780
781   /* Check max connections */
782   if (sock > SILC_SERVER_MAX_CONNECTIONS) {
783     if (server->config->redirect) {
784       /* XXX Redirecting connection to somewhere else now?? */
785       /*silc_server_send_notify("Server is full, trying to redirect..."); */
786     } else {
787       SILC_LOG_ERROR(("Refusing connection, server is full"));
788     }
789     return;
790   }
791
792   /* Set socket options */
793   silc_net_set_socket_nonblock(sock);
794   silc_net_set_socket_opt(sock, SOL_SOCKET, SO_REUSEADDR, 1);
795
796   /* We don't create a ID yet, since we don't know what type of connection
797      this is yet. But, we do add the connection to the socket table. */
798   silc_socket_alloc(sock, SILC_SOCKET_TYPE_UNKNOWN, NULL, &newsocket);
799   server->sockets[sock] = newsocket;
800
801   /* XXX This MUST be done async as this will block the entire server
802      process. Either we have to do our own resolver stuff or in the future
803      we can use threads. */
804   /* Perform name and address lookups for the remote host. */
805   silc_net_check_host_by_sock(sock, &newsocket->hostname, &newsocket->ip);
806   if ((server->params->require_reverse_mapping && !newsocket->hostname) ||
807       !newsocket->ip) {
808     SILC_LOG_ERROR(("IP/DNS lookup failed"));
809     return;
810   }
811   if (!newsocket->hostname)
812     newsocket->hostname = strdup(newsocket->ip);
813
814   SILC_LOG_INFO(("Incoming connection from %s (%s)", newsocket->hostname,
815                  newsocket->ip));
816
817   /* Allocate internal context for key exchange protocol. This is
818      sent as context for the protocol. */
819   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
820   proto_ctx->server = context;
821   proto_ctx->sock = newsocket;
822   proto_ctx->rng = server->rng;
823   proto_ctx->responder = TRUE;
824
825   /* Prepare the connection for key exchange protocol. We allocate the
826      protocol but will not start it yet. The connector will be the
827      initiator of the protocol thus we will wait for initiation from 
828      there before we start the protocol. */
829   silc_protocol_alloc(SILC_PROTOCOL_SERVER_KEY_EXCHANGE, 
830                       &newsocket->protocol, proto_ctx, 
831                       silc_server_accept_new_connection_second);
832
833   /* Register a timeout task that will be executed if the connector
834      will not start the key exchange protocol within 60 seconds. For
835      now, this is a hard coded limit. After 60 secs the connection will
836      be closed if the key exchange protocol has not been started. */
837   proto_ctx->timeout_task = 
838     silc_task_register(server->timeout_queue, newsocket->sock, 
839                        silc_server_timeout_remote,
840                        context, 60, 0,
841                        SILC_TASK_TIMEOUT,
842                        SILC_TASK_PRI_LOW);
843
844   /* Register the connection for network input and output. This sets
845      that scheduler will listen for incoming packets for this connection 
846      and sets that outgoing packets may be sent to this connection as well.
847      However, this doesn't set the scheduler for outgoing traffic, it
848      will be set separately by calling SILC_SET_CONNECTION_FOR_OUTPUT,
849      later when outgoing data is available. */
850   SILC_REGISTER_CONNECTION_FOR_IO(sock);
851 }
852
853 /* Second part of accepting new connection. Key exchange protocol has been
854    performed and now it is time to do little connection authentication
855    protocol to figure out whether this connection is client or server
856    and whether it has right to access this server (especially server
857    connections needs to be authenticated). */
858
859 SILC_TASK_CALLBACK(silc_server_accept_new_connection_second)
860 {
861   SilcProtocol protocol = (SilcProtocol)context;
862   SilcServerKEInternalContext *ctx = 
863     (SilcServerKEInternalContext *)protocol->context;
864   SilcServer server = (SilcServer)ctx->server;
865   SilcSocketConnection sock = NULL;
866   SilcServerConnAuthInternalContext *proto_ctx;
867
868   SILC_LOG_DEBUG(("Start"));
869
870   if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
871     /* Error occured during protocol */
872     silc_protocol_free(protocol);
873     if (ctx->packet)
874       silc_packet_context_free(ctx->packet);
875     if (ctx->ske)
876       silc_ske_free(ctx->ske);
877     if (ctx->dest_id)
878       silc_free(ctx->dest_id);
879     silc_free(ctx);
880     if (sock)
881       sock->protocol = NULL;
882     silc_server_disconnect_remote(server, sock, "Server closed connection: "
883                                   "Key exchange failed");
884     return;
885   }
886
887   /* Allocate internal context for the authentication protocol. This
888      is sent as context for the protocol. */
889   proto_ctx = silc_calloc(1, sizeof(*proto_ctx));
890   proto_ctx->server = (void *)server;
891   proto_ctx->sock = sock = server->sockets[fd];
892   proto_ctx->ske = ctx->ske;    /* Save SKE object from previous protocol */
893   proto_ctx->responder = TRUE;
894   proto_ctx->dest_id_type = ctx->dest_id_type;
895   proto_ctx->dest_id = ctx->dest_id;
896
897   /* Free old protocol as it is finished now */
898   silc_protocol_free(protocol);
899   if (ctx->packet)
900     silc_packet_context_free(ctx->packet);
901   silc_free(ctx);
902   sock->protocol = NULL;
903
904   /* Allocate the authentication protocol. This is allocated here
905      but we won't start it yet. We will be receiving party of this
906      protocol thus we will wait that connecting party will make
907      their first move. */
908   silc_protocol_alloc(SILC_PROTOCOL_SERVER_CONNECTION_AUTH, 
909                       &sock->protocol, proto_ctx, 
910                       silc_server_accept_new_connection_final);
911
912   /* Register timeout task. If the protocol is not executed inside
913      this timelimit the connection will be terminated. Currently
914      this is 60 seconds and is hard coded limit (XXX). */
915   proto_ctx->timeout_task = 
916     silc_task_register(server->timeout_queue, sock->sock, 
917                        silc_server_timeout_remote,
918                        (void *)server, 60, 0,
919                        SILC_TASK_TIMEOUT,
920                        SILC_TASK_PRI_LOW);
921 }
922
923 /* Final part of accepting new connection. The connection has now
924    been authenticated and keys has been exchanged. We also know whether
925    this is client or server connection. */
926
927 SILC_TASK_CALLBACK(silc_server_accept_new_connection_final)
928 {
929   SilcProtocol protocol = (SilcProtocol)context;
930   SilcServerConnAuthInternalContext *ctx = 
931     (SilcServerConnAuthInternalContext *)protocol->context;
932   SilcServer server = (SilcServer)ctx->server;
933   SilcSocketConnection sock = ctx->sock;
934   void *id_entry = NULL;
935
936   SILC_LOG_DEBUG(("Start"));
937
938   if (protocol->state == SILC_PROTOCOL_STATE_ERROR) {
939     /* Error occured during protocol */
940     silc_protocol_free(protocol);
941     if (ctx->packet)
942       silc_packet_context_free(ctx->packet);
943     if (ctx->ske)
944       silc_ske_free(ctx->ske);
945     if (ctx->dest_id)
946       silc_free(ctx->dest_id);
947     silc_free(ctx);
948     if (sock)
949       sock->protocol = NULL;
950     silc_server_disconnect_remote(server, sock, "Server closed connection: "
951                                   "Authentication failed");
952     return;
953   }
954
955   sock->type = ctx->conn_type;
956   switch(sock->type) {
957   case SILC_SOCKET_TYPE_CLIENT:
958     {
959       SilcClientEntry client;
960
961       SILC_LOG_DEBUG(("Remote host is client"));
962       SILC_LOG_INFO(("Connection from %s (%s) is client", sock->hostname,
963                      sock->ip));
964
965       /* Add the client to the client ID cache. The nickname and Client ID
966          and other information is created after we have received NEW_CLIENT
967          packet from client. */
968       client = silc_idlist_add_client(server->local_list, 
969                                       NULL, NULL, NULL, NULL, NULL, sock);
970       if (!client) {
971         SILC_LOG_ERROR(("Could not add new client to cache"));
972         silc_free(sock->user_data);
973         break;
974       }
975
976       id_entry = (void *)client;
977       break;
978     }
979   case SILC_SOCKET_TYPE_SERVER:
980   case SILC_SOCKET_TYPE_ROUTER:
981     {
982       SilcServerEntry new_server;
983
984       SILC_LOG_DEBUG(("Remote host is %s", 
985                       sock->type == SILC_SOCKET_TYPE_SERVER ? 
986                       "server" : "router"));
987       SILC_LOG_INFO(("Connection from %s (%s) is %s", sock->hostname,
988                      sock->ip, sock->type == SILC_SOCKET_TYPE_SERVER ? 
989                      "server" : "router"));
990
991       /* Add the server into server cache. The server name and Server ID
992          is updated after we have received NEW_SERVER packet from the
993          server. We mark ourselves as router for this server if we really
994          are router. */
995       new_server = 
996         silc_idlist_add_server(server->local_list, NULL,
997                                sock->type == SILC_SOCKET_TYPE_SERVER ?
998                                SILC_SERVER : SILC_ROUTER, NULL, 
999                                sock->type == SILC_SOCKET_TYPE_SERVER ?
1000                                server->id_entry : NULL, sock);
1001       if (!new_server) {
1002         SILC_LOG_ERROR(("Could not add new server to cache"));
1003         silc_free(sock->user_data);
1004         break;
1005       }
1006
1007       id_entry = (void *)new_server;
1008       
1009       /* There is connection to other server now, if it is router then
1010          we will have connection to outside world.  If we are router but
1011          normal server connected to us then we will remain standalone,
1012          if we are standlone. */
1013       if (server->standalone && sock->type == SILC_SOCKET_TYPE_ROUTER) {
1014         SILC_LOG_DEBUG(("We are not standalone server anymore"));
1015         server->standalone = FALSE;
1016         if (!server->id_entry->router) {
1017           server->id_entry->router = id_entry;
1018           server->router = id_entry;
1019         }
1020       }
1021       break;
1022     }
1023   default:
1024     break;
1025   }
1026
1027   /* Add the common data structure to the ID entry. */
1028   if (id_entry)
1029     silc_idlist_add_data(id_entry, (SilcIDListData)sock->user_data);
1030       
1031   /* Add to sockets internal pointer for fast referencing */
1032   silc_free(sock->user_data);
1033   sock->user_data = id_entry;
1034
1035   /* Connection has been fully established now. Everything is ok. */
1036   SILC_LOG_DEBUG(("New connection authenticated"));
1037
1038   silc_protocol_free(protocol);
1039   if (ctx->packet)
1040     silc_packet_context_free(ctx->packet);
1041   if (ctx->ske)
1042     silc_ske_free(ctx->ske);
1043   if (ctx->dest_id)
1044     silc_free(ctx->dest_id);
1045   silc_free(ctx);
1046   sock->protocol = NULL;
1047 }
1048
1049 /* This function is used to read packets from network and send packets to
1050    network. This is usually a generic task. */
1051
1052 SILC_TASK_CALLBACK(silc_server_packet_process)
1053 {
1054   SilcServer server = (SilcServer)context;
1055   SilcSocketConnection sock = server->sockets[fd];
1056   SilcIDListData idata;
1057   SilcCipher cipher = NULL;
1058   SilcHmac hmac = NULL;
1059   int ret;
1060
1061   SILC_LOG_DEBUG(("Processing packet"));
1062
1063   /* Packet sending */
1064
1065   if (type == SILC_TASK_WRITE) {
1066     if (sock->outbuf->data - sock->outbuf->head)
1067       silc_buffer_push(sock->outbuf, sock->outbuf->data - sock->outbuf->head);
1068
1069     ret = silc_server_packet_send_real(server, sock, TRUE);
1070
1071     /* If returned -2 could not write to connection now, will do
1072        it later. */
1073     if (ret == -2)
1074       return;
1075     
1076     /* The packet has been sent and now it is time to set the connection
1077        back to only for input. When there is again some outgoing data 
1078        available for this connection it will be set for output as well. 
1079        This call clears the output setting and sets it only for input. */
1080     SILC_SET_CONNECTION_FOR_INPUT(fd);
1081     SILC_UNSET_OUTBUF_PENDING(sock);
1082
1083     silc_buffer_clear(sock->outbuf);
1084     return;
1085   }
1086
1087   /* Packet receiving */
1088
1089   /* Read some data from connection */
1090   ret = silc_packet_receive(sock);
1091   if (ret < 0)
1092     return;
1093     
1094   /* EOF */
1095   if (ret == 0) {
1096     SILC_LOG_DEBUG(("Read EOF"));
1097       
1098     /* If connection is disconnecting already we will finally
1099        close the connection */
1100     if (SILC_IS_DISCONNECTING(sock)) {
1101       if (sock->user_data)
1102         silc_server_free_sock_user_data(server, sock);
1103       silc_server_close_connection(server, sock);
1104       return;
1105     }
1106       
1107     SILC_LOG_DEBUG(("Premature EOF from connection %d", sock->sock));
1108
1109     if (sock->user_data)
1110       silc_server_free_sock_user_data(server, sock);
1111     silc_server_close_connection(server, sock);
1112     return;
1113   }
1114
1115   /* If connection is disconnecting or disconnected we will ignore
1116      what we read. */
1117   if (SILC_IS_DISCONNECTING(sock) || SILC_IS_DISCONNECTED(sock)) {
1118     SILC_LOG_DEBUG(("Ignoring read data from invalid connection"));
1119     return;
1120   }
1121
1122   /* Get keys and stuff from ID entry */
1123   idata = (SilcIDListData)sock->user_data;
1124   if (idata) {
1125     idata->last_receive = time(NULL);
1126     cipher = idata->receive_key;
1127     hmac = idata->hmac;
1128   }
1129  
1130   /* Process the packet. This will call the parser that will then
1131      decrypt and parse the packet. */
1132   silc_packet_receive_process(sock, cipher, hmac, silc_server_packet_parse, 
1133                               server);
1134 }
1135
1136 /* Parses whole packet, received earlier. */
1137
1138 SILC_TASK_CALLBACK(silc_server_packet_parse_real)
1139 {
1140   SilcPacketParserContext *parse_ctx = (SilcPacketParserContext *)context;
1141   SilcServer server = (SilcServer)parse_ctx->context;
1142   SilcSocketConnection sock = parse_ctx->sock;
1143   SilcPacketContext *packet = parse_ctx->packet;
1144   int ret;
1145
1146   SILC_LOG_DEBUG(("Start"));
1147
1148   /* Decrypt the received packet */
1149   ret = silc_packet_decrypt(parse_ctx->cipher, parse_ctx->hmac, 
1150                             packet->buffer, packet);
1151   if (ret < 0)
1152     goto out;
1153
1154   if (ret == 0) {
1155     /* Parse the packet. Packet type is returned. */
1156     ret = silc_packet_parse(packet);
1157   } else {
1158     /* Parse the packet header in special way as this is "special"
1159        packet type. */
1160     ret = silc_packet_parse_special(packet);
1161   }
1162
1163   if (ret == SILC_PACKET_NONE)
1164     goto out;
1165
1166   if (server->server_type == SILC_ROUTER) {
1167     /* Route the packet if it is not destined to us. Other ID types but
1168        server are handled separately after processing them. */
1169     if (packet->dst_id_type == SILC_ID_SERVER && 
1170         sock->type != SILC_SOCKET_TYPE_CLIENT &&
1171         SILC_ID_SERVER_COMPARE(packet->dst_id, server->id_string)) {
1172       
1173       /* Route the packet to fastest route for the destination ID */
1174       void *id = silc_id_str2id(packet->dst_id, packet->dst_id_type);
1175       silc_server_packet_route(server,
1176                                silc_server_route_get(server, id,
1177                                                      packet->dst_id_type),
1178                                packet);
1179       silc_free(id);
1180       goto out;
1181     }
1182     
1183     /* Broadcast packet if it is marked as broadcast packet and it is
1184        originated from router and we are router. */
1185     if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
1186         packet->flags & SILC_PACKET_FLAG_BROADCAST) {
1187       silc_server_packet_broadcast(server, server->router->connection, packet);
1188     }
1189   }
1190
1191   /* Parse the incoming packet type */
1192   silc_server_packet_parse_type(server, sock, packet);
1193
1194  out:
1195   silc_buffer_clear(sock->inbuf);
1196   silc_packet_context_free(packet);
1197   silc_free(parse_ctx);
1198 }
1199
1200 /* Parser callback called by silc_packet_receive_process. This merely
1201    registers timeout that will handle the actual parsing when appropriate. */
1202
1203 void silc_server_packet_parse(SilcPacketParserContext *parser_context)
1204 {
1205   SilcServer server = (SilcServer)parser_context->context;
1206   SilcSocketConnection sock = parser_context->sock;
1207
1208   switch (sock->type) {
1209   case SILC_SOCKET_TYPE_CLIENT:
1210   case SILC_SOCKET_TYPE_UNKNOWN:
1211     /* Parse the packet with timeout */
1212     silc_task_register(server->timeout_queue, sock->sock,
1213                        silc_server_packet_parse_real,
1214                        (void *)parser_context, 0, 100000,
1215                        SILC_TASK_TIMEOUT,
1216                        SILC_TASK_PRI_NORMAL);
1217     break;
1218   case SILC_SOCKET_TYPE_SERVER:
1219   case SILC_SOCKET_TYPE_ROUTER:
1220     /* Packets from servers are parsed as soon as possible */
1221     silc_task_register(server->timeout_queue, sock->sock,
1222                        silc_server_packet_parse_real,
1223                        (void *)parser_context, 0, 1,
1224                        SILC_TASK_TIMEOUT,
1225                        SILC_TASK_PRI_NORMAL);
1226     break;
1227   default:
1228     return;
1229   }
1230 }
1231
1232 /* Parses the packet type and calls what ever routines the packet type
1233    requires. This is done for all incoming packets. */
1234
1235 void silc_server_packet_parse_type(SilcServer server, 
1236                                    SilcSocketConnection sock,
1237                                    SilcPacketContext *packet)
1238 {
1239   SilcPacketType type = packet->type;
1240
1241   SILC_LOG_DEBUG(("Parsing packet type %d", type));
1242
1243   /* Parse the packet type */
1244   switch(type) {
1245   case SILC_PACKET_DISCONNECT:
1246     SILC_LOG_DEBUG(("Disconnect packet"));
1247     break;
1248
1249   case SILC_PACKET_SUCCESS:
1250     /*
1251      * Success received for something. For now we can have only
1252      * one protocol for connection executing at once hence this
1253      * success message is for whatever protocol is executing currently.
1254      */
1255     SILC_LOG_DEBUG(("Success packet"));
1256     if (sock->protocol) {
1257       sock->protocol->execute(server->timeout_queue, 0,
1258                               sock->protocol, sock->sock, 0, 0);
1259     }
1260     break;
1261
1262   case SILC_PACKET_FAILURE:
1263     /*
1264      * Failure received for something. For now we can have only
1265      * one protocol for connection executing at once hence this
1266      * failure message is for whatever protocol is executing currently.
1267      */
1268     SILC_LOG_DEBUG(("Failure packet"));
1269     if (sock->protocol) {
1270       /* XXX Audit the failure type */
1271       sock->protocol->state = SILC_PROTOCOL_STATE_FAILURE;
1272       sock->protocol->execute(server->timeout_queue, 0,
1273                               sock->protocol, sock->sock, 0, 0);
1274     }
1275     break;
1276
1277   case SILC_PACKET_REJECT:
1278     SILC_LOG_DEBUG(("Reject packet"));
1279     return;
1280     break;
1281
1282   case SILC_PACKET_NOTIFY:
1283     /*
1284      * Received notify packet. Server can receive notify packets from
1285      * router. Server then relays the notify messages to clients if needed.
1286      */
1287     SILC_LOG_DEBUG(("Notify packet"));
1288     silc_server_notify(server, sock, packet);
1289     break;
1290
1291     /* 
1292      * Channel packets
1293      */
1294   case SILC_PACKET_CHANNEL_MESSAGE:
1295     /*
1296      * Received channel message. Channel messages are special packets
1297      * (although probably most common ones) thus they are handled
1298      * specially.
1299      */
1300     SILC_LOG_DEBUG(("Channel Message packet"));
1301     silc_server_channel_message(server, sock, packet);
1302     break;
1303
1304   case SILC_PACKET_CHANNEL_KEY:
1305     /*
1306      * Received key for channel. As channels are created by the router
1307      * the keys are as well. We will distribute the key to all of our
1308      * locally connected clients on the particular channel. Router
1309      * never receives this channel and thus is ignored.
1310      */
1311     SILC_LOG_DEBUG(("Channel Key packet"));
1312     silc_server_channel_key(server, sock, packet);
1313     break;
1314
1315     /*
1316      * Command packets
1317      */
1318   case SILC_PACKET_COMMAND:
1319     /*
1320      * Recived command. Processes the command request and allocates the
1321      * command context and calls the command.
1322      */
1323     SILC_LOG_DEBUG(("Command packet"));
1324     silc_server_command_process(server, sock, packet);
1325     break;
1326
1327   case SILC_PACKET_COMMAND_REPLY:
1328     /*
1329      * Received command reply packet. Received command reply to command. It
1330      * may be reply to command sent by us or reply to command sent by client
1331      * that we've routed further.
1332      */
1333     SILC_LOG_DEBUG(("Command Reply packet"));
1334     silc_server_command_reply(server, sock, packet);
1335     break;
1336
1337     /*
1338      * Private Message packets
1339      */
1340   case SILC_PACKET_PRIVATE_MESSAGE:
1341     /*
1342      * Received private message packet. The packet is coming from either
1343      * client or server.
1344      */
1345     SILC_LOG_DEBUG(("Private Message packet"));
1346     silc_server_private_message(server, sock, packet);
1347     break;
1348
1349   case SILC_PACKET_PRIVATE_MESSAGE_KEY:
1350     /*
1351      * Private message key packet.
1352      */
1353     break;
1354
1355     /*
1356      * Key Exchange protocol packets
1357      */
1358   case SILC_PACKET_KEY_EXCHANGE:
1359     SILC_LOG_DEBUG(("KE packet"));
1360     if (sock->protocol && sock->protocol->protocol->type 
1361         == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1362
1363       SilcServerKEInternalContext *proto_ctx = 
1364         (SilcServerKEInternalContext *)sock->protocol->context;
1365
1366       proto_ctx->packet = silc_packet_context_dup(packet);
1367
1368       /* Let the protocol handle the packet */
1369       sock->protocol->execute(server->timeout_queue, 0, 
1370                               sock->protocol, sock->sock, 0, 100000);
1371     } else {
1372       SILC_LOG_ERROR(("Received Key Exchange packet but no key exchange "
1373                       "protocol active, packet dropped."));
1374
1375       /* XXX Trigger KE protocol?? Rekey actually, maybe. */
1376     }
1377     break;
1378
1379   case SILC_PACKET_KEY_EXCHANGE_1:
1380     SILC_LOG_DEBUG(("KE 1 packet"));
1381     if (sock->protocol && sock->protocol->protocol->type 
1382         == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1383
1384       SilcServerKEInternalContext *proto_ctx = 
1385         (SilcServerKEInternalContext *)sock->protocol->context;
1386
1387       if (proto_ctx->packet)
1388         silc_packet_context_free(proto_ctx->packet);
1389
1390       proto_ctx->packet = silc_packet_context_dup(packet);
1391       proto_ctx->dest_id_type = packet->src_id_type;
1392       proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_type);
1393
1394       /* Let the protocol handle the packet */
1395       sock->protocol->execute(server->timeout_queue, 0, 
1396                               sock->protocol, sock->sock,
1397                               0, 100000);
1398     } else {
1399       SILC_LOG_ERROR(("Received Key Exchange 1 packet but no key exchange "
1400                       "protocol active, packet dropped."));
1401     }
1402     break;
1403
1404   case SILC_PACKET_KEY_EXCHANGE_2:
1405     SILC_LOG_DEBUG(("KE 2 packet"));
1406     if (sock->protocol && sock->protocol->protocol->type 
1407         == SILC_PROTOCOL_SERVER_KEY_EXCHANGE) {
1408
1409       SilcServerKEInternalContext *proto_ctx = 
1410         (SilcServerKEInternalContext *)sock->protocol->context;
1411
1412       if (proto_ctx->packet)
1413         silc_packet_context_free(proto_ctx->packet);
1414
1415       proto_ctx->packet = silc_packet_context_dup(packet);
1416       proto_ctx->dest_id_type = packet->src_id_type;
1417       proto_ctx->dest_id = silc_id_str2id(packet->src_id, packet->src_id_type);
1418
1419       /* Let the protocol handle the packet */
1420       sock->protocol->execute(server->timeout_queue, 0, 
1421                               sock->protocol, sock->sock,
1422                               0, 100000);
1423     } else {
1424       SILC_LOG_ERROR(("Received Key Exchange 2 packet but no key exchange "
1425                       "protocol active, packet dropped."));
1426     }
1427     break;
1428
1429   case SILC_PACKET_CONNECTION_AUTH_REQUEST:
1430     /*
1431      * Connection authentication request packet. When we receive this packet
1432      * we will send to the other end information about our mandatory
1433      * authentication method for the connection. This packet maybe received
1434      * at any time. 
1435      */
1436     SILC_LOG_DEBUG(("Connection authentication request packet"));
1437     break;
1438
1439     /*
1440      * Connection Authentication protocol packets
1441      */
1442   case SILC_PACKET_CONNECTION_AUTH:
1443     /* Start of the authentication protocol. We receive here the 
1444        authentication data and will verify it. */
1445     SILC_LOG_DEBUG(("Connection auth packet"));
1446     if (sock->protocol && sock->protocol->protocol->type 
1447         == SILC_PROTOCOL_SERVER_CONNECTION_AUTH) {
1448
1449       SilcServerConnAuthInternalContext *proto_ctx = 
1450         (SilcServerConnAuthInternalContext *)sock->protocol->context;
1451
1452       proto_ctx->packet = silc_packet_context_dup(packet);
1453
1454       /* Let the protocol handle the packet */
1455       sock->protocol->execute(server->timeout_queue, 0, 
1456                               sock->protocol, sock->sock, 0, 0);
1457     } else {
1458       SILC_LOG_ERROR(("Received Connection Auth packet but no authentication "
1459                       "protocol active, packet dropped."));
1460     }
1461     break;
1462
1463   case SILC_PACKET_NEW_ID:
1464     /*
1465      * Received New ID packet. This includes some new ID that has been
1466      * created. It may be for client, server or channel. This is the way
1467      * to distribute information about new registered entities in the
1468      * SILC network.
1469      */
1470     SILC_LOG_DEBUG(("New ID packet"));
1471     silc_server_new_id(server, sock, packet);
1472     break;
1473
1474   case SILC_PACKET_NEW_CLIENT:
1475     /*
1476      * Received new client packet. This includes client information that
1477      * we will use to create initial client ID. After creating new
1478      * ID we will send it to the client.
1479      */
1480     SILC_LOG_DEBUG(("New Client packet"));
1481     silc_server_new_client(server, sock, packet);
1482     break;
1483
1484   case SILC_PACKET_NEW_SERVER:
1485     /*
1486      * Received new server packet. This includes Server ID and some other
1487      * information that we may save. This is received after server has 
1488      * connected to us.
1489      */
1490     SILC_LOG_DEBUG(("New Server packet"));
1491     silc_server_new_server(server, sock, packet);
1492     break;
1493
1494   case SILC_PACKET_NEW_CHANNEL:
1495     /*
1496      * Received new channel packet. Information about new channel in the
1497      * network are distributed using this packet.
1498      */
1499     SILC_LOG_DEBUG(("New Channel packet"));
1500     silc_server_new_channel(server, sock, packet);
1501     break;
1502
1503   case SILC_PACKET_NEW_CHANNEL_USER:
1504     /*
1505      * Received new channel user packet. Information about new users on a
1506      * channel are distributed between routers using this packet.  The
1507      * router receiving this will redistribute it and also sent JOIN notify
1508      * to local clients on the same channel. Normal server sends JOIN notify
1509      * to its local clients on the channel.
1510      */
1511     SILC_LOG_DEBUG(("New Channel User packet"));
1512     silc_server_new_channel_user(server, sock, packet);
1513     break;
1514
1515   case SILC_PACKET_NEW_CHANNEL_LIST:
1516     /*
1517      * List of new channel packets received. This is usually received when
1518      * existing server or router connects to us and distributes information
1519      * of all channels it has.
1520      */
1521     break;
1522
1523   case SILC_PACKET_NEW_CHANNEL_USER_LIST:
1524     /*
1525      * List of new channel user packets received. This is usually received
1526      * when existing server or router connects to us and distributes 
1527      * information of all channel users it has.
1528      */
1529     break;
1530
1531   case SILC_PACKET_REPLACE_ID:
1532     /*
1533      * Received replace ID packet. This sends the old ID that is to be
1534      * replaced with the new one included into the packet. Client must not
1535      * send this packet.
1536      */
1537     SILC_LOG_DEBUG(("Replace ID packet"));
1538     silc_server_replace_id(server, sock, packet);
1539     break;
1540
1541   case SILC_PACKET_REMOVE_ID:
1542     /*
1543      * Received remove ID Packet. 
1544      */
1545     SILC_LOG_DEBUG(("Remove ID packet"));
1546     silc_server_remove_id(server, sock, packet);
1547     break;
1548
1549   case SILC_PACKET_REMOVE_CHANNEL_USER:
1550     /*
1551      * Received packet to remove user from a channel. Routers notify other
1552      * routers about a user leaving a channel.
1553      */
1554     SILC_LOG_DEBUG(("Remove Channel User packet"));
1555     silc_server_remove_channel_user(server, sock, packet);
1556     break;
1557
1558   default:
1559     SILC_LOG_ERROR(("Incorrect packet type %d, packet dropped", type));
1560     break;
1561   }
1562   
1563 }
1564
1565 /* Closes connection to socket connection */
1566
1567 void silc_server_close_connection(SilcServer server,
1568                                   SilcSocketConnection sock)
1569 {
1570
1571   SILC_LOG_DEBUG(("Closing connection %d", sock->sock));
1572
1573   /* We won't listen for this connection anymore */
1574   silc_schedule_unset_listen_fd(sock->sock);
1575
1576   /* Unregister all tasks */
1577   silc_task_unregister_by_fd(server->io_queue, sock->sock);
1578   silc_task_unregister_by_fd(server->timeout_queue, sock->sock);
1579
1580   /* Close the actual connection */
1581   silc_net_close_connection(sock->sock);
1582   server->sockets[sock->sock] = NULL;
1583   silc_socket_free(sock);
1584 }
1585
1586 /* Sends disconnect message to remote connection and disconnects the 
1587    connection. */
1588
1589 void silc_server_disconnect_remote(SilcServer server,
1590                                    SilcSocketConnection sock,
1591                                    const char *fmt, ...)
1592 {
1593   va_list ap;
1594   unsigned char buf[4096];
1595
1596   memset(buf, 0, sizeof(buf));
1597   va_start(ap, fmt);
1598   vsprintf(buf, fmt, ap);
1599   va_end(ap);
1600
1601   SILC_LOG_DEBUG(("Disconnecting remote host"));
1602
1603   /* Notify remote end that the conversation is over. The notify message
1604      is tried to be sent immediately. */
1605   silc_server_packet_send(server, sock, SILC_PACKET_DISCONNECT, 0,  
1606                           buf, strlen(buf), TRUE);
1607
1608   /* Mark the connection to be disconnected */
1609   SILC_SET_DISCONNECTED(sock);
1610   silc_server_close_connection(server, sock);
1611 }
1612
1613 /* Free's user_data pointer from socket connection object. This also sends
1614    appropriate notify packets to the network to inform about leaving
1615    entities. */
1616
1617 void silc_server_free_sock_user_data(SilcServer server, 
1618                                      SilcSocketConnection sock)
1619 {
1620   SILC_LOG_DEBUG(("Start"));
1621
1622   switch(sock->type) {
1623   case SILC_SOCKET_TYPE_CLIENT:
1624     {
1625       SilcClientEntry user_data = (SilcClientEntry)sock->user_data;
1626
1627       /* Remove client from all channels */
1628       silc_server_remove_from_channels(server, sock, user_data);
1629
1630       /* XXX must take some info to history before freeing */
1631
1632       /* Send REMOVE_ID packet to routers. */
1633       silc_server_send_remove_id(server, server->router->connection,
1634                                  server->server_type == SILC_SERVER ?
1635                                  FALSE : TRUE, user_data->id, 
1636                                  SILC_ID_CLIENT_LEN, SILC_ID_CLIENT);
1637
1638       /* Free the client entry and everything in it */
1639       silc_idlist_del_data(user_data);
1640       silc_idlist_del_client(server->local_list, user_data);
1641       break;
1642     }
1643   case SILC_SOCKET_TYPE_SERVER:
1644   case SILC_SOCKET_TYPE_ROUTER:
1645     {
1646       SilcServerEntry user_data = (SilcServerEntry)sock->user_data;
1647
1648       /* Send REMOVE_ID packet to routers. */
1649       silc_server_send_remove_id(server, server->router->connection,
1650                                  server->server_type == SILC_SERVER ?
1651                                  FALSE : TRUE, user_data->id, 
1652                                  SILC_ID_SERVER_LEN, SILC_ID_SERVER);
1653       break;
1654     }
1655     break;
1656   default:
1657     {
1658       SilcUnknownEntry user_data = (SilcUnknownEntry)sock->user_data;
1659
1660       silc_idlist_del_data(user_data);
1661       silc_free(user_data);
1662       break;
1663     }
1664   }
1665
1666   sock->user_data = NULL;
1667 }
1668
1669 /* Checks whether given channel has global users.  If it does this returns
1670    TRUE and FALSE if there is only locally connected clients on the channel. */
1671
1672 int silc_server_channel_has_global(SilcChannelEntry channel)
1673 {
1674   SilcChannelClientEntry chl;
1675
1676   silc_list_start(channel->user_list);
1677   while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
1678     if (chl->client->router)
1679       return TRUE;
1680   }
1681
1682   return FALSE;
1683 }
1684
1685 /* Checks whether given channel has locally connected users.  If it does this
1686    returns TRUE and FALSE if there is not one locally connected client. */
1687
1688 int silc_server_channel_has_local(SilcChannelEntry channel)
1689 {
1690   SilcChannelClientEntry chl;
1691
1692   silc_list_start(channel->user_list);
1693   while ((chl = silc_list_get(channel->user_list)) != SILC_LIST_END) {
1694     if (!chl->client->router)
1695       return TRUE;
1696   }
1697
1698   return FALSE;
1699 }
1700
1701 /* Removes client from all channels it has joined. This is used when client
1702    connection is disconnected. If the client on a channel is last, the
1703    channel is removed as well. This sends the SIGNOFF notify types. */
1704
1705 void silc_server_remove_from_channels(SilcServer server, 
1706                                       SilcSocketConnection sock,
1707                                       SilcClientEntry client)
1708 {
1709   SilcChannelEntry channel;
1710   SilcChannelClientEntry chl;
1711   SilcBuffer chidp, clidp;
1712
1713   SILC_LOG_DEBUG(("Start"));
1714
1715   if (!client || !client->id)
1716     return;
1717
1718   clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
1719
1720   /* Remove the client from all channels. The client is removed from
1721      the channels' user list. */
1722   silc_list_start(client->channels);
1723   while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
1724     channel = chl->channel;
1725     chidp = silc_id_payload_encode(channel->id, SILC_ID_CHANNEL);
1726
1727     /* Remove from list */
1728     silc_list_del(client->channels, chl);
1729
1730     /* If this client is last one on the channel the channel
1731        is removed all together. */
1732     if (silc_list_count(channel->user_list) < 2) {
1733
1734       /* However, if the channel has marked global users then the 
1735          channel is not created locally, and this does not remove the
1736          channel globally from SILC network, in this case we will
1737          notify that this client has left the channel. */
1738       if (channel->global_users)
1739         silc_server_send_notify_to_channel(server, channel, FALSE,
1740                                            SILC_NOTIFY_TYPE_SIGNOFF, 1,
1741                                            clidp->data, clidp->len);
1742       
1743       silc_idlist_del_channel(server->local_list, channel);
1744       continue;
1745     }
1746
1747     /* Remove from list */
1748     silc_list_del(channel->user_list, chl);
1749     silc_free(chl);
1750
1751     /* Send notify to channel about client leaving SILC and thus
1752        the entire channel. */
1753     silc_server_send_notify_to_channel(server, channel, FALSE,
1754                                        SILC_NOTIFY_TYPE_SIGNOFF, 1,
1755                                        clidp->data, clidp->len);
1756     silc_buffer_free(chidp);
1757   }
1758
1759   silc_buffer_free(clidp);
1760 }
1761
1762 /* Removes client from one channel. This is used for example when client
1763    calls LEAVE command to remove itself from the channel. Returns TRUE
1764    if channel still exists and FALSE if the channel is removed when
1765    last client leaves the channel. If `notify' is FALSE notify messages
1766    are not sent. */
1767
1768 int silc_server_remove_from_one_channel(SilcServer server, 
1769                                         SilcSocketConnection sock,
1770                                         SilcChannelEntry channel,
1771                                         SilcClientEntry client,
1772                                         int notify)
1773 {
1774   SilcChannelEntry ch;
1775   SilcChannelClientEntry chl;
1776   SilcBuffer clidp;
1777
1778   SILC_LOG_DEBUG(("Start"));
1779
1780   clidp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
1781
1782   /* Remove the client from the channel. The client is removed from
1783      the channel's user list. */
1784   silc_list_start(client->channels);
1785   while ((chl = silc_list_get(client->channels)) != SILC_LIST_END) {
1786     if (chl->channel != channel)
1787       continue;
1788
1789     ch = chl->channel;
1790
1791     /* Remove from list */
1792     silc_list_del(client->channels, chl);
1793
1794     /* If this client is last one on the channel the channel
1795        is removed all together. */
1796     if (silc_list_count(channel->user_list) < 2) {
1797       /* Notify about leaving client if this channel has global users. */
1798       if (notify && channel->global_users)
1799         silc_server_send_notify_to_channel(server, channel, FALSE,
1800                                            SILC_NOTIFY_TYPE_LEAVE, 1,
1801                                            clidp->data, clidp->len);
1802       
1803       silc_idlist_del_channel(server->local_list, channel);
1804       silc_buffer_free(clidp);
1805       return FALSE;
1806     }
1807
1808     /* Remove from list */
1809     silc_list_del(channel->user_list, chl);
1810     silc_free(chl);
1811
1812     /* If there is no global users on the channel anymore mark the channel
1813        as local channel. */
1814     if (server->server_type == SILC_SERVER &&
1815         !silc_server_channel_has_global(channel))
1816       channel->global_users = FALSE;
1817
1818     /* If tehre is not at least one local user on the channel then we don't
1819        need the channel entry anymore, we can remove it safely. */
1820     if (server->server_type == SILC_SERVER &&
1821         !silc_server_channel_has_local(channel)) {
1822       silc_idlist_del_channel(server->local_list, channel);
1823       silc_buffer_free(clidp);
1824       return FALSE;
1825     }
1826
1827     /* Send notify to channel about client leaving the channel */
1828     if (notify)
1829       silc_server_send_notify_to_channel(server, channel, FALSE,
1830                                          SILC_NOTIFY_TYPE_LEAVE, 1,
1831                                          clidp->data, clidp->len);
1832     break;
1833   }
1834
1835   silc_buffer_free(clidp);
1836   return TRUE;
1837 }
1838
1839 /* Returns TRUE if the given client is on the channel.  FALSE if not. 
1840    This works because we assure that the user list on the channel is
1841    always in up to date thus we can only check the channel list from 
1842    `client' which is faster than checking the user list from `channel'. */
1843
1844 int silc_server_client_on_channel(SilcClientEntry client,
1845                                   SilcChannelEntry channel)
1846 {
1847   SilcChannelClientEntry chl;
1848
1849   if (!client || !channel)
1850     return FALSE;
1851
1852   silc_list_start(client->channels);
1853   while ((chl = silc_list_get(client->channels)) != SILC_LIST_END)
1854     if (chl->channel == channel)
1855       return TRUE;
1856
1857   return FALSE;
1858 }
1859
1860 /* Timeout callback. This is called if connection is idle or for some
1861    other reason is not responding within some period of time. This 
1862    disconnects the remote end. */
1863
1864 SILC_TASK_CALLBACK(silc_server_timeout_remote)
1865 {
1866   SilcServerConnection sconn = (SilcServerConnection)context;
1867   SilcSocketConnection sock = sconn->server->sockets[fd];
1868
1869   silc_server_disconnect_remote(sconn->server, sock, 
1870                                 "Server closed connection: "
1871                                 "Connection timeout");
1872 }
1873
1874 /* Creates new channel. Sends NEW_CHANNEL packet to primary route. This
1875    function may be used only by router. In real SILC network all channels
1876    are created by routers thus this function is never used by normal
1877    server. */
1878
1879 SilcChannelEntry silc_server_create_new_channel(SilcServer server, 
1880                                                 SilcServerID *router_id,
1881                                                 char *cipher, 
1882                                                 char *channel_name)
1883 {
1884   SilcChannelID *channel_id;
1885   SilcChannelEntry entry;
1886   SilcCipher key;
1887
1888   SILC_LOG_DEBUG(("Creating new channel"));
1889
1890   if (!cipher)
1891     cipher = "twofish";
1892
1893   /* Allocate cipher */
1894   silc_cipher_alloc(cipher, &key);
1895
1896   channel_name = strdup(channel_name);
1897
1898   /* Create the channel */
1899   silc_id_create_channel_id(router_id, server->rng, &channel_id);
1900   entry = silc_idlist_add_channel(server->local_list, channel_name, 
1901                                   SILC_CHANNEL_MODE_NONE, channel_id, 
1902                                   NULL, key);
1903   if (!entry) {
1904     silc_free(channel_name);
1905     return NULL;
1906   }
1907
1908   /* Now create the actual key material */
1909   silc_server_create_channel_key(server, entry, 16);
1910
1911   /* Notify other routers about the new channel. We send the packet
1912      to our primary route. */
1913   if (server->standalone == FALSE) {
1914     silc_server_send_new_channel(server, server->router->connection, TRUE, 
1915                                  channel_name, entry->id, SILC_ID_CHANNEL_LEN);
1916   }
1917
1918   return entry;
1919 }
1920
1921 /* Generates new channel key. This is used to create the initial channel key
1922    but also to re-generate new key for channel. If `key_len' is provided
1923    it is the bytes of the key length. */
1924
1925 void silc_server_create_channel_key(SilcServer server, 
1926                                     SilcChannelEntry channel,
1927                                     unsigned int key_len)
1928 {
1929   int i;
1930   unsigned char channel_key[32];
1931   unsigned int len;
1932
1933   if (!channel->channel_key)
1934     silc_cipher_alloc("twofish", &channel->channel_key);
1935
1936   if (key_len)
1937     len = key_len;
1938   else if (channel->key_len)
1939     len = channel->key_len / 8;
1940   else
1941     len = sizeof(channel_key);
1942
1943   /* Create channel key */
1944   for (i = 0; i < len; i++) channel_key[i] = silc_rng_get_byte(server->rng);
1945   
1946   /* Set the key */
1947   channel->channel_key->cipher->set_key(channel->channel_key->context, 
1948                                         channel_key, len);
1949
1950   /* Remove old key if exists */
1951   if (channel->key) {
1952     memset(channel->key, 0, channel->key_len / 8);
1953     silc_free(channel->key);
1954   }
1955
1956   /* Save the key */
1957   channel->key_len = len * 8;
1958   channel->key = silc_calloc(len, sizeof(*channel->key));
1959   memcpy(channel->key, channel_key, len);
1960   memset(channel_key, 0, sizeof(channel_key));
1961 }
1962
1963 /* Saves the channel key found in the encoded `key_payload' buffer. This 
1964    function is used when we receive Channel Key Payload and also when we're
1965    processing JOIN command reply. Returns entry to the channel. */
1966
1967 SilcChannelEntry silc_server_save_channel_key(SilcServer server,
1968                                               SilcBuffer key_payload,
1969                                               SilcChannelEntry channel)
1970 {
1971   SilcChannelKeyPayload payload = NULL;
1972   SilcChannelID *id = NULL;
1973   unsigned char *tmp;
1974   unsigned int tmp_len;
1975   char *cipher;
1976
1977   /* Decode channel key payload */
1978   payload = silc_channel_key_payload_parse(key_payload);
1979   if (!payload) {
1980     SILC_LOG_ERROR(("Bad channel key payload, dropped"));
1981     channel = NULL;
1982     goto out;
1983   }
1984
1985   /* Get the channel entry */
1986   if (!channel) {
1987
1988     /* Get channel ID */
1989     tmp = silc_channel_key_get_id(payload, &tmp_len);
1990     id = silc_id_str2id(tmp, SILC_ID_CHANNEL);
1991     if (!id) {
1992       channel = NULL;
1993       goto out;
1994     }
1995
1996     channel = silc_idlist_find_channel_by_id(server->local_list, id, NULL);
1997     if (!channel) {
1998       SILC_LOG_ERROR(("Received key for non-existent channel"));
1999       goto out;
2000     }
2001   }
2002
2003   tmp = silc_channel_key_get_key(payload, &tmp_len);
2004   if (!tmp) {
2005     channel = NULL;
2006     goto out;
2007   }
2008
2009   cipher = silc_channel_key_get_cipher(payload, NULL);;
2010   if (!cipher) {
2011     channel = NULL;
2012     goto out;
2013   }
2014
2015   /* Remove old key if exists */
2016   if (channel->key) {
2017     memset(channel->key, 0, channel->key_len / 8);
2018     silc_free(channel->key);
2019     silc_cipher_free(channel->channel_key);
2020   }
2021
2022   /* Create new cipher */
2023   if (!silc_cipher_alloc(cipher, &channel->channel_key)) {
2024     channel = NULL;
2025     goto out;
2026   }
2027
2028   /* Save the key */
2029   channel->key_len = tmp_len * 8;
2030   channel->key = silc_calloc(tmp_len, sizeof(unsigned char));
2031   memcpy(channel->key, tmp, tmp_len);
2032   channel->channel_key->cipher->set_key(channel->channel_key->context, 
2033                                         tmp, tmp_len);
2034
2035  out:
2036   if (id)
2037     silc_free(id);
2038   if (payload)
2039     silc_channel_key_payload_free(payload);
2040
2041   return channel;
2042 }