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