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