The silc_client_connect_to_[server|client] and
[silc.git] / lib / silcclient / client.c
index 5fdb9dad3ef5b6f6c54131fdcf310dfb5edba441..0c001e82d4f4df6e537bcfc1f2e28461bffe8e65 100644 (file)
@@ -37,6 +37,8 @@ static void silc_client_connection_destructor(SilcFSM fsm,
   SilcClientConnection conn = fsm_context;
   SilcFSMThread thread = destructor_context;
 
+  SILC_LOG_DEBUG(("Connection %p finished", conn));
+
   /* Delete connection */
   silc_client_del_connection(conn->client, conn);
 
@@ -44,6 +46,25 @@ static void silc_client_connection_destructor(SilcFSM fsm,
   silc_fsm_finish(thread);
 }
 
+/* Connection thread FSM destructor.  This was the thread where the connection
+   machine was running (may be real thread).  From here we notify client
+   that the connection thread has finished. */
+
+static void silc_client_connection_finished(SilcFSMThread fsm,
+                                           void *fsm_context,
+                                           void *destructor_context)
+{
+  SilcClient client = silc_fsm_get_state_context(fsm);
+
+  /* Signal client that we have finished */
+  silc_atomic_sub_int16(&client->internal->conns, 1);
+  client->internal->connection_closed = TRUE;
+  SILC_FSM_SEMA_POST(&client->internal->wait_event);
+
+  silc_fsm_free(fsm);
+}
+
+
 /* Packet FSM thread destructor */
 
 static void silc_client_packet_destructor(SilcFSMThread thread,
@@ -78,7 +99,6 @@ static SilcBool silc_client_packet_receive(SilcPacketEngine engine,
   case SILC_PACKET_KEY_EXCHANGE:
   case SILC_PACKET_KEY_EXCHANGE_1:
   case SILC_PACKET_KEY_EXCHANGE_2:
-  case SILC_PACKET_REKEY:
   case SILC_PACKET_REKEY_DONE:
   case SILC_PACKET_CONNECTION_AUTH:
   case SILC_PACKET_CONNECTION_AUTH_REQUEST:
@@ -113,7 +133,22 @@ static void silc_client_packet_eos(SilcPacketEngine engine,
                                   void *callback_context,
                                   void *stream_context)
 {
-  SILC_LOG_DEBUG(("End of stream received"));
+  SilcClientConnection conn = stream_context;
+  SilcClient client = conn->client;
+
+  SILC_LOG_DEBUG(("Remote disconnected connection"));
+
+  /* Call connection callback */
+  if (!conn->internal->callback_called)
+    conn->callback(client, conn, SILC_CLIENT_CONN_DISCONNECTED, 0, NULL,
+                  conn->callback_context);
+  conn->internal->callback_called = TRUE;
+
+  /* Signal to close connection */
+  if (!conn->internal->disconnected) {
+    conn->internal->disconnected = TRUE;
+    SILC_FSM_SEMA_POST(&conn->internal->wait_event);
+  }
 }
 
 /* Packet engine callback to indicate error */
@@ -124,7 +159,7 @@ static void silc_client_packet_error(SilcPacketEngine engine,
                                     void *callback_context,
                                     void *stream_context)
 {
-
+  /* Nothing */
 }
 
 /* Packet stream callbacks */
@@ -143,6 +178,21 @@ void silc_client_fsm_destructor(SilcFSM fsm, void *fsm_context,
   silc_fsm_free(fsm);
 }
 
+/* Connect abort operation */
+
+static void silc_client_connect_abort(SilcAsyncOperation op, void *context)
+{
+  SilcClientConnection conn = context;
+
+  SILC_LOG_DEBUG(("Connection %p aborted by application", conn));
+  conn->internal->aborted = TRUE;
+
+  /* Signal to close connection */
+  if (!conn->internal->disconnected) {
+    conn->internal->disconnected = TRUE;
+    SILC_FSM_SEMA_POST(&conn->internal->wait_event);
+  }
+}
 
 /************************** Connection's machine ****************************/
 
@@ -211,12 +261,22 @@ SILC_FSM_STATE(silc_client_connection_st_run)
     return SILC_FSM_CONTINUE;
   }
 
+  if (conn->internal->rekeying) {
+    SILC_LOG_DEBUG(("Event: rekey"));
+    conn->internal->rekeying = FALSE;
+
+    /*** Event: rekey */
+    silc_fsm_thread_init(thread, &conn->internal->fsm, conn,
+                        NULL, NULL, FALSE);
+    silc_fsm_start_sync(thread, silc_client_st_rekey);
+    return SILC_FSM_CONTINUE;
+  }
+
   if (conn->internal->disconnected) {
     /** Event: disconnected */
     SILC_LOG_DEBUG(("Event: disconnected"));
-    conn->internal->disconnected = FALSE;
     silc_fsm_next(fsm, silc_client_connection_st_close);
-    return SILC_FSM_CONTINUE;
+    return SILC_FSM_YIELD;
   }
 
   /* NOT REACHED */
@@ -229,6 +289,7 @@ SILC_FSM_STATE(silc_client_connection_st_run)
 
 SILC_FSM_STATE(silc_client_connection_st_packet)
 {
+  SilcClientConnection conn = fsm_context;
   SilcPacket packet = state_context;
 
   SILC_LOG_DEBUG(("Parsing %s packet", silc_get_packet_name(packet->type)));
@@ -281,8 +342,8 @@ SILC_FSM_STATE(silc_client_connection_st_packet)
     break;
 
   case SILC_PACKET_KEY_AGREEMENT:
-    /* Key agreement */
-    //    silc_client_key_agreement(client, conn, packet);
+    /** Key agreement */
+    silc_fsm_next(fsm, silc_client_key_agreement);
     break;
 
   case SILC_PACKET_COMMAND:
@@ -293,6 +354,7 @@ SILC_FSM_STATE(silc_client_connection_st_packet)
   case SILC_PACKET_NEW_ID:
     /** New ID */
     silc_fsm_next(fsm, silc_client_new_id);
+    break;
 
   case SILC_PACKET_CONNECTION_AUTH_REQUEST:
     /* Reply to connection authentication request to resolve authentication
@@ -300,6 +362,16 @@ SILC_FSM_STATE(silc_client_connection_st_packet)
     //    silc_client_connection_auth_request(client, conn, packet);
     break;
 
+  case SILC_PACKET_REKEY:
+    /* Signal to start rekey */
+    conn->internal->rekey_responder = TRUE;
+    conn->internal->rekeying = TRUE;
+    SILC_FSM_SEMA_POST(&conn->internal->wait_event);
+
+    silc_packet_free(packet);
+    return SILC_FSM_FINISH;
+    break;
+
   default:
     silc_packet_free(packet);
     return SILC_FSM_FINISH;
@@ -309,7 +381,7 @@ SILC_FSM_STATE(silc_client_connection_st_packet)
   return SILC_FSM_CONTINUE;
 }
 
-/* Disconnection even to close remote connection.  We close the connection
+/* Disconnection event to close remote connection.  We close the connection
    and finish the connection machine in this state.  The connection context
    is deleted in the machine destructor.  The connection callback must be
    already called back to application before getting here. */
@@ -317,10 +389,40 @@ SILC_FSM_STATE(silc_client_connection_st_packet)
 SILC_FSM_STATE(silc_client_connection_st_close)
 {
   SilcClientConnection conn = fsm_context;
+  SilcClientCommandContext cmd;
+
+  /* Finish running command threads.  This will also finish waiting packet
+     thread, as they are always waiting for some command.  If any thread is
+     waiting something else than command, they must be finished explicitly. */
+  if (silc_list_count(conn->internal->pending_commands)) {
+    SILC_LOG_DEBUG(("Finish pending commands"));
+    silc_list_start(conn->internal->pending_commands);
+    while ((cmd = silc_list_get(conn->internal->pending_commands))) {
+      if (silc_fsm_is_started(&cmd->thread)) {
+        cmd->verbose = FALSE;
+        silc_fsm_continue_sync(&cmd->thread);
+      }
+    }
 
-  SILC_LOG_DEBUG(("Closing remote connection"));
+    /* Give threads time to finish */
+    return SILC_FSM_YIELD;
+  }
+
+  /* Abort ongoing events */
+  if (conn->internal->op) {
+    SILC_LOG_DEBUG(("Abort event"));
+    silc_async_abort(conn->internal->op, NULL, NULL);
+    conn->internal->op = NULL;
+  }
 
-  /* XXX abort any ongoing events (protocols) */
+  /* If event thread is running, finish it. */
+  if (silc_fsm_is_started(&conn->internal->event_thread)) {
+    SILC_LOG_DEBUG(("Finish event thread"));
+    silc_fsm_continue_sync(&conn->internal->event_thread);
+    return SILC_FSM_YIELD;
+  }
+
+  SILC_LOG_DEBUG(("Closing remote connection"));
 
   /* Close connection */
   silc_packet_stream_destroy(conn->stream);
@@ -378,15 +480,19 @@ SILC_FSM_STATE(silc_client_disconnect)
                          silc_buffer_len(&packet->buffer));
 
   /* Call connection callback */
-  conn->callback(client, conn, SILC_CLIENT_CONN_DISCONNECTED, status,
-                message, conn->callback_context);
+  if (!conn->internal->callback_called)
+    conn->callback(client, conn, SILC_CLIENT_CONN_DISCONNECTED, status,
+                  message, conn->callback_context);
+  conn->internal->callback_called = TRUE;
 
   silc_free(message);
   silc_packet_free(packet);
 
   /* Signal to close connection */
-  conn->internal->disconnected = TRUE;
-  SILC_FSM_SEMA_POST(&conn->internal->wait_event);
+  if (!conn->internal->disconnected) {
+    conn->internal->disconnected = TRUE;
+    SILC_FSM_SEMA_POST(&conn->internal->wait_event);
+  }
 
   return SILC_FSM_FINISH;
 }
@@ -404,10 +510,30 @@ SILC_FSM_STATE(silc_client_st_run)
 
   /* Process events */
 
-  if (client->internal->run_callback && client->internal->ops->running) {
+  if (client->internal->run_callback && client->internal->running) {
     /* Call running callbcak back to application */
+    SILC_LOG_DEBUG(("We are up, call running callback"));
     client->internal->run_callback = FALSE;
-    client->internal->ops->running(client, client->application);
+    client->internal->running(client, client->internal->running_context);
+    return SILC_FSM_CONTINUE;
+  }
+
+  if (client->internal->connection_closed) {
+    /* A connection finished */
+    SILC_LOG_DEBUG(("Event: connection closed"));
+    client->internal->connection_closed = FALSE;
+    if (silc_atomic_get_int16(&client->internal->conns) == 0 &&
+       client->internal->stop)
+      SILC_FSM_SEMA_POST(&client->internal->wait_event);
+    return SILC_FSM_CONTINUE;
+  }
+
+  if (client->internal->stop) {
+    /* Stop client libarry.  If we have running connections, wait until
+       they finish first. */
+    SILC_LOG_DEBUG(("Event: stop"));
+    if (silc_atomic_get_int16(&client->internal->conns) == 0)
+      silc_fsm_next(fsm, silc_client_st_stop);
     return SILC_FSM_CONTINUE;
   }
 
@@ -416,6 +542,25 @@ SILC_FSM_STATE(silc_client_st_run)
   return SILC_FSM_CONTINUE;
 }
 
+/* Stop event.  Stops the client library. */
+
+SILC_FSM_STATE(silc_client_st_stop)
+{
+  SilcClient client = fsm_context;
+
+  SILC_LOG_DEBUG(("Client stopped"));
+
+  /* Stop scheduler */
+  silc_schedule_stop(client->schedule);
+  silc_client_commands_unregister(client);
+
+  /* Call stopped callback to application */
+  if (client->internal->running)
+    client->internal->running(client, client->internal->running_context);
+
+  return SILC_FSM_FINISH;
+}
+
 /******************************* Private API ********************************/
 
 /* Adds new connection.  Creates the connection context and returns it. */
@@ -456,14 +601,26 @@ silc_client_add_connection(SilcClient client,
     silc_free(conn);
     return NULL;
   }
+  conn->internal->retry_timer = SILC_CLIENT_RETRY_MIN;
+  silc_mutex_alloc(&conn->internal->lock);
+  silc_atomic_init16(&conn->internal->cmd_ident, 0);
 
   if (!silc_hash_alloc("sha1", &conn->internal->sha1hash)) {
     silc_free(conn);
     silc_free(conn->internal);
     return NULL;
   }
+
+  /* Set parameters */
   if (params)
     conn->internal->params = *params;
+  if (!conn->internal->params.rekey_secs)
+    conn->internal->params.rekey_secs = 3600;
+#ifndef SILC_DIST_INPLACE
+  if (conn->internal->params.rekey_secs < 300)
+    conn->internal->params.rekey_secs = 300;
+#endif /* SILC_DIST_INPLACE */
+
   conn->internal->verbose = TRUE;
   silc_list_init(conn->internal->pending_commands,
                 struct SilcClientCommandContextStruct, next);
@@ -483,110 +640,91 @@ silc_client_add_connection(SilcClient client,
 
   conn->internal->ftp_sessions = silc_dlist_init();
 
+  /* Initiatlize our async operation so that application may abort us
+     while were connecting. */
+  conn->internal->cop = silc_async_alloc(silc_client_connect_abort,
+                                        NULL, conn);
+  if (!conn->internal->cop) {
+    silc_client_del_connection(client, conn);
+    return NULL;
+  }
+
   /* Run the connection state machine.  If threads are in use the machine
      is always run in a real thread. */
   thread = silc_fsm_thread_alloc(&client->internal->fsm, conn,
-                                silc_client_fsm_destructor, NULL,
+                                silc_client_connection_finished, NULL,
                                 client->internal->params->threads);
   if (!thread) {
     silc_client_del_connection(client, conn);
     return NULL;
   }
+  silc_fsm_set_state_context(thread, client);
   silc_fsm_start(thread, silc_client_connection_st_start);
 
+  SILC_LOG_DEBUG(("New connection %p", conn));
+  silc_atomic_add_int16(&client->internal->conns, 1);
+
   return conn;
 }
 
-/* Removes connection from client. Frees all memory. */
+/* Deletes connection.  This is always called from the connection machine
+   destructor.  Do not call this directly other places. */
 
 void silc_client_del_connection(SilcClient client, SilcClientConnection conn)
 {
-#if 0
-  SilcClientConnection c;
-  SilcIDCacheList list;
+  SilcList list;
   SilcIDCacheEntry entry;
-  SilcClientCommandPending *r;
-  SilcBool ret;
-
-  silc_dlist_start(client->internal->conns);
-  while ((c = silc_dlist_get(client->internal->conns)) != SILC_LIST_END) {
-    if (c != conn)
-      continue;
-
-    /* Free all cache entries */
-    if (silc_idcache_get_all(conn->internal->client_cache, &list)) {
-      ret = silc_idcache_list_first(list, &entry);
-      while (ret) {
-       silc_client_del_client(client, conn, entry->context);
-       ret = silc_idcache_list_next(list, &entry);
-      }
-      silc_idcache_list_free(list);
-    }
-
-    if (silc_idcache_get_all(conn->internal->channel_cache, &list)) {
-      ret = silc_idcache_list_first(list, &entry);
-      while (ret) {
-       silc_client_del_channel(client, conn, entry->context);
-       ret = silc_idcache_list_next(list, &entry);
-      }
-      silc_idcache_list_free(list);
-    }
+  SilcFSMThread thread;
 
-    if (silc_idcache_get_all(conn->internal->server_cache, &list)) {
-      ret = silc_idcache_list_first(list, &entry);
-      while (ret) {
-       silc_client_del_server(client, conn, entry->context);
-       ret = silc_idcache_list_next(list, &entry);
-      }
-      silc_idcache_list_free(list);
-    }
+  SILC_LOG_DEBUG(("Freeing connection %p", conn));
 
-    /* Clear ID caches */
-    if (conn->internal->client_cache)
-      silc_idcache_free(conn->internal->client_cache);
-    if (conn->internal->channel_cache)
-      silc_idcache_free(conn->internal->channel_cache);
-    if (conn->internal->server_cache)
-      silc_idcache_free(conn->internal->server_cache);
-
-    /* Free data (my ID is freed in above silc_client_del_client).
-       conn->nickname is freed when freeing the local_entry->nickname. */
-    silc_free(conn->remote_host);
-    silc_free(conn->local_id_data);
-    if (conn->internal->send_key)
-      silc_cipher_free(conn->internal->send_key);
-    if (conn->internal->receive_key)
-      silc_cipher_free(conn->internal->receive_key);
-    if (conn->internal->hmac_send)
-      silc_hmac_free(conn->internal->hmac_send);
-    if (conn->internal->hmac_receive)
-      silc_hmac_free(conn->internal->hmac_receive);
-    silc_free(conn->internal->rekey);
-
-    if (conn->internal->active_session) {
-      if (conn->sock)
-       conn->sock->user_data = NULL;
-      silc_client_ftp_session_free(conn->internal->active_session);
-      conn->internal->active_session = NULL;
-    }
+  silc_schedule_task_del_by_context(conn->internal->schedule, conn);
 
-    silc_client_ftp_free_sessions(client, conn);
-
-    if (conn->internal->pending_commands) {
-      silc_dlist_start(conn->internal->pending_commands);
-      while ((r = silc_dlist_get(conn->internal->pending_commands))
-            != SILC_LIST_END)
-       silc_dlist_del(conn->internal->pending_commands, r);
-      silc_dlist_uninit(conn->internal->pending_commands);
+  /* Free all cache entries */
+  if (silc_idcache_get_all(conn->internal->server_cache, &list)) {
+    silc_list_start(list);
+    while ((entry = silc_list_get(list)))
+      silc_client_del_server(client, conn, entry->context);
+  }
+  if (silc_idcache_get_all(conn->internal->channel_cache, &list)) {
+    silc_list_start(list);
+    while ((entry = silc_list_get(list))) {
+      silc_client_empty_channel(client, conn, entry->context);
+      silc_client_del_channel(client, conn, entry->context);
     }
-
-    silc_free(conn->internal);
-    memset(conn, 0, sizeof(*conn));
-    silc_free(conn);
-
-    silc_dlist_del(client->internal->conns, conn);
   }
-#endif /* 0 */
+  if (silc_idcache_get_all(conn->internal->client_cache, &list)) {
+    silc_list_start(list);
+    while ((entry = silc_list_get(list)))
+      silc_client_del_client(client, conn, entry->context);
+  }
+
+  /* Free ID caches */
+  if (conn->internal->client_cache)
+    silc_idcache_free(conn->internal->client_cache);
+  if (conn->internal->channel_cache)
+    silc_idcache_free(conn->internal->channel_cache);
+  if (conn->internal->server_cache)
+    silc_idcache_free(conn->internal->server_cache);
+
+  /* Free thread pool */
+  silc_list_start(conn->internal->thread_pool);
+  while ((thread = silc_list_get(conn->internal->thread_pool)))
+    silc_fsm_free(thread);
+
+  silc_free(conn->remote_host);
+  silc_buffer_free(conn->internal->local_idp);
+  silc_buffer_free(conn->internal->remote_idp);
+  silc_mutex_free(conn->internal->lock);
+  if (conn->internal->hash)
+    silc_hash_free(conn->internal->hash);
+  if (conn->internal->sha1hash)
+    silc_hash_free(conn->internal->sha1hash);
+  silc_atomic_uninit16(&conn->internal->cmd_ident);
+
+  silc_free(conn->internal);
+  memset(conn, 'F', sizeof(*conn));
+  silc_free(conn);
 }
 
 
@@ -596,18 +734,19 @@ void silc_client_del_connection(SilcClient client, SilcClientConnection conn)
    to remote SILC server.  Performs key exchange also.  Returns the
    connection context to the connection callback. */
 
-SilcBool silc_client_connect_to_server(SilcClient client,
-                                      SilcClientConnectionParams *params,
-                                      SilcPublicKey public_key,
-                                      SilcPrivateKey private_key,
-                                      char *remote_host, int port,
-                                      SilcClientConnectCallback callback,
-                                      void *context)
+SilcAsyncOperation
+silc_client_connect_to_server(SilcClient client,
+                             SilcClientConnectionParams *params,
+                             SilcPublicKey public_key,
+                             SilcPrivateKey private_key,
+                             char *remote_host, int port,
+                             SilcClientConnectCallback callback,
+                             void *context)
 {
   SilcClientConnection conn;
 
   if (!client || !remote_host)
-    return FALSE;
+    return NULL;
 
   /* Add new connection */
   conn = silc_client_add_connection(client, SILC_CONN_SERVER, params,
@@ -615,7 +754,7 @@ SilcBool silc_client_connect_to_server(SilcClient client,
                                    port, callback, context);
   if (!conn) {
     callback(client, NULL, SILC_CLIENT_CONN_ERROR, 0, NULL, context);
-    return FALSE;
+    return NULL;
   }
 
   client->internal->ops->say(client, conn, SILC_CLIENT_MESSAGE_AUDIT,
@@ -624,24 +763,25 @@ SilcBool silc_client_connect_to_server(SilcClient client,
 
   /* Signal connection machine to start connecting */
   conn->internal->connect = TRUE;
-  return TRUE;
+  return conn->internal->cop;
 }
 
 /* Connects to remote client.  Performs key exchange also.  Returns the
    connection context to the connection callback. */
 
-SilcBool silc_client_connect_to_client(SilcClient client,
-                                      SilcClientConnectionParams *params,
-                                      SilcPublicKey public_key,
-                                      SilcPrivateKey private_key,
-                                      char *remote_host, int port,
-                                      SilcClientConnectCallback callback,
-                                      void *context)
+SilcAsyncOperation
+silc_client_connect_to_client(SilcClient client,
+                             SilcClientConnectionParams *params,
+                             SilcPublicKey public_key,
+                             SilcPrivateKey private_key,
+                             char *remote_host, int port,
+                             SilcClientConnectCallback callback,
+                             void *context)
 {
   SilcClientConnection conn;
 
   if (!client || !remote_host)
-    return FALSE;
+    return NULL;
 
   /* Add new connection */
   conn = silc_client_add_connection(client, SILC_CONN_CLIENT, params,
@@ -649,39 +789,39 @@ SilcBool silc_client_connect_to_client(SilcClient client,
                                    port, callback, context);
   if (!conn) {
     callback(client, NULL, SILC_CLIENT_CONN_ERROR, 0, NULL, context);
-    return FALSE;
+    return NULL;
   }
 
-  client->internal->ops->say(client, conn, SILC_CLIENT_MESSAGE_AUDIT,
-                            "Connecting to port %d of client host %s",
-                            port, remote_host);
-
   /* Signal connection machine to start connecting */
   conn->internal->connect = TRUE;
-  return TRUE;
+  return conn->internal->cop;
 }
 
 /* Starts key exchange in the remote stream indicated by `stream'.  This
    creates the connection context and returns it in the connection callback. */
 
-SilcBool silc_client_key_exchange(SilcClient client,
-                                 SilcClientConnectionParams *params,
-                                 SilcPublicKey public_key,
-                                 SilcPrivateKey private_key,
-                                 SilcStream stream,
-                                 SilcConnectionType conn_type,
-                                 SilcClientConnectCallback callback,
-                                 void *context)
+SilcAsyncOperation
+silc_client_key_exchange(SilcClient client,
+                        SilcClientConnectionParams *params,
+                        SilcPublicKey public_key,
+                        SilcPrivateKey private_key,
+                        SilcStream stream,
+                        SilcConnectionType conn_type,
+                        SilcClientConnectCallback callback,
+                        void *context)
 {
   SilcClientConnection conn;
   const char *host;
   SilcUInt16 port;
 
   if (!client || !stream)
-    return FALSE;
+    return NULL;
 
-  if (!silc_socket_stream_get_info(stream, NULL, &host, NULL, &port))
-    return FALSE;
+  if (!silc_socket_stream_get_info(stream, NULL, &host, NULL, &port)) {
+    SILC_LOG_ERROR(("Socket stream does not have remote host name set"));
+    callback(client, NULL, SILC_CLIENT_CONN_ERROR, 0, NULL, context);
+    return NULL;
+  }
 
   /* Add new connection */
   conn = silc_client_add_connection(client, conn_type, params,
@@ -689,13 +829,13 @@ SilcBool silc_client_key_exchange(SilcClient client,
                                    (char *)host, port, callback, context);
   if (!conn) {
     callback(client, NULL, SILC_CLIENT_CONN_ERROR, 0, NULL, context);
-    return FALSE;
+    return NULL;
   }
   conn->stream = (void *)stream;
 
   /* Signal connection to start key exchange */
   conn->internal->key_exchange = TRUE;
-  return TRUE;
+  return conn->internal->cop;
 }
 
 /* Closes remote connection */
@@ -703,7 +843,13 @@ SilcBool silc_client_key_exchange(SilcClient client,
 void silc_client_close_connection(SilcClient client,
                                  SilcClientConnection conn)
 {
+  SILC_LOG_DEBUG(("Closing connection %p", conn));
 
+  /* Signal to close connection */
+  if (!conn->internal->disconnected) {
+    conn->internal->disconnected = TRUE;
+    SILC_FSM_SEMA_POST(&conn->internal->wait_event);
+  }
 }
 
 #if 0
@@ -817,8 +963,6 @@ SILC_TASK_CALLBACK(silc_client_connect_to_server_final)
 
   silc_protocol_free(protocol);
   silc_free(ctx->auth_data);
-  if (ctx->ske)
-    silc_ske_free(ctx->ske);
   silc_socket_free(ctx->sock);
   silc_free(ctx);
   conn->sock->protocol = NULL;
@@ -828,8 +972,6 @@ SILC_TASK_CALLBACK(silc_client_connect_to_server_final)
   silc_protocol_free(protocol);
   silc_free(ctx->auth_data);
   silc_free(ctx->dest_id);
-  if (ctx->ske)
-    silc_ske_free(ctx->ske);
   conn->sock->protocol = NULL;
   silc_socket_free(ctx->sock);
 
@@ -1009,12 +1151,6 @@ SilcClient silc_client_alloc(SilcClientOperations *ops,
   if (params)
     memcpy(new_client->internal->params, params, sizeof(*params));
 
-  if (!new_client->internal->params->task_max)
-    new_client->internal->params->task_max = 200;
-
-  if (!new_client->internal->params->rekey_secs)
-    new_client->internal->params->rekey_secs = 3600;
-
   if (!new_client->internal->params->connauth_request_secs)
     new_client->internal->params->connauth_request_secs = 2;
 
@@ -1022,6 +1158,8 @@ SilcClient silc_client_alloc(SilcClientOperations *ops,
     nickname_format[sizeof(new_client->internal->
                           params->nickname_format) - 1] = 0;
 
+  silc_atomic_init16(&new_client->internal->conns, 0);
+
   return new_client;
 }
 
@@ -1029,22 +1167,26 @@ SilcClient silc_client_alloc(SilcClientOperations *ops,
 
 void silc_client_free(SilcClient client)
 {
-  if (client) {
-    if (client->rng)
-      silc_rng_free(client->rng);
-
-    if (!client->internal->params->dont_register_crypto_library) {
-      silc_cipher_unregister_all();
-      silc_pkcs_unregister_all();
-      silc_hash_unregister_all();
-      silc_hmac_unregister_all();
-    }
+  silc_schedule_uninit(client->schedule);
+
+  if (client->rng)
+    silc_rng_free(client->rng);
 
-    silc_free(client->internal->params);
-    silc_free(client->internal->silc_client_version);
-    silc_free(client->internal);
-    silc_free(client);
+  if (!client->internal->params->dont_register_crypto_library) {
+    silc_cipher_unregister_all();
+    silc_pkcs_unregister_all();
+    silc_hash_unregister_all();
+    silc_hmac_unregister_all();
   }
+
+  silc_atomic_uninit16(&client->internal->conns);
+  silc_free(client->username);
+  silc_free(client->hostname);
+  silc_free(client->realname);
+  silc_free(client->internal->params);
+  silc_free(client->internal->silc_client_version);
+  silc_free(client->internal);
+  silc_free(client);
 }
 
 /* Initializes the client. This makes all the necessary steps to make
@@ -1052,18 +1194,21 @@ void silc_client_free(SilcClient client)
    client. Returns FALSE if error occured, TRUE otherwise. */
 
 SilcBool silc_client_init(SilcClient client, const char *username,
-                         const char *hostname, const char *realname)
+                         const char *hostname, const char *realname,
+                         SilcClientRunning running, void *context)
 {
   SILC_LOG_DEBUG(("Initializing client"));
 
   if (!client)
     return FALSE;
 
-  if (!username || !hostname || !realname) {
+  if (!username || !hostname) {
     SILC_LOG_ERROR(("Username, hostname and realname must be given to "
                    "silc_client_init"));
     return FALSE;
   }
+  if (!realname)
+    realname = username;
 
   /* Validate essential strings */
   if (!silc_identifier_verify(username, strlen(username),
@@ -1103,13 +1248,13 @@ SilcBool silc_client_init(SilcClient client, const char *username,
 
   /* Initialize random number generator */
   client->rng = silc_rng_alloc();
+  if (!client->rng)
+    return FALSE;
   silc_rng_init(client->rng);
   silc_rng_global_init(client->rng);
 
   /* Initialize the scheduler */
-  client->schedule =
-    silc_schedule_init(client->internal->params->task_max ?
-                      client->internal->params->task_max : 0, client);
+  client->schedule = silc_schedule_init(0, client);
   if (!client->schedule)
     return FALSE;
 
@@ -1120,19 +1265,17 @@ SilcBool silc_client_init(SilcClient client, const char *username,
   if (!client->internal->packet_engine)
     return FALSE;
 
-  /* Initialize FSM */
-  if (!silc_fsm_init(&client->internal->fsm, client, NULL, NULL,
-                    client->schedule))
-    return FALSE;
-  silc_fsm_sema_init(&client->internal->wait_event, &client->internal->fsm, 0);
-
   /* Allocate client lock */
   silc_mutex_alloc(&client->internal->lock);
 
   /* Register commands */
   silc_client_commands_register(client);
 
-  /* Start the client machine */
+  /* Initialize and start the client FSM */
+  client->internal->running = running;
+  client->internal->running_context = context;
+  silc_fsm_init(&client->internal->fsm, client, NULL, NULL, client->schedule);
+  silc_fsm_sema_init(&client->internal->wait_event, &client->internal->fsm, 0);
   silc_fsm_start_sync(&client->internal->fsm, silc_client_st_run);
 
   /* Signal the application when we are running */
@@ -1142,20 +1285,6 @@ SilcBool silc_client_init(SilcClient client, const char *username,
   return TRUE;
 }
 
-/* Stops the client. This is called to stop the client and thus to stop
-   the program. */
-
-void silc_client_stop(SilcClient client)
-{
-  SILC_LOG_DEBUG(("Stopping client"));
-
-  silc_schedule_stop(client->schedule);
-  silc_schedule_uninit(client->schedule);
-  silc_client_commands_unregister(client);
-
-  SILC_LOG_DEBUG(("Client stopped"));
-}
-
 /* Starts the SILC client FSM machine and blocks here.  When this returns
    the client has ended. */
 
@@ -1172,5 +1301,22 @@ void silc_client_run(SilcClient client)
 
 void silc_client_run_one(SilcClient client)
 {
-  silc_schedule_one(client->schedule, 0);
+  if (silc_fsm_is_started(&client->internal->fsm))
+    silc_schedule_one(client->schedule, 0);
+}
+
+/* Stops the client. This is called to stop the client and thus to stop
+   the program. */
+
+void silc_client_stop(SilcClient client, SilcClientStopped stopped,
+                     void *context)
+{
+  SILC_LOG_DEBUG(("Stopping client"));
+
+  client->internal->running = (SilcClientRunning)stopped;
+  client->internal->running_context = context;
+
+  /* Signal to stop */
+  client->internal->stop = TRUE;
+  SILC_FSM_SEMA_POST(&client->internal->wait_event);
 }