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