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