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