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