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