Added preliminary Symbian support.
[silc.git] / lib / silcserver / server_st_accept.c
1 /*
2
3   server_st_accept.c
4
5   Author: Pekka Riikonen <priikone@silcnet.org>
6
7   Copyright (C) 1997 - 2006 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; version 2 of the License.
12
13   This program is distributed in the hope that it will be useful,
14   but WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16   GNU General Public License for more details.
17
18 */
19
20 #include "silc.h"
21 #include "silcserver.h"
22 #include "server_internal.h"
23
24 /************************ Static utility functions **************************/
25
26 /* SKE public key verification callback */
27
28 static void
29 silc_server_accept_verify_key(SilcSKE ske,
30                               SilcSKEPKType pk_type,
31                               SilcPublicKey public_key,
32                               void *context,
33                               SilcSKEVerifyCbCompletion completion,
34                               void *completion_context)
35 {
36   SilcServerAccept ac = context;
37
38   SILC_LOG_DEBUG(("Verifying public key"));
39
40   if (pk_type != SILC_SKE_PK_TYPE_SILC) {
41     SILC_LOG_WARNING(("We don't support %s (%s) port %d public key type %d",
42                       ac->hostname, ac->ip, ac->port, pk_type));
43     completion(ac->data.ske, SILC_SKE_STATUS_UNSUPPORTED_PUBLIC_KEY,
44                completion_context);
45     return;
46   }
47
48   /* We accept all keys without explicit verification */
49   completion(ac->data.ske, SILC_SKE_STATUS_OK, completion_context);
50 }
51
52 /* SKE completion callback */
53
54 static void
55 silc_server_accept_completed(SilcSKE ske, SilcSKEStatus status,
56                              SilcSKESecurityProperties prop,
57                              SilcSKEKeyMaterial keymat,
58                              SilcSKERekeyMaterial rekey,
59                              void *context)
60 {
61   SilcServerAccept ac = context;
62
63   ac->status = status;
64   ac->prop = prop;
65   ac->keymat = keymat;
66   ac->rekey = rekey;
67
68   /* Continue synchronously to take keys into use immediately */
69   SILC_FSM_CALL_CONTINUE_SYNC(&ac->t);
70 }
71
72 /* Authentication data callback */
73
74 static SilcBool
75 silc_server_accept_get_auth(SilcConnAuth connauth,
76                             SilcConnectionType conn_type,
77                             unsigned char **passphrase,
78                             SilcUInt32 *passphrase_len,
79                             SilcSKR *repository,
80                             void *context)
81 {
82   SilcServerAccept ac = context;
83
84   SILC_LOG_DEBUG(("Remote connection type %d", conn_type));
85
86   /* Remote end is client */
87   if (conn_type == SILC_CONN_CLIENT) {
88     if (!ac->cconfig)
89       return FALSE;
90
91     *passphrase = ac->cconfig->passphrase;
92     *passphrase_len = ac->cconfig->passphrase_len;
93     if (ac->cconfig->pubkey_auth)
94       *repository = ac->thread->server->repository;
95   }
96
97   /* Remote end is server */
98   if (conn_type == SILC_CONN_SERVER) {
99     if (!ac->sconfig)
100       return FALSE;
101
102     *passphrase = ac->sconfig->passphrase;
103     *passphrase_len = ac->sconfig->passphrase_len;
104     if (ac->sconfig->pubkey_auth)
105       *repository = ac->thread->server->repository;
106   }
107
108   /* Remote end is router */
109   if (conn_type == SILC_CONN_ROUTER) {
110     if (!ac->rconfig)
111       return FALSE;
112
113     *passphrase = ac->rconfig->passphrase;
114     *passphrase_len = ac->rconfig->passphrase_len;
115     if (ac->rconfig->pubkey_auth)
116       *repository = ac->thread->server->repository;
117   }
118
119   ac->data.type = conn_type;
120
121   return TRUE;
122 }
123
124 /* Authentication completion callback */
125
126 static void
127 silc_server_accept_auth_compl(SilcConnAuth connauth, SilcBool success,
128                               void *context)
129 {
130   SilcServerAccept ac = context;
131   ac->auth_success = success;
132   SILC_FSM_CALL_CONTINUE(&ac->t);
133 }
134
135 /* Free context */
136
137 static void silc_server_accept_free(SilcServerAccept ac)
138 {
139   if (ac->connauth)
140     silc_connauth_free(ac->connauth);
141   silc_free(ac->error_string);
142   silc_free(ac);
143 }
144
145 void silc_server_accept_connection_dest(SilcFSM fsm, void *fsm_context,
146                                         void *destructor_context)
147 {
148   SilcServerAccept ac = fsm_context;
149   silc_server_accept_free(ac);
150 }
151
152
153 /********************* Accepting new connection thread **********************/
154
155 SILC_FSM_STATE(silc_server_st_accept_connection)
156 {
157   SilcServerAccept ac = fsm_context;
158   SilcServer server = ac->thread->server;
159   SilcServerParamDeny deny;
160   SilcSKESecurityPropertyFlag flags = 0;
161
162   SILC_LOG_DEBUG(("Accepting new connection"));
163
164   /* Create packet stream */
165   ac->packet_stream = silc_packet_stream_create(ac->thread->packet_engine,
166                                                 silc_fsm_get_schedule(fsm),
167                                                 ac->stream);
168   if (!ac->packet_stream) {
169     /** Cannot create packet stream */
170     ac->error = SILC_STATUS_ERR_RESOURCE_LIMIT;
171     silc_fsm_next(fsm, silc_server_st_accept_error);
172     SILC_FSM_CONTINUE;
173   }
174
175   silc_packet_set_context(ac->packet_stream, ac);
176
177   /* Set source ID to packet stream */
178   if (!silc_packet_set_ids(ac->packet_stream, SILC_ID_SERVER, &server->id,
179                            0, NULL)) {
180     /** Out of memory */
181     ac->error = SILC_STATUS_ERR_RESOURCE_LIMIT;
182     silc_fsm_next(fsm, silc_server_st_accept_error);
183     SILC_FSM_CONTINUE;
184   }
185
186   if (!silc_socket_stream_get_info(ac->stream, NULL, &ac->hostname,
187                                    &ac->ip, &ac->port)) {
188     /** Bad socket stream */
189     ac->error = SILC_STATUS_ERR_RESOURCE_LIMIT;
190     silc_fsm_next(fsm, silc_server_st_accept_error);
191     SILC_FSM_CONTINUE;
192   }
193
194   /* Check whether this connection is denied to connect to us. */
195   deny = silc_server_params_find_denied(server, ac->ip, ac->hostname);
196   if (deny) {
197     /** Connection is denied */
198     SILC_LOG_INFO(("Connection %s (%s) is denied", ac->hostname, ac->ip));
199     ac->error = SILC_STATUS_ERR_BANNED_FROM_SERVER;
200     silc_fsm_next(fsm, silc_server_st_accept_error);
201     SILC_FSM_CONTINUE;
202   }
203
204   server->params->refcnt++;
205
206   /* Check whether we have configured this sort of connection at all. We
207      have to check all configurations since we don't know what type of
208      connection this is. */
209   ac->cconfig = silc_server_params_find_client(server, ac->ip, ac->hostname);
210   ac->sconfig = silc_server_params_find_server(server, ac->ip, ac->hostname);
211   if (server->server_type == SILC_ROUTER)
212     ac->rconfig = silc_server_params_find_router(server, ac->ip,
213                                                  ac->hostname, ac->port);
214   if (!ac->cconfig && !ac->sconfig && !ac->rconfig) {
215     /** Connection not configured */
216     SILC_LOG_INFO(("Connection %s (%s) not configured", ac->hostname,
217                    ac->ip));
218     ac->error = SILC_STATUS_ERR_BANNED_FROM_SERVER;
219     silc_fsm_next(fsm, silc_server_st_accept_error);
220     SILC_FSM_CONTINUE;
221   }
222
223   SILC_LOG_INFO(("Incoming connection %s (%s)", ac->hostname, ac->ip));
224
225   /* Take flags for key exchange. Since we do not know what type of connection
226      this is, we go through all found configurations and use the global ones
227      as well. This will result always into strictest key exchange flags. */
228   SILC_GET_SKE_FLAGS(ac->cconfig, flags);
229   SILC_GET_SKE_FLAGS(ac->sconfig, flags);
230   SILC_GET_SKE_FLAGS(ac->rconfig, flags);
231   if (server->params->param.key_exchange_pfs)
232     flags |= SILC_SKE_SP_FLAG_PFS;
233
234   server->stat.conn_attempts++;
235
236   /* Start SILC Key Exchange protocol */
237   SILC_LOG_DEBUG(("Starting key exchange protocol"));
238   ac->data.ske = silc_ske_alloc(server->rng, silc_fsm_get_schedule(fsm),
239                                 server->public_key, server->private_key, ac);
240   if (!ac->data.ske) {
241     /** Out of memory */
242     ac->error = SILC_STATUS_ERR_RESOURCE_LIMIT;
243     silc_fsm_next(fsm, silc_server_st_accept_error);
244     SILC_FSM_CONTINUE;
245   }
246   silc_ske_set_callbacks(ac->data.ske, silc_server_accept_verify_key,
247                          silc_server_accept_completed, ac);
248
249   /** Waiting for SKE completion */
250   silc_fsm_next(fsm, silc_server_st_accept_set_keys);
251   SILC_FSM_CALL((ac->op = silc_ske_responder(ac->data.ske, ac->packet_stream,
252                                              silc_version_string, flags)));
253 }
254
255 SILC_FSM_STATE(silc_server_st_accept_set_keys)
256 {
257   SilcServerAccept ac = fsm_context;
258   SilcServer server = ac->thread->server;
259   SilcCipher send_key, receive_key;
260   SilcHmac hmac_send, hmac_receive;
261
262   if (ac->status != SILC_SKE_STATUS_OK) {
263     /** SKE failed */
264     SILC_LOG_ERROR(("Error (%s) during Key Exchange protocol with %s (%s)",
265                     silc_ske_map_status(ac->status), ac->hostname, ac->ip));
266     ac->error = SILC_STATUS_ERR_KEY_EXCHANGE_FAILED;
267     silc_fsm_next(fsm, silc_server_st_accept_error);
268     SILC_FSM_CONTINUE;
269   }
270
271   SILC_LOG_DEBUG(("Setting keys into use"));
272
273   /* Set the keys into use.  The data will be encrypted after this. */
274   if (!silc_ske_set_keys(ac->data.ske, ac->keymat, ac->prop, &send_key,
275                          &receive_key, &hmac_send, &hmac_receive,
276                          &ac->hash)) {
277     /** Error setting keys */
278     ac->error = SILC_STATUS_ERR_KEY_EXCHANGE_FAILED;
279     silc_fsm_next(fsm, silc_server_st_accept_error);
280     SILC_FSM_CONTINUE;
281   }
282   silc_packet_set_ciphers(ac->packet_stream, send_key, receive_key);
283   silc_packet_set_hmacs(ac->packet_stream, hmac_send, hmac_receive);
284
285   SILC_LOG_DEBUG(("Starting connection authentication"));
286   server->stat.auth_attempts++;
287
288   ac->connauth = silc_connauth_alloc(silc_fsm_get_schedule(fsm), ac->data.ske,
289                                      server->params->conn_auth_timeout);
290   if (!ac->connauth) {
291     /** Error allocating auth protocol */
292     ac->error = SILC_STATUS_ERR_RESOURCE_LIMIT;
293     silc_fsm_next(fsm, silc_server_st_accept_error);
294     SILC_FSM_CONTINUE;
295   }
296
297   /** Waiting authentication completion */
298   silc_fsm_next(fsm, silc_server_st_accept_authenticated);
299   SILC_FSM_CALL((ac->op = silc_connauth_responder(
300                                           ac->connauth,
301                                           silc_server_accept_get_auth,
302                                           silc_server_accept_auth_compl,
303                                           ac)));
304 }
305
306 SILC_FSM_STATE(silc_server_st_accept_authenticated)
307 {
308   SilcServerAccept ac = fsm_context;
309   SilcServer server = ac->thread->server;
310   SilcUInt32 conn_number, num_sockets, max_hosts, max_per_host;
311   SilcUInt32 r_protocol_version, l_protocol_version;
312   SilcUInt32 r_software_version, l_software_version;
313   char *r_vendor_version = NULL, *l_vendor_version;
314   SilcServerParamConnParams params, global;
315   SilcBool backup_router = FALSE;
316
317   if (ac->auth_success == FALSE) {
318     /** Authentication failed */
319     SILC_LOG_INFO(("Authentication failed for %s (%s) [%s]",
320                    ac->hostname, ac->ip,
321                    SILC_CONNTYPE_STRING(ac->data.type)));
322     ac->error = SILC_STATUS_ERR_AUTH_FAILED;
323     silc_fsm_next(fsm, silc_server_st_accept_error);
324     SILC_FSM_CONTINUE;
325   }
326
327   SILC_LOG_DEBUG(("Checking whether connection is allowed"));
328
329   global = &server->params->param;
330
331   if (ac->data.type == SILC_CONN_CLIENT) {
332     /** Accept client connection */
333     silc_fsm_next(fsm, silc_server_st_accept_client);
334     params = ac->cconfig->param;
335     conn_number = server->stat.my_clients;
336   } else if (ac->data.type == SILC_CONN_SERVER) {
337     /** Accept server connection */
338     silc_fsm_next(fsm, silc_server_st_accept_server);
339     params = ac->sconfig->param;
340     backup_router = ac->sconfig->backup_router;
341     conn_number = server->stat.my_servers;
342   } else {
343     /** Accept router connection */
344     silc_fsm_next(fsm, silc_server_st_accept_server);
345     params = ac->rconfig->param;
346     backup_router = ac->rconfig->backup_router;
347     conn_number = server->stat.my_routers;
348   }
349
350   silc_fsm_event_init(&ac->wait_register, silc_fsm_get_machine(fsm), 0);
351
352   /* Check version */
353   l_protocol_version = silc_version_to_num(params && params->version_protocol ?
354                                            params->version_protocol :
355                                            global->version_protocol);
356   l_software_version = silc_version_to_num(params && params->version_software ?
357                                            params->version_software :
358                                            global->version_software);
359   l_vendor_version = (params && params->version_software_vendor ?
360                       params->version_software_vendor :
361                       global->version_software_vendor);
362
363   silc_ske_parse_version(ac->data.ske, &r_protocol_version, NULL,
364                          &r_software_version, NULL, &r_vendor_version);
365
366   /* Match protocol version */
367   if (l_protocol_version && r_protocol_version &&
368       r_protocol_version < l_protocol_version) {
369     /** Protocol version mismatch */
370     SILC_LOG_INFO(("Connection %s (%s) is too old version", ac->hostname,
371                    ac->ip));
372     ac->error = SILC_STATUS_ERR_BAD_VERSION;
373     ac->error_string = strdup("You support too old protocol version");
374     silc_fsm_next(fsm, silc_server_st_accept_error);
375     SILC_FSM_CONTINUE;
376   }
377
378   /* Match software version */
379   if (l_software_version && r_software_version &&
380       r_software_version < l_software_version) {
381     /** Software version mismatch */
382     SILC_LOG_INFO(("Connection %s (%s) is too old version", ac->hostname,
383                    ac->ip));
384     ac->error = SILC_STATUS_ERR_BAD_VERSION;
385     ac->error_string = strdup("You support too old software version");
386     silc_fsm_next(fsm, silc_server_st_accept_error);
387     SILC_FSM_CONTINUE;
388   }
389
390   /* Regex match vendor version */
391   if (l_vendor_version && r_vendor_version &&
392       !silc_string_match(l_vendor_version, r_vendor_version)) {
393     /** Vendor version mismatch */
394     SILC_LOG_INFO(("Connection %s (%s) is unsupported version", ac->hostname,
395                    ac->ip));
396     ac->error = SILC_STATUS_ERR_BAD_VERSION;
397     ac->error_string = strdup("Your software is not supported");
398     silc_fsm_next(fsm, silc_server_st_accept_error);
399     SILC_FSM_CONTINUE;
400   }
401   silc_free(r_vendor_version);
402
403   /* Check for maximum connections limit */
404   //  num_sockets = silc_server_num_sockets_by_ip(server, sock->ip, type);
405   max_hosts = (params ? params->connections_max : global->connections_max);
406   max_per_host = (params ? params->connections_max_per_host :
407                   global->connections_max_per_host);
408
409   if (max_hosts && conn_number >= max_hosts) {
410     /** Server is full */
411     SILC_LOG_INFO(("Server is full, closing %s (%s) connection", ac->hostname,
412                    ac->ip));
413     ac->error = SILC_STATUS_ERR_RESOURCE_LIMIT;
414     ac->error_string = strdup("Server is full, try again later");
415     silc_fsm_next(fsm, silc_server_st_accept_error);
416     SILC_FSM_CONTINUE;
417   }
418
419   /* XXX */
420   num_sockets = 0;
421   if (num_sockets >= max_per_host) {
422     /** Too many connections */
423     SILC_LOG_INFO(("Too many connections from %s (%s), closing connection",
424                    ac->hostname, ac->ip));
425     ac->error = SILC_STATUS_ERR_RESOURCE_LIMIT;
426     ac->error_string = strdup("Too many connections from your host");
427     silc_fsm_next(fsm, silc_server_st_accept_error);
428     SILC_FSM_CONTINUE;
429   }
430
431   /* If we are waiting backup router connection, do not accept any other
432      connections. */
433   if (server->wait_backup && !backup_router) {
434     /** No backup established */
435     SILC_LOG_INFO(("Will not accept connections because we do "
436                    "not have backup router connection established"));
437     ac->error = SILC_STATUS_ERR_PERM_DENIED;
438     ac->error_string = strdup("We do not have connection to backup router "
439                               "established, try later");
440     silc_fsm_next(fsm, silc_server_st_accept_error);
441     SILC_FSM_CONTINUE;
442   }
443
444   /* If we are backup router and this is incoming server connection
445      and we do not have connection to primary router, do not allow
446      the connection. */
447   if (server->server_type == SILC_BACKUP_ROUTER &&
448       ac->data.type == SILC_CONN_SERVER &&
449       !SILC_PRIMARY_ROUTE(server)) {
450     /** No primary established */
451     SILC_LOG_INFO(("Will not accept server connection because we do "
452                    "not have primary router connection established"));
453     ac->error = SILC_STATUS_ERR_PERM_DENIED;
454     ac->error_string = strdup("We do not have connection to primary router "
455                               "established, try later");
456     silc_fsm_next(fsm, silc_server_st_accept_error);
457     SILC_FSM_CONTINUE;
458   }
459
460   SILC_FSM_CONTINUE;
461 }
462
463 SILC_FSM_STATE(silc_server_st_accept_client)
464 {
465   SilcServerAccept ac = fsm_context;
466   SilcServer server = ac->thread->server;
467   SilcServerParamClient conn = ac->cconfig;
468   SilcServerParamConnParams param = &server->params->param;
469   SilcClientEntry client;
470   SilcClientID client_id;
471   SilcBool timedout;
472   char *username = NULL, *realname = NULL;
473   SilcUInt16 username_len;
474   SilcUInt32 id_len, mode = 0;
475   char n[128], u[384], h[256];
476   int ret;
477
478   /* Wait here for the NEW_CLIENT or RESUME_CLIENT packet */
479   SILC_FSM_EVENT_TIMEDWAIT(&ac->wait_register, 20, 0, &timedout);
480
481   if (!ac->register_packet || timedout) {
482     /** Client did not register */
483     SILC_LOG_INFO(("Client connection %s (%s) did not register",
484                    ac->hostname, ac->ip));
485     ac->error = SILC_STATUS_ERR_NOT_REGISTERED;
486     silc_fsm_next(fsm, silc_server_st_accept_error);
487     SILC_FSM_CONTINUE;
488   }
489
490   SILC_LOG_DEBUG(("Connection %s (%s) is client", ac->hostname, ac->ip));
491   SILC_LOG_INFO(("Connection %s (%s) is client", ac->hostname, ac->ip));
492
493   /* Handle resuming separately */
494   if (ac->register_packet->type == SILC_PACKET_RESUME_CLIENT) {
495     /** Resume client connection */
496     silc_fsm_next(fsm, silc_server_st_accept_resume_client);
497     SILC_FSM_CONTINUE;
498   }
499
500   /* Get connection parameters */
501   if (conn->param) {
502     param = conn->param;
503
504     if (!param->keepalive_secs)
505       param->keepalive_secs = server->params->param.keepalive_secs;
506
507     if (!param->qos && server->params->param.qos) {
508       param->qos = server->params->param.qos;
509       param->qos_rate_limit = server->params->param.qos_rate_limit;
510       param->qos_bytes_limit = server->params->param.qos_bytes_limit;
511       param->qos_limit_sec = server->params->param.qos_limit_sec;
512       param->qos_limit_usec = server->params->param.qos_limit_usec;
513     }
514
515     /* Check if to be anonymous connection */
516     if (param->anonymous)
517       mode |= SILC_UMODE_ANONYMOUS;
518   }
519
520   /* Parse NEW_CLIENT packet */
521   ret = silc_buffer_unformat(&ac->register_packet->buffer,
522                              SILC_STR_UI16_NSTRING(&username,
523                                                    &username_len),
524                              SILC_STR_UI16_STRING(&realname),
525                              SILC_STR_END);
526   if (ret < 0) {
527     /** Bad NEW_CLIENT packet */
528     SILC_LOG_ERROR(("Client %s (%s) sent incomplete information",
529                     ac->hostname, ac->ip));
530     ac->error = SILC_STATUS_ERR_INCOMPLETE_INFORMATION;
531     ac->error_string = strdup("Bad NEW_CLIENT packet");
532     silc_fsm_next(fsm, silc_server_st_accept_error);
533     SILC_FSM_CONTINUE;
534   }
535
536   if (!username) {
537     /** Client did not send username */
538     SILC_LOG_ERROR(("Client %s (%s) did not send its username",
539                     ac->hostname, ac->ip));
540     ac->error = SILC_STATUS_ERR_INCOMPLETE_INFORMATION;
541     ac->error_string = strdup("You did not send username");
542     silc_fsm_next(fsm, silc_server_st_accept_error);
543     SILC_FSM_CONTINUE;
544   }
545
546   if (username_len > 128) {
547     username_len = 128;
548     username[username_len - 1] = '\0';
549   }
550
551   memset(n, 0, sizeof(n));
552   memset(u, 0, sizeof(u));
553   memset(h, 0, sizeof(h));
554
555   ret = silc_parse_userfqdn(username, u, 128, h, sizeof(h));
556   if (ret < 2) {
557     /* Hostname not present, add it */
558     silc_snprintf(n, sizeof(n), "%s", u);
559     silc_snprintf(u, sizeof(u) - 1, "%s@%s", n, ac->hostname);
560   } else {
561     /* Verify that hostname is same than resolved hostname */
562     if (strcmp(ac->hostname, h)) {
563       /** Wrong hostname string */
564       SILC_LOG_ERROR(("Client %s (%s) sent wrong hostname string",
565                       ac->hostname, ac->ip));
566       ac->error = SILC_STATUS_ERR_INCOMPLETE_INFORMATION;
567       ac->error_string = strdup("You sent wrong hostname string");
568       silc_fsm_next(fsm, silc_server_st_accept_error);
569       SILC_FSM_CONTINUE;
570     }
571     silc_snprintf(n, sizeof(n), "%s", u);
572     silc_snprintf(u, sizeof(u) - 1, "%s@%s", n, h);
573   }
574
575   /* If configured as anonymous, scramble the username and hostname */
576   if (mode & SILC_UMODE_ANONYMOUS) {
577     char *scramble;
578
579     u[0] = silc_rng_get_byte_fast(server->rng);
580     u[1] = silc_rng_get_byte_fast(server->rng);
581     u[2] = silc_rng_get_byte_fast(server->rng);
582     u[3] = silc_rng_get_byte_fast(server->rng);
583
584     scramble = silc_hash_babbleprint(server->sha1hash, u, strlen(u));
585     if (!scramble) {
586       /** Out of memory */
587       ac->error = SILC_STATUS_ERR_RESOURCE_LIMIT;
588       silc_fsm_next(fsm, silc_server_st_accept_error);
589       SILC_FSM_CONTINUE;
590     }
591
592     username_len = strlen(scramble);
593     memset(u, 0, username_len);
594     memcpy(u, scramble, username_len);
595     u[5] = '@';
596     u[11] = '.';
597     memcpy(&u[16], ".silc", 5);
598     u[21] = '\0';
599
600     /* Get nickname from scrambled username */
601     silc_parse_userfqdn(u, n, sizeof(n), NULL, 0);
602     silc_free(scramble);
603   }
604
605   /* Create Client ID */
606   if (!silc_server_create_client_id(server, n, &client_id)) {
607     /** Could not create Client ID */
608     SILC_LOG_ERROR(("Client %s (%s) sent bad nickname string",
609                     ac->hostname, ac->ip));
610     ac->error = SILC_STATUS_ERR_BAD_NICKNAME;
611     ac->error_string = strdup("Bad nickname");
612     silc_fsm_next(fsm, silc_server_st_accept_error);
613     SILC_FSM_CONTINUE;
614   }
615
616   /* Create client entry */
617   client = silc_server_add_client(server, n, u, realname, &client_id,
618                                   mode, ac->packet_stream);
619   if (!client) {
620     /** Could not create client entry */
621     SILC_LOG_ERROR(("Could not create new client entry"));
622     ac->error = SILC_STATUS_ERR_RESOURCE_LIMIT;
623     silc_fsm_next(fsm, silc_server_st_accept_error);
624     SILC_FSM_CONTINUE;
625   }
626
627   /* Save entry data */
628   client->data = ac->data;
629   client->data.registered = TRUE;
630   client->data.local = TRUE;
631   silc_packet_set_context(ac->packet_stream, client);
632
633   /* Set destination ID to packet stream */
634   if (!silc_packet_set_ids(client->stream, 0, NULL, SILC_ID_CLIENT,
635                            &client->id)) {
636     /** Out of memory */
637     ac->error = SILC_STATUS_ERR_RESOURCE_LIMIT;
638     silc_fsm_next(fsm, silc_server_st_accept_error);
639     SILC_FSM_CONTINUE;
640   }
641
642   /* Send the new client ID to the client. */
643   silc_server_send_new_id(ac->packet_stream, FALSE, &client->id,
644                           SILC_ID_CLIENT);
645
646   /* Send nice welcome to the client */
647   silc_server_send_welcome(ac, client);
648
649   /* Notify our router about new client on the SILC network */
650   silc_server_send_new_id(SILC_PRIMARY_ROUTE(server), SILC_BROADCAST(server),
651                           &client->id, SILC_ID_CLIENT);
652
653 #if 0
654   /* Distribute to backup routers */
655   if (server->server_type == SILC_ROUTER) {
656     SilcBuffer idp = silc_id_payload_encode(client->id, SILC_ID_CLIENT);
657     silc_server_backup_send(server, sock->user_data, SILC_PACKET_NEW_ID, 0,
658                             idp->data, idp->len, FALSE, TRUE);
659     silc_buffer_free(idp);
660   }
661 #endif /* 0 */
662
663   /* Check if anyone is watching this nickname */
664   if (server->server_type == SILC_ROUTER)
665     silc_server_check_watcher_list(server, client, NULL, 0);
666
667   /* Statistics */
668   /* XXX */
669
670   silc_packet_free(ac->register_packet);
671
672   /** Connection accepted */
673   silc_fsm_next(fsm, silc_server_st_accept_finish);
674   SILC_FSM_CONTINUE;
675 }
676
677 SILC_FSM_STATE(silc_server_st_accept_resume_client)
678 {
679
680   /** Connection accepted */
681   silc_fsm_next(fsm, silc_server_st_accept_finish);
682   SILC_FSM_CONTINUE;
683 }
684
685 SILC_FSM_STATE(silc_server_st_accept_server)
686 {
687   SilcServerAccept ac = fsm_context;
688   SilcServer server = ac->thread->server;
689   SilcBool initiator = FALSE;
690   SilcBool backup_local = FALSE;
691   SilcBool backup_router = FALSE;
692   char *backup_replace_ip = NULL;
693   SilcUInt16 backup_replace_port = 0;
694   SilcServerParamServer sconn = ac->sconfig;
695   SilcServerParamRouter rconn = ac->rconfig;
696   SilcServerEntry server_entry;
697   SilcServerID server_id;
698   SilcBool timedout;
699   unsigned char *server_name, *server_namec, *id_string;
700   SilcUInt16 id_len, name_len;
701   int ret;
702
703 #if 0
704
705   /* Wait here for the NEW_SERVER packet */
706   SILC_FSM_EVENT_TIMEDWAIT(&ac->wait_register, 20, 0, &timedout);
707
708   if (!ac->register_packet || timedout) {
709     /** Server did not register */
710     SILC_LOG_INFO(("%s connection %s (%s) did not register",
711                    SILC_CONNTYPE_STRING(ac->data.type),
712                    ac->hostname, ac->ip));
713     ac->error = SILC_STATUS_ERR_NOT_REGISTERED;
714     silc_fsm_next(fsm, silc_server_st_accept_error);
715     SILC_FSM_CONTINUE;
716   }
717
718   /* Get connection parameters */
719   if (ac->data.type == SILC_CONN_ROUTER) {
720     if (rconn) {
721       if (rconn->param) {
722         param = rconn->param;
723
724         if (!param->keepalive_secs)
725           param->keepalive_secs = server->params->param.keepalive_secs;
726
727         if (!param->qos && server->params->param.qos) {
728           param->qos = server->params->param.qos;
729           param->qos_rate_limit = server->params->param.qos_rate_limit;
730           param->qos_bytes_limit = server->params->param.qos_bytes_limit;
731           param->qos_limit_sec = server->params->param.qos_limit_sec;
732           param->qos_limit_usec = server->params->param.qos_limit_usec;
733         }
734       }
735
736       initiator = rconn->initiator;
737       backup_local = rconn->backup_local;
738       backup_router = rconn->backup_router;
739       backup_replace_ip = rconn->backup_replace_ip;
740       backup_replace_port = rconn->backup_replace_port;
741     }
742   } else if (ac->data.type == SILC_CONN_SERVER) {
743     if (sconn) {
744       if (sconn->param) {
745         param = sconn->param;
746
747         if (!param->keepalive_secs)
748           param->keepalive_secs = server->params->param.keepalive_secs;
749
750         if (!param->qos && server->params->param.qos) {
751           param->qos = server->params->param.qos;
752           param->qos_rate_limit = server->params->param.qos_rate_limit;
753           param->qos_bytes_limit = server->params->param.qos_bytes_limit;
754           param->qos_limit_sec = server->params->param.qos_limit_sec;
755           param->qos_limit_usec = server->params->param.qos_limit_usec;
756         }
757       }
758
759       backup_router = sconn->backup_router;
760     }
761   }
762
763   SILC_LOG_DEBUG(("Connection %s (%s) is %s", sock->hostname,
764                   sock->ip, ac->data.type == SILC_CONN_SERVER ?
765                   "server" : (backup_router ? "backup router" : "router")));
766   SILC_LOG_INFO(("Connection %s (%s) is %s", sock->hostname,
767                  sock->ip, ac->data.type == SILC_CONN_SERVER ?
768                  "server" : (backup_router ? "backup router" : "router")));
769
770   /* Parse NEW_SERVER packet */
771   ret = silc_buffer_unformat(buffer,
772                              SILC_STR_UI16_NSTRING(&id_string, &id_len),
773                              SILC_STR_UI16_NSTRING(&server_name, &name_len),
774                              SILC_STR_END);
775   if (ret < 0) {
776     /** Bad NEW_SERVER packet */
777     SILC_LOG_ERROR(("%s %s (%s) sent incomplete information",
778                     SILC_CONNTYPE_STRING(ac->data.type),
779                     ac->hostname, ac->ip));
780     ac->error = SILC_STATUS_ERR_INCOMPLETE_INFORMATION;
781     ac->error_string = strdup("Bad NEW_SERVER packet");
782     silc_fsm_next(fsm, silc_server_st_accept_error);
783     SILC_FSM_CONTINUE;
784   }
785
786   if (name_len > 256) {
787     name_len = 256;
788     server_name[name_len - 1] = '\0';
789   }
790
791   /* Get server ID */
792   if (!silc_id_str2id(id_string, id_len, SILC_ID_SERVER, &server_id,
793                       sizeof(server_id))) {
794     /** Bad Server ID */
795     SILC_LOG_ERROR(("%s %s (%s) sent incomplete information",
796                     SILC_CONNTYPE_STRING(ac->data.type),
797                     ac->hostname, ac->ip));
798     ac->error = SILC_STATUS_ERR_INCOMPLETE_INFORMATION;
799     ac->error_string = strdup("Bad Server ID");
800     silc_fsm_next(fsm, silc_server_st_accept_error);
801     SILC_FSM_CONTINUE;
802   }
803
804   /* Check for valid server ID */
805   if (!silc_server_check_server_id(ac->ip, &server_id)) {
806     /** Invalid Server ID */
807     SILC_LOG_ERROR(("%s %s (%s) sent incomplete information",
808                     SILC_CONNTYPE_STRING(ac->data.type),
809                     ac->hostname, ac->ip));
810     ac->error = SILC_STATUS_ERR_INCOMPLETE_INFORMATION;
811     ac->error_string = strdup("Your Server ID is not based on your real "
812                               "IP address.  Check your configuration.");
813     silc_fsm_next(fsm, silc_server_st_accept_error);
814     SILC_FSM_CONTINUE;
815   }
816
817   /* Create server entry */
818   server_entry =
819     silc_server_add_server(server, server_name,
820                            (ac->data.type == SILC_CONN_SERVER ?
821                             SILC_SERVER : SILC_ROUTER), &server_id,
822                            ac->stream);
823   if (!server_entry) {
824     /** Could not create server entry */
825     SILC_LOG_ERROR(("Could not create new server entry"));
826     ac->error = SILC_STATUS_ERR_RESOURCE_LIMIT;
827     silc_fsm_next(fsm, silc_server_st_accept_error);
828     SILC_FSM_CONTINUE;
829   }
830
831   /* Save entry data */
832   server_entry->data = ac->data;
833   server_entry->data.registered = TRUE;
834   server_entry->data.local = TRUE;
835   silc_packet_set_context(ac->packet_stream, server_entry);
836
837   /* Set source ID to packet stream */
838   if (!silc_packet_set_ids(server_entry->stream, 0, NULL, SILC_ID_SERVER,
839                            &server_entry->id)) {
840     /** Out of memory */
841     ac->error = SILC_STATUS_ERR_RESOURCE_LIMIT;
842     silc_fsm_next(fsm, silc_server_st_accept_error);
843     SILC_FSM_CONTINUE;
844   }
845
846   /* If the incoming connection is router and marked as backup router
847      then add it to be one of our backups */
848   if (ac->data.type == SILC_CONN_ROUTER && backup_router) {
849     /* Change it back to SERVER type since that's what it really is. */
850     if (backup_local)
851       server->data.type = SILC_CONN_SERVER;
852     server_entry->thread->server_type = SILC_BACKUP_ROUTER;
853
854     SILC_SERVER_SEND_OPERS(server, FALSE, TRUE, SILC_NOTIFY_TYPE_NONE,
855                            ("Backup router %s is now online",
856                             ac->hostname));
857   }
858
859   /* Check whether this connection is to be our primary router connection
860      if we do not already have the primary route. */
861   if (!backup_router && server->standalone &&
862       server_entry->data.type == SILC_CONN_ROUTER) {
863     if (silc_server_config_is_primary_route(server) && !initiator)
864       break;
865
866     SILC_LOG_DEBUG(("We are not standalone server anymore"));
867     server->standalone = FALSE;
868     if (!server->id_entry->router) {
869       server->id_entry->router = id_entry;
870       server->router = id_entry;
871     }
872   }
873
874
875
876   /* Distribute the information about new server in the SILC network
877      to our router. If we are normal server we won't send anything
878      since this connection must be our router connection. */
879   if (server->server_type == SILC_ROUTER && !server->standalone &&
880       SILC_PRIMARY_ROUTE(server) != sock)
881     silc_server_send_new_id(server, SILC_PRIMARY_ROUTE(server),
882                             TRUE, new_server->id, SILC_ID_SERVER,
883                             silc_id_get_len(server_id, SILC_ID_SERVER));
884
885   if (server->server_type == SILC_ROUTER) {
886     /* Distribute to backup routers */
887     SilcBuffer idp = silc_id_payload_encode(new_server->id, SILC_ID_SERVER);
888     silc_server_backup_send(server, sock->user_data, SILC_PACKET_NEW_ID, 0,
889                             idp->data, idp->len, FALSE, TRUE);
890     silc_buffer_free(idp);
891   }
892
893   /* Check whether this router connection has been replaced by an
894      backup router. If it has been then we'll disable the server and will
895      ignore everything it will send until the backup router resuming
896      protocol has been completed. */
897   if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
898       silc_server_backup_replaced_get(server, server_id, NULL)) {
899     /* Send packet to the router indicating that it cannot use this
900        connection as it has been replaced by backup router. */
901     SILC_LOG_DEBUG(("Remote router has been replaced by backup router, "
902                     "disabling its connection"));
903
904     silc_server_backup_send_replaced(server, sock);
905
906     /* Mark the router disabled. The data sent earlier will go but nothing
907        after this goes to this connection. */
908     idata->status |= SILC_IDLIST_STATUS_DISABLED;
909   } else {
910     /* If it is router announce our stuff to it. */
911     if (sock->type == SILC_SOCKET_TYPE_ROUTER &&
912         server->server_type == SILC_ROUTER) {
913       silc_server_announce_servers(server, FALSE, 0, sock);
914       silc_server_announce_clients(server, 0, sock);
915       silc_server_announce_channels(server, 0, sock);
916     }
917
918     /* Announce our information to backup router */
919     if (new_server->thread->server_type == SILC_BACKUP_ROUTER &&
920         sock->type == SILC_SOCKET_TYPE_SERVER &&
921         server->thread->server_type == SILC_ROUTER) {
922       silc_server_announce_servers(server, TRUE, 0, sock);
923       silc_server_announce_clients(server, 0, sock);
924       silc_server_announce_channels(server, 0, sock);
925     }
926
927     /* If backup router, mark it as one of ours.  This server is considered
928        to be backup router after this setting. */
929     if (new_server->thread->server_type == SILC_BACKUP_ROUTER) {
930       SilcServerParamRouter backup;
931       backup = silc_server_params_find_backup(server, sock->ip,
932                                               sock->hostname);
933       if (backup) {
934         /* Add as our backup router */
935         silc_server_backup_add(server, new_server, backup->backup_replace_ip,
936                                backup->backup_replace_port,
937                                backup->backup_local);
938       }
939     }
940
941     /* By default the servers connected to backup router are disabled
942        until backup router has become the primary */
943     if (server->thread->server_type == SILC_BACKUP_ROUTER &&
944         server_entry->data.type == SILC_CONN_SERVER)
945       server_entry->data.disabled = TRUE;
946   }
947
948   /* Statistics */
949   /* XXX */
950
951   silc_packet_free(ac->register_packet);
952 #endif /* 0 */
953
954   /** Connection accepted */
955   silc_fsm_next(fsm, silc_server_st_accept_finish);
956   SILC_FSM_CONTINUE;
957 }
958
959 SILC_FSM_STATE(silc_server_st_accept_finish)
960 {
961   SilcServerAccept ac = fsm_context;
962   SilcServer server = ac->thread->server;
963
964   SILC_LOG_DEBUG(("New connection accepted"));
965
966   SILC_FSM_FINISH;
967 }
968
969 SILC_FSM_STATE(silc_server_st_accept_error)
970 {
971   SilcServerAccept ac = fsm_context;
972   SilcServer server = ac->thread->server;
973
974   SILC_LOG_DEBUG(("Error accepting new connection"));
975
976   /* Disconnect remote connection */
977   if (ac->packet_stream)
978     silc_server_disconnect(server, ac->packet_stream, ac->error,
979                            ac->error_string);
980   else
981     silc_stream_destroy(ac->stream);
982
983   /* Statistics */
984   server->stat.conn_failures++;
985   if (ac->connauth)
986     server->stat.auth_failures++;
987
988   SILC_FSM_FINISH;
989 }