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