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