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