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