Added preliminary Symbian support.
[silc.git] / lib / silcclient / client_entry.c
index ce3717aaf0cd98d68e49a7d6c9bbf9496ee3141f..a58298fc05f81ebf0610ce48f9455910eb0d097f 100644 (file)
@@ -22,8 +22,6 @@
 #include "silcclient.h"
 #include "client_internal.h"
 
-/* XXX locking */
-
 /************************ Client Searching Locally **************************/
 
 /* Finds entry for client by the client's ID. Returns the entry or NULL
@@ -78,11 +76,12 @@ SilcDList silc_client_get_clients_local(SilcClient client,
   if (!client || !conn || !nickname)
     return NULL;
 
+  SILC_LOG_DEBUG(("Find clients by nickname %s", nickname));
+
   /* Normalize nickname for search */
   nicknamec = silc_identifier_check(nickname, strlen(nickname),
                                    SILC_STRING_UTF8, 128, NULL);
   if (!nicknamec)
-    silc_free(nicknamec);
     return NULL;
 
   clients = silc_dlist_init();
@@ -94,6 +93,7 @@ SilcDList silc_client_get_clients_local(SilcClient client,
   silc_mutex_lock(conn->internal->lock);
 
   /* Find from cache */
+  silc_list_init(list, struct SilcIDCacheEntryStruct, next);
   if (!silc_idcache_find_by_name(conn->internal->client_cache, nicknamec,
                                 &list)) {
     silc_mutex_unlock(conn->internal->lock);
@@ -106,7 +106,7 @@ SilcDList silc_client_get_clients_local(SilcClient client,
     /* Take all without any further checking */
     silc_list_start(list);
     while ((id_cache = silc_list_get(list))) {
-      silc_client_ref_client(client, conn, entry);
+      silc_client_ref_client(client, conn, id_cache->context);
       silc_dlist_add(clients, id_cache->context);
     }
   } else {
@@ -186,12 +186,13 @@ static SilcBool silc_client_get_clients_cb(SilcClient client,
 
 /* Resolves client information from server by the client ID. */
 
-void silc_client_get_client_by_id_resolve(SilcClient client,
-                                         SilcClientConnection conn,
-                                         SilcClientID *client_id,
-                                         SilcBuffer attributes,
-                                         SilcGetClientCallback completion,
-                                         void *context)
+SilcUInt16
+silc_client_get_client_by_id_resolve(SilcClient client,
+                                    SilcClientConnection conn,
+                                    SilcClientID *client_id,
+                                    SilcBuffer attributes,
+                                    SilcGetClientCallback completion,
+                                    void *context)
 {
   SilcClientGetClientInternal i;
   SilcClientEntry client_entry;
@@ -199,20 +200,20 @@ void silc_client_get_client_by_id_resolve(SilcClient client,
   SilcUInt16 cmd_ident;
 
   if (!client || !conn | !client_id)
-    return;
+    return 0;
 
   SILC_LOG_DEBUG(("Resolve client by ID (%s)",
                  silc_id_render(client_id, SILC_ID_CLIENT)));
 
   i = silc_calloc(1, sizeof(*i));
   if (!i)
-    return;
+    return 0;
   i->completion = completion;
   i->context = context;
   i->clients = silc_dlist_init();
   if (!i->clients) {
     silc_free(i);
-    return;
+    return 0;
   }
 
   /* Attach to resolving, if on going */
@@ -223,7 +224,7 @@ void silc_client_get_client_by_id_resolve(SilcClient client,
     silc_client_command_pending(conn, SILC_COMMAND_NONE,
                                client_entry->internal.resolve_cmd_ident,
                                silc_client_get_clients_cb, i);
-    return;
+    return client_entry->internal.resolve_cmd_ident;
   }
 
   /* Send the command */
@@ -232,7 +233,7 @@ void silc_client_get_client_by_id_resolve(SilcClient client,
                                       silc_client_get_clients_cb, i,
                                       2, 3, silc_buffer_datalen(attributes),
                                       4, silc_buffer_datalen(idp));
-  if (!cmd_ident)
+  if (!cmd_ident && completion)
     completion(client, conn, SILC_STATUS_ERR_RESOURCE_LIMIT, NULL, context);
 
   if (client_entry && cmd_ident)
@@ -240,6 +241,8 @@ void silc_client_get_client_by_id_resolve(SilcClient client,
 
   silc_client_unref_client(client, conn, client_entry);
   silc_buffer_free(idp);
+
+  return cmd_ident;
 }
 
 /* Finds client entry or entries by the `nickname' and `server'. The
@@ -392,8 +395,11 @@ static SilcBool silc_client_get_clients_list_cb(SilcClient client,
  out:
   if (status != SILC_STATUS_OK && i->completion)
     i->completion(client, conn, status, NULL, i->context);
+
   silc_client_list_free(client, conn, clients);
+  silc_buffer_free(i->client_id_list);
   silc_free(i);
+
   return FALSE;
 }
 
@@ -404,29 +410,30 @@ static SilcBool silc_client_get_clients_list_cb(SilcClient client,
    command reply for example returns this sort of list. The `completion'
    will be called after the entries are available. */
 
-void silc_client_get_clients_by_list(SilcClient client,
-                                    SilcClientConnection conn,
-                                    SilcUInt32 list_count,
-                                    SilcBuffer client_id_list,
-                                    SilcGetClientCallback completion,
-                                    void *context)
+SilcUInt16 silc_client_get_clients_by_list(SilcClient client,
+                                          SilcClientConnection conn,
+                                          SilcUInt32 list_count,
+                                          SilcBuffer client_id_list,
+                                          SilcGetClientCallback completion,
+                                          void *context)
 {
   GetClientsByListInternal in;
   SilcClientEntry entry;
   unsigned char **res_argv = NULL;
   SilcUInt32 *res_argv_lens = NULL, *res_argv_types = NULL, res_argc = 0;
-  SilcUInt16 idp_len;
+  SilcUInt16 idp_len, cmd_ident;
   SilcID id;
+  va_list tmp;
   int i;
 
   SILC_LOG_DEBUG(("Resolve clients from Client ID list"));
 
   if (!client || !conn || !client_id_list)
-    return;
+    return 0;
 
   in = silc_calloc(1, sizeof(*in));
   if (!in)
-    return;
+    return 0;
   in->completion = completion;
   in->context = context;
   in->list_count = list_count;
@@ -458,7 +465,7 @@ void silc_client_get_clients_by_list(SilcClient client,
 
       res_argv[res_argc] = client_id_list->data;
       res_argv_lens[res_argc] = idp_len;
-      res_argv_types[res_argc] = res_argc + 5;
+      res_argv_types[res_argc] = res_argc + 4;
       res_argc++;
     }
     silc_client_unref_client(client, conn, entry);
@@ -470,20 +477,22 @@ void silc_client_get_clients_by_list(SilcClient client,
 
   /* Query the unknown client information from server */
   if (res_argc) {
-    silc_client_command_send_argv(client, conn, SILC_COMMAND_WHOIS,
-                                 silc_client_get_clients_list_cb,
-                                 in, res_argc, res_argv, res_argv_lens,
-                                 res_argv_types);
+    cmd_ident = silc_client_command_send_argv(client,
+                                             conn, SILC_COMMAND_WHOIS,
+                                             silc_client_get_clients_list_cb,
+                                             in, res_argc, res_argv,
+                                             res_argv_lens,
+                                             res_argv_types);
     silc_free(res_argv);
     silc_free(res_argv_lens);
     silc_free(res_argv_types);
-    return;
+    return cmd_ident;
   }
 
   /* We have the clients in cache, get them and call the completion */
   silc_client_get_clients_list_cb(client, conn, SILC_COMMAND_WHOIS,
-                                 SILC_STATUS_OK, SILC_STATUS_OK, in, NULL);
-  return;
+                                 SILC_STATUS_OK, SILC_STATUS_OK, in, tmp);
+  return 0;
 
  err:
   silc_buffer_free(in->client_id_list);
@@ -491,6 +500,7 @@ void silc_client_get_clients_by_list(SilcClient client,
   silc_free(res_argv);
   silc_free(res_argv_lens);
   silc_free(res_argv_types);
+  return 0;
 }
 
 #if 0
@@ -686,6 +696,7 @@ SilcClientEntry silc_client_add_client(SilcClient client,
   if (!client_entry)
     return NULL;
 
+  silc_atomic_init8(&client_entry->internal.refcnt, 0);
   client_entry->id = *id;
   client_entry->internal.valid = TRUE;
   client_entry->mode = mode;
@@ -720,7 +731,7 @@ SilcClientEntry silc_client_add_client(SilcClient client,
   }
 
   /* Format the nickname */
-  silc_client_nickname_format(client, conn, client_entry);
+  silc_client_nickname_format(client, conn, client_entry, FALSE);
 
   silc_mutex_lock(conn->internal->lock);
 
@@ -738,6 +749,9 @@ SilcClientEntry silc_client_add_client(SilcClient client,
   client_entry->nickname_normalized = nick;
 
   silc_mutex_unlock(conn->internal->lock);
+  silc_client_ref_client(client, conn, client_entry);
+
+  SILC_LOG_DEBUG(("Added %p", client_entry));
 
   return client_entry;
 }
@@ -777,26 +791,79 @@ void silc_client_update_client(SilcClient client,
       return;
 
     /* Format nickname */
-    silc_client_nickname_format(client, conn, client_entry);
+    silc_client_nickname_format(client, conn, client_entry,
+                               client_entry == conn->local_entry);
 
-    /* Remove the old cache entry and create a new one */
-    silc_idcache_del_by_context(conn->internal->client_cache, client_entry,
-                               NULL);
-    silc_idcache_add(conn->internal->client_cache, nick, &client_entry->id,
-                    client_entry);
+    /* Update cache entry */
+    silc_mutex_lock(conn->internal->lock);
+    silc_idcache_update_by_context(conn->internal->client_cache,
+                                  client_entry, NULL, nick, TRUE);
+    silc_mutex_unlock(conn->internal->lock);
+    client_entry->nickname_normalized = nick;
   }
   client_entry->mode = mode;
 }
 
+/* Change a client's nickname */
+
+SilcBool silc_client_change_nickname(SilcClient client,
+                                    SilcClientConnection conn,
+                                    SilcClientEntry client_entry,
+                                    const char *new_nick,
+                                    SilcClientID *new_id,
+                                    const unsigned char *idp,
+                                    SilcUInt32 idp_len)
+{
+  char *tmp;
+
+  SILC_LOG_DEBUG(("Change nickname %s to %s", client_entry->nickname,
+                 new_nick));
+
+  /* Normalize nickname */
+  tmp = silc_identifier_check(new_nick, strlen(new_nick),
+                             SILC_STRING_UTF8, 128, NULL);
+  if (!tmp)
+    return FALSE;
+
+  /* Update the client entry */
+  silc_mutex_lock(conn->internal->lock);
+  if (!silc_idcache_update_by_context(conn->internal->client_cache,
+                                     client_entry, new_id, tmp, TRUE)) {
+    silc_free(tmp);
+    silc_mutex_unlock(conn->internal->lock);
+    return FALSE;
+  }
+  silc_mutex_unlock(conn->internal->lock);
+
+  memset(client_entry->nickname, 0, sizeof(client_entry->nickname));
+  memcpy(client_entry->nickname, new_nick, strlen(new_nick));
+  client_entry->nickname_normalized = tmp;
+  silc_client_nickname_format(client, conn, client_entry,
+                             client_entry == conn->local_entry);
+
+  /* For my client entry, update ID and set new ID to packet stream */
+  if (client_entry == conn->local_entry) {
+    if (idp && idp_len) {
+      silc_buffer_enlarge(conn->internal->local_idp, idp_len);
+      silc_buffer_put(conn->internal->local_idp, idp, idp_len);
+    }
+    if (new_id)
+      silc_packet_set_ids(conn->stream, SILC_ID_CLIENT, conn->local_id,
+                         0, NULL);
+  }
+
+  return TRUE;
+}
+
 /* Deletes the client entry and frees all memory. */
 
 void silc_client_del_client_entry(SilcClient client,
                                  SilcClientConnection conn,
                                  SilcClientEntry client_entry)
 {
-  SILC_LOG_DEBUG(("Start"));
-
   silc_free(client_entry->realname);
+  silc_free(client_entry->nickname_normalized);
+  silc_free(client_entry->internal.key);
   if (client_entry->public_key)
     silc_pkcs_public_key_free(client_entry->public_key);
   silc_hash_table_free(client_entry->channels);
@@ -804,12 +871,16 @@ void silc_client_del_client_entry(SilcClient client,
     silc_cipher_free(client_entry->internal.send_key);
   if (client_entry->internal.receive_key)
     silc_cipher_free(client_entry->internal.receive_key);
-  silc_free(client_entry->internal.key);
+  if (client_entry->internal.hmac_send)
+    silc_hmac_free(client_entry->internal.hmac_send);
+  if (client_entry->internal.hmac_receive)
+    silc_hmac_free(client_entry->internal.hmac_receive);
 #if 0
   silc_client_ftp_session_free_client(conn, client_entry);
   if (client_entry->internal->ke)
     silc_client_abort_key_agreement(client, conn, client_entry);
 #endif /* 0 */
+  silc_atomic_uninit8(&client_entry->internal.refcnt);
   silc_free(client_entry);
 }
 
@@ -818,9 +889,21 @@ void silc_client_del_client_entry(SilcClient client,
 SilcBool silc_client_del_client(SilcClient client, SilcClientConnection conn,
                                SilcClientEntry client_entry)
 {
-  SilcBool ret = silc_idcache_del_by_context(conn->internal->client_cache,
-                                            client_entry, NULL);
-#if 0
+  SilcBool ret;
+
+  if (!client_entry)
+    return FALSE;
+
+  if (silc_atomic_sub_int8(&client_entry->internal.refcnt, 1) > 0)
+    return FALSE;
+
+  SILC_LOG_DEBUG(("Deleting client %p", client_entry));
+
+  silc_mutex_lock(conn->internal->lock);
+  ret = silc_idcache_del_by_context(conn->internal->client_cache,
+                                   client_entry, NULL);
+  silc_mutex_unlock(conn->internal->lock);
+
   if (ret) {
     /* Remove from channels */
     silc_client_remove_from_channels(client, conn, client_entry);
@@ -828,7 +911,6 @@ SilcBool silc_client_del_client(SilcClient client, SilcClientConnection conn,
     /* Free the client entry data */
     silc_client_del_client_entry(client, conn, client_entry);
   }
-#endif
 
   return ret;
 }
@@ -839,6 +921,9 @@ void silc_client_ref_client(SilcClient client, SilcClientConnection conn,
                            SilcClientEntry client_entry)
 {
   silc_atomic_add_int8(&client_entry->internal.refcnt, 1);
+  SILC_LOG_DEBUG(("Client %p refcnt %d->%d", client_entry,
+                 silc_atomic_get_int8(&client_entry->internal.refcnt) - 1,
+                 silc_atomic_get_int8(&client_entry->internal.refcnt)));
 }
 
 /* Release reference of client entry */
@@ -846,9 +931,12 @@ void silc_client_ref_client(SilcClient client, SilcClientConnection conn,
 void silc_client_unref_client(SilcClient client, SilcClientConnection conn,
                              SilcClientEntry client_entry)
 {
-  if (client_entry &&
-      silc_atomic_sub_int8(&client_entry->internal.refcnt, 1) == 0)
+  if (client_entry) {
+    SILC_LOG_DEBUG(("Client %p refcnt %d->%d", client_entry,
+                   silc_atomic_get_int8(&client_entry->internal.refcnt),
+                   silc_atomic_get_int8(&client_entry->internal.refcnt) - 1));
     silc_client_del_client(client, conn, client_entry);
+  }
 }
 
 /* Free client entry list */
@@ -867,15 +955,16 @@ void silc_client_list_free(SilcClient client, SilcClientConnection conn,
   }
 }
 
-
 /* Formats the nickname of the client specified by the `client_entry'.
    If the format is specified by the application this will format the
    nickname and replace the old nickname in the client entry. If the
-   format string is not specified then this function has no effect. */
+   format string is not specified then this function has no effect.
+   Returns the client entry that was formatted. */
 
-void silc_client_nickname_format(SilcClient client,
-                                SilcClientConnection conn,
-                                SilcClientEntry client_entry)
+SilcClientEntry silc_client_nickname_format(SilcClient client,
+                                           SilcClientConnection conn,
+                                           SilcClientEntry client_entry,
+                                           SilcBool priority)
 {
   char *cp;
   char newnick[128 + 1];
@@ -884,21 +973,25 @@ void silc_client_nickname_format(SilcClient client,
   SilcDList clients;
   SilcClientEntry entry, unformatted = NULL;
 
-  SILC_LOG_DEBUG(("Start"));
+  SILC_LOG_DEBUG(("Format nickname"));
 
   if (!client->internal->params->nickname_format[0])
-    return;
-
+    return client_entry;
   if (!client_entry->nickname[0])
-    return;
+    return NULL;
 
   /* Get all clients with same nickname. Do not perform the formatting
      if there aren't any clients with same nickname unless the application
      is forcing us to do so. */
   clients = silc_client_get_clients_local(client, conn,
                                          client_entry->nickname, NULL);
-  if (!clients && !client->internal->params->nickname_force_format)
-    return;
+  if (!clients)
+    return NULL;
+  if (silc_dlist_count(clients) == 1 &&
+      !client->internal->params->nickname_force_format) {
+    silc_client_list_free(client, conn, clients);
+    return client_entry;
+  }
 
   len = 0;
   freebase = TRUE;
@@ -909,20 +1002,21 @@ void silc_client_nickname_format(SilcClient client,
        silc_utf8_strcasecmp(entry->nickname, client_entry->nickname)) {
       freebase = FALSE;
       unformatted = entry;
+      break;
     }
   }
-  if (!len || freebase)
-    return;
+  if (!len || freebase) {
+    silc_client_list_free(client, conn, clients);
+    return client_entry;
+  }
 
-  /* If we are changing nickname of our local entry we'll enforce
-     that we will always get the unformatted nickname.  Give our
-     format number to the one that is not formatted now. */
-  if (unformatted && client_entry == conn->local_entry)
+  /* If priority formatting, this client always gets unformatted nickname. */
+  if (unformatted && priority)
     client_entry = unformatted;
 
   memset(newnick, 0, sizeof(newnick));
   cp = client->internal->params->nickname_format;
-  while (*cp) {
+  while (cp && *cp) {
     if (*cp == '%') {
       cp++;
       continue;
@@ -993,7 +1087,7 @@ void silc_client_nickname_format(SilcClient client,
        }
 
        memset(tmp, 0, sizeof(tmp));
-       snprintf(tmp, sizeof(tmp) - 1, "%d", ++max);
+       silc_snprintf(tmp, sizeof(tmp) - 1, "%d", ++max);
        len = strlen(tmp);
        memcpy(&newnick[off], tmp, len);
        off += len;
@@ -1012,6 +1106,79 @@ void silc_client_nickname_format(SilcClient client,
   newnick[off] = 0;
   memcpy(client_entry->nickname, newnick, strlen(newnick));
   silc_client_list_free(client, conn, clients);
+
+  return client_entry;
+}
+
+/* Parses nickname according to nickname format string */
+
+SilcBool silc_client_nickname_parse(SilcClient client,
+                                   SilcClientConnection conn,
+                                   char *nickname,
+                                   char **ret_nick)
+{
+  char *cp, s = 0, e = 0, *nick;
+  SilcBool n = FALSE;
+  int len;
+
+  if (!client->internal->params->nickname_format[0])
+    return TRUE;
+
+  if (!nickname || !nickname[0])
+    return FALSE;
+
+  cp = client->internal->params->nickname_format;
+  while (cp && *cp) {
+    if (*cp == '%') {
+      cp++;
+      continue;
+    }
+
+    switch(*cp) {
+    case 'n':
+      n = TRUE;
+      break;
+
+    case 'h':
+    case 'H':
+    case 's':
+    case 'S':
+    case 'a':
+      break;
+
+    default:
+      /* Get separator character */
+      if (n)
+       e = *cp;
+      else
+       s = *cp;
+      break;
+    }
+
+     cp++;
+  }
+  if (!n)
+    return FALSE;
+
+  /* Parse the nickname */
+  nick = nickname;
+  len = strlen(nick);
+  if (s)
+    if (strchr(nickname, s))
+      nick = strchr(nickname, s) + 1;
+  if (e)
+    if (strchr(nick, e))
+      len = strchr(nick, e) - nick;
+  if (!len)
+    return FALSE;
+
+  *ret_nick = silc_memdup(nick, len);
+  if (!(*ret_nick))
+    return FALSE;
+
+  SILC_LOG_DEBUG(("Parsed nickname: %s", *ret_nick));
+
+  return TRUE;
 }
 
 /************************ Channel Searching Locally *************************/
@@ -1179,49 +1346,40 @@ void silc_client_get_channel_resolve(SilcClient client,
   /* Send the command */
   if (!silc_client_command_send(client, conn, SILC_COMMAND_IDENTIFY,
                                silc_client_get_channel_cb, i, 1,
-                               3, channel_name, strlen(channel_name)))
-    completion(client, conn, SILC_STATUS_ERR_RESOURCE_LIMIT, NULL, context);
+                               3, channel_name, strlen(channel_name))) {
+    if (completion)
+      completion(client, conn, SILC_STATUS_ERR_RESOURCE_LIMIT, NULL, context);
+  }
 }
 
 /* Resolves channel information from the server by the channel ID. */
 
-void silc_client_get_channel_by_id_resolve(SilcClient client,
-                                          SilcClientConnection conn,
-                                          SilcChannelID *channel_id,
-                                          SilcGetChannelCallback completion,
-                                          void *context)
+SilcUInt16
+silc_client_get_channel_by_id_resolve(SilcClient client,
+                                     SilcClientConnection conn,
+                                     SilcChannelID *channel_id,
+                                     SilcGetChannelCallback completion,
+                                     void *context)
 {
   SilcClientGetChannelInternal i;
-  SilcChannelEntry channel;
   SilcBuffer idp;
   SilcUInt16 cmd_ident;
 
   if (!client || !conn || !channel_id || !completion)
-    return;
+    return 0;
 
   SILC_LOG_DEBUG(("Resolve channel by id %s",
                  silc_id_render(channel_id, SILC_ID_CHANNEL)));
 
   i = silc_calloc(1, sizeof(*i));
   if (!i)
-    return;
+    return 0;
   i->completion = completion;
   i->context = context;
   i->channels = silc_dlist_init();
   if (!i->channels) {
     silc_free(i);
-    return;
-  }
-
-  /* Attach to resolving, if on going */
-  channel = silc_client_get_channel_by_id(client, conn, channel_id);
-  if (channel && channel->internal.resolve_cmd_ident) {
-    SILC_LOG_DEBUG(("Attach to existing resolving"));
-    silc_client_unref_channel(client, conn, channel);
-    silc_client_command_pending(conn, SILC_COMMAND_NONE,
-                               channel->internal.resolve_cmd_ident,
-                               silc_client_get_channel_cb, i);
-    return;
+    return 0;
   }
 
   /* Send the command */
@@ -1230,13 +1388,10 @@ void silc_client_get_channel_by_id_resolve(SilcClient client,
                                       silc_client_get_channel_cb, i, 1,
                                       5, silc_buffer_datalen(idp));
   silc_buffer_free(idp);
-  if (!cmd_ident)
+  if (!cmd_ident && completion)
     completion(client, conn, SILC_STATUS_ERR_RESOURCE_LIMIT, NULL, context);
 
-  if (channel && cmd_ident)
-    channel->internal.resolve_cmd_ident = cmd_ident;
-
-  silc_client_unref_channel(client, conn, channel);
+  return cmd_ident;
 }
 
 /************************* Channel Entry Routines ***************************/
@@ -1258,6 +1413,7 @@ SilcChannelEntry silc_client_add_channel(SilcClient client,
   if (!channel)
     return NULL;
 
+  silc_atomic_init16(&channel->internal.refcnt, 0);
   channel->id = *channel_id;
   channel->mode = mode;
 
@@ -1285,6 +1441,8 @@ SilcChannelEntry silc_client_add_channel(SilcClient client,
     return NULL;
   }
 
+  silc_mutex_lock(conn->internal->lock);
+
   /* Add channel to cache, the normalized channel name is saved to cache */
   if (!silc_idcache_add(conn->internal->channel_cache, channel_namec,
                        &channel->id, channel)) {
@@ -1292,26 +1450,16 @@ SilcChannelEntry silc_client_add_channel(SilcClient client,
     silc_free(channel->channel_name);
     silc_hash_table_free(channel->user_list);
     silc_free(channel);
+    silc_mutex_unlock(conn->internal->lock);
     return NULL;
   }
 
-  return channel;
-}
-
-/* Foreach callbcak to free all users from the channel when deleting a
-   channel entry. */
-
-static void silc_client_del_channel_foreach(void *key, void *context,
-                                           void *user_context)
-{
-  SilcChannelUser chu = (SilcChannelUser)context;
+  silc_mutex_unlock(conn->internal->lock);
+  silc_client_ref_channel(client, conn, channel);
 
-  SILC_LOG_DEBUG(("Start"));
+  SILC_LOG_DEBUG(("Added %p", channel));
 
-  /* Remove the context from the client's channel hash table as that
-     table and channel's user_list hash table share this same context. */
-  silc_hash_table_del(chu->client->channels, chu->channel);
-  silc_free(chu);
+  return channel;
 }
 
 /* Removes channel from the cache by the channel entry. */
@@ -1319,46 +1467,56 @@ static void silc_client_del_channel_foreach(void *key, void *context,
 SilcBool silc_client_del_channel(SilcClient client, SilcClientConnection conn,
                                 SilcChannelEntry channel)
 {
-  SilcBool ret = silc_idcache_del_by_context(conn->internal->channel_cache,
-                                            channel, NULL);
-#if 0
+  SilcBool ret;
+  SilcCipher key;
+  SilcHmac hmac;
 
-  SILC_LOG_DEBUG(("Start"));
+  if (!channel)
+    return FALSE;
 
-  /* Free all client entrys from the users list. The silc_hash_table_free
-     will free all the entries so they are not freed at the foreach
-     callback. */
-  silc_hash_table_foreach(channel->user_list, silc_client_del_channel_foreach,
-                         NULL);
-  silc_hash_table_free(channel->user_list);
+  if (silc_atomic_sub_int16(&channel->internal.refcnt, 1) > 0)
+    return FALSE;
+
+  SILC_LOG_DEBUG(("Deleting channel %p", channel));
 
+  silc_mutex_lock(conn->internal->lock);
+  ret = silc_idcache_del_by_context(conn->internal->channel_cache,
+                                   channel, NULL);
+  silc_mutex_unlock(conn->internal->lock);
+
+  if (!ret)
+    return FALSE;
+
+  silc_client_empty_channel(client, conn, channel);
+  silc_hash_table_free(channel->user_list);
   silc_free(channel->channel_name);
   silc_free(channel->topic);
   if (channel->founder_key)
     silc_pkcs_public_key_free(channel->founder_key);
-  silc_free(channel->key);
-  if (channel->channel_key)
-    silc_cipher_free(channel->channel_key);
-  if (channel->hmac)
-    silc_hmac_free(channel->hmac);
-  if (channel->old_channel_keys) {
-    SilcCipher key;
-    silc_dlist_start(channel->old_channel_keys);
-    while ((key = silc_dlist_get(channel->old_channel_keys)) != SILC_LIST_END)
+  if (channel->internal.channel_key)
+    silc_cipher_free(channel->internal.channel_key);
+  if (channel->internal.hmac)
+    silc_hmac_free(channel->internal.hmac);
+  if (channel->internal.old_channel_keys) {
+    silc_dlist_start(channel->internal.old_channel_keys);
+    while ((key = silc_dlist_get(channel->internal.old_channel_keys)))
       silc_cipher_free(key);
-    silc_dlist_uninit(channel->old_channel_keys);
+    silc_dlist_uninit(channel->internal.old_channel_keys);
   }
-  if (channel->old_hmacs) {
-    SilcHmac hmac;
-    silc_dlist_start(channel->old_hmacs);
-    while ((hmac = silc_dlist_get(channel->old_hmacs)) != SILC_LIST_END)
+  if (channel->internal.old_hmacs) {
+    silc_dlist_start(channel->internal.old_hmacs);
+    while ((hmac = silc_dlist_get(channel->internal.old_hmacs)))
       silc_hmac_free(hmac);
-    silc_dlist_uninit(channel->old_hmacs);
+    silc_dlist_uninit(channel->internal.old_hmacs);
   }
-  silc_schedule_task_del_by_context(conn->client->schedule, channel);
+  if (channel->channel_pubkeys)
+    silc_argument_list_free(channel->channel_pubkeys,
+                           SILC_ARGUMENT_PUBLIC_KEY);
   silc_client_del_channel_private_keys(client, conn, channel);
+  silc_atomic_uninit16(&channel->internal.refcnt);
+  silc_schedule_task_del_by_context(conn->client->schedule, channel);
   silc_free(channel);
-#endif
+
   return ret;
 }
 
@@ -1370,7 +1528,6 @@ SilcBool silc_client_replace_channel_id(SilcClient client,
                                        SilcChannelEntry channel,
                                        SilcChannelID *new_id)
 {
-  SilcIDCacheEntry id_cache;
   SilcBool ret = FALSE;
 
   if (!new_id)
@@ -1381,14 +1538,10 @@ SilcBool silc_client_replace_channel_id(SilcClient client,
   SILC_LOG_DEBUG(("New Channel ID id(%s)",
                  silc_id_render(new_id, SILC_ID_CHANNEL)));
 
-  silc_mutex_lock(conn->internal->lock);
-
   /* Update the ID */
-  if (silc_idcache_find_by_id_one(conn->internal->channel_cache,
-                                  &channel->id, &id_cache))
-    ret = silc_idcache_update(conn->internal->channel_cache, id_cache,
-                             &channel->id, new_id, NULL, NULL, FALSE);
-
+  silc_mutex_lock(conn->internal->lock);
+  silc_idcache_update_by_context(conn->internal->channel_cache, channel,
+                                new_id, NULL, FALSE);
   silc_mutex_unlock(conn->internal->lock);
 
   return ret;
@@ -1399,7 +1552,10 @@ SilcBool silc_client_replace_channel_id(SilcClient client,
 void silc_client_ref_channel(SilcClient client, SilcClientConnection conn,
                             SilcChannelEntry channel_entry)
 {
-  silc_atomic_add_int8(&channel_entry->internal.refcnt, 1);
+  silc_atomic_add_int16(&channel_entry->internal.refcnt, 1);
+  SILC_LOG_DEBUG(("Channel %p refcnt %d->%d", channel_entry,
+                 silc_atomic_get_int16(&channel_entry->internal.refcnt) - 1,
+                 silc_atomic_get_int16(&channel_entry->internal.refcnt)));
 }
 
 /* Release reference of channel entry */
@@ -1407,9 +1563,13 @@ void silc_client_ref_channel(SilcClient client, SilcClientConnection conn,
 void silc_client_unref_channel(SilcClient client, SilcClientConnection conn,
                               SilcChannelEntry channel_entry)
 {
-  if (channel_entry &&
-      silc_atomic_sub_int8(&channel_entry->internal.refcnt, 1) == 0)
+  if (channel_entry) {
+    SILC_LOG_DEBUG(("Channel %p refcnt %d->%d", channel_entry,
+                   silc_atomic_get_int16(&channel_entry->internal.refcnt),
+                   silc_atomic_get_int16(&channel_entry->internal.refcnt)
+                   - 1));
     silc_client_del_channel(client, conn, channel_entry);
+  }
 }
 
 /* Free channel entry list */
@@ -1456,6 +1616,7 @@ SilcServerEntry silc_client_get_server(SilcClient client,
   if (!silc_idcache_find_by_name_one(conn->internal->server_cache,
                                     server_name, &id_cache)) {
     silc_free(server_name);
+    silc_mutex_unlock(conn->internal->lock);
     return NULL;
   }
 
@@ -1490,13 +1651,15 @@ SilcServerEntry silc_client_get_server_by_id(SilcClient client,
   silc_mutex_lock(conn->internal->lock);
 
   if (!silc_idcache_find_by_id_one(conn->internal->server_cache,
-                                  (void *)server_id, &id_cache))
+                                  server_id, &id_cache)) {
+    silc_mutex_unlock(conn->internal->lock);
     return NULL;
+  }
 
   SILC_LOG_DEBUG(("Found"));
 
   /* Reference */
-  entry = (SilcServerEntry)id_cache->context;
+  entry = id_cache->context;
   silc_client_ref_server(client, conn, entry);
 
   silc_mutex_unlock(conn->internal->lock);
@@ -1561,11 +1724,12 @@ static SilcBool silc_client_get_server_cb(SilcClient client,
 
 /* Resolve server by server ID */
 
-void silc_client_get_server_by_id_resolve(SilcClient client,
-                                         SilcClientConnection conn,
-                                         SilcServerID *server_id,
-                                         SilcGetServerCallback completion,
-                                         void *context)
+SilcUInt16
+silc_client_get_server_by_id_resolve(SilcClient client,
+                                    SilcClientConnection conn,
+                                    SilcServerID *server_id,
+                                    SilcGetServerCallback completion,
+                                    void *context)
 {
   SilcClientGetServerInternal i;
   SilcServerEntry server;
@@ -1573,20 +1737,20 @@ void silc_client_get_server_by_id_resolve(SilcClient client,
   SilcUInt16 cmd_ident;
 
   if (!client || !conn || !server_id || !completion)
-    return;
+    return 0;
 
   SILC_LOG_DEBUG(("Resolve server by id %s",
                  silc_id_render(server_id, SILC_ID_SERVER)));
 
   i = silc_calloc(1, sizeof(*i));
   if (!i)
-    return;
+    return 0;
   i->completion = completion;
   i->context = context;
   i->servers = silc_dlist_init();
   if (!i->servers) {
     silc_free(i);
-    return;
+    return 0;
   }
 
   /* Attach to resolving, if on going */
@@ -1597,7 +1761,7 @@ void silc_client_get_server_by_id_resolve(SilcClient client,
     silc_client_command_pending(conn, SILC_COMMAND_NONE,
                                server->internal.resolve_cmd_ident,
                                silc_client_get_server_cb, i);
-    return;
+    return server->internal.resolve_cmd_ident;
   }
 
   /* Send the command */
@@ -1606,13 +1770,15 @@ void silc_client_get_server_by_id_resolve(SilcClient client,
                                       silc_client_get_server_cb, i, 1,
                                       5, silc_buffer_datalen(idp));
   silc_buffer_free(idp);
-  if (!cmd_ident)
+  if (!cmd_ident && completion)
     completion(client, conn, SILC_STATUS_ERR_RESOURCE_LIMIT, NULL, context);
 
   if (server && cmd_ident)
     server->internal.resolve_cmd_ident = cmd_ident;
 
   silc_client_unref_server(client, conn, server);
+
+  return cmd_ident;
 }
 
 /************************** Server Entry Routines ***************************/
@@ -1628,12 +1794,16 @@ SilcServerEntry silc_client_add_server(SilcClient client,
   SilcServerEntry server_entry;
   char *server_namec = NULL;
 
-  SILC_LOG_DEBUG(("Start"));
+  if (!server_id)
+    return NULL;
+
+  SILC_LOG_DEBUG(("Adding new server %s", server_name));
 
   server_entry = silc_calloc(1, sizeof(*server_entry));
-  if (!server_entry || !server_id)
+  if (!server_entry)
     return NULL;
 
+  silc_atomic_init8(&server_entry->internal.refcnt, 0);
   server_entry->id = *server_id;
   if (server_name)
     server_entry->server_name = strdup(server_name);
@@ -1666,6 +1836,9 @@ SilcServerEntry silc_client_add_server(SilcClient client,
   }
 
   silc_mutex_unlock(conn->internal->lock);
+  silc_client_ref_server(client, conn, server_entry);
+
+  SILC_LOG_DEBUG(("Added %p", server_entry));
 
   return server_entry;
 }
@@ -1675,11 +1848,28 @@ SilcServerEntry silc_client_add_server(SilcClient client,
 SilcBool silc_client_del_server(SilcClient client, SilcClientConnection conn,
                                SilcServerEntry server)
 {
-  SilcBool ret = silc_idcache_del_by_context(conn->internal->server_cache,
-                                            server, NULL);
+  SilcBool ret;
+
+  if (!server)
+    return FALSE;
+
+  if (silc_atomic_sub_int8(&server->internal.refcnt, 1) > 0)
+    return FALSE;
+
+  SILC_LOG_DEBUG(("Deleting server %p", server));
+
+  silc_mutex_lock(conn->internal->lock);
+  ret = silc_idcache_del_by_context(conn->internal->server_cache,
+                                   server, NULL);
+  silc_mutex_unlock(conn->internal->lock);
+
   silc_free(server->server_name);
   silc_free(server->server_info);
+  if (server->public_key)
+    silc_pkcs_public_key_free(server->public_key);
+  silc_atomic_uninit8(&server->internal.refcnt);
   silc_free(server);
+
   return ret;
 }
 
@@ -1693,27 +1883,27 @@ void silc_client_update_server(SilcClient client,
 {
   char *server_namec = NULL;
 
-  SILC_LOG_DEBUG(("Start"));
+  SILC_LOG_DEBUG(("Updating server %p", server_entry));
 
   if (server_name &&
       (!server_entry->server_name ||
        !silc_utf8_strcasecmp(server_entry->server_name, server_name))) {
 
-    silc_idcache_del_by_context(conn->internal->server_cache,
-                               server_entry, NULL);
+    server_namec = silc_identifier_check(server_name, strlen(server_name),
+                                        SILC_STRING_UTF8, 256, NULL);
+    if (!server_namec)
+      return;
+
     silc_free(server_entry->server_name);
     server_entry->server_name = strdup(server_name);
+    if (!server_entry->server_name)
+      return;
 
-    /* Normalize server name */
-    if (server_name) {
-      server_namec = silc_identifier_check(server_name, strlen(server_name),
-                                          SILC_STRING_UTF8, 256, NULL);
-      if (!server_namec)
-       return;
-
-      silc_idcache_add(conn->internal->server_cache, server_namec,
-                      &server_entry->id, server_entry);
-    }
+    /* Update cache entry */
+    silc_mutex_lock(conn->internal->lock);
+    silc_idcache_update_by_context(conn->internal->server_cache, server_entry,
+                                  NULL, server_namec, TRUE);
+    silc_mutex_unlock(conn->internal->lock);
   }
 
   if (server_info &&
@@ -1730,6 +1920,9 @@ void silc_client_ref_server(SilcClient client, SilcClientConnection conn,
                            SilcServerEntry server_entry)
 {
   silc_atomic_add_int8(&server_entry->internal.refcnt, 1);
+  SILC_LOG_DEBUG(("Server %p refcnt %d->%d", server_entry,
+                 silc_atomic_get_int8(&server_entry->internal.refcnt) - 1,
+                 silc_atomic_get_int8(&server_entry->internal.refcnt)));
 }
 
 /* Release reference of server entry */
@@ -1737,9 +1930,13 @@ void silc_client_ref_server(SilcClient client, SilcClientConnection conn,
 void silc_client_unref_server(SilcClient client, SilcClientConnection conn,
                              SilcServerEntry server_entry)
 {
-  if (server_entry &&
-      silc_atomic_sub_int8(&server_entry->internal.refcnt, 1) == 0)
+  if (server_entry) {
+    SILC_LOG_DEBUG(("Server %p refcnt %d->%d", server_entry,
+                   silc_atomic_get_int8(&server_entry->internal.refcnt),
+                   silc_atomic_get_int8(&server_entry->internal.refcnt)
+                   - 1));
     silc_client_del_server(client, conn, server_entry);
+  }
 }
 
 /* Free server entry list */