merged gtk2_imap_c branch with HEAD
authorHoà Viêt Dinh <dinh.viet.hoa@free.fr>
Sun, 3 Jul 2005 15:09:13 +0000 (15:09 +0000)
committerHoà Viêt Dinh <dinh.viet.hoa@free.fr>
Sun, 3 Jul 2005 15:09:13 +0000 (15:09 +0000)
14 files changed:
configure.ac
src/Makefile.am
src/etpan/Makefile.am [new file with mode: 0644]
src/etpan/etpan-errors.h [new file with mode: 0644]
src/etpan/etpan-log.c [new file with mode: 0644]
src/etpan/etpan-log.h [new file with mode: 0644]
src/etpan/etpan-thread-manager-types.h [new file with mode: 0644]
src/etpan/etpan-thread-manager.c [new file with mode: 0644]
src/etpan/etpan-thread-manager.h [new file with mode: 0644]
src/etpan/imap-thread.c [new file with mode: 0644]
src/etpan/imap-thread.h [new file with mode: 0644]
src/imap.c
src/main.c
src/prefs_other.c

index 93fd37a..8c691b5 100644 (file)
@@ -613,6 +613,29 @@ fi
 AC_SUBST(CLAMAV_LIBS)
 AM_CONDITIONAL(BUILD_CLAMAV_PLUGIN, test x"$ac_cv_enable_clamav_plugin" = xyes)
 
+dnl Libetpan
+libetpan=no
+AC_PATH_PROG(libetpanconfig, [libetpan-config])
+if test "x$libetpanconfig" != "x"; then
+  CPPFLAGS="$CPPFLAGS `$libetpanconfig --cflags 2>/dev/null`"
+  AC_CHECK_HEADER(libetpan/libetpan.h, [libetpan=yes])
+  if test "x$libetpan" = "xyes"; then
+    AC_MSG_CHECKING([whether libetpan-config hints compiles and links fine])
+    LDFLAGS="$LDFLAGS `$libetpanconfig --libs 2>/dev/null`"
+    AC_TRY_LINK([], [db_mailstorage_init();], [libetpan=yes], [libetpan=no])
+    AC_MSG_RESULT([$libetpan])
+  fi
+fi
+if test "x$libetpan" = "xyes"; then
+   LIBETPAN_CPPFLAGS="`$libetpanconfig --cflags`"
+   LIBETPAN_LIBS="`$libetpanconfig --libs`"
+else
+   AC_MSG_ERROR([Sylpheed requires libetpan.])
+fi
+
+AC_SUBST(LIBETPAN_FLAGS)
+AC_SUBST(LIBETPAN_LIBS)
+
 dnl ****************************
 dnl ** Final configure output **
 dnl ****************************
@@ -627,6 +650,7 @@ src/Makefile
 src/common/Makefile
 src/common/passcrypt.h
 src/gtk/Makefile
+src/etpan/Makefile
 src/plugins/Makefile
 src/plugins/demo/Makefile
 src/plugins/spamassassin/Makefile
index dc515e1..ab23921 100644 (file)
@@ -1,4 +1,4 @@
-SUBDIRS = common gtk plugins
+SUBDIRS = common gtk plugins etpan
 
 bin_PROGRAMS = sylpheed
 
@@ -384,12 +384,14 @@ EXTRA_DIST = \
 
 INCLUDES = \
        -Icommon \
-       -Igtk
+       -Igtk \
+       -Ietpan
 
 sylpheed_LDFLAGS = \
        -export-dynamic
 
 sylpheed_LDADD = \
+       etpan/libsylpheedetpan.la \
        gtk/libsylpheedgtk.la \
        $(ASPELL_LIBS) \
        $(INTLLIBS) \
@@ -402,7 +404,8 @@ sylpheed_LDADD = \
        $(PTHREAD_LIBS) \
        $(GNOMEPRINT_LIBS) \
        $(LIBICONV) \
-       $(STARTUP_NOTIFICATION_LIBS)
+       $(STARTUP_NOTIFICATION_LIBS) \
+       $(LIBETPAN_LIBS)
 
 AM_CPPFLAGS = \
        -DG_LOG_DOMAIN=\"Sylpheed\" \
@@ -416,6 +419,7 @@ AM_CPPFLAGS = \
        $(GPGME_CFLAGS) \
        $(OPENSSL_CFLAGS) \
        $(GNOMEPRINT_CFLAGS) \
+       $(LIBETPAN_CPPFLAGS) \
        $(STARTUP_NOTIFICATION_CFLAGS)
 
 AM_YFLAGS = -d
diff --git a/src/etpan/Makefile.am b/src/etpan/Makefile.am
new file mode 100644 (file)
index 0000000..aed004d
--- /dev/null
@@ -0,0 +1,27 @@
+PLUGINDIR = $(pkglibdir)/plugins/
+
+noinst_LTLIBRARIES = libsylpheedetpan.la
+
+libsylpheedetpan_la_SOURCES = \
+       etpan-thread-manager.c \
+       etpan-log.c \
+       imap-thread.c
+
+sylpheedetpanincludedir = $(pkgincludedir)/etpan
+sylpheedetpaninclude_HEADERS = \
+       etpan-thread-manager-types.h \
+       etpan-thread-manager.h \
+       etpan-errors.h \
+       etpan-log.h \
+       imap-thread.h
+
+AM_CPPFLAGS = \
+       -I../common \
+       -I.. \
+       $(GTK_CFLAGS) \
+       $(LIBETPAN_CFLAGS)
+
+libsylpheedetpan_la_LIBADD = \
+       ../common/libsylpheedcommon.la \
+       $(GTK_LIBS) \
+       $(LIBETPAN_LIBS)
diff --git a/src/etpan/etpan-errors.h b/src/etpan/etpan-errors.h
new file mode 100644 (file)
index 0000000..a2c8791
--- /dev/null
@@ -0,0 +1,82 @@
+/*
+ * etPan! -- a mail user agent
+ *
+ * Copyright (C) 2001, 2002 - DINH Viet Hoa
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of the libEtPan! project nor the names of its
+ *    contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/*
+ * $Id$
+ */
+
+#ifndef ETPAN_ERRORS_H
+
+#define ETPAN_ERRORS_H
+
+enum {
+  NO_ERROR = 0,
+  ERROR_CACHE,
+  ERROR_MEMORY,
+  ERROR_CONFIG,
+  ERROR_INVAL,
+  ERROR_PARSE,
+  ERROR_MOVE,
+  ERROR_COPY,
+  ERROR_MSG_LIST,
+  ERROR_ENV_LIST,
+  ERROR_CONNECT, /* 10 */
+  ERROR_FETCH,
+  ERROR_APPEND,
+  ERROR_SEND,
+  ERROR_NOT_IMPLEMENTED,
+  ERROR_FILE,
+  ERROR_TOO_MUCH_RECIPIENT,
+  ERROR_COMMAND,
+  ERROR_STREAM,
+  ERROR_CANCELLED,
+  ERROR_CREATE, /* 20 */
+  ERROR_UNKNOWN_PROTOCOL,
+  ERROR_COULD_NOT_ENCRYPT,
+  ERROR_CHECK,
+  ERROR_STATUS,
+  ERROR_EXPUNGE,
+  ERROR_MARK_AS_SPAM,
+  ERROR_BUSY,
+  ERROR_NEWSGROUPS_LIST,
+  ERROR_IMAP_MAILBOX_LIST,
+  ERROR_IMAP_SELECT, /* 30 */
+  ERROR_IMAP_CREATE,
+  ERROR_PRIVACY,
+  ERROR_DIRECTORY_NOT_FOUND,
+  ERROR_LDAP_SEARCH,
+  ERROR_NOT_SUPPORTED,
+  ERROR_COULD_NOT_POSTPONE,
+  ERROR_NO_FROM,
+  ERROR_AUTH,
+};
+
+#endif
diff --git a/src/etpan/etpan-log.c b/src/etpan/etpan-log.c
new file mode 100644 (file)
index 0000000..5d45981
--- /dev/null
@@ -0,0 +1,187 @@
+#include "etpan-log.h"
+
+#include <pthread.h>
+#include <stdio.h>
+#include <stdarg.h>
+#include <sys/time.h>
+#include <libetpan/libetpan.h>
+#include <stdlib.h>
+#include <string.h>
+
+#define MAX_LOG_LINE 1024
+static pthread_mutex_t log_lock = PTHREAD_MUTEX_INITIALIZER;
+static char log_line[MAX_LOG_LINE];
+static chash * log_filter = NULL;
+
+static void etpan_str_log(void)
+{
+  fprintf(stderr, "%s\n", log_line);
+}
+
+void etpan_log_init(void)
+{
+  pthread_mutex_lock(&log_lock);
+  if (log_filter == NULL) {
+    char * env_value;
+    
+    env_value = getenv("ETPAN_LOG");
+    if (env_value != NULL) {
+      strncpy(log_line, env_value, sizeof(log_line));
+      log_line[sizeof(log_line) - 1] = '\0';
+    }
+    else {
+      * log_line = '\0';
+    }
+    env_value = log_line;
+    
+    log_filter = chash_new(CHASH_DEFAULTSIZE, CHASH_COPYKEY);
+    if (log_filter != NULL) {
+      chashdatum key;
+      chashdatum value;
+      
+      key.data = "LOG";
+      key.len = strlen("LOG");
+      value.data = NULL;
+      value.len = 0;
+      chash_set(log_filter, &key, &value, NULL);
+      
+      while (env_value != NULL) {
+        char * p;
+        
+        p = strchr(env_value, ' ');
+        if (p != NULL) {
+          * p = '\0';
+          key.data = env_value;
+          key.len = strlen(env_value);
+          value.data = NULL;
+          value.len = 0;
+          chash_set(log_filter, &key, &value, NULL);
+          
+          env_value = p + 1;
+        }
+        else {
+          key.data = env_value;
+          key.len = strlen(env_value);
+          value.data = NULL;
+          value.len = 0;
+          chash_set(log_filter, &key, &value, NULL);
+          
+          env_value = p;
+        }
+      }
+    }
+  }
+  pthread_mutex_unlock(&log_lock);
+}
+
+void etpan_log_done(void)
+{
+  pthread_mutex_lock(&log_lock);
+  if (log_filter != NULL) {
+    chash_free(log_filter);
+    log_filter = NULL;
+  }
+  pthread_mutex_unlock(&log_lock);
+}
+
+void etpan_log(char * log_id, char * format, ...)
+{
+  va_list argp;
+  struct timeval time_info;
+  int r;
+  chashdatum key;
+  chashdatum value;
+  
+  etpan_log_init();
+  
+  key.data = log_id;
+  key.len = strlen(log_id);
+  r = chash_get(log_filter, &key, &value);
+  if (r < 0)
+    return;
+  
+  r = gettimeofday(&time_info, NULL);
+  if (r == 0) {
+    fprintf(stderr, "%4lu.%03u [%s] ", time_info.tv_sec % 3600,
+        (unsigned int) (time_info.tv_usec / 1000), log_id);
+  }
+  
+  va_start(argp, format);
+  pthread_mutex_lock(&log_lock);
+  vsnprintf(log_line, sizeof(log_line), format, argp);
+  etpan_str_log();
+  pthread_mutex_unlock(&log_lock);
+  va_end(argp);
+}
+
+#if defined(__APPLE__) && defined(__MACH__)
+#include <mach/vm_types.h>
+
+extern void thread_stack_pcs(vm_address_t *buffer,
+    unsigned max, unsigned *num);
+
+void etpan_log_stack(void)
+{
+  unsigned buffer[256];
+  int num_frames;
+  int i;
+  char output[1024];
+  char * current_output;
+  size_t remaining;
+  
+  thread_stack_pcs(buffer, sizeof(buffer) / sizeof(buffer[0]), &num_frames);
+  remaining = sizeof(output);
+  current_output = output;
+  for(i = 0 ; i < num_frames ; i ++) {
+    size_t len;
+    
+    snprintf(current_output, remaining, "0x%x ", buffer[i]);
+    len = strlen(current_output);
+    remaining -= len;
+    current_output += len;
+    if (remaining == 0)
+      break;
+  }
+  ETPAN_STACK_LOG(output);
+}
+#else
+#if defined(__linux__)
+#include <execinfo.h>
+
+extern char **backtrace_symbols (void *__const *__array, int __size) __THROW;
+
+void etpan_log_stack(void)
+{
+  void * buffer[256];
+  char ** table;
+  int num_frames;
+  int i;
+  char output[1024];
+  char * current_output;
+  size_t remaining;
+  
+  num_frames = backtrace(buffer, sizeof(buffer) / sizeof(buffer[0]));
+  remaining = sizeof(output);
+  current_output = output;
+  for(i = 0 ; i < num_frames ; i ++) {
+    size_t len;
+    
+    snprintf(current_output, remaining, "%p ", buffer[i]);
+    len = strlen(current_output);
+    remaining -= len;
+    current_output += len;
+    if (remaining == 0)
+      break;
+  }
+  ETPAN_STACK_LOG(output);
+}
+
+#else
+
+void etpan_log_stack(void)
+{
+  ETPAN_STACK_LOG("this feature not available");
+}
+
+#endif
+#endif
diff --git a/src/etpan/etpan-log.h b/src/etpan/etpan-log.h
new file mode 100644 (file)
index 0000000..c0950fc
--- /dev/null
@@ -0,0 +1,54 @@
+#ifndef ETPAN_LOG_H
+
+#define ETPAN_LOG_H
+
+#define ENABLE_LOG
+
+#ifdef ENABLE_LOG
+
+/*
+  an environment variable ETPAN_LOG must be set
+  and will contains the log identifier separated with spaces.
+*/
+
+#define ETPAN_GTK_TREE_MODEL_LOG(...) ETPAN_LOG_ID("GTKTREEMODEL", __VA_ARGS__)
+#define ETPAN_TABBED_LOG(...) ETPAN_LOG_ID("TABBED", __VA_ARGS__)
+#define ETPAN_MSGVIEW_LOG(...) ETPAN_LOG_ID("MSGVIEW", __VA_ARGS__)
+#define ETPAN_MSGLIST_LOG(...) ETPAN_LOG_ID("MSGLIST", __VA_ARGS__)
+#define ETPAN_FOLDERLIST_LOG(...) ETPAN_LOG_ID("FOLDERLIST", __VA_ARGS__)
+#define ETPAN_MAINWINDOW_LOG(...) ETPAN_LOG_ID("MAINWINDOW", __VA_ARGS__)
+#define ETPAN_SIGNAL_LOG(...) ETPAN_LOG_ID("SIGNAL", __VA_ARGS__)
+#define ETPAN_MEM_LOG(...) ETPAN_LOG_ID("MEM", __VA_ARGS__)
+#define ETPAN_UI_LOG(...) ETPAN_LOG_ID("UI", __VA_ARGS__)
+#define ETPAN_PROGRESS_LOG(...) ETPAN_LOG_ID("PROGRESS", __VA_ARGS__)
+#define ETPAN_DEBUG_LOG(...) ETPAN_LOG_ID("DEBUG", __VA_ARGS__)
+#define ETPAN_STACK_LOG(...) ETPAN_LOG_ID("STACK", __VA_ARGS__)
+#define ETPAN_LOG(...) ETPAN_LOG_ID("LOG", __VA_ARGS__)
+
+#else
+
+#define ETPAN_GTK_TREE_MODEL_LOG(...)
+#define ETPAN_TABBED_LOG(...)
+#define ETPAN_MSGVIEW_LOG(...)
+#define ETPAN_MSGLIST_LOG(...)
+#define ETPAN_FOLDERLIST_LOG(...)
+#define ETPAN_MAINWINDOW_LOG(...)
+#define ETPAN_SIGNAL_LOG(...)
+#define ETPAN_MEM_LOG(...)
+#define ETPAN_UI_LOG(...)
+#define ETPAN_PROGRESS_LOG(...)
+#define ETPAN_DEBUG_LOG(...)
+#define ETPAN_STACK_LOG(...)
+#define ETPAN_LOG(...) ETPAN_LOG_ID("LOG", __VA_ARGS__)
+
+#endif
+
+#define ETPAN_LOG_ID(...) etpan_log(__VA_ARGS__)
+
+void etpan_log_init(void);
+void etpan_log_done(void);
+void etpan_log(char * log_id, char * format, ...);
+
+void etpan_log_stack(void);
+
+#endif
diff --git a/src/etpan/etpan-thread-manager-types.h b/src/etpan/etpan-thread-manager-types.h
new file mode 100644 (file)
index 0000000..6d5b800
--- /dev/null
@@ -0,0 +1,53 @@
+#ifndef ETPAN_THREAD_MANAGER_TYPES_H
+
+#define ETPAN_THREAD_MANAGER_TYPES_H
+
+#include <libetpan/libetpan.h>
+
+struct etpan_thread_manager {
+  /* thread pool */
+  carray * thread_pool;
+  carray * thread_pending;
+  int can_create_thread;
+  
+  int unbound_count;
+  
+  int notify_fds[2];
+};
+
+struct etpan_thread {
+  struct etpan_thread_manager * manager;
+  
+  pthread_t th_id;
+  
+  pthread_mutex_t lock;
+  carray * op_list;
+  carray * op_done_list;
+  
+  int bound_count;
+  int terminate_state;
+  
+  struct mailsem * start_sem;
+  struct mailsem * stop_sem;
+  struct mailsem * op_sem;
+};
+
+struct etpan_thread_op {
+  struct etpan_thread * thread;
+  
+  void (* run)(struct etpan_thread_op * op);
+  
+  void (* callback)(int cancelled, void * result, void * callback_data);
+  void * callback_data;
+  
+  void (* cleanup)(struct etpan_thread_op * op);
+  
+  pthread_mutex_t lock;
+  int callback_called;
+  int cancellable;
+  int cancelled;
+  void * param;
+  void * result;
+};
+
+#endif
diff --git a/src/etpan/etpan-thread-manager.c b/src/etpan/etpan-thread-manager.c
new file mode 100644 (file)
index 0000000..c530e0a
--- /dev/null
@@ -0,0 +1,633 @@
+#include "etpan-thread-manager.h"
+
+#include <stdlib.h>
+#include <pthread.h>
+#include <libetpan/mailsem.h>
+#include <semaphore.h>
+#include <unistd.h>
+
+#include "etpan-log.h"
+#include "etpan-errors.h"
+
+#define POOL_UNBOUND_MAX 4
+
+#define POOL_INIT_SIZE 8
+#define OP_INIT_SIZE 8
+
+enum {
+  TERMINATE_STATE_NONE,
+  TERMINATE_STATE_REQUESTED,
+  TERMINATE_STATE_DONE,
+};
+
+struct etpan_thread_manager * etpan_thread_manager_new(void)
+{
+  struct etpan_thread_manager * manager;
+  int r;
+  
+  manager = malloc(sizeof(* manager));
+  if (manager == NULL)
+    goto err;
+  
+  manager->thread_pool = carray_new(POOL_INIT_SIZE);
+  if (manager->thread_pool == NULL)
+    goto free;
+
+  manager->thread_pending = carray_new(POOL_INIT_SIZE);
+  if (manager->thread_pending == NULL)
+    goto free_pool;
+  
+  manager->can_create_thread = 1;
+  manager->unbound_count = 0;
+  
+  r = pipe(manager->notify_fds);
+  if (r < 0)
+    goto free_pending;
+  
+  return manager;
+  
+ free_pending:
+  carray_free(manager->thread_pending);
+ free_pool:
+  carray_free(manager->thread_pool);
+ free:
+  free(manager);
+ err:
+  return NULL;
+}
+
+void etpan_thread_manager_free(struct etpan_thread_manager * manager)
+{
+  close(manager->notify_fds[1]);
+  close(manager->notify_fds[0]);
+  carray_free(manager->thread_pending);
+  carray_free(manager->thread_pool);
+  free(manager);
+}
+
+struct etpan_thread * etpan_thread_new(void)
+{
+  struct etpan_thread * thread;
+  int r;
+  
+  thread = malloc(sizeof(* thread));
+  if (thread == NULL)
+    goto err;
+  
+  r = pthread_mutex_init(&thread->lock, NULL);
+  if (r != 0)
+    goto free;
+
+  thread->op_list = carray_new(OP_INIT_SIZE);
+  if (thread->op_list == NULL)
+    goto destroy_lock;
+  
+  thread->op_done_list = carray_new(OP_INIT_SIZE);
+  if (thread->op_done_list == NULL)
+    goto free_op_list;
+  
+  thread->start_sem = mailsem_new();
+  if (thread->start_sem == NULL)
+    goto free_op_done_list;
+  
+  thread->stop_sem = mailsem_new();
+  if (thread->stop_sem == NULL)
+    goto free_startsem;
+  
+  thread->op_sem = mailsem_new();
+  if (thread->op_sem == NULL)
+    goto free_stopsem;
+  
+  thread->manager = NULL;
+  thread->bound_count = 0;
+  thread->terminate_state = TERMINATE_STATE_NONE;
+  
+  return thread;
+  
+ free_stopsem:
+  mailsem_free(thread->stop_sem);
+ free_startsem:
+  mailsem_free(thread->start_sem);
+ free_op_done_list:
+  carray_free(thread->op_done_list);
+ free_op_list:
+  carray_free(thread->op_list);
+ destroy_lock:
+  pthread_mutex_destroy(&thread->lock);
+ free:
+  free(thread);
+ err:
+  return NULL;
+}
+
+void etpan_thread_free(struct etpan_thread * thread)
+{
+  mailsem_free(thread->op_sem);
+  mailsem_free(thread->stop_sem);
+  mailsem_free(thread->start_sem);
+  carray_free(thread->op_done_list);
+  carray_free(thread->op_list);
+  pthread_mutex_destroy(&thread->lock);
+  free(thread);
+}
+
+struct etpan_thread_op * etpan_thread_op_new(void)
+{
+  struct etpan_thread_op * op;
+  int r;
+  
+  op = malloc(sizeof(* op));
+  if (op == NULL)
+    goto err;
+  
+  op->thread = NULL;
+  op->run = NULL;
+  op->callback = NULL;
+  op->callback_data = NULL;
+  op->callback_called = 0;
+  op->cancellable = 0;
+  op->cancelled = 0;
+  op->param = NULL;
+  op->result = NULL;
+  
+  r = pthread_mutex_init(&op->lock, NULL);
+  if (r != 0)
+    goto free;
+  
+  return op;
+  
+ free:
+  free(op);
+ err:
+  return NULL;
+}
+
+void etpan_thread_op_free(struct etpan_thread_op * op)
+{
+  pthread_mutex_destroy(&op->lock);
+  free(op);
+}
+
+static struct etpan_thread *
+etpan_thread_manager_create_thread(struct etpan_thread_manager * manager)
+{
+  struct etpan_thread * thread;
+  int r;
+  
+  thread = etpan_thread_new();
+  if (thread == NULL)
+    goto err;
+  
+  thread->manager = manager;
+  
+  r = etpan_thread_start(thread);
+  if (r != NO_ERROR)
+    goto free_thread;
+  
+  r = carray_add(manager->thread_pool, thread, NULL);
+  if (r < 0) {
+    etpan_thread_stop(thread);
+    goto free_thread;
+  }
+  
+  return thread;
+  
+ free_thread:
+  etpan_thread_free(thread);
+ err:
+  return NULL;
+}
+
+static void
+etpan_thread_manager_terminate_thread(struct etpan_thread_manager * manager,
+    struct etpan_thread * thread)
+{
+  unsigned int i;
+  int r;
+  
+  for(i = 0 ; i < carray_count(manager->thread_pool) ; i ++) {
+    if (carray_get(manager->thread_pool, i) == thread) {
+      carray_delete(manager->thread_pool, i);
+      break;
+    }
+  }
+  
+  if (!etpan_thread_is_bound(thread))
+    manager->unbound_count --;
+  
+  r = carray_add(manager->thread_pending, thread, NULL);
+  if (r < 0) {
+    ETPAN_LOG("complete failure of thread due to lack of memory (thread stop)");
+  }
+  
+  etpan_thread_stop(thread);
+}
+
+static void manager_notify(struct etpan_thread_manager * manager)
+{
+  char ch;
+  ssize_t r;
+  
+  ch = 1;
+  r = write(manager->notify_fds[1], &ch, 1);
+}
+
+static void manager_ack(struct etpan_thread_manager * manager)
+{
+  char ch;
+  ssize_t r;
+  
+  r = read(manager->notify_fds[0], &ch, 1);
+}
+
+static void thread_lock(struct etpan_thread * thread)
+{
+  pthread_mutex_lock(&thread->lock);
+}
+
+static void thread_unlock(struct etpan_thread * thread)
+{
+  pthread_mutex_unlock(&thread->lock);
+}
+
+static void thread_notify(struct etpan_thread * thread)
+{
+  manager_notify(thread->manager);
+}
+
+static void * thread_run(void * data)
+{
+  struct etpan_thread * thread;
+  int r;
+  
+  thread = data;
+  
+  mailsem_up(thread->start_sem);
+  
+  while (1) {
+    int do_quit;
+    struct etpan_thread_op * op;
+    
+    mailsem_down(thread->op_sem);
+    
+    do_quit = 0;
+    op = NULL;
+    thread_lock(thread);
+    if (carray_count(thread->op_list) > 0) {
+      op = carray_get(thread->op_list, 0);
+      carray_delete_slow(thread->op_list, 0);
+    }
+    else {
+      do_quit = 1;
+    }
+    thread_unlock(thread);
+    
+    if (do_quit) {
+      break;
+    }
+    
+    if (!etpan_thread_op_cancelled(op)) {
+      if (op->run != NULL)
+        op->run(op);
+    }
+    
+    thread_lock(thread);
+    r = carray_add(thread->op_done_list, op, NULL);
+    if (r < 0) {
+      ETPAN_LOG("complete failure of thread due to lack of memory (op done)");
+    }
+    thread_unlock(thread);
+    
+    thread_notify(thread);
+  }
+  
+  thread_lock(thread);
+  thread->terminate_state = TERMINATE_STATE_DONE;
+  thread_unlock(thread);
+  
+  thread_notify(thread);
+  
+  mailsem_up(thread->stop_sem);
+  
+  return NULL;
+}
+
+int etpan_thread_start(struct etpan_thread * thread)
+{
+  int r;
+  
+  r = pthread_create(&thread->th_id, NULL, thread_run, thread);
+  if (r != 0)
+    return ERROR_MEMORY;
+  
+  mailsem_down(thread->start_sem);
+  
+  return NO_ERROR;
+}
+
+void etpan_thread_stop(struct etpan_thread * thread)
+{
+  thread_lock(thread);
+  thread->terminate_state = TERMINATE_STATE_REQUESTED;
+  thread_unlock(thread);
+  
+  mailsem_up(thread->op_sem);
+  
+  /* this thread will be joined in the manager loop */
+}
+
+int etpan_thread_is_stopped(struct etpan_thread * thread)
+{
+  int stopped;
+  
+  thread_lock(thread);
+  stopped = (thread->terminate_state == TERMINATE_STATE_DONE);
+  thread_unlock(thread);
+  
+  return stopped;
+}
+
+void etpan_thread_join(struct etpan_thread * thread)
+{
+  mailsem_down(thread->stop_sem);
+  pthread_join(thread->th_id, NULL);
+}
+
+struct etpan_thread *
+etpan_thread_manager_get_thread(struct etpan_thread_manager * manager)
+{
+  struct etpan_thread * chosen_thread;
+  unsigned int chosen_thread_load;
+  unsigned int i;
+  struct etpan_thread * thread;
+  
+  /* chose a thread */
+  
+  chosen_thread = NULL;
+  chosen_thread_load = 0;
+  
+  for(i = 0 ; i < carray_count(manager->thread_pool) ; i ++) {
+    thread = carray_get(manager->thread_pool, i);
+    if (etpan_thread_is_bound(thread))
+      continue;
+    
+    if (chosen_thread == NULL) {
+      chosen_thread = thread;
+      chosen_thread_load = etpan_thread_get_load(thread);
+      
+      if (chosen_thread_load == 0)
+        break;
+    }
+    else {
+      unsigned int load;
+      
+      load = etpan_thread_get_load(thread);
+      
+      if (load < chosen_thread_load) {
+        chosen_thread = thread;
+        chosen_thread_load = load;
+      }
+    }
+  }
+  
+  if (chosen_thread != NULL) {
+    if (manager->can_create_thread && (chosen_thread_load != 0)) {
+      chosen_thread = NULL;
+    }
+  }
+  
+  /* choice done */
+  
+  if (chosen_thread != NULL)
+    return chosen_thread;
+  
+  thread = etpan_thread_manager_create_thread(manager);
+  if (thread == NULL)
+    goto err;
+  
+  manager->unbound_count ++;
+  if (manager->unbound_count >= POOL_UNBOUND_MAX)
+    manager->can_create_thread = 0;
+  
+  return thread;
+  
+ err:
+  return NULL;
+}
+
+unsigned int etpan_thread_get_load(struct etpan_thread * thread)
+{
+  unsigned int load;
+  
+  thread_lock(thread);
+  load = carray_count(thread->op_list);
+  thread_unlock(thread);
+  
+  return load;
+}
+
+void etpan_thread_bind(struct etpan_thread * thread)
+{
+  thread->bound_count ++;
+}
+
+void etpan_thread_unbind(struct etpan_thread * thread)
+{
+  thread->bound_count --;
+}
+
+int etpan_thread_is_bound(struct etpan_thread * thread)
+{
+  return (thread->bound_count != 0);
+}
+
+int etpan_thread_op_schedule(struct etpan_thread * thread,
+                             struct etpan_thread_op * op)
+{
+  int r;
+  
+  if (thread->terminate_state != TERMINATE_STATE_NONE)
+    return ERROR_INVAL;
+  
+  thread_lock(thread);
+  r = carray_add(thread->op_list, op, NULL);
+  thread_unlock(thread);
+  
+  if (r < 0)
+    return ERROR_MEMORY;
+  
+  op->thread = thread;
+  mailsem_up(thread->op_sem);
+  
+  return NO_ERROR;
+}
+
+void etpan_thread_op_lock(struct etpan_thread_op * op)
+{
+  pthread_mutex_lock(&op->lock);
+}
+
+void etpan_thread_op_unlock(struct etpan_thread_op * op)
+{
+  pthread_mutex_unlock(&op->lock);
+}
+
+int etpan_thread_op_cancelled(struct etpan_thread_op * op)
+{
+  int cancelled;
+  
+  cancelled = 0;
+  etpan_thread_op_lock(op);
+  if (op->cancellable)
+    cancelled = op->cancelled;
+  etpan_thread_op_unlock(op);
+  
+  return cancelled;
+}
+
+void etpan_thread_op_cancel(struct etpan_thread_op * op)
+{ 
+  etpan_thread_op_lock(op);
+  if (op->cancelled) {
+    ETPAN_LOG("cancelled twice");
+  }
+  op->cancelled = 1;
+  if ((op->callback != NULL) && (!op->callback_called)) {
+    op->callback(op->cancelled, op->result, op->callback_data);
+    op->callback_called = 1;
+  }
+  etpan_thread_op_unlock(op);
+}
+
+int etpan_thread_manager_op_schedule(struct etpan_thread_manager * manager,
+    struct etpan_thread_op * op)
+{
+  struct etpan_thread * thread;
+  
+  thread = etpan_thread_manager_get_thread(manager);
+  
+  if (thread == NULL)
+    goto err;
+  
+  return etpan_thread_op_schedule(thread, op);
+  
+ err:
+  return ERROR_MEMORY;
+}
+
+int etpan_thread_manager_get_fd(struct etpan_thread_manager * manager)
+{
+  return manager->notify_fds[0];
+}
+
+static void loop_thread_list(carray * op_to_notify,
+    carray * thread_list)
+{
+  unsigned int i;
+  int r;
+  
+  for(i = 0 ; i < carray_count(thread_list) ; i ++) {
+    struct etpan_thread * thread;
+    unsigned int j;
+    
+    thread = carray_get(thread_list, i);
+    
+    thread_lock(thread);
+    
+    for(j = 0 ; j < carray_count(thread->op_done_list) ; j ++) {
+      struct etpan_thread_op * op;
+      
+      op = carray_get(thread->op_done_list, j);
+      r = carray_add(op_to_notify, op, NULL);
+      if (r < 0) {
+        ETPAN_LOG("complete failure of thread due to lack of memory (callback)");
+        break;
+      }
+    }
+    carray_set_size(thread->op_done_list, 0);
+    
+    thread_unlock(thread);
+  }
+}
+
+void etpan_thread_manager_loop(struct etpan_thread_manager * manager)
+{
+  carray * op_to_notify;
+  unsigned int i;
+  
+  manager_ack(manager);
+  
+  op_to_notify = carray_new(OP_INIT_SIZE);
+  
+  loop_thread_list(op_to_notify, manager->thread_pool);
+  loop_thread_list(op_to_notify, manager->thread_pending);
+  
+  for(i = 0 ; i < carray_count(op_to_notify) ; i ++) {
+    struct etpan_thread_op * op;
+    int cancelled;
+    
+    op = carray_get(op_to_notify, i);
+    
+    cancelled = etpan_thread_op_cancelled(op);
+    
+    etpan_thread_op_lock(op);
+    
+    if (!op->callback_called) {
+      if (op->callback != NULL)
+        op->callback(op->cancelled, op->result, op->callback_data);
+    }
+    
+    etpan_thread_op_unlock(op);
+    
+    if (op->cleanup != NULL)
+      op->cleanup(op);
+  }
+  
+  carray_free(op_to_notify);
+  
+  i = 0;
+  while (i < carray_count(manager->thread_pending)) {
+    struct etpan_thread * thread;
+    
+    thread = carray_get(manager->thread_pending, i);
+    
+    if (etpan_thread_is_stopped(thread)) {
+      etpan_thread_join(thread);
+      
+      etpan_thread_free(thread);
+      
+      carray_delete_slow(manager->thread_pending, i);
+    }
+    else {
+      i ++;
+    }
+  }
+}
+
+void etpan_thread_manager_start(struct etpan_thread_manager * manager)
+{
+  /* do nothing */
+}
+
+void etpan_thread_manager_stop(struct etpan_thread_manager * manager)
+{
+  while (carray_count(manager->thread_pool) > 0) {
+    struct etpan_thread * thread;
+    
+    thread = carray_get(manager->thread_pool, 0);
+    etpan_thread_manager_terminate_thread(manager, thread);
+  }
+}
+
+int etpan_thread_manager_is_stopped(struct etpan_thread_manager * manager)
+{
+  return ((carray_count(manager->thread_pending) == 0) && 
+      (carray_count(manager->thread_pool) == 0));
+}
+
+void etpan_thread_manager_join(struct etpan_thread_manager * manager)
+{
+  while (!etpan_thread_manager_is_stopped(manager)) {
+    etpan_thread_manager_loop(manager);
+  }
+}
diff --git a/src/etpan/etpan-thread-manager.h b/src/etpan/etpan-thread-manager.h
new file mode 100644 (file)
index 0000000..9b89b8f
--- /dev/null
@@ -0,0 +1,58 @@
+#ifndef ETPAN_THREAD_MANAGER_H
+
+#define ETPAN_THREAD_MANAGER_H
+
+#include "etpan-thread-manager-types.h"
+
+/* ** object creation ** */
+
+struct etpan_thread_manager * etpan_thread_manager_new(void);
+void etpan_thread_manager_free(struct etpan_thread_manager * manager);
+
+struct etpan_thread * etpan_thread_new(void);
+void etpan_thread_free(struct etpan_thread * thread);
+
+struct etpan_thread_op * etpan_thread_op_new(void);
+void etpan_thread_op_free(struct etpan_thread_op * op);
+
+/* ** thread creation ** */
+
+int etpan_thread_start(struct etpan_thread * thread);
+
+void etpan_thread_stop(struct etpan_thread * thread);
+int etpan_thread_is_stopped(struct etpan_thread * thread);
+void etpan_thread_join(struct etpan_thread * thread);
+
+struct etpan_thread *
+etpan_thread_manager_get_thread(struct etpan_thread_manager * manager);
+
+unsigned int etpan_thread_get_load(struct etpan_thread * thread);
+void etpan_thread_bind(struct etpan_thread * thread);
+void etpan_thread_unbind(struct etpan_thread * thread);
+int etpan_thread_is_bound(struct etpan_thread * thread);
+
+/* ** op schedule ** */
+
+int etpan_thread_op_schedule(struct etpan_thread * thread,
+                             struct etpan_thread_op * op);
+
+int etpan_thread_op_cancelled(struct etpan_thread_op * op);
+void etpan_thread_op_cancel(struct etpan_thread_op * op);
+void etpan_thread_op_lock(struct etpan_thread_op * op);
+void etpan_thread_op_unlock(struct etpan_thread_op * op);
+
+int etpan_thread_manager_op_schedule(struct etpan_thread_manager * manager,
+    struct etpan_thread_op * op);
+
+/* ** manager main loop ** */
+
+void etpan_thread_manager_start(struct etpan_thread_manager * manager);
+
+void etpan_thread_manager_stop(struct etpan_thread_manager * manager);
+int etpan_thread_manager_is_stopped(struct etpan_thread_manager * manager);
+void etpan_thread_manager_join(struct etpan_thread_manager * manager);
+
+int etpan_thread_manager_get_fd(struct etpan_thread_manager * manager);
+void etpan_thread_manager_loop(struct etpan_thread_manager * manager);
+
+#endif
diff --git a/src/etpan/imap-thread.c b/src/etpan/imap-thread.c
new file mode 100644 (file)
index 0000000..4d76e07
--- /dev/null
@@ -0,0 +1,2160 @@
+#include "imap-thread.h"
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <sys/mman.h>
+#include <sys/wait.h>
+
+#include <gtk/gtk.h>
+#include "etpan-thread-manager.h"
+
+static struct etpan_thread_manager * thread_manager = NULL;
+static chash * imap_hash = NULL;
+static chash * session_hash = NULL;
+static guint thread_manager_signal = 0;
+static GIOChannel * io_channel = NULL;
+
+
+static gboolean thread_manager_event(GIOChannel * source,
+    GIOCondition condition,
+    gpointer data)
+{
+       etpan_thread_manager_loop(thread_manager);
+       
+       return TRUE;
+}
+
+
+#define ETPAN_DEFAULT_NETWORK_TIMEOUT 60
+
+void imap_main_init(void)
+{
+       int fd_thread_manager;
+       
+       mailstream_network_delay.tv_sec = ETPAN_DEFAULT_NETWORK_TIMEOUT;
+       mailstream_network_delay.tv_usec = 0;
+
+#if 0  
+       mailstream_debug = 1;
+#endif
+       imap_hash = chash_new(CHASH_COPYKEY, CHASH_DEFAULTSIZE);
+       session_hash = chash_new(CHASH_COPYKEY, CHASH_DEFAULTSIZE);
+       
+       thread_manager = etpan_thread_manager_new();
+       
+       fd_thread_manager = etpan_thread_manager_get_fd(thread_manager);
+       
+       io_channel = g_io_channel_unix_new(fd_thread_manager);
+       
+       thread_manager_signal = g_io_add_watch_full(io_channel, 0, G_IO_IN,
+                                                   thread_manager_event,
+                                                   (gpointer) NULL,
+                                                   NULL);
+}
+
+void imap_main_set_timeout(int sec)
+{
+       mailstream_network_delay.tv_sec = sec;
+       mailstream_network_delay.tv_usec = 0;
+}
+
+void imap_main_done(void)
+{
+       g_source_remove(thread_manager_signal);
+       g_io_channel_unref(io_channel);
+       
+       etpan_thread_manager_stop(thread_manager);
+       etpan_thread_manager_join(thread_manager);
+       etpan_thread_manager_free(thread_manager);
+       
+       chash_free(session_hash);
+       chash_free(imap_hash);
+}
+
+void imap_init(Folder * folder)
+{
+       struct etpan_thread * thread;
+       chashdatum key;
+       chashdatum value;
+       
+       thread = etpan_thread_manager_get_thread(thread_manager);
+       
+       key.data = &folder;
+       key.len = sizeof(folder);
+       value.data = thread;
+       value.len = 0;
+       
+       chash_set(imap_hash, &key, &value, NULL);
+}
+
+void imap_done(Folder * folder)
+{
+       struct etpan_thread * thread;
+       chashdatum key;
+       chashdatum value;
+       int r;
+       
+       key.data = &folder;
+       key.len = sizeof(folder);
+       
+       r = chash_get(imap_hash, &key, &value);
+       if (r < 0)
+               return;
+       
+       thread = value.data;
+       
+       etpan_thread_stop(thread);
+       
+       chash_delete(imap_hash, &key, NULL);
+}
+
+static struct etpan_thread * get_thread(Folder * folder)
+{
+       struct etpan_thread * thread;
+       chashdatum key;
+       chashdatum value;
+       
+       key.data = &folder;
+       key.len = sizeof(folder);
+       
+       chash_get(imap_hash, &key, &value);
+       thread = value.data;
+       
+       return thread;
+}
+
+static mailimap * get_imap(Folder * folder)
+{
+       mailimap * imap;
+       chashdatum key;
+       chashdatum value;
+       int r;
+       
+       key.data = &folder;
+       key.len = sizeof(folder);
+       
+       r = chash_get(session_hash, &key, &value);
+       if (r < 0)
+               return NULL;
+       
+       imap = value.data;
+       
+       return imap;
+}
+
+
+static void generic_cb(int cancelled, void * result, void * callback_data)
+{
+       int * p_finished;
+       
+       p_finished = callback_data;
+       
+       * p_finished = 1;
+}
+
+static void threaded_run(Folder * folder, void * param, void * result,
+                        void (* func)(struct etpan_thread_op * ))
+{
+       struct etpan_thread_op * op;
+       struct etpan_thread * thread;
+       int finished;
+       
+       op = etpan_thread_op_new();
+       op->param = param;
+       op->result = result;
+       
+       op->cancellable = 0;
+       op->run = func;
+       op->callback = generic_cb;
+       op->callback_data = &finished;
+       op->cleanup = NULL;
+       
+       finished = 0;
+       
+       thread = get_thread(folder);
+       etpan_thread_op_schedule(thread, op);
+       
+       while (!finished) {
+               gtk_main_iteration();
+       }
+       
+       etpan_thread_op_free(op);
+}
+
+
+/* connect */
+
+struct connect_param {
+       mailimap * imap;
+       const char * server;
+       int port;
+};
+
+struct connect_result {
+       int error;
+};
+
+static void connect_run(struct etpan_thread_op * op)
+{
+       int r;
+       struct connect_param * param;
+       struct connect_result * result;
+       
+       param = op->param;
+       result = op->result;
+       
+       r = mailimap_socket_connect(param->imap,
+                                   param->server, param->port);
+       
+       result->error = r;
+}
+
+
+int imap_threaded_connect(Folder * folder, const char * server, int port)
+{
+       struct connect_param param;
+       struct connect_result result;
+       chashdatum key;
+       chashdatum value;
+       mailimap * imap;
+       
+       imap = mailimap_new(0, NULL);
+       
+       key.data = &folder;
+       key.len = sizeof(folder);
+       value.data = imap;
+       value.len = 0;
+       chash_set(session_hash, &key, &value, NULL);
+       
+       param.imap = imap;
+       param.server = server;
+       param.port = port;
+       
+       threaded_run(folder, &param, &result, connect_run);
+       
+       debug_print("connect ok %i\n", result.error);
+       
+       return result.error;
+}
+
+
+static void connect_ssl_run(struct etpan_thread_op * op)
+{
+       int r;
+       struct connect_param * param;
+       struct connect_result * result;
+       
+       param = op->param;
+       result = op->result;
+       
+       r = mailimap_ssl_connect(param->imap,
+                                param->server, param->port);
+       
+       result->error = r;
+}
+
+int imap_threaded_connect_ssl(Folder * folder, const char * server, int port)
+{
+       struct connect_param param;
+       struct connect_result result;
+       chashdatum key;
+       chashdatum value;
+       mailimap * imap;
+       
+       imap = mailimap_new(0, NULL);
+       
+       key.data = &folder;
+       key.len = sizeof(folder);
+       value.data = imap;
+       value.len = 0;
+       chash_set(session_hash, &key, &value, NULL);
+       
+       param.imap = imap;
+       param.server = server;
+       param.port = port;
+       
+       threaded_run(folder, &param, &result, connect_ssl_run);
+       
+       debug_print("connect ok\n");
+       
+       return result.error;
+}
+       
+struct disconnect_param {
+       mailimap * imap;
+};
+
+struct disconnect_result {
+       int error;
+};
+
+static void disconnect_run(struct etpan_thread_op * op)
+{
+       int r;
+       struct disconnect_param * param;
+       struct disconnect_result * result;
+       
+       param = op->param;
+       result = op->result;
+       
+       r = mailimap_logout(param->imap);
+       
+       result->error = r;
+}
+
+void imap_threaded_disconnect(Folder * folder)
+{
+       struct connect_param param;
+       struct connect_result result;
+       chashdatum key;
+       chashdatum value;
+       mailimap * imap;
+       
+       imap = get_imap(folder);
+       if (imap == NULL) {
+               debug_print("was disconnected\n");
+               return;
+       }
+       
+       param.imap = imap;
+       
+       threaded_run(folder, &param, &result, disconnect_run);
+       
+       key.data = &folder;
+       key.len = sizeof(folder);
+       value.data = imap;
+       value.len = 0;
+       chash_delete(session_hash, &key, NULL);
+       
+       mailimap_free(imap);
+       
+       debug_print("disconnect ok\n");
+}
+
+
+struct list_param {
+       mailimap * imap;
+       const char * base;
+       const char * wildcard;
+};
+
+struct list_result {
+       int error;
+       clist * list;
+};
+
+static void list_run(struct etpan_thread_op * op)
+{
+       struct list_param * param;
+       struct list_result * result;
+       int r;
+       clist * list;
+       
+       param = op->param;
+       list = NULL;
+       r = mailimap_list(param->imap, param->base,
+                         param->wildcard, &list);
+       
+       result = op->result;
+       result->error = r;
+       result->list = list;
+       debug_print("imap list run - end\n");
+}
+
+int imap_threaded_list(Folder * folder, const char * base,
+                      const char * wildcard,
+                      clist ** p_result)
+{
+       struct list_param param;
+       struct list_result result;
+       
+       debug_print("imap list - begin\n");
+       
+       param.imap = get_imap(folder);
+       param.base = base;
+       param.wildcard = wildcard;
+       
+       threaded_run(folder, &param, &result, list_run);
+       
+       * p_result = result.list;
+       
+       debug_print("imap list - end %p\n", result.list);
+       
+       return result.error;
+}
+
+
+
+struct login_param {
+       mailimap * imap;
+       const char * login;
+       const char * password;
+};
+
+struct login_result {
+       int error;
+};
+
+static void login_run(struct etpan_thread_op * op)
+{
+       struct login_param * param;
+       struct login_result * result;
+       int r;
+       
+       param = op->param;
+       r = mailimap_login(param->imap,
+                          param->login, param->password);
+       
+       result = op->result;
+       result->error = r;
+       debug_print("imap login run - end %i\n", r);
+}
+
+int imap_threaded_login(Folder * folder,
+                       const char * login, const char * password)
+{
+       struct login_param param;
+       struct login_result result;
+       
+       debug_print("imap login - begin\n");
+       
+       param.imap = get_imap(folder);
+       param.login = login;
+       param.password = password;
+       
+       threaded_run(folder, &param, &result, login_run);
+       
+       debug_print("imap login - end\n");
+       
+       return result.error;
+}
+
+
+struct status_param {
+       mailimap * imap;
+       const char * mb;
+       struct mailimap_status_att_list * status_att_list;
+};
+
+struct status_result {
+       int error;
+       struct mailimap_mailbox_data_status * data_status;
+};
+
+static void status_run(struct etpan_thread_op * op)
+{
+       struct status_param * param;
+       struct status_result * result;
+       int r;
+       
+       param = op->param;
+       result = op->result;
+       
+       r = mailimap_status(param->imap, param->mb,
+                           param->status_att_list,
+                           &result->data_status);
+       
+       result->error = r;
+       debug_print("imap status run - end %i\n", r);
+}
+
+int imap_threaded_status(Folder * folder, const char * mb,
+                        struct mailimap_mailbox_data_status ** data_status)
+{
+       struct status_param param;
+       struct status_result result;
+       struct mailimap_status_att_list * status_att_list;
+       
+       debug_print("imap status - begin\n");
+       
+       status_att_list = mailimap_status_att_list_new_empty();
+       mailimap_status_att_list_add(status_att_list,
+                                    MAILIMAP_STATUS_ATT_MESSAGES);
+       mailimap_status_att_list_add(status_att_list,
+                                    MAILIMAP_STATUS_ATT_RECENT);
+       mailimap_status_att_list_add(status_att_list,
+                                    MAILIMAP_STATUS_ATT_UIDNEXT);
+       mailimap_status_att_list_add(status_att_list,
+                                    MAILIMAP_STATUS_ATT_UIDVALIDITY);
+       mailimap_status_att_list_add(status_att_list,
+                                    MAILIMAP_STATUS_ATT_UNSEEN);
+       
+       param.imap = get_imap(folder);
+       param.mb = mb;
+       param.status_att_list = status_att_list;
+       
+       threaded_run(folder, &param, &result, status_run);
+       
+       debug_print("imap status - end\n");
+       
+       * data_status = result.data_status;
+       
+       return result.error;
+}
+
+
+
+struct noop_param {
+       mailimap * imap;
+};
+
+struct noop_result {
+       int error;
+};
+
+static void noop_run(struct etpan_thread_op * op)
+{
+       struct noop_param * param;
+       struct noop_result * result;
+       int r;
+       
+       param = op->param;
+       r = mailimap_noop(param->imap);
+       
+       result = op->result;
+       result->error = r;
+       debug_print("imap noop run - end %i\n", r);
+}
+
+int imap_threaded_noop(Folder * folder)
+{
+       struct noop_param param;
+       struct noop_result result;
+       
+       debug_print("imap noop - begin\n");
+       
+       param.imap = get_imap(folder);
+       
+       threaded_run(folder, &param, &result, noop_run);
+       
+       debug_print("imap noop - end\n");
+       
+       return result.error;
+}
+
+
+struct starttls_param {
+       mailimap * imap;
+};
+
+struct starttls_result {
+       int error;
+};
+
+static void starttls_run(struct etpan_thread_op * op)
+{
+       struct starttls_param * param;
+       struct starttls_result * result;
+       int r;
+       
+       param = op->param;
+       r = mailimap_starttls(param->imap);
+       
+       result = op->result;
+       result->error = r;
+       debug_print("imap starttls run - end %i\n", r);
+}
+
+int imap_threaded_starttls(Folder * folder)
+{
+       struct starttls_param param;
+       struct starttls_result result;
+       
+       debug_print("imap starttls - begin\n");
+       
+       param.imap = get_imap(folder);
+       
+       threaded_run(folder, &param, &result, starttls_run);
+       
+       debug_print("imap starttls - end\n");
+       
+       return result.error;
+}
+
+
+
+struct create_param {
+       mailimap * imap;
+       const char * mb;
+};
+
+struct create_result {
+       int error;
+};
+
+static void create_run(struct etpan_thread_op * op)
+{
+       struct create_param * param;
+       struct create_result * result;
+       int r;
+       
+       param = op->param;
+       r = mailimap_create(param->imap, param->mb);
+       
+       result = op->result;
+       result->error = r;
+       debug_print("imap create run - end %i\n", r);
+}
+
+int imap_threaded_create(Folder * folder, const char * mb)
+{
+       struct create_param param;
+       struct create_result result;
+       
+       debug_print("imap create - begin\n");
+       
+       param.imap = get_imap(folder);
+       param.mb = mb;
+       
+       threaded_run(folder, &param, &result, create_run);
+       
+       debug_print("imap create - end\n");
+       
+       return result.error;
+}
+
+
+
+
+struct rename_param {
+       mailimap * imap;
+       const char * mb;
+       const char * new_name;
+};
+
+struct rename_result {
+       int error;
+};
+
+static void rename_run(struct etpan_thread_op * op)
+{
+       struct rename_param * param;
+       struct rename_result * result;
+       int r;
+       
+       param = op->param;
+       r = mailimap_rename(param->imap, param->mb, param->new_name);
+       
+       result = op->result;
+       result->error = r;
+       debug_print("imap rename run - end %i\n", r);
+}
+
+int imap_threaded_rename(Folder * folder,
+                        const char * mb, const char * new_name)
+{
+       struct rename_param param;
+       struct rename_result result;
+       
+       debug_print("imap rename - begin\n");
+       
+       param.imap = get_imap(folder);
+       param.mb = mb;
+       param.new_name = new_name;
+       
+       threaded_run(folder, &param, &result, rename_run);
+       
+       debug_print("imap rename - end\n");
+       
+       return result.error;
+}
+
+
+
+
+struct delete_param {
+       mailimap * imap;
+       const char * mb;
+};
+
+struct delete_result {
+       int error;
+};
+
+static void delete_run(struct etpan_thread_op * op)
+{
+       struct delete_param * param;
+       struct delete_result * result;
+       int r;
+       
+       param = op->param;
+       r = mailimap_delete(param->imap, param->mb);
+       
+       result = op->result;
+       result->error = r;
+       debug_print("imap delete run - end %i\n", r);
+}
+
+int imap_threaded_delete(Folder * folder, const char * mb)
+{
+       struct delete_param param;
+       struct delete_result result;
+       
+       debug_print("imap delete - begin\n");
+       
+       param.imap = get_imap(folder);
+       param.mb = mb;
+       
+       threaded_run(folder, &param, &result, delete_run);
+       
+       debug_print("imap delete - end\n");
+       
+       return result.error;
+}
+
+
+
+struct select_param {
+       mailimap * imap;
+       const char * mb;
+};
+
+struct select_result {
+       int error;
+};
+
+static void select_run(struct etpan_thread_op * op)
+{
+       struct select_param * param;
+       struct select_result * result;
+       int r;
+       
+       param = op->param;
+       r = mailimap_select(param->imap, param->mb);
+       
+       result = op->result;
+       result->error = r;
+       debug_print("imap select run - end %i\n", r);
+}
+
+int imap_threaded_select(Folder * folder, const char * mb,
+                        gint * exists, gint * recent, gint * unseen,
+                        guint32 * uid_validity)
+{
+       struct select_param param;
+       struct select_result result;
+       mailimap * imap;
+       
+       debug_print("imap select - begin\n");
+       
+       imap = get_imap(folder);
+       param.imap = imap;
+       param.mb = mb;
+       
+       threaded_run(folder, &param, &result, select_run);
+       
+       if (result.error != MAILIMAP_NO_ERROR)
+               return result.error;
+       
+       if (imap->imap_selection_info == NULL)
+               return MAILIMAP_ERROR_PARSE;
+       
+       * exists = imap->imap_selection_info->sel_exists;
+       * recent = imap->imap_selection_info->sel_recent;
+       * unseen = imap->imap_selection_info->sel_unseen;
+       * uid_validity = imap->imap_selection_info->sel_uidvalidity;
+       
+       debug_print("imap select - end\n");
+       
+       return result.error;
+}
+
+
+
+struct examine_param {
+       mailimap * imap;
+       const char * mb;
+};
+
+struct examine_result {
+       int error;
+};
+
+static void examine_run(struct etpan_thread_op * op)
+{
+       struct examine_param * param;
+       struct examine_result * result;
+       int r;
+       
+       param = op->param;
+       r = mailimap_examine(param->imap, param->mb);
+       
+       result = op->result;
+       result->error = r;
+       debug_print("imap examine run - end %i\n", r);
+}
+
+int imap_threaded_examine(Folder * folder, const char * mb,
+                         gint * exists, gint * recent, gint * unseen,
+                         guint32 * uid_validity)
+{
+       struct examine_param param;
+       struct examine_result result;
+       mailimap * imap;
+       
+       debug_print("imap examine - begin\n");
+       
+       imap = get_imap(folder);
+       param.imap = imap;
+       param.mb = mb;
+       
+       threaded_run(folder, &param, &result, examine_run);
+       
+       if (result.error != MAILIMAP_NO_ERROR)
+               return result.error;
+       
+       if (imap->imap_selection_info == NULL)
+               return MAILIMAP_ERROR_PARSE;
+       
+       * exists = imap->imap_selection_info->sel_exists;
+       * recent = imap->imap_selection_info->sel_recent;
+       * unseen = imap->imap_selection_info->sel_unseen;
+       * uid_validity = imap->imap_selection_info->sel_uidvalidity;
+       
+       debug_print("imap examine - end\n");
+       
+       return result.error;
+}
+
+
+
+
+struct search_param {
+       mailimap * imap;
+       int type;
+       struct mailimap_set * set;
+};
+
+struct search_result {
+       int error;
+       clist * search_result;
+};
+
+static void search_run(struct etpan_thread_op * op)
+{
+       struct search_param * param;
+       struct search_result * result;
+       int r;
+       struct mailimap_search_key * key;
+       struct mailimap_search_key * uid_key;
+       struct mailimap_search_key * search_type_key;
+       clist * search_result;
+       
+       param = op->param;
+       
+       uid_key = mailimap_search_key_new_uid(param->set);
+       
+       search_type_key = NULL;
+       switch (param->type) {
+       case IMAP_SEARCH_TYPE_SIMPLE:
+               search_type_key = NULL;
+               break;
+               
+       case IMAP_SEARCH_TYPE_SEEN:
+               search_type_key = mailimap_search_key_new(MAILIMAP_SEARCH_KEY_SEEN,
+                                                         NULL, NULL, NULL, NULL, NULL,
+                                                         NULL, NULL, NULL, NULL, NULL,
+                                                         NULL, NULL, NULL, NULL, 0,
+                                                         NULL, NULL, NULL, NULL, NULL,
+                                                         NULL, 0, NULL, NULL, NULL);
+               break;
+               
+       case IMAP_SEARCH_TYPE_UNSEEN:
+               search_type_key = mailimap_search_key_new(MAILIMAP_SEARCH_KEY_UNSEEN,
+                                                         NULL, NULL, NULL, NULL, NULL,
+                                                         NULL, NULL, NULL, NULL, NULL,
+                                                         NULL, NULL, NULL, NULL, 0,
+                                                         NULL, NULL, NULL, NULL, NULL,
+                                                         NULL, 0, NULL, NULL, NULL);
+               break;
+               
+       case IMAP_SEARCH_TYPE_ANSWERED:
+               search_type_key = mailimap_search_key_new(MAILIMAP_SEARCH_KEY_ANSWERED,
+                                                         NULL, NULL, NULL, NULL, NULL,
+                                                         NULL, NULL, NULL, NULL, NULL,
+                                                         NULL, NULL, NULL, NULL, 0,
+                                                         NULL, NULL, NULL, NULL, NULL,
+                                                         NULL, 0, NULL, NULL, NULL);
+               break;
+               
+       case IMAP_SEARCH_TYPE_FLAGGED:
+               search_type_key = mailimap_search_key_new(MAILIMAP_SEARCH_KEY_FLAGGED,
+                                                         NULL, NULL, NULL, NULL, NULL,
+                                                         NULL, NULL, NULL, NULL, NULL,
+                                                         NULL, NULL, NULL, NULL, 0,
+                                                         NULL, NULL, NULL, NULL, NULL,
+                                                         NULL, 0, NULL, NULL, NULL);
+               break;
+       }
+       
+       if (search_type_key != NULL) {
+               key = mailimap_search_key_new_multiple_empty();
+               mailimap_search_key_multiple_add(key, search_type_key);
+               mailimap_search_key_multiple_add(key, uid_key);
+       }
+       else {
+               key = uid_key;
+       }
+       
+       r = mailimap_uid_search(param->imap, NULL, key, &search_result);
+       
+       result = op->result;
+       result->error = r;
+       result->search_result = search_result;
+       debug_print("imap search run - end %i\n", r);
+}
+
+int imap_threaded_search(Folder * folder, int search_type,
+                        struct mailimap_set * set, clist ** search_result)
+{
+       struct search_param param;
+       struct search_result result;
+       mailimap * imap;
+       
+       debug_print("imap search - begin\n");
+       
+       imap = get_imap(folder);
+       param.imap = imap;
+       param.set = set;
+       param.type = search_type;
+       
+       threaded_run(folder, &param, &result, search_run);
+       
+       if (result.error != MAILIMAP_NO_ERROR)
+               return result.error;
+       
+       debug_print("imap search - end\n");
+       
+       * search_result = result.search_result;
+       
+       return result.error;
+}
+
+
+
+
+static int
+uid_list_to_env_list(clist * fetch_result, carray ** result)
+{
+       clistiter * cur;
+       int r;
+       int res;
+       carray * tab;
+       unsigned int i;
+       
+       tab = carray_new(128);
+       if (tab == NULL) {
+               res = MAILIMAP_ERROR_MEMORY;
+               goto err;
+       }
+       
+       for(cur = clist_begin(fetch_result) ; cur != NULL ;
+           cur = clist_next(cur)) {
+               struct mailimap_msg_att * msg_att;
+               clistiter * item_cur;
+               uint32_t uid;
+               size_t size;
+               uint32_t * puid;
+               
+               msg_att = clist_content(cur);
+               
+               uid = 0;
+               size = 0;
+               for(item_cur = clist_begin(msg_att->att_list) ;
+                   item_cur != NULL ;
+                   item_cur = clist_next(item_cur)) {
+                       struct mailimap_msg_att_item * item;
+                       
+                       item = clist_content(item_cur);
+                       
+                       switch (item->att_type) {
+                       case MAILIMAP_MSG_ATT_ITEM_STATIC:
+                               switch (item->att_data.att_static->att_type) {
+                               case MAILIMAP_MSG_ATT_UID:
+                                       uid = item->att_data.att_static->att_data.att_uid;
+                                       break;
+                               }
+                       }
+               }
+               
+               puid = malloc(sizeof(* puid));
+               if (puid == NULL) {
+                       res = MAILIMAP_ERROR_MEMORY;
+                       goto free_list;
+               }
+               * puid = uid;
+                       
+               r = carray_add(tab, puid, NULL);
+               if (r < 0) {
+                       free(puid);
+                       res = MAILIMAP_ERROR_MEMORY;
+                       goto free_list;
+               }
+       }
+               
+       * result = tab;
+
+       return MAILIMAP_NO_ERROR;
+  
+ free_list:
+       for(i = 0 ; i < carray_count(tab) ; i++)
+               mailmessage_free(carray_get(tab, i));
+ err:
+       return res;
+}
+
+static int imap_get_messages_list(mailimap * imap,
+                                 uint32_t first_index,
+                                 carray ** result)
+{
+       carray * env_list;
+       int r;
+       struct mailimap_fetch_att * fetch_att;
+       struct mailimap_fetch_type * fetch_type;
+       struct mailimap_set * set;
+       clist * fetch_result;
+       int res;
+       
+       set = mailimap_set_new_interval(first_index, 0);
+       if (set == NULL) {
+               res = MAILIMAP_ERROR_MEMORY;
+               goto err;
+       }
+
+       fetch_type = mailimap_fetch_type_new_fetch_att_list_empty();
+       if (fetch_type == NULL) {
+               res = MAILIMAP_ERROR_MEMORY;
+               goto free_set;
+       }
+
+       fetch_att = mailimap_fetch_att_new_uid();
+       if (fetch_att == NULL) {
+               res = MAILIMAP_ERROR_MEMORY;
+               goto free_fetch_type;
+       }
+
+       r = mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att);
+       if (r != MAILIMAP_NO_ERROR) {
+               mailimap_fetch_att_free(fetch_att);
+               res = MAILIMAP_ERROR_MEMORY;
+               goto free_fetch_type;
+       }
+
+       r = mailimap_uid_fetch(imap, set,
+                              fetch_type, &fetch_result);
+
+       mailimap_fetch_type_free(fetch_type);
+       mailimap_set_free(set);
+
+       if (r != MAILIMAP_NO_ERROR) {
+               res = r;
+               goto err;
+       }
+
+       env_list = NULL;
+       r = uid_list_to_env_list(fetch_result, &env_list);
+       mailimap_fetch_list_free(fetch_result);
+       
+       * result = env_list;
+
+       return MAILIMAP_NO_ERROR;
+
+ free_fetch_type:
+       mailimap_fetch_type_free(fetch_type);
+ free_set:
+       mailimap_set_free(set);
+ err:
+       return res;
+}
+
+
+
+
+struct fetch_uid_param {
+       mailimap * imap;
+       uint32_t first_index;
+};
+
+struct fetch_uid_result {
+       int error;
+       carray * fetch_result;
+};
+
+static void fetch_uid_run(struct etpan_thread_op * op)
+{
+       struct fetch_uid_param * param;
+       struct fetch_uid_result * result;
+       carray * fetch_result;
+       int r;
+       
+       param = op->param;
+       
+       r = imap_get_messages_list(param->imap, param->first_index,
+                                  &fetch_result);
+       
+       result = op->result;
+       result->error = r;
+       result->fetch_result = fetch_result;
+       debug_print("imap fetch_uid run - end %i\n", r);
+}
+
+int imap_threaded_fetch_uid(Folder * folder, uint32_t first_index,
+                           carray ** fetch_result)
+{
+       struct fetch_uid_param param;
+       struct fetch_uid_result result;
+       mailimap * imap;
+       
+       debug_print("imap fetch_uid - begin\n");
+       
+       imap = get_imap(folder);
+       param.imap = imap;
+       param.first_index = first_index;
+       
+       threaded_run(folder, &param, &result, fetch_uid_run);
+       
+       if (result.error != MAILIMAP_NO_ERROR)
+               return result.error;
+       
+       debug_print("imap fetch_uid - end\n");
+       
+       * fetch_result = result.fetch_result;
+       
+       return result.error;
+}
+
+
+void imap_fetch_uid_list_free(carray * uid_list)
+{
+       unsigned int i;
+       
+       for(i = 0 ; i < carray_count(uid_list) ; i ++) {
+               uint32_t * puid;
+               
+               puid = carray_get(uid_list, i);
+               free(puid);
+       }
+       carray_free(uid_list);
+}
+
+
+
+static int imap_fetch(mailimap * imap,
+                     uint32_t msg_index,
+                     char ** result,
+                     size_t * result_len)
+{
+       int r;
+       struct mailimap_set * set;
+       struct mailimap_fetch_att * fetch_att;
+       struct mailimap_fetch_type * fetch_type;
+       clist * fetch_result;
+       struct mailimap_msg_att * msg_att;
+       struct mailimap_msg_att_item * msg_att_item;
+       char * text;
+       size_t text_length;
+       int res;
+       clistiter * cur;
+       struct mailimap_section * section;
+
+       set = mailimap_set_new_single(msg_index);
+       if (set == NULL) {
+               res = MAILIMAP_ERROR_MEMORY;
+               goto err;
+       }
+
+       section = mailimap_section_new(NULL);
+       if (section == NULL) {
+               res = MAILIMAP_ERROR_MEMORY;
+               goto free_set;
+       }
+  
+       fetch_att = mailimap_fetch_att_new_body_peek_section(section);
+       if (fetch_att == NULL) {
+               mailimap_section_free(section);
+               res = MAILIMAP_ERROR_MEMORY;
+               goto free_set;
+       }
+  
+       fetch_type = mailimap_fetch_type_new_fetch_att(fetch_att);
+       if (fetch_type == NULL) {
+               res = MAILIMAP_ERROR_MEMORY;
+               goto free_fetch_att;
+       }
+
+       r = mailimap_uid_fetch(imap, set,
+                              fetch_type, &fetch_result);
+  
+       mailimap_fetch_type_free(fetch_type);
+       mailimap_set_free(set);
+  
+       switch (r) {
+       case MAILIMAP_NO_ERROR:
+               break;
+       default:
+               return r;
+       }
+  
+       if (clist_begin(fetch_result) == NULL) {
+               mailimap_fetch_list_free(fetch_result);
+               return MAILIMAP_ERROR_FETCH;
+       }
+
+       msg_att = clist_begin(fetch_result)->data;
+
+       text = NULL;
+       text_length = 0;
+
+       for(cur = clist_begin(msg_att->att_list) ; cur != NULL ;
+           cur = clist_next(cur)) {
+               msg_att_item = clist_content(cur);
+
+               if (msg_att_item->att_type == MAILIMAP_MSG_ATT_ITEM_STATIC) {
+                       if (msg_att_item->att_data.att_static->att_type ==
+                           MAILIMAP_MSG_ATT_BODY_SECTION) {
+                               text = msg_att_item->att_data.att_static->att_data.att_body_section->sec_body_part;
+                               /* detach */
+                               msg_att_item->att_data.att_static->att_data.att_body_section->sec_body_part = NULL;
+                               text_length =
+                                       msg_att_item->att_data.att_static->att_data.att_body_section->sec_length;
+                       }
+               }
+       }
+
+       mailimap_fetch_list_free(fetch_result);
+
+       if (text == NULL)
+               return MAILIMAP_ERROR_FETCH;
+
+       * result = text;
+       * result_len = text_length;
+  
+       return MAILIMAP_NO_ERROR;
+
+ free_fetch_att:
+       mailimap_fetch_att_free(fetch_att);
+ free_set:
+       mailimap_set_free(set);
+ err:
+       return res;
+}
+
+static int imap_fetch_header(mailimap * imap,
+                            uint32_t msg_index,
+                            char ** result,
+                            size_t * result_len)
+{
+  int r;
+  struct mailimap_set * set;
+  struct mailimap_fetch_att * fetch_att;
+  struct mailimap_fetch_type * fetch_type;
+  clist * fetch_result;
+  struct mailimap_msg_att * msg_att;
+  struct mailimap_msg_att_item * msg_att_item;
+  char * text;
+  size_t text_length;
+  int res;
+  clistiter * cur;
+  struct mailimap_section * section;
+  
+  set = mailimap_set_new_single(msg_index);
+  if (set == NULL) {
+    res = MAILIMAP_ERROR_MEMORY;
+    goto err;
+  }
+
+  section = mailimap_section_new_header();
+  if (section == NULL) {
+    res = MAILIMAP_ERROR_MEMORY;
+    goto free_set;
+  }
+  
+  fetch_att = mailimap_fetch_att_new_body_peek_section(section);
+  if (fetch_att == NULL) {
+    mailimap_section_free(section);
+    res = MAILIMAP_ERROR_MEMORY;
+    goto free_set;
+  }
+  
+  fetch_type = mailimap_fetch_type_new_fetch_att(fetch_att);
+  if (fetch_type == NULL) {
+    res = MAILIMAP_ERROR_MEMORY;
+    goto free_fetch_att;
+  }
+
+  r = mailimap_uid_fetch(imap, set, fetch_type, &fetch_result);
+  
+  mailimap_fetch_type_free(fetch_type);
+  mailimap_set_free(set);
+
+  switch (r) {
+  case MAILIMAP_NO_ERROR:
+    break;
+  default:
+    return r;
+  }
+
+  if (clist_begin(fetch_result) == NULL) {
+    mailimap_fetch_list_free(fetch_result);
+    return MAILIMAP_ERROR_FETCH;
+  }
+
+  msg_att = clist_begin(fetch_result)->data;
+
+  text = NULL;
+  text_length = 0;
+
+  for(cur = clist_begin(msg_att->att_list) ; cur != NULL ;
+      cur = clist_next(cur)) {
+    msg_att_item = clist_content(cur);
+
+    if (msg_att_item->att_type == MAILIMAP_MSG_ATT_ITEM_STATIC) {
+      if (msg_att_item->att_data.att_static->att_type ==
+         MAILIMAP_MSG_ATT_BODY_SECTION) {
+       text = msg_att_item->att_data.att_static->att_data.att_body_section->sec_body_part;
+       msg_att_item->att_data.att_static->att_data.att_body_section->sec_body_part = NULL;
+       text_length =
+         msg_att_item->att_data.att_static->att_data.att_body_section->sec_length;
+      }
+    }
+  }
+
+  mailimap_fetch_list_free(fetch_result);
+
+  if (text == NULL)
+    return MAILIMAP_ERROR_FETCH;
+
+  * result = text;
+  * result_len = text_length;
+
+  return MAILIMAP_NO_ERROR;
+
+ free_fetch_att:
+  mailimap_fetch_att_free(fetch_att);
+ free_set:
+  mailimap_set_free(set);
+ err:
+  return res;
+}
+
+
+
+struct fetch_content_param {
+       mailimap * imap;
+       uint32_t msg_index;
+       const char * filename;
+       int with_body;
+};
+
+struct fetch_content_result {
+       int error;
+};
+
+static void fetch_content_run(struct etpan_thread_op * op)
+{
+       struct fetch_content_param * param;
+       struct fetch_content_result * result;
+       char * content;
+       size_t content_size;
+       int r;
+       int fd;
+       FILE * f;
+       
+       param = op->param;
+       
+       if (param->with_body)
+               r = imap_fetch(param->imap, param->msg_index,
+                              &content, &content_size);
+       else
+               r = imap_fetch_header(param->imap, param->msg_index,
+                                     &content, &content_size);
+       
+       result = op->result;
+       result->error = r;
+       
+       if (r == MAILIMAP_NO_ERROR) {
+               fd = open(param->filename, O_RDWR | O_CREAT, 0600);
+               if (fd < 0) {
+                       result->error = MAILIMAP_ERROR_FETCH;
+                       goto free;
+               }
+               
+               f = fdopen(fd, "wb");
+               if (f == NULL) {
+                       result->error = MAILIMAP_ERROR_FETCH;
+                       goto close;
+               }
+               
+               r = fwrite(content, 1, content_size, f);
+               if (r == 0) {
+                       goto fclose;
+               }
+               
+               r = fclose(f);
+               if (r == EOF) {
+                       unlink(param->filename);
+                       goto close;
+               }
+               goto free;
+               
+       fclose:
+               fclose(f);
+               goto unlink;
+       close:
+               close(fd);
+       unlink:
+               unlink(param->filename);
+       
+       free:
+               if (mmap_string_unref(content) != 0)
+                       free(content);
+       }
+       
+       debug_print("imap fetch_content run - end %i\n", r);
+}
+
+int imap_threaded_fetch_content(Folder * folder, uint32_t msg_index,
+                               int with_body,
+                               const char * filename)
+{
+       struct fetch_content_param param;
+       struct fetch_content_result result;
+       mailimap * imap;
+       
+       debug_print("imap fetch_content - begin\n");
+       
+       imap = get_imap(folder);
+       param.imap = imap;
+       param.msg_index = msg_index;
+       param.filename = filename;
+       param.with_body = with_body;
+       
+       threaded_run(folder, &param, &result, fetch_content_run);
+       
+       if (result.error != MAILIMAP_NO_ERROR)
+               return result.error;
+       
+       debug_print("imap fetch_content - end\n");
+       
+       return result.error;
+}
+
+
+
+static int imap_flags_to_flags(struct mailimap_msg_att_dynamic * att_dyn)
+{
+       int flags;
+       clist * flag_list;
+       clistiter * cur;
+       
+       flags = MSG_UNREAD;
+       
+       flag_list = att_dyn->att_list;
+       if (flag_list == NULL)
+               return flags;
+       
+       for(cur = clist_begin(flag_list) ; cur != NULL ;
+           cur = clist_next(cur)) {
+               struct mailimap_flag_fetch * flag_fetch;
+                       
+               flag_fetch = clist_content(cur);
+               if (flag_fetch->fl_type == MAILIMAP_FLAG_FETCH_RECENT)
+                       flags |= MSG_NEW;
+               else {
+                       switch (flag_fetch->fl_flag->fl_type) {
+                       case MAILIMAP_FLAG_ANSWERED:
+                               flags |= MSG_REPLIED;
+                               break;
+                       case MAILIMAP_FLAG_FLAGGED:
+                               flags |= MSG_MARKED;
+                               break;
+                       case MAILIMAP_FLAG_DELETED:
+                               flags |= MSG_DELETED;
+                               break;
+                       case MAILIMAP_FLAG_SEEN:
+                               flags &= ~MSG_UNREAD;
+                               flags &= ~MSG_NEW;
+                               break;
+                       }
+               }
+       }
+       
+       return flags;
+}
+
+static int imap_get_msg_att_info(struct mailimap_msg_att * msg_att,
+                                uint32_t * puid,
+                                char ** pheaders,
+                                size_t * pref_size,
+                                struct mailimap_msg_att_dynamic ** patt_dyn)
+{
+  clistiter * item_cur;
+  uint32_t uid;
+  char * headers;
+  size_t ref_size;
+  struct mailimap_msg_att_dynamic * att_dyn;
+
+  uid = 0;
+  headers = NULL;
+  ref_size = 0;
+  att_dyn = NULL;
+
+  for(item_cur = clist_begin(msg_att->att_list) ; item_cur != NULL ;
+      item_cur = clist_next(item_cur)) {
+    struct mailimap_msg_att_item * item;
+
+    item = clist_content(item_cur);
+      
+    switch (item->att_type) {
+    case MAILIMAP_MSG_ATT_ITEM_STATIC:
+      switch (item->att_data.att_static->att_type) {
+      case MAILIMAP_MSG_ATT_UID:
+       uid = item->att_data.att_static->att_data.att_uid;
+       break;
+
+      case MAILIMAP_MSG_ATT_BODY_SECTION:
+       if (headers == NULL) {
+         headers = item->att_data.att_static->att_data.att_body_section->sec_body_part;
+       }
+       break;
+      case MAILIMAP_MSG_ATT_RFC822_SIZE:
+             ref_size = item->att_data.att_static->att_data.att_rfc822_size;
+             break;
+      }
+      break;
+      
+    case MAILIMAP_MSG_ATT_ITEM_DYNAMIC:
+      if (att_dyn == NULL) {
+       att_dyn = item->att_data.att_dyn;
+      }
+      break;
+    }
+  }
+
+  if (puid != NULL)
+    * puid = uid;
+  if (pheaders != NULL)
+    * pheaders = headers;
+  if (pref_size != NULL)
+    * pref_size = ref_size;
+  if (patt_dyn != NULL)
+    * patt_dyn = att_dyn;
+
+  return MAIL_NO_ERROR;
+}
+
+static struct imap_fetch_env_info *
+fetch_to_env_info(struct mailimap_msg_att * msg_att)
+{
+       struct imap_fetch_env_info * info;
+       uint32_t uid;
+       char * headers;
+       size_t size;
+       struct mailimap_msg_att_dynamic * att_dyn;
+       
+       imap_get_msg_att_info(msg_att, &uid, &headers, &size,
+                             &att_dyn);
+       
+       info = malloc(sizeof(* info));
+       info->uid = uid;
+       info->headers = strdup(headers);
+       info->size = size;
+       info->flags = imap_flags_to_flags(att_dyn);
+       
+       return info;
+}
+
+static int
+imap_fetch_result_to_envelop_list(clist * fetch_result,
+                                 carray ** p_env_list)
+{
+       clistiter * cur;
+       unsigned int i;
+       carray * env_list;
+  
+       i = 0;
+  
+       env_list = carray_new(16);
+  
+       for(cur = clist_begin(fetch_result) ; cur != NULL ;
+           cur = clist_next(cur)) {
+               struct mailimap_msg_att * msg_att;
+               struct imap_fetch_env_info * env_info;
+    
+               msg_att = clist_content(cur);
+
+               env_info = fetch_to_env_info(msg_att);
+               carray_add(env_list, env_info, NULL);
+       }
+  
+       * p_env_list = env_list;
+  
+       return MAIL_NO_ERROR;
+}
+
+int imap_add_envelope_fetch_att(struct mailimap_fetch_type * fetch_type)
+{
+       struct mailimap_fetch_att * fetch_att;
+       int r;
+       char * header;
+       clist * hdrlist;
+       struct mailimap_header_list * imap_hdrlist;
+       struct mailimap_section * section;
+
+       hdrlist = clist_new();
+  
+       header = strdup("Date");
+       r = clist_append(hdrlist, header);
+       header = strdup("From");
+       r = clist_append(hdrlist, header);
+       header = strdup("To");
+       r = clist_append(hdrlist, header);
+       header = strdup("Cc");
+       r = clist_append(hdrlist, header);
+       header = strdup("Subject");
+       r = clist_append(hdrlist, header);
+       header = strdup("Message-ID");
+       r = clist_append(hdrlist, header);
+       header = strdup("References");
+       r = clist_append(hdrlist, header);
+       header = strdup("In-Reply-To");
+       r = clist_append(hdrlist, header);
+  
+       imap_hdrlist = mailimap_header_list_new(hdrlist);
+       section = mailimap_section_new_header_fields(imap_hdrlist);
+       fetch_att = mailimap_fetch_att_new_body_peek_section(section);
+       mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att);
+  
+       return MAIL_NO_ERROR;
+}
+
+static int
+imap_get_envelopes_list(mailimap * imap, struct mailimap_set * set,
+                       carray ** p_env_list)
+{
+       struct mailimap_fetch_att * fetch_att;
+       struct mailimap_fetch_type * fetch_type;
+       int res;
+       clist * fetch_result;
+       int r;
+       carray * env_list;
+       
+       fetch_type = mailimap_fetch_type_new_fetch_att_list_empty();
+  
+       /* uid */
+       fetch_att = mailimap_fetch_att_new_uid();
+       r = mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att);
+  
+       /* flags */
+       fetch_att = mailimap_fetch_att_new_flags();
+       r = mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att);
+  
+       /* rfc822 size */
+       fetch_att = mailimap_fetch_att_new_rfc822_size();
+       r = mailimap_fetch_type_new_fetch_att_list_add(fetch_type, fetch_att);
+  
+       /* headers */
+       r = imap_add_envelope_fetch_att(fetch_type);
+       
+       r = mailimap_uid_fetch(imap, set, fetch_type, &fetch_result);
+       
+       switch (r) {
+       case MAILIMAP_NO_ERROR:
+               break;
+       default:
+               mailimap_fetch_type_free(fetch_type);
+               return r;
+       }
+       
+       if (clist_begin(fetch_result) == NULL) {
+               res = MAILIMAP_ERROR_FETCH;
+               goto err;
+       }
+       
+       r = imap_fetch_result_to_envelop_list(fetch_result, &env_list);
+       mailimap_fetch_list_free(fetch_result);
+       
+       if (r != MAILIMAP_NO_ERROR) {
+               mailimap_fetch_type_free(fetch_type);
+               res = MAILIMAP_ERROR_MEMORY;
+               goto err;
+       }
+       
+       mailimap_fetch_type_free(fetch_type);
+       
+       * p_env_list = env_list;
+       
+       return MAILIMAP_NO_ERROR;
+  
+ err:
+       return res;
+}
+
+struct fetch_env_param {
+       mailimap * imap;
+       struct mailimap_set * set;
+};
+
+struct fetch_env_result {
+       carray * fetch_env_result;
+       int error;
+};
+
+static void fetch_env_run(struct etpan_thread_op * op)
+{
+       struct fetch_env_param * param;
+       struct fetch_env_result * result;
+       carray * env_list;
+       int r;
+       
+       param = op->param;
+       
+       r = imap_get_envelopes_list(param->imap, param->set,
+                                   &env_list);
+       
+       result = op->result;
+       result->error = r;
+       result->fetch_env_result = env_list;
+       
+       debug_print("imap fetch_env run - end %i\n", r);
+}
+
+int imap_threaded_fetch_env(Folder * folder, struct mailimap_set * set,
+                           carray ** p_env_list)
+{
+       struct fetch_env_param param;
+       struct fetch_env_result result;
+       mailimap * imap;
+       
+       debug_print("imap fetch_env - begin\n");
+       
+       imap = get_imap(folder);
+       param.imap = imap;
+       param.set = set;
+       
+       threaded_run(folder, &param, &result, fetch_env_run);
+       
+       if (result.error != MAILIMAP_NO_ERROR)
+               return result.error;
+       
+       debug_print("imap fetch_env - end\n");
+       
+       * p_env_list = result.fetch_env_result;
+       
+       return result.error;
+}
+
+void imap_fetch_env_free(carray * env_list)
+{
+       unsigned int i;
+       
+       for(i = 0 ; i < carray_count(env_list) ; i ++) {
+               struct imap_fetch_env_info * env_info;
+               
+               env_info = carray_get(env_list, i);
+               free(env_info->headers);
+               free(env_info);
+       }
+       carray_free(env_list);
+}
+
+
+
+
+
+struct append_param {
+       mailimap * imap;
+       const char * mailbox;
+       const char * filename;
+       struct mailimap_flag_list * flag_list;
+};
+
+struct append_result {
+       int error;
+};
+
+static void append_run(struct etpan_thread_op * op)
+{
+       struct append_param * param;
+       struct append_result * result;
+       int r;
+       char * data;
+       size_t size;
+       struct stat stat_buf;
+       int fd;
+       
+       param = op->param;
+       result = op->result;
+       
+       r = stat(param->filename, &stat_buf);
+       if (r < 0) {
+               result->error = MAILIMAP_ERROR_APPEND;
+               return;
+       }
+       size = stat_buf.st_size;
+       
+       fd = open(param->filename, O_RDONLY);
+       if (fd < 0) {
+               result->error = MAILIMAP_ERROR_APPEND;
+               return;
+       }
+       
+       data = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
+       if (data == (void *) MAP_FAILED) {
+               close(fd);
+               result->error = MAILIMAP_ERROR_APPEND;
+               return;
+       }
+       
+       r = mailimap_append(param->imap, param->mailbox,
+                           param->flag_list, NULL,
+                           data, size);
+       
+       munmap(data, size);
+       close(fd);
+       
+       result->error = r;
+       
+       debug_print("imap append run - end %i\n", r);
+}
+
+int imap_threaded_append(Folder * folder, const char * mailbox,
+                        const char * filename,
+                        struct mailimap_flag_list * flag_list)
+{
+       struct append_param param;
+       struct append_result result;
+       mailimap * imap;
+       
+       debug_print("imap append - begin\n");
+       
+       imap = get_imap(folder);
+       param.imap = imap;
+       param.mailbox = mailbox;
+       param.filename = filename;
+       param.flag_list = flag_list;
+       
+       threaded_run(folder, &param, &result, append_run);
+       
+       if (result.error != MAILIMAP_NO_ERROR)
+               return result.error;
+       
+       debug_print("imap append - end\n");
+       
+       return result.error;
+}
+
+
+
+
+struct expunge_param {
+       mailimap * imap;
+};
+
+struct expunge_result {
+       int error;
+};
+
+static void expunge_run(struct etpan_thread_op * op)
+{
+       struct expunge_param * param;
+       struct expunge_result * result;
+       int r;
+       
+       param = op->param;
+       r = mailimap_expunge(param->imap);
+       
+       result = op->result;
+       result->error = r;
+       debug_print("imap expunge run - end %i\n", r);
+}
+
+int imap_threaded_expunge(Folder * folder)
+{
+       struct expunge_param param;
+       struct expunge_result result;
+       
+       debug_print("imap expunge - begin\n");
+       
+       param.imap = get_imap(folder);
+       
+       threaded_run(folder, &param, &result, expunge_run);
+       
+       debug_print("imap expunge - end\n");
+       
+       return result.error;
+}
+
+
+struct copy_param {
+       mailimap * imap;
+       struct mailimap_set * set;
+       const char * mb;
+};
+
+struct copy_result {
+       int error;
+};
+
+static void copy_run(struct etpan_thread_op * op)
+{
+       struct copy_param * param;
+       struct copy_result * result;
+       int r;
+       
+       param = op->param;
+       
+       r = mailimap_uid_copy(param->imap, param->set, param->mb);
+       
+       result = op->result;
+       result->error = r;
+       
+       debug_print("imap copy run - end %i\n", r);
+}
+
+int imap_threaded_copy(Folder * folder, struct mailimap_set * set,
+                      const char * mb)
+{
+       struct copy_param param;
+       struct copy_result result;
+       mailimap * imap;
+       
+       debug_print("imap copy - begin\n");
+       
+       imap = get_imap(folder);
+       param.imap = imap;
+       param.set = set;
+       param.mb = mb;
+       
+       threaded_run(folder, &param, &result, copy_run);
+       
+       if (result.error != MAILIMAP_NO_ERROR)
+               return result.error;
+       
+       debug_print("imap copy - end\n");
+       
+       return result.error;
+}
+
+
+
+struct store_param {
+       mailimap * imap;
+       struct mailimap_set * set;
+       struct mailimap_store_att_flags * store_att_flags;
+};
+
+struct store_result {
+       int error;
+};
+
+static void store_run(struct etpan_thread_op * op)
+{
+       struct store_param * param;
+       struct store_result * result;
+       int r;
+       
+       param = op->param;
+       
+       r = mailimap_uid_store(param->imap, param->set,
+                              param->store_att_flags);
+       
+       result = op->result;
+       result->error = r;
+       
+       debug_print("imap store run - end %i\n", r);
+}
+
+int imap_threaded_store(Folder * folder, struct mailimap_set * set,
+                       struct mailimap_store_att_flags * store_att_flags)
+{
+       struct store_param param;
+       struct store_result result;
+       mailimap * imap;
+       
+       debug_print("imap store - begin\n");
+       
+       imap = get_imap(folder);
+       param.imap = imap;
+       param.set = set;
+       param.store_att_flags = store_att_flags;
+       
+       threaded_run(folder, &param, &result, store_run);
+       
+       if (result.error != MAILIMAP_NO_ERROR)
+               return result.error;
+       
+       debug_print("imap store - end\n");
+       
+       return result.error;
+}
+
+
+
+static void do_exec_command(int fd, const char * command,
+                           const char * servername, uint16_t port)
+{
+       int i, maxopen;
+  
+       if (fork() > 0) {
+               /* Fork again to become a child of init rather than
+                  the etpan client. */
+               exit(0);
+       }
+  
+       if (servername)
+               setenv("ETPANSERVER", servername, 1);
+       else
+               unsetenv("ETPANSERVER");
+  
+       if (port) {
+               char porttext[20];
+    
+               snprintf(porttext, sizeof(porttext), "%d", port);
+               setenv("ETPANPORT", porttext, 1);
+       }
+       else {
+               unsetenv("ETPANPORT");
+       }
+  
+       /* Not a lot we can do if there's an error other than bail. */
+       if (dup2(fd, 0) == -1)
+               exit(1);
+       if (dup2(fd, 1) == -1)
+               exit(1);
+  
+       /* Should we close stderr and reopen /dev/null? */
+  
+       maxopen = sysconf(_SC_OPEN_MAX);
+       for (i=3; i < maxopen; i++)
+               close(i);
+  
+#ifdef TIOCNOTTY
+       /* Detach from the controlling tty if we have one. Otherwise,
+          SSH might do something stupid like trying to use it instead
+          of running $SSH_ASKPASS. Doh. */
+       fd = open("/dev/tty", O_RDONLY);
+       if (fd != -1) {
+               ioctl(fd, TIOCNOTTY, NULL);
+               close(fd);
+       }
+#endif /* TIOCNOTTY */
+
+       execl("/bin/sh", "/bin/sh", "-c", command, NULL);
+  
+       /* Eep. Shouldn't reach this */
+       exit(1);
+}
+
+static int subcommand_connect(const char *command,
+                             const char *servername, uint16_t port)
+{
+       /* SEB unsupported on Windows */
+       int sockfds[2];
+       pid_t childpid;
+  
+       if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockfds))
+               return -1;
+  
+       childpid = fork();
+       if (!childpid) {
+               do_exec_command(sockfds[1], command, servername, port);
+       }
+       else if (childpid == -1) {
+               close(sockfds[0]);
+               close(sockfds[1]);
+               return -1;
+       }
+  
+       close(sockfds[1]);
+  
+       /* Reap child, leaving grandchild process to run */
+       waitpid(childpid, NULL, 0);
+  
+       return sockfds[0];
+}
+
+int socket_connect_cmd(mailimap * imap, const char * command,
+                      const char * server, int port)
+{
+       int fd;
+       mailstream * s;
+       int r;
+       
+       fd = subcommand_connect(command, server, port);
+       if (fd < 0)
+               return MAILIMAP_ERROR_STREAM;
+       
+       s = mailstream_socket_open(fd);
+       if (s == NULL) {
+               close(fd);
+               return MAILIMAP_ERROR_STREAM;
+       }
+       
+       r = mailimap_connect(imap, s);
+       if (r != MAILIMAP_NO_ERROR) {
+               mailstream_close(s);
+               return r;
+       }
+       
+       return MAILIMAP_NO_ERROR;
+}
+
+/* connect cmd */
+
+struct connect_cmd_param {
+       mailimap * imap;
+       const char * command;
+       const char * server;
+       int port;
+};
+
+struct connect_cmd_result {
+       int error;
+};
+
+static void connect_cmd_run(struct etpan_thread_op * op)
+{
+       int r;
+       struct connect_cmd_param * param;
+       struct connect_cmd_result * result;
+       
+       param = op->param;
+       result = op->result;
+       
+       r = socket_connect_cmd(param->imap, param->command,
+                              param->server, param->port);
+       
+       result->error = r;
+}
+
+
+int imap_threaded_connect_cmd(Folder * folder, const char * command,
+                             const char * server, int port)
+{
+       struct connect_cmd_param param;
+       struct connect_cmd_result result;
+       chashdatum key;
+       chashdatum value;
+       mailimap * imap;
+       
+       imap = mailimap_new(0, NULL);
+       
+       key.data = &folder;
+       key.len = sizeof(folder);
+       value.data = imap;
+       value.len = 0;
+       chash_set(session_hash, &key, &value, NULL);
+       
+       param.imap = imap;
+       param.command = command;
+       param.server = server;
+       param.port = port;
+       
+       threaded_run(folder, &param, &result, connect_cmd_run);
+       
+       debug_print("connect_cmd ok %i\n", result.error);
+       
+       return result.error;
+}
diff --git a/src/etpan/imap-thread.h b/src/etpan/imap-thread.h
new file mode 100644 (file)
index 0000000..591f13c
--- /dev/null
@@ -0,0 +1,89 @@
+#ifndef IMAP_THREAD_H
+
+#define IMAP_THREAD_H
+
+#include <libetpan/libetpan.h>
+#include "folder.h"
+
+#define IMAP_SET_MAX_COUNT 100
+
+void imap_main_set_timeout(int sec);
+void imap_main_init(void);
+void imap_main_done(void);
+
+void imap_init(Folder * folder);
+void imap_done(Folder * folder);
+
+int imap_threaded_connect(Folder * folder, const char * server, int port);
+int imap_threaded_connect_ssl(Folder * folder, const char * server, int port);
+int imap_threaded_connect_cmd(Folder * folder, const char * command,
+                             const char * server, int port);
+
+void imap_threaded_disconnect(Folder * folder);
+
+int imap_threaded_list(Folder * folder, const char * base,
+                      const char * wildcard,
+                      clist ** p_result);
+int imap_threaded_login(Folder * folder,
+                       const char * login, const char * password);
+int imap_threaded_status(Folder * folder, const char * mb,
+               struct mailimap_mailbox_data_status ** data_status);
+
+int imap_threaded_noop(Folder * folder);
+int imap_threaded_starttls(Folder * folder);
+int imap_threaded_create(Folder * folder, const char * mb);
+int imap_threaded_rename(Folder * folder,
+                        const char * mb, const char * new_name);
+int imap_threaded_delete(Folder * folder, const char * mb);
+int imap_threaded_select(Folder * folder, const char * mb,
+                        gint * exists, gint * recent, gint * unseen,
+                        guint32 * uid_validity);
+int imap_threaded_examine(Folder * folder, const char * mb,
+                         gint * exists, gint * recent, gint * unseen,
+                         guint32 * uid_validity);
+
+enum {
+       IMAP_SEARCH_TYPE_SIMPLE,
+       IMAP_SEARCH_TYPE_SEEN,
+       IMAP_SEARCH_TYPE_UNSEEN,
+       IMAP_SEARCH_TYPE_ANSWERED,
+       IMAP_SEARCH_TYPE_FLAGGED,
+};
+
+int imap_threaded_search(Folder * folder, int search_type,
+                        struct mailimap_set * set, clist ** result);
+
+int imap_threaded_fetch_uid(Folder * folder, uint32_t first_index,
+                           carray ** result);
+
+void imap_fetch_uid_list_free(carray * uid_list);
+
+int imap_threaded_fetch_content(Folder * folder, uint32_t msg_index,
+                               int with_body,
+                               const char * filename);
+
+struct imap_fetch_env_info {
+       uint32_t uid;
+       char * headers;
+       uint32_t size;
+       int flags;
+};
+
+int imap_threaded_fetch_env(Folder * folder, struct mailimap_set * set,
+                           carray ** p_env_list);
+
+void imap_fetch_env_free(carray * env_list);
+
+int imap_threaded_append(Folder * folder, const char * mailbox,
+                        const char * filename,
+                        struct mailimap_flag_list * flag_list);
+
+int imap_threaded_expunge(Folder * folder);
+
+int imap_threaded_copy(Folder * folder, struct mailimap_set * set,
+                      const char * mb);
+
+int imap_threaded_store(Folder * folder, struct mailimap_set * set,
+                       struct mailimap_store_att_flags * store_att_flags);
+
+#endif
index da901dc..f4a0f09 100644 (file)
 #if USE_OPENSSL
 #  include "ssl.h"
 #endif
+
 #include "folder.h"
 #include "session.h"
 #include "procmsg.h"
 #include "imap.h"
 #include "imap_gtk.h"
 #include "socket.h"
-#include "ssl.h"
 #include "recv.h"
 #include "procheader.h"
 #include "prefs_account.h"
@@ -62,6 +62,7 @@
 #include "sylpheed.h"
 #include "statusbar.h"
 #include "msgcache.h"
+#include "imap-thread.h"
 
 #ifdef USE_PTHREAD
 #include <pthread.h>
@@ -72,6 +73,7 @@ static const char *mutex_hold = NULL;
 #define __FUNCTION__ __FILE__
 #endif 
 
+#if 0
 #define MUTEX_TRYLOCK_OR_RETURN() {                                    \
        debug_print("%s: locking mutex\n", __FUNCTION__);               \
        if (pthread_mutex_trylock(&imap_mutex) == EBUSY) {              \
@@ -103,6 +105,11 @@ static const char *mutex_hold = NULL;
 #define MUTEX_TRYLOCK_OR_RETURN_VAL(retval) do {} while(0)
 #define MUTEX_UNLOCK() do {} while(0)
 #endif
+#endif
+
+#define MUTEX_TRYLOCK_OR_RETURN() do {} while(0)
+#define MUTEX_TRYLOCK_OR_RETURN_VAL(retval) do {} while(0)
+#define MUTEX_UNLOCK() do {} while(0)
 
 typedef struct _IMAPFolder     IMAPFolder;
 typedef struct _IMAPSession    IMAPSession;
@@ -140,6 +147,7 @@ struct _IMAPSession
        /* CLAWS */
        gboolean folder_content_changed;
        guint exists;
+       Folder * folder;
 };
 
 struct _IMAPNameSpace
@@ -181,23 +189,6 @@ typedef enum
 
 #define IMAP_CMD_LIMIT 1000
 
-#define QUOTE_IF_REQUIRED(out, str)                            \
-{                                                              \
-       if (*str != '"' && strpbrk(str, " \t(){}[]%*\\") != NULL) {     \
-               gchar *__tmp;                                   \
-               gint len;                                       \
-                                                               \
-               len = strlen(str) + 3;                          \
-               Xalloca(__tmp, len, return IMAP_ERROR);         \
-               g_snprintf(__tmp, len, "\"%s\"", str);          \
-               out = __tmp;                                    \
-       } else {                                                \
-               Xstrdup_a(out, str, return IMAP_ERROR);         \
-       }                                                       \
-}
-
-typedef gchar * IMAPSet;
-
 struct _IMAPFolderItem
 {
        FolderItem item;
@@ -216,7 +207,8 @@ static Folder       *imap_folder_new        (const gchar    *name,
                                         const gchar    *path);
 static void     imap_folder_destroy    (Folder         *folder);
 
-static IMAPSession *imap_session_new   (const PrefsAccount     *account);
+static IMAPSession *imap_session_new   (Folder         *folder,
+                                        const PrefsAccount     *account);
 static void    imap_session_authenticate(IMAPSession           *session,
                                          const PrefsAccount    *account);
 static void    imap_session_destroy    (Session        *session);
@@ -282,7 +274,6 @@ static void imap_folder_item_destroy        (Folder         *folder,
 
 static IMAPSession *imap_session_get   (Folder         *folder);
 
-static gint imap_greeting              (IMAPSession    *session);
 static gint imap_auth                  (IMAPSession    *session,
                                         const gchar    *user,
                                         const gchar    *pass,
@@ -290,10 +281,6 @@ static gint imap_auth                      (IMAPSession    *session,
 
 static gint imap_scan_tree_recursive   (IMAPSession    *session,
                                         FolderItem     *item);
-static GSList *imap_parse_list         (IMAPFolder     *folder,
-                                        IMAPSession    *session,
-                                        const gchar    *real_path,
-                                        gchar          *separator);
 
 static void imap_create_missing_folders        (Folder         *folder);
 static FolderItem *imap_create_special_folder
@@ -310,31 +297,6 @@ static void imap_delete_all_cached_messages        (FolderItem     *item);
 static void imap_set_batch             (Folder         *folder,
                                         FolderItem     *item,
                                         gboolean        batch);
-#if USE_OPENSSL
-static SockInfo *imap_open             (const gchar    *server,
-                                        gushort         port,
-                                        SSLType         ssl_type);
-#else
-static SockInfo *imap_open             (const gchar    *server,
-                                        gushort         port);
-#endif
-
-#if USE_OPENSSL
-static SockInfo *imap_open_tunnel(const gchar *server,
-                                 const gchar *tunnelcmd,
-                                 SSLType ssl_type);
-#else
-static SockInfo *imap_open_tunnel(const gchar *server,
-                                 const gchar *tunnelcmd);
-#endif
-
-#if USE_OPENSSL
-static SockInfo *imap_init_sock(SockInfo *sock, SSLType        ssl_type);
-#else
-static SockInfo *imap_init_sock(SockInfo *sock);
-#endif
-
-static gchar *imap_get_flag_str                (IMAPFlags       flags);
 static gint imap_set_message_flags     (IMAPSession    *session,
                                         MsgNumberList  *numlist,
                                         IMAPFlags       flags,
@@ -357,10 +319,6 @@ static gint imap_status                    (IMAPSession    *session,
                                         gint           *unseen,
                                         gboolean        block);
 
-static void imap_parse_namespace               (IMAPSession    *session,
-                                                IMAPFolder     *folder);
-static void imap_get_namespace_by_list         (IMAPSession    *session,
-                                                IMAPFolder     *folder);
 static IMAPNameSpace *imap_find_namespace      (IMAPFolder     *folder,
                                                 const gchar    *path);
 static gchar imap_get_path_separator           (IMAPFolder     *folder,
@@ -368,26 +326,9 @@ static gchar imap_get_path_separator               (IMAPFolder     *folder,
 static gchar *imap_get_real_path               (IMAPFolder     *folder,
                                                 const gchar    *path);
 
-static gchar *imap_parse_atom          (SockInfo       *sock,
-                                        gchar          *src,
-                                        gchar          *dest,
-                                        gint            dest_len,
-                                        GString        *str);
-static MsgFlags imap_parse_flags       (const gchar    *flag_str);
-static MsgInfo *imap_parse_envelope    (SockInfo       *sock,
-                                        FolderItem     *item,
-                                        GString        *line_str);
-
-static gboolean imap_has_capability    (IMAPSession    *session,
-                                        const gchar    *cap);
 static void imap_free_capabilities     (IMAPSession    *session);
 
 /* low-level IMAP4rev1 commands */
-static gint imap_cmd_authenticate
-                               (IMAPSession    *session,
-                                const gchar    *user,
-                                const gchar    *pass,
-                                IMAPAuthType    type);
 static gint imap_cmd_login     (IMAPSession    *session,
                                 const gchar    *user,
                                 const gchar    *pass);
@@ -396,20 +337,6 @@ static gint imap_cmd_noop  (IMAPSession    *session);
 #if USE_OPENSSL
 static gint imap_cmd_starttls  (IMAPSession    *session);
 #endif
-static gint imap_cmd_namespace (IMAPSession    *session,
-                                gchar         **ns_str);
-static gint imap_cmd_list      (IMAPSession    *session,
-                                const gchar    *ref,
-                                const gchar    *mailbox,
-                                GPtrArray      *argbuf);
-static gint imap_cmd_do_select (IMAPSession    *session,
-                                const gchar    *folder,
-                                gboolean        examine,
-                                gint           *exists,
-                                gint           *recent,
-                                gint           *unseen,
-                                guint32        *uid_validity,
-                                gboolean        block);
 static gint imap_cmd_select    (IMAPSession    *session,
                                 const gchar    *folder,
                                 gint           *exists,
@@ -431,8 +358,6 @@ static gint imap_cmd_rename (IMAPSession    *sock,
                                 const gchar    *newfolder);
 static gint imap_cmd_delete    (IMAPSession    *session,
                                 const gchar    *folder);
-static gint imap_cmd_envelope  (IMAPSession    *session,
-                                IMAPSet         set);
 static gint imap_cmd_fetch     (IMAPSession    *sock,
                                 guint32         uid,
                                 const gchar    *filename,
@@ -443,59 +368,22 @@ static gint imap_cmd_append       (IMAPSession    *session,
                                 const gchar    *file,
                                 IMAPFlags       flags,
                                 guint32        *new_uid);
-static gint imap_cmd_copy       (IMAPSession    *session, 
-                                 const gchar    *seq_set, 
-                                 const gchar    *destfolder,
-                                GRelation      *uid_mapping);
+static gint imap_cmd_copy       (IMAPSession *session,
+                                struct mailimap_set * set,
+                                const gchar *destfolder,
+                                GRelation *uid_mapping);
 static gint imap_cmd_store     (IMAPSession    *session,
-                                IMAPSet         set,
-                                gchar          *sub_cmd);
-static gint imap_cmd_expunge   (IMAPSession    *session,
-                                IMAPSet         seq_set);
-static gint imap_cmd_close      (IMAPSession    *session);
-
-static gint imap_cmd_ok                (IMAPSession    *session,
-                                GPtrArray      *argbuf);
-static gint imap_cmd_ok_block  (IMAPSession    *session,
-                                GPtrArray      *argbuf);
-static gint imap_cmd_ok_with_block
-                               (IMAPSession    *session, 
-                                GPtrArray      *argbuf, 
-                                gboolean       block);
-static void imap_gen_send      (IMAPSession    *session,
-                                const gchar    *format, ...);
-static gint imap_gen_recv      (IMAPSession    *session,
-                                gchar         **ret);
-static gint imap_gen_recv_block        (IMAPSession    *session,
-                                gchar         **ret);
-static gint imap_gen_recv_with_block   
-                               (IMAPSession    *session,
-                                gchar         **ret,
-                                gboolean        block);
+                                struct mailimap_set * set,
+                                IMAPFlags flags,
+                                int do_add);
+static gint imap_cmd_expunge   (IMAPSession    *session);
 
-/* misc utility functions */
-static gchar *strchr_cpy                       (const gchar    *src,
-                                                gchar           ch,
-                                                gchar          *dest,
-                                                gint            len);
-static gchar *get_quoted                       (const gchar    *src,
-                                                gchar           ch,
-                                                gchar          *dest,
-                                                gint            len);
-static gchar *search_array_contain_str         (GPtrArray      *array,
-                                                const gchar    *str);
-static gchar *search_array_str                 (GPtrArray      *array,
-                                                const gchar    *str);
 static void imap_path_separator_subst          (gchar          *str,
                                                 gchar           separator);
 
 static gchar *imap_utf8_to_modified_utf7       (const gchar    *from);
 static gchar *imap_modified_utf7_to_utf8       (const gchar    *mutf7_str);
 
-static GSList *imap_get_seq_set_from_numlist    (MsgNumberList  *msglist);
-static GSList *imap_get_seq_set_from_msglist   (MsgInfoList    *msglist);
-static void imap_seq_set_free                   (GSList         *seq_list);
-
 static gboolean imap_rename_folder_func                (GNode          *node,
                                                 gpointer        data);
 static gint imap_get_num_list                  (Folder         *folder,
@@ -522,6 +410,21 @@ static gchar *imap_folder_get_path         (Folder         *folder);
 static gchar *imap_item_get_path               (Folder         *folder,
                                                 FolderItem     *item);
 static MsgInfo *imap_parse_msg(const gchar *file, FolderItem *item);
+
+
+/* data types conversion libetpan <-> sylpheed */
+static GSList * imap_list_from_lep(IMAPFolder * folder,
+                                  clist * list, const gchar * real_path);
+static GSList * imap_get_lep_set_from_numlist(MsgNumberList *numlist);
+static GSList * imap_get_lep_set_from_msglist(MsgInfoList *msglist);
+static GSList * imap_uid_list_from_lep(clist * list);
+static GSList * imap_uid_list_from_lep_tab(carray * list);
+static MsgInfo *imap_envelope_from_lep(struct imap_fetch_env_info * info,
+                                      FolderItem *item);
+static void imap_lep_set_free(GSList *seq_list);
+static struct mailimap_flag_list * imap_flag_to_lep(IMAPFlags flags);
+
+
 static GHashTable *flags_set_table = NULL;
 static GHashTable *flags_unset_table = NULL;
 typedef struct _hashtable_data {
@@ -541,54 +444,6 @@ typedef struct _thread_data {
 #endif
 } thread_data;
 
-#ifdef USE_PTHREAD
-void *imap_getline_thread(void *data)
-{
-       thread_data *td = (thread_data *)data;
-       gchar *line = NULL;
-       
-       line = sock_getline(td->sock);
-       
-       td->done = TRUE;
-       
-       return (void *)line;
-}
-#endif
-
-/* imap_getline just wraps sock_getline inside a thread, 
- * performing gtk updates so that the interface isn't frozen.
- */
-static gchar *imap_getline(SockInfo *sock)
-{
-#if (defined USE_PTHREAD && defined __GLIBC__ && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)))
-       thread_data *td = g_new0(thread_data, 1);
-       pthread_t pt;
-       gchar *line;
-       td->sock = sock;
-       td->done = FALSE;
-       if (pthread_create(&pt, PTHREAD_CREATE_JOINABLE,
-                       imap_getline_thread, td) != 0) {
-               g_free(td);
-               return sock_getline(sock);
-       }
-       
-       debug_print("+++waiting for imap_getline_thread...\n");
-       while(!td->done) {
-               /* don't let the interface freeze while waiting */
-               sylpheed_do_idle();
-       }
-       debug_print("---imap_getline_thread done\n");
-
-       /* get the thread's return value and clean its resources */
-       pthread_join(pt, (void *)&line);
-       g_free(td);
-
-       return line;
-#else
-       return sock_getline(sock);
-#endif
-}
-
 FolderClass *imap_get_class(void)
 {
        if (imap_class.idstr == NULL) {
@@ -637,28 +492,6 @@ FolderClass *imap_get_class(void)
        return &imap_class;
 }
 
-static gchar *get_seq_set_from_seq_list(GSList *seq_list)
-{
-       gchar *val = NULL;
-       gchar *tmp = NULL;
-       GSList *cur = NULL;
-       
-       if (seq_list != NULL) {
-               cur = seq_list;
-               val = g_strdup((gchar *)(cur->data));
-               cur = cur->next;
-               while (cur != NULL) {
-                       tmp = val;
-                       val = g_strconcat(tmp, ",", (gchar *)(cur->data),
-                                         NULL);
-                       g_free(tmp);
-                       cur = cur->next;
-               }
-       }
-       return val;
-}
-
-
 static Folder *imap_folder_new(const gchar *name, const gchar *path)
 {
        Folder *folder;
@@ -674,6 +507,7 @@ static void imap_folder_destroy(Folder *folder)
 {
        gchar *dir;
 
+       imap_done(folder);
        dir = imap_folder_get_path(folder);
        if (is_dir_exist(dir))
                remove_dir_recursive(dir);
@@ -731,49 +565,13 @@ static void imap_reset_uid_lists(Folder *folder)
        g_node_traverse(folder->node, G_IN_ORDER, G_TRAVERSE_ALL, -1, imap_reset_uid_lists_func, NULL); 
 }
 
-/* Send CAPABILITY, and examine the server's response to see whether this
- * connection is pre-authenticated or not and build a list of CAPABILITIES. */
-static gint imap_greeting(IMAPSession *session)
-{
-       gchar *capstr;
-       GPtrArray *argbuf;
-
-       imap_gen_send(session, "CAPABILITY");
-       
-       argbuf = g_ptr_array_new();
-
-       if (imap_cmd_ok(session, argbuf) != IMAP_SUCCESS ||
-           ((capstr = search_array_str(argbuf, "CAPABILITY ")) == NULL)) {
-               ptr_array_free_strings(argbuf);
-               g_ptr_array_free(argbuf, TRUE);
-               return -1;
-       }
-
-       session->authenticated = search_array_str(argbuf, "PREAUTH") != NULL;
-       
-       capstr += strlen("CAPABILITY ");
-
-       IMAP_SESSION(session)->capability = g_strsplit(capstr, " ", 0);
-       
-       ptr_array_free_strings(argbuf);
-       g_ptr_array_free(argbuf, TRUE);
-
-       if (imap_has_capability(session, "UIDPLUS")) 
-               session->uidplus = TRUE; 
-
-       return 0;
-}
-
 static gint imap_auth(IMAPSession *session, const gchar *user, const gchar *pass,
                      IMAPAuthType type)
 {
        gint ok;
 
-       if (type == 0 || type == IMAP_AUTH_LOGIN)
-               ok = imap_cmd_login(session, user, pass);
-       else
-               ok = imap_cmd_authenticate(session, user, pass, type);
-
+       ok = imap_cmd_login(session, user, pass);
+       
        if (ok == IMAP_SUCCESS)
                session->authenticated = TRUE;
 
@@ -798,30 +596,26 @@ static IMAPSession *imap_session_get(Folder *folder)
                session = IMAP_SESSION(rfolder->session);
        } else {
                imap_reset_uid_lists(folder);
-               session = imap_session_new(folder->account);
+               session = imap_session_new(folder, folder->account);
        }
        if(session == NULL)
                return NULL;
 
-       if (SESSION(session)->sock->state == CONN_DISCONNECTED) {
-               debug_print("IMAP server disconnected\n");
-               session_destroy(SESSION(session));
-               imap_reset_uid_lists(folder);
-               session = imap_session_new(folder->account);
-       }
-
        /* Make sure session is authenticated */
        if (!IMAP_SESSION(session)->authenticated)
                imap_session_authenticate(IMAP_SESSION(session), folder->account);
+       
        if (!IMAP_SESSION(session)->authenticated) {
                session_destroy(SESSION(session));
                rfolder->session = NULL;
                return NULL;
        }
 
+#if 0
        /* Make sure we have parsed the IMAP namespace */
        imap_parse_namespace(IMAP_SESSION(session),
                             IMAP_FOLDER(folder));
+#endif
 
        /* I think the point of this code is to avoid sending a
         * keepalive if we've used the session recently and therefore
@@ -865,12 +659,14 @@ static IMAPSession *imap_session_get(Folder *folder)
        return IMAP_SESSION(session);
 }
 
-static IMAPSession *imap_session_new(const PrefsAccount *account)
+static IMAPSession *imap_session_new(Folder * folder,
+                                    const PrefsAccount *account)
 {
        IMAPSession *session;
-       SockInfo *imap_sock;
        gushort port;
-
+       int r;
+       int authenticated;
+       
 #ifdef USE_OPENSSL
        /* FIXME: IMAP over SSL only... */ 
        SSLType ssl_type;
@@ -883,55 +679,63 @@ static IMAPSession *imap_session_new(const PrefsAccount *account)
                : IMAP4_PORT;
 #endif
 
+       imap_init(folder);
+       statusbar_print_all(_("Connecting to IMAP4 server: %s..."), folder->account->recv_server);
        if (account->set_tunnelcmd) {
-               log_message(_("creating tunneled IMAP4 connection\n"));
-#if USE_OPENSSL
-               if ((imap_sock = imap_open_tunnel(account->recv_server, 
-                                                 account->tunnelcmd,
-                                                 ssl_type)) == NULL)
-#else
-               if ((imap_sock = imap_open_tunnel(account->recv_server, 
-                                                 account->tunnelcmd)) == NULL)
+               r = imap_threaded_connect_cmd(folder,
+                                             account->tunnelcmd,
+                                             account->recv_server,
+                                             port);
+       }
+       else {
+#ifdef USE_OPENSSL
+               if (ssl_type == SSL_TUNNEL) {
+                       r = imap_threaded_connect_ssl(folder,
+                                                     account->recv_server,
+                                                     port);
+               }
+               else 
 #endif
-                       return NULL;
-       } else {
-               g_return_val_if_fail(account->recv_server != NULL, NULL);
-
-               log_message(_("creating IMAP4 connection to %s:%d ...\n"),
-                           account->recv_server, port);
+               {
+                       r = imap_threaded_connect(folder,
+                                                 account->recv_server,
+                                                 port);
+               }
+       }
+       
+       statusbar_pop_all();
+       if (r == MAILIMAP_NO_ERROR_AUTHENTICATED) {
+               authenticated = TRUE;
+       }
+       else if (r == MAILIMAP_NO_ERROR_NON_AUTHENTICATED) {
+               authenticated = FALSE;
+       }
+       else {
+               if(!prefs_common.no_recv_err_panel) {
+                       alertpanel_error(_("Can't connect to IMAP4 server: %s:%d"),
+                                        account->recv_server, port);
+               }
                
-#if USE_OPENSSL
-               if ((imap_sock = imap_open(account->recv_server, port,
-                                          ssl_type)) == NULL)
-#else
-               if ((imap_sock = imap_open(account->recv_server, port)) == NULL)
-#endif
-                       return NULL;
+               return NULL;
        }
-
+       
        session = g_new0(IMAPSession, 1);
        session_init(SESSION(session));
        SESSION(session)->type             = SESSION_IMAP;
        SESSION(session)->server           = g_strdup(account->recv_server);
-       SESSION(session)->sock             = imap_sock;
-
+       SESSION(session)->sock             = NULL;
+       
        SESSION(session)->destroy          = imap_session_destroy;
 
        session->capability = NULL;
-
-       session->authenticated = FALSE;
+       
+       session->authenticated = authenticated;
        session->mbox = NULL;
        session->cmd_count = 0;
-
-       /* Only need to log in if the connection was not PREAUTH */
-       if (imap_greeting(session) != IMAP_SUCCESS) {
-               session_destroy(SESSION(session));
-               return NULL;
-       }
+       session->folder = folder;
 
 #if USE_OPENSSL
-       if (account->ssl_imap == SSL_STARTTLS && 
-           imap_has_capability(session, "STARTTLS")) {
+       if (account->ssl_imap == SSL_STARTTLS) {
                gint ok;
 
                ok = imap_cmd_starttls(session);
@@ -940,26 +744,16 @@ static IMAPSession *imap_session_new(const PrefsAccount *account)
                        session_destroy(SESSION(session));
                        return NULL;
                }
-               if (!ssl_init_socket_with_method(SESSION(session)->sock, 
-                   SSL_METHOD_TLSv1)) {
-                       session_destroy(SESSION(session));
-                       return NULL;
-               }
 
                imap_free_capabilities(session);
                session->authenticated = FALSE;
                session->uidplus = FALSE;
                session->cmd_count = 1;
-
-               if (imap_greeting(session) != IMAP_SUCCESS) {
-                       session_destroy(SESSION(session));
-                       return NULL;
-               }               
        }
 #endif
        log_message("IMAP connection is %s-authenticated\n",
                    (session->authenticated) ? "pre" : "un");
-
+       
        return session;
 }
 
@@ -982,6 +776,7 @@ static void imap_session_authenticate(IMAPSession *session,
        statusbar_print_all(_("Connecting to IMAP4 server %s...\n"),
                                account->recv_server);
        if (imap_auth(session, account->userid, pass, account->imap_auth_type) != IMAP_SUCCESS) {
+               imap_threaded_disconnect(session->folder);
                imap_cmd_logout(session);
                statusbar_pop_all();
                
@@ -993,6 +788,8 @@ static void imap_session_authenticate(IMAPSession *session,
 
 static void imap_session_destroy(Session *session)
 {
+       imap_threaded_disconnect(IMAP_SESSION(session)->folder);
+       
        imap_free_capabilities(IMAP_SESSION(session));
        g_free(IMAP_SESSION(session)->mbox);
        sock_close(session->sock);
@@ -1056,7 +853,7 @@ static gchar *imap_fetch_msg_full(Folder *folder, FolderItem *item, gint uid,
                debug_print("message %d has been already %scached (%d/%d).\n", uid,
                                have_size == cached->size ? "fully ":"",
                                have_size, cached? (int)cached->size : -1);
-                               
+               
                if (cached && (cached->size == have_size || !body)) {
                        procmsg_msginfo_free(cached);
                        procmsg_msginfo_free(msginfo);
@@ -1223,13 +1020,15 @@ static gint imap_do_copy_msgs(Folder *folder, FolderItem *dest,
        }
 
        destdir = imap_get_real_path(IMAP_FOLDER(folder), dest->path);
-       seq_list = imap_get_seq_set_from_msglist(msglist);
+       seq_list = imap_get_lep_set_from_msglist(msglist);
        uid_mapping = g_relation_new(2);
        g_relation_index(uid_mapping, 0, g_direct_hash, g_direct_equal);
        
        for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
-               gchar *seq_set = (gchar *)cur->data;
-
+               struct mailimap_set * seq_set;
+               
+               seq_set = cur->data;
+               
                debug_print("Copying message %s%c[%s] to %s ...\n",
                            src->path, G_DIR_SEPARATOR,
                            seq_set, destdir);
@@ -1237,7 +1036,7 @@ static gint imap_do_copy_msgs(Folder *folder, FolderItem *dest,
                ok = imap_cmd_copy(session, seq_set, destdir, uid_mapping);
                if (ok != IMAP_SUCCESS) {
                        g_relation_destroy(uid_mapping);
-                       imap_seq_set_free(seq_list);
+                       imap_lep_set_free(seq_list);
                        return -1;
                }
        }
@@ -1262,7 +1061,7 @@ static gint imap_do_copy_msgs(Folder *folder, FolderItem *dest,
        }
 
        g_relation_destroy(uid_mapping);
-       imap_seq_set_free(seq_list);
+       imap_lep_set_free(seq_list);
 
        g_free(destdir);
        
@@ -1368,7 +1167,7 @@ static gint imap_do_remove_msgs(Folder *folder, FolderItem *dest,
                MUTEX_UNLOCK();
                return ok;
        }
-       ok = imap_cmd_expunge(session, NULL);
+       ok = imap_cmd_expunge(session);
        if (ok != IMAP_SUCCESS) {
                log_warning(_("can't expunge\n"));
                MUTEX_UNLOCK();
@@ -1420,30 +1219,6 @@ static gboolean imap_is_msg_changed(Folder *folder, FolderItem *item,
 
 static gint imap_close(Folder *folder, FolderItem *item)
 {
-       gint ok;
-       IMAPSession *session;
-
-       g_return_val_if_fail(folder != NULL, -1);
-       g_return_val_if_fail(item != NULL, -1);
-       g_return_val_if_fail(item->path != NULL, -1);
-
-       session = imap_session_get(folder);
-       if (!session) return -1;
-
-       if (session->mbox) {
-               if (strcmp2(session->mbox, item->path) != 0) return -1;
-
-               ok = imap_cmd_close(session);
-               if (ok != IMAP_SUCCESS)
-                       log_warning(_("can't close folder\n"));
-
-               g_free(session->mbox);
-
-               session->mbox = NULL;
-
-               return ok;
-       }
-
        return 0;
 }
 
@@ -1472,8 +1247,8 @@ static gint imap_scan_tree(Folder *folder)
 
        if (folder->account->imap_dir && *folder->account->imap_dir) {
                gchar *real_path;
-               GPtrArray *argbuf;
-               gint ok;
+               int r;
+               clist * lep_list;
 
                Xstrdup_a(root_folder, folder->account->imap_dir, {MUTEX_UNLOCK();return -1;});
                extract_quote(root_folder, '"');
@@ -1487,14 +1262,10 @@ static gint imap_scan_tree(Folder *folder)
                debug_print("IMAP root directory: %s\n", real_path);
 
                /* check if root directory exist */
-               argbuf = g_ptr_array_new();
-               ok = imap_cmd_list(session, NULL, real_path, argbuf);
-               if (ok != IMAP_SUCCESS ||
-                   search_array_str(argbuf, "LIST ") == NULL) {
-                       log_warning(_("root folder %s does not exist\n"), real_path);
-                       g_ptr_array_free(argbuf, TRUE);
-                       g_free(real_path);
 
+               r = imap_threaded_list(session->folder, "", real_path,
+                                      &lep_list);
+               if ((r != MAILIMAP_NO_ERROR) || (clist_count(lep_list) == 0)) {
                        if (!folder->node) {
                                item = folder_item_new(folder, folder->name, NULL);
                                item->folder = folder;
@@ -1503,7 +1274,9 @@ static gint imap_scan_tree(Folder *folder)
                        MUTEX_UNLOCK();
                        return -1;
                }
-               g_ptr_array_free(argbuf, TRUE);
+               
+               mailimap_list_result_free(lep_list);
+               
                g_free(real_path);
        }
 
@@ -1535,7 +1308,9 @@ static gint imap_scan_tree_recursive(IMAPSession *session, FolderItem *item)
        gchar *wildcard_path;
        gchar separator;
        gchar wildcard[3];
-
+       clist * lep_list;
+       int r;
+       
        g_return_val_if_fail(item != NULL, -1);
        g_return_val_if_fail(item->folder != NULL, -1);
        g_return_val_if_fail(item->no_sub == FALSE, -1);
@@ -1561,13 +1336,17 @@ static gint imap_scan_tree_recursive(IMAPSession *session, FolderItem *item)
 
        Xstrcat_a(wildcard_path, real_path, wildcard,
                  {g_free(real_path); return IMAP_ERROR;});
-       QUOTE_IF_REQUIRED(wildcard_path, wildcard_path);
-
-       imap_gen_send(session, "LIST \"\" %s",
-                     wildcard_path);
-
-       strtailchomp(real_path, separator);
-       item_list = imap_parse_list(imapfolder, session, real_path, NULL);
+       lep_list = NULL;
+       r = imap_threaded_list(folder, "", wildcard_path, &lep_list);
+       if (r != MAILIMAP_NO_ERROR) {
+               item_list = NULL;
+       }
+       else {
+               item_list = imap_list_from_lep(imapfolder,
+                                              lep_list, real_path);
+               mailimap_list_result_free(lep_list);
+       }
+       
        g_free(real_path);
 
        node = item->node->children;
@@ -1653,97 +1432,6 @@ static gint imap_scan_tree_recursive(IMAPSession *session, FolderItem *item)
        return IMAP_SUCCESS;
 }
 
-static GSList *imap_parse_list(IMAPFolder *folder, IMAPSession *session,
-                              const gchar *real_path, gchar *separator)
-{
-       gchar buf[IMAPBUFSIZE];
-       gchar flags[256];
-       gchar separator_str[16];
-       gchar *p;
-       gchar *base;
-       gchar *loc_name, *loc_path;
-       GSList *item_list = NULL;
-       GString *str;
-       FolderItem *new_item;
-
-       debug_print("getting list of %s ...\n",
-                   *real_path ? real_path : "\"\"");
-
-       str = g_string_new(NULL);
-
-       for (;;) {
-               if (sock_gets(SESSION(session)->sock, buf, sizeof(buf)) <= 0) {
-                       log_warning(_("error occurred while getting LIST.\n"));
-                       break;
-               }
-               strretchomp(buf);
-               if (buf[0] != '*' || buf[1] != ' ') {
-                       log_print("IMAP4< %s\n", buf);
-                       if (sscanf(buf, "%*d %16s", buf) < 1 ||
-                           strcmp(buf, "OK") != 0)
-                               log_warning(_("error occurred while getting LIST.\n"));
-                               
-                       break;
-               }
-               debug_print("IMAP4< %s\n", buf);
-
-               g_string_assign(str, buf);
-               p = str->str + 2;
-               if (strncmp(p, "LIST ", 5) != 0) continue;
-               p += 5;
-
-               if (*p != '(') continue;
-               p++;
-               p = strchr_cpy(p, ')', flags, sizeof(flags));
-               if (!p) continue;
-               while (*p == ' ') p++;
-
-               p = strchr_cpy(p, ' ', separator_str, sizeof(separator_str));
-               if (!p) continue;
-               extract_quote(separator_str, '"');
-               if (!strcmp(separator_str, "NIL"))
-                       separator_str[0] = '\0';
-               if (separator)
-                       *separator = separator_str[0];
-
-               buf[0] = '\0';
-               while (*p == ' ') p++;
-               if (*p == '{' || *p == '"')
-                       p = imap_parse_atom(SESSION(session)->sock, p,
-                                           buf, sizeof(buf), str);
-               else
-                       strncpy2(buf, p, sizeof(buf));
-               strtailchomp(buf, separator_str[0]);
-               if (buf[0] == '\0') continue;
-               if (!strcmp(buf, real_path)) continue;
-
-               if (separator_str[0] != '\0')
-                       subst_char(buf, separator_str[0], '/');
-               base = g_path_get_basename(buf);
-               if (base[0] == '.') continue;
-
-               loc_name = imap_modified_utf7_to_utf8(base);
-               loc_path = imap_modified_utf7_to_utf8(buf);
-               new_item = folder_item_new(FOLDER(folder), loc_name, loc_path);
-               if (strcasestr(flags, "\\Noinferiors") != NULL)
-                       new_item->no_sub = TRUE;
-               if (strcmp(buf, "INBOX") != 0 &&
-                   strcasestr(flags, "\\Noselect") != NULL)
-                       new_item->no_select = TRUE;
-
-               item_list = g_slist_append(item_list, new_item);
-
-               debug_print("folder '%s' found.\n", loc_path);
-               g_free(base);
-               g_free(loc_path);
-               g_free(loc_name);
-       }
-
-       g_string_free(str, TRUE);
-
-       return item_list;
-}
-
 static gint imap_create_tree(Folder *folder)
 {
        g_return_val_if_fail(folder != NULL, -1);
@@ -1764,17 +1452,6 @@ static void imap_create_missing_folders(Folder *folder)
        if (!folder->inbox)
                folder->inbox = imap_create_special_folder
                        (folder, F_INBOX, "INBOX");
-#if 0
-       if (!folder->outbox)
-               folder->outbox = imap_create_special_folder
-                       (folder, F_OUTBOX, "Sent");
-       if (!folder->draft)
-               folder->draft = imap_create_special_folder
-                       (folder, F_DRAFT, "Drafts");
-       if (!folder->queue)
-               folder->queue = imap_create_special_folder
-                       (folder, F_QUEUE, "Queue");
-#endif
        if (!folder->trash)
                folder->trash = imap_create_special_folder
                        (folder, F_TRASH, "Trash");
@@ -1912,13 +1589,13 @@ static FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
 
        if (strcmp(name, "INBOX") != 0) {
                GPtrArray *argbuf;
-               gint i;
                gboolean exist = FALSE;
-
+               int r;
+               clist * lep_list;
+               
                argbuf = g_ptr_array_new();
-               ok = imap_cmd_list(session, NULL, imap_path,
-                                  argbuf);
-               if (ok != IMAP_SUCCESS) {
+               r = imap_threaded_list(folder, "", imap_path, &lep_list);
+               if (r != MAILIMAP_NO_ERROR) {
                        log_warning(_("can't create mailbox: LIST failed\n"));
                        g_free(imap_path);
                        g_free(dirpath);
@@ -1927,18 +1604,10 @@ static FolderItem *imap_create_folder(Folder *folder, FolderItem *parent,
                        MUTEX_UNLOCK();
                        return NULL;
                }
-
-               for (i = 0; i < argbuf->len; i++) {
-                       gchar *str;
-                       str = g_ptr_array_index(argbuf, i);
-                       if (!strncmp(str, "LIST ", 5)) {
-                               exist = TRUE;
-                               break;
-                       }
-               }
-               ptr_array_free_strings(argbuf);
-               g_ptr_array_free(argbuf, TRUE);
-
+               
+               if (clist_count(lep_list) > 0)
+                       exist = TRUE;
+               
                if (!exist) {
                        ok = imap_cmd_create(session, imap_path);
                        if (ok != IMAP_SUCCESS) {
@@ -2148,88 +1817,54 @@ static void *imap_get_uncached_messages_thread(void *data)
        IMAPSession *session = stuff->session;
        FolderItem *item = stuff->item;
        MsgNumberList *numlist = stuff->numlist;
-
-       gchar *tmp;
+       
        GSList *newlist = NULL;
        GSList *llast = NULL;
-       GString *str = NULL;
-       MsgInfo *msginfo;
        GSList *seq_list, *cur;
-       IMAPSet imapset;
-       
-       stuff->total = g_slist_length(numlist);
-       stuff->cur = 0;
 
+       debug_print("uncached_messages\n");
+       
        if (session == NULL || item == NULL || item->folder == NULL
            || FOLDER_CLASS(item->folder) != &imap_class) {
                stuff->done = TRUE;
                return NULL;
        }
-
-       seq_list = imap_get_seq_set_from_numlist(numlist);
+       
+       seq_list = imap_get_lep_set_from_numlist(numlist);
+       debug_print("get msgs info\n");
        for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
+               struct mailimap_set * imapset;
+               unsigned int i;
+               int r;
+               carray * env_list;
+               int count;
+               
                imapset = cur->data;
                
-               if (!imapset || strlen(imapset) == 0)
-                       continue;
-
-               if (imap_cmd_envelope(session, imapset)
-                   != IMAP_SUCCESS) {
-                       log_warning(_("can't get envelope\n"));
+               r = imap_threaded_fetch_env(session->folder,
+                                           imapset, &env_list);
+               if (r != MAILIMAP_NO_ERROR)
                        continue;
-               }
-
-               str = g_string_new(NULL);
-
-               for (;;) {
-                       if ((tmp =sock_getline(SESSION(session)->sock)) == NULL) {
-                               log_warning(_("error occurred while getting envelope.\n"));
-                               g_string_free(str, TRUE);
-                               str = NULL;
-                               break;
-                       }
-                       strretchomp(tmp);
-                       if (tmp[0] != '*' || tmp[1] != ' ') {
-                               log_print("IMAP4< %s\n", tmp);
-                               g_free(tmp);
-                               break;
-                       }
-                       if (strstr(tmp, "FETCH") == NULL) {
-                               log_print("IMAP4< %s\n", tmp);
-                               g_free(tmp);
-                               continue;
-                       }
-                       log_print("IMAP4< %s\n", tmp);
-                       g_string_assign(str, tmp);
-                       g_free(tmp);
+               
+               count = 0;
+               for(i = 0 ; i < carray_count(env_list) ; i ++) {
+                       struct imap_fetch_env_info * info;
+                       MsgInfo * msginfo;
                        
-                       stuff->cur++;
-
-                       msginfo = imap_parse_envelope
-                               (SESSION(session)->sock, item, str);
-                       if (!msginfo) {
-                               log_warning(_("can't parse envelope: %s\n"), str->str);
-                               continue;
-                       }
-                       if (item->stype == F_QUEUE) {
-                               MSG_SET_TMP_FLAGS(msginfo->flags, MSG_QUEUED);
-                       } else if (item->stype == F_DRAFT) {
-                               MSG_SET_TMP_FLAGS(msginfo->flags, MSG_DRAFT);
-                       }
-
+                       info = carray_get(env_list, i);
+                       msginfo = imap_envelope_from_lep(info, item);
                        msginfo->folder = item;
-
                        if (!newlist)
                                llast = newlist = g_slist_append(newlist, msginfo);
                        else {
                                llast = g_slist_append(llast, msginfo);
                                llast = llast->next;
                        }
+                       count ++;
                }
-               if (str)
-                       g_string_free(str, TRUE);
+               
+               imap_fetch_env_free(env_list);
        }
-       imap_seq_set_free(seq_list);
        
        session_set_access_time(SESSION(session));
        stuff->done = TRUE;
@@ -2237,70 +1872,87 @@ static void *imap_get_uncached_messages_thread(void *data)
        return newlist;
 }
 
+#define MAX_MSG_NUM 50
+
 static GSList *imap_get_uncached_messages(IMAPSession *session,
                                        FolderItem *item,
                                        MsgNumberList *numlist)
 {
-       uncached_data *data = g_new0(uncached_data, 1);
        GSList *result = NULL;
-       gint last_cur = 0;
-#ifdef USE_PTHREAD
-       pthread_t pt;
-#endif
-       data->done = FALSE;
-       data->session = session;
-       data->item = item;
-       data->numlist = numlist;
-       data->cur = 0;
-       data->total = 0;
+       GSList * cur;
+       uncached_data *data = g_new0(uncached_data, 1);
+       int finished;
        
-       if (prefs_common.work_offline && !imap_gtk_should_override()) {
-               g_free(data);
-               return NULL;
-       }
-
-#if (defined USE_PTHREAD && defined __GLIBC__ && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)))
-       MUTEX_TRYLOCK_OR_RETURN_VAL(NULL);
-
-       if (pthread_create(&pt, PTHREAD_CREATE_JOINABLE,
-                       imap_get_uncached_messages_thread, data) != 0) {
-               result = (GSList *)imap_get_uncached_messages_thread(data);
-               g_free(data);
-               MUTEX_UNLOCK();
-               return result;
-       }
-       debug_print("+++waiting for imap_get_uncached_messages_thread...\n");
-       statusbar_print_all(_("IMAP4 Fetching uncached short headers..."));
-       while(!data->done) {
-               /* don't let the interface freeze while waiting */
-               sylpheed_do_idle();
-               if (data->total != 0 && last_cur != data->cur && data->cur % 10 == 0) {
-                       gchar buf[32];
-                       g_snprintf(buf, sizeof(buf), "%d / %d",
-                                  data->cur, data->total);
+       finished = 0;
+       cur = numlist;
+       data->total = g_slist_length(numlist);
+       debug_print("messages list : %i\n", data->total);
+       while (cur != NULL) {
+               GSList * partial_result;
+               int count;
+               GSList * newlist;
+               GSList * llast;
+               
+               llast = NULL;
+               count = 0;
+               newlist = NULL;
+               while (count < MAX_MSG_NUM) {
+                       void * p;
+                       
+                       p = cur->data;
+                       
+                       if (newlist == NULL)
+                               llast = newlist = g_slist_append(newlist, p);
+                       else {
+                               llast = g_slist_append(llast, p);
+                               llast = llast->next;
+                       }
+                       count ++;
+                       
+                       cur = cur->next;
+                       if (cur == NULL)
+                               break;
+               }
+               
+               data->done = FALSE;
+               data->session = session;
+               data->item = item;
+               data->numlist = newlist;
+               data->cur += count;
+               
+               if (prefs_common.work_offline && !imap_gtk_should_override()) {
+                       g_free(data);
+                       return NULL;
+               }
+               
+               partial_result =
+                       (GSList *)imap_get_uncached_messages_thread(data);
+               
+               {
+                       gchar buf[32];
+                       g_snprintf(buf, sizeof(buf), "%d / %d",
+                                  data->cur, data->total);
                        gtk_progress_bar_set_text
                                (GTK_PROGRESS_BAR(mainwindow_get_mainwindow()->progressbar), buf);
                        gtk_progress_bar_set_fraction
-                       (GTK_PROGRESS_BAR(mainwindow_get_mainwindow()->progressbar),
-                        (gfloat)data->cur / (gfloat)data->total);
-                       last_cur = data->cur;
+                               (GTK_PROGRESS_BAR(mainwindow_get_mainwindow()->progressbar),
+                                (gfloat)data->cur / (gfloat)data->total);
+                       debug_print("update progress %g\n",
+                               (gfloat)data->cur / (gfloat)data->total);
                }
+               
+               g_slist_free(newlist);
+               
+               result = g_slist_concat(result, partial_result);
        }
+       g_free(data);
+       
        gtk_progress_bar_set_fraction
                (GTK_PROGRESS_BAR(mainwindow_get_mainwindow()->progressbar), 0);
        gtk_progress_bar_set_text
                (GTK_PROGRESS_BAR(mainwindow_get_mainwindow()->progressbar), "");
        statusbar_pop_all();
-
-       debug_print("---imap_get_uncached_messages_thread done\n");
-
-       /* get the thread's return value and clean its resources */
-       pthread_join(pt, (void *)&result);
-       MUTEX_UNLOCK();
-#else
-       result = (GSList *)imap_get_uncached_messages_thread(data);
-#endif
-       g_free(data);
+       
        return result;
 }
 
@@ -2322,234 +1974,6 @@ static void imap_delete_all_cached_messages(FolderItem *item)
        debug_print("done.\n");
 }
 
-#if USE_OPENSSL
-static SockInfo *imap_open_tunnel(const gchar *server,
-                          const gchar *tunnelcmd,
-                          SSLType ssl_type)
-#else
-static SockInfo *imap_open_tunnel(const gchar *server,
-                          const gchar *tunnelcmd)
-#endif
-{
-       SockInfo *sock;
-
-       if ((sock = sock_connect_cmd(server, tunnelcmd)) == NULL) {
-               log_warning(_("Can't establish IMAP4 session with: %s\n"),
-                           server);
-               return NULL;
-       }
-#if USE_OPENSSL
-       return imap_init_sock(sock, ssl_type);
-#else
-       return imap_init_sock(sock);
-#endif
-}
-
-void *imap_open_thread(void *data)
-{
-       SockInfo *sock = NULL;
-       thread_data *td = (thread_data *)data;
-       if ((sock = sock_connect(td->server, td->port)) == NULL) {
-               log_warning(_("Can't connect to IMAP4 server: %s:%d\n"),
-                           td->server, td->port);
-               td->done = TRUE;
-               return NULL;
-       }
-
-       td->done = TRUE;
-       return sock;
-}
-
-#if USE_OPENSSL
-static SockInfo *imap_open(const gchar *server, gushort port,
-                          SSLType ssl_type)
-#else
-static SockInfo *imap_open(const gchar *server, gushort port)
-#endif
-{
-       thread_data *td = g_new0(thread_data, 1);
-#if USE_PTHREAD
-       pthread_t pt;
-#endif
-       SockInfo *sock = NULL;
-
-#if USE_OPENSSL
-       td->ssl_type = ssl_type;
-#endif
-       td->server = g_strdup(server);
-       td->port = port;
-       td->done = FALSE;
-
-       statusbar_print_all(_("Connecting to IMAP4 server: %s..."), server);
-
-#if (defined USE_PTHREAD && defined __GLIBC__ && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)))
-       if (pthread_create(&pt, PTHREAD_CREATE_JOINABLE,
-                       imap_open_thread, td) != 0) {
-               statusbar_pop_all();
-               sock = imap_open_thread(td);
-       } else {        
-               debug_print("+++waiting for imap_open_thread...\n");
-               while(!td->done) {
-                       /* don't let the interface freeze while waiting */
-                       sylpheed_do_idle();
-               }
-
-               /* get the thread's return value and clean its resources */
-               pthread_join(pt, (void *)&sock);
-       }
-#else
-       sock = imap_open_thread(td);
-#endif
-#if USE_OPENSSL
-       if (sock && td->ssl_type == SSL_TUNNEL && !ssl_init_socket(sock)) {
-               log_warning(_("Can't establish IMAP4 session with: %s:%d\n"),
-                           td->server, td->port);
-               sock_close(sock);
-               sock = NULL;
-               td->done = TRUE;
-       }
-#endif
-       g_free(td->server);
-       g_free(td);
-
-       debug_print("---imap_open_thread returned %p\n", sock);
-       statusbar_pop_all();
-
-       if(!sock && !prefs_common.no_recv_err_panel) {
-               alertpanel_error(_("Can't connect to IMAP4 server: %s:%d"),
-                                server, port);
-       }
-
-       return sock;
-}
-
-#if USE_OPENSSL
-static SockInfo *imap_init_sock(SockInfo *sock, SSLType ssl_type)
-#else
-static SockInfo *imap_init_sock(SockInfo *sock)
-#endif
-{
-
-       return sock;
-}
-
-static GList *imap_parse_namespace_str(gchar *str)
-{
-       guchar *p = str;
-       gchar *name;
-       gchar *separator;
-       IMAPNameSpace *namespace;
-       GList *ns_list = NULL;
-
-       while (*p != '\0') {
-               /* parse ("#foo" "/") */
-
-               while (*p && *p != '(') p++;
-               if (*p == '\0') break;
-               p++;
-
-               while (*p && *p != '"') p++;
-               if (*p == '\0') break;
-               p++;
-               name = p;
-
-               while (*p && *p != '"') p++;
-               if (*p == '\0') break;
-               *p = '\0';
-               p++;
-
-               while (*p && isspace(*p)) p++;
-               if (*p == '\0') break;
-               if (strncmp(p, "NIL", 3) == 0)
-                       separator = NULL;
-               else if (*p == '"') {
-                       p++;
-                       separator = p;
-                       while (*p && *p != '"') p++;
-                       if (*p == '\0') break;
-                       *p = '\0';
-                       p++;
-               } else break;
-
-               while (*p && *p != ')') p++;
-               if (*p == '\0') break;
-               p++;
-
-               namespace = g_new(IMAPNameSpace, 1);
-               namespace->name = g_strdup(name);
-               namespace->separator = separator ? separator[0] : '\0';
-               ns_list = g_list_append(ns_list, namespace);
-       }
-
-       return ns_list;
-}
-
-static void imap_parse_namespace(IMAPSession *session, IMAPFolder *folder)
-{
-       gchar *ns_str;
-       gchar **str_array;
-
-       g_return_if_fail(session != NULL);
-       g_return_if_fail(folder != NULL);
-
-       if (folder->ns_personal != NULL ||
-           folder->ns_others   != NULL ||
-           folder->ns_shared   != NULL)
-               return;
-
-       if (!imap_has_capability(session, "NAMESPACE")) {
-               imap_get_namespace_by_list(session, folder);
-               return;
-       }
-       
-       if (imap_cmd_namespace(session, &ns_str)
-           != IMAP_SUCCESS) {
-               log_warning(_("can't get namespace\n"));
-               return;
-       }
-
-       str_array = strsplit_parenthesis(ns_str, '(', ')', 3);
-       if (str_array == NULL) {
-               g_free(ns_str);
-               imap_get_namespace_by_list(session, folder);
-               return;
-       }
-       if (str_array[0])
-               folder->ns_personal = imap_parse_namespace_str(str_array[0]);
-       if (str_array[0] && str_array[1])
-               folder->ns_others = imap_parse_namespace_str(str_array[1]);
-       if (str_array[0] && str_array[1] && str_array[2])
-               folder->ns_shared = imap_parse_namespace_str(str_array[2]);
-       g_strfreev(str_array);
-       g_free(ns_str);
-}
-
-static void imap_get_namespace_by_list(IMAPSession *session, IMAPFolder *folder)
-{
-       GSList *item_list, *cur;
-       gchar separator = '\0';
-       IMAPNameSpace *namespace;
-
-       g_return_if_fail(session != NULL);
-       g_return_if_fail(folder != NULL);
-
-       if (folder->ns_personal != NULL ||
-           folder->ns_others   != NULL ||
-           folder->ns_shared   != NULL)
-               return;
-
-       imap_gen_send(session, "LIST \"\" \"\"");
-       item_list = imap_parse_list(folder, session, "", &separator);
-       for (cur = item_list; cur != NULL; cur = cur->next)
-               folder_item_destroy(FOLDER_ITEM(cur->data));
-       g_slist_free(item_list);
-
-       namespace = g_new(IMAPNameSpace, 1);
-       namespace->name = g_strdup("");
-       namespace->separator = separator;
-       folder->ns_personal = g_list_append(NULL, namespace);
-}
-
 static IMAPNameSpace *imap_find_namespace_from_list(GList *ns_list,
                                                    const gchar *path)
 {
@@ -2618,299 +2042,29 @@ static gchar *imap_get_real_path(IMAPFolder *folder, const gchar *path)
        return real_path;
 }
 
-static gchar *imap_parse_atom(SockInfo *sock, gchar *src,
-                             gchar *dest, gint dest_len, GString *str)
-{
-       gchar *cur_pos = src;
-       gchar *nextline;
-
-       g_return_val_if_fail(str != NULL, cur_pos);
-
-       /* read the next line if the current response buffer is empty */
-       while (isspace(*(guchar *)cur_pos)) cur_pos++;
-       while (*cur_pos == '\0') {
-               if ((nextline = imap_getline(sock)) == NULL)
-                       return cur_pos;
-               g_string_assign(str, nextline);
-               cur_pos = str->str;
-               strretchomp(nextline);
-               /* log_print("IMAP4< %s\n", nextline); */
-               debug_print("IMAP4< %s\n", nextline);
-               g_free(nextline);
-
-               while (isspace(*(guchar *)cur_pos)) cur_pos++;
-       }
-
-       if (!strncmp(cur_pos, "NIL", 3)) {
-               *dest = '\0';
-               cur_pos += 3;
-       } else if (*cur_pos == '\"') {
-               gchar *p;
-
-               p = get_quoted(cur_pos, '\"', dest, dest_len);
-               cur_pos = p ? p : cur_pos + 2;
-       } else if (*cur_pos == '{') {
-               gchar buf[32];
-               gint len;
-               gint line_len = 0;
-
-               cur_pos = strchr_cpy(cur_pos + 1, '}', buf, sizeof(buf));
-               len = atoi(buf);
-               g_return_val_if_fail(len >= 0, cur_pos);
-
-               g_string_truncate(str, 0);
-               cur_pos = str->str;
-
-               do {
-                       if ((nextline = imap_getline(sock)) == NULL)
-                               return cur_pos;
-                       line_len += strlen(nextline);
-                       g_string_append(str, nextline);
-                       cur_pos = str->str;
-                       strretchomp(nextline);
-                       /* log_print("IMAP4< %s\n", nextline); */
-                       debug_print("IMAP4< %s\n", nextline);
-                       g_free(nextline);
-               } while (line_len < len);
-
-               memcpy(dest, cur_pos, MIN(len, dest_len - 1));
-               dest[MIN(len, dest_len - 1)] = '\0';
-               cur_pos += len;
-       }
-
-       return cur_pos;
-}
-
-static gchar *imap_get_header(SockInfo *sock, gchar *cur_pos, gchar **headers,
-                             GString *str)
-{
-       gchar *nextline;
-       gchar buf[32];
-       gint len;
-       gint block_len = 0;
-
-       *headers = NULL;
-
-       g_return_val_if_fail(str != NULL, cur_pos);
-
-       while (isspace(*(guchar *)cur_pos)) cur_pos++;
-
-       g_return_val_if_fail(*cur_pos == '{', cur_pos);
-
-       cur_pos = strchr_cpy(cur_pos + 1, '}', buf, sizeof(buf));
-       len = atoi(buf);
-       g_return_val_if_fail(len >= 0, cur_pos);
-
-       g_string_truncate(str, 0);
-       cur_pos = str->str;
-
-       do {
-               if ((nextline = sock_getline(sock)) == NULL) {
-                       *headers = NULL;
-                       return cur_pos;
-               }
-               block_len += strlen(nextline);
-               g_string_append(str, nextline);
-               cur_pos = str->str;
-               strretchomp(nextline);
-               /* debug_print("IMAP4< %s\n", nextline); */
-               g_free(nextline);
-       } while (block_len < len);
-
-       debug_print("IMAP4< [contents of BODY.PEEK[HEADER_FIELDS (...)]\n");
-
-       *headers = g_strndup(cur_pos, len);
-       cur_pos += len;
-
-       while (isspace(*(guchar *)cur_pos)) cur_pos++;
-       while (*cur_pos == '\0') {
-               if ((nextline = sock_getline(sock)) == NULL)
-                       return cur_pos;
-               g_string_assign(str, nextline);
-               cur_pos = str->str;
-               strretchomp(nextline);
-               debug_print("IMAP4< %s\n", nextline);
-               g_free(nextline);
-
-               while (isspace(*(guchar *)cur_pos)) cur_pos++;
-       }
-
-       return cur_pos;
-}
-
-static MsgFlags imap_parse_flags(const gchar *flag_str)  
-{
-       const gchar *p = flag_str;
-       MsgFlags flags = {0, 0};
-
-       flags.perm_flags = MSG_UNREAD;
-
-       while ((p = strchr(p, '\\')) != NULL) {
-               p++;
-
-               if (g_ascii_strncasecmp(p, "Recent", 6) == 0 && MSG_IS_UNREAD(flags)) {
-                       MSG_SET_PERM_FLAGS(flags, MSG_NEW);
-               } else if (g_ascii_strncasecmp(p, "Seen", 4) == 0) {
-                       MSG_UNSET_PERM_FLAGS(flags, MSG_NEW|MSG_UNREAD);
-               } else if (g_ascii_strncasecmp(p, "Deleted", 7) == 0) {
-                       MSG_SET_PERM_FLAGS(flags, MSG_DELETED);
-               } else if (g_ascii_strncasecmp(p, "Flagged", 7) == 0) {
-                       MSG_SET_PERM_FLAGS(flags, MSG_MARKED);
-               } else if (g_ascii_strncasecmp(p, "Answered", 8) == 0) {
-                       MSG_SET_PERM_FLAGS(flags, MSG_REPLIED);
-               }
-       }
-
-       return flags;
-}
-
-static MsgInfo *imap_parse_envelope(SockInfo *sock, FolderItem *item,
-                                   GString *line_str)
-{
-       gchar buf[IMAPBUFSIZE];
-       MsgInfo *msginfo = NULL;
-       gchar *cur_pos;
-       gint msgnum;
-       guint32 uid = 0;
-       size_t size = 0;
-       MsgFlags flags = {0, 0}, imap_flags = {0, 0};
-
-       g_return_val_if_fail(line_str != NULL, NULL);
-       g_return_val_if_fail(line_str->str[0] == '*' &&
-                            line_str->str[1] == ' ', NULL);
-
-       MSG_SET_TMP_FLAGS(flags, MSG_IMAP);
-       if (item->stype == F_QUEUE) {
-               MSG_SET_TMP_FLAGS(flags, MSG_QUEUED);
-       } else if (item->stype == F_DRAFT) {
-               MSG_SET_TMP_FLAGS(flags, MSG_DRAFT);
-       }
-
-       cur_pos = line_str->str + 2;
-
-#define PARSE_ONE_ELEMENT(ch)                                  \
-{                                                              \
-       cur_pos = strchr_cpy(cur_pos, ch, buf, sizeof(buf));    \
-       if (cur_pos == NULL) {                                  \
-               g_warning("cur_pos == NULL\n");                 \
-               procmsg_msginfo_free(msginfo);                  \
-               return NULL;                                    \
-       }                                                       \
-}
-
-       PARSE_ONE_ELEMENT(' ');
-       msgnum = atoi(buf);
-
-       PARSE_ONE_ELEMENT(' ');
-       g_return_val_if_fail(!strcmp(buf, "FETCH"), NULL);
-
-       g_return_val_if_fail(*cur_pos == '(', NULL);
-       cur_pos++;
-
-       while (*cur_pos != '\0' && *cur_pos != ')') {
-               while (*cur_pos == ' ') cur_pos++;
-
-               if (!strncmp(cur_pos, "UID ", 4)) {
-                       cur_pos += 4;
-                       uid = strtoul(cur_pos, &cur_pos, 10);
-               } else if (!strncmp(cur_pos, "FLAGS ", 6)) {
-                       cur_pos += 6;
-                       if (*cur_pos != '(') {
-                               g_warning("*cur_pos != '('\n");
-                               procmsg_msginfo_free(msginfo);
-                               return NULL;
-                       }
-                       cur_pos++;
-                       PARSE_ONE_ELEMENT(')');
-                       imap_flags = imap_parse_flags(buf);
-               } else if (!strncmp(cur_pos, "RFC822.SIZE ", 12)) {
-                       cur_pos += 12;
-                       size = strtol(cur_pos, &cur_pos, 10);
-               } else if (!strncmp(cur_pos, "BODY[HEADER.FIELDS ", 19)) {
-                       gchar *headers;
-
-                       cur_pos += 19;
-                       if (*cur_pos != '(') {
-                               g_warning("*cur_pos != '('\n");
-                               procmsg_msginfo_free(msginfo);
-                               return NULL;
-                       }
-                       cur_pos++;
-                       PARSE_ONE_ELEMENT(')');
-                       if (*cur_pos != ']') {
-                               g_warning("*cur_pos != ']'\n");
-                               procmsg_msginfo_free(msginfo);
-                               return NULL;
-                       }
-                       cur_pos++;
-                       cur_pos = imap_get_header(sock, cur_pos, &headers,
-                                                 line_str);
-                       msginfo = procheader_parse_str(headers, flags, FALSE, FALSE);
-                       g_free(headers);
-               } else {
-                       g_warning("invalid FETCH response: %s\n", cur_pos);
-                       break;
-               }
-       }
-
-       if (msginfo) {
-               msginfo->msgnum = uid;
-               msginfo->size = size;
-               msginfo->flags.tmp_flags |= imap_flags.tmp_flags;
-               msginfo->flags.perm_flags = imap_flags.perm_flags;
-       }
-
-       return msginfo;
-}
-
-static gchar *imap_get_flag_str(IMAPFlags flags)
-{
-       GString *str;
-       gchar *ret;
-
-       str = g_string_new(NULL);
-
-       if (IMAP_IS_SEEN(flags))        g_string_append(str, "\\Seen ");
-       if (IMAP_IS_ANSWERED(flags))    g_string_append(str, "\\Answered ");
-       if (IMAP_IS_FLAGGED(flags))     g_string_append(str, "\\Flagged ");
-       if (IMAP_IS_DELETED(flags))     g_string_append(str, "\\Deleted ");
-       if (IMAP_IS_DRAFT(flags))       g_string_append(str, "\\Draft");
-
-       if (str->len > 0 && str->str[str->len - 1] == ' ')
-               g_string_truncate(str, str->len - 1);
-
-       ret = str->str;
-       g_string_free(str, FALSE);
-
-       return ret;
-}
-
 static gint imap_set_message_flags(IMAPSession *session,
                                   MsgNumberList *numlist,
                                   IMAPFlags flags,
                                   gboolean is_set)
 {
-       gchar *cmd;
-       gchar *flag_str;
        gint ok = 0;
        GSList *seq_list;
-       IMAPSet imapset;
+       GSList * cur;
 
-       flag_str = imap_get_flag_str(flags);
-       cmd = g_strconcat(is_set ? "+FLAGS.SILENT (" : "-FLAGS.SILENT (",
-                         flag_str, ")", NULL);
-       g_free(flag_str);
-
-       seq_list = imap_get_seq_set_from_numlist(numlist);
-       imapset = get_seq_set_from_seq_list(seq_list);
-
-       ok = imap_cmd_store(session, imapset, cmd);
+       seq_list = imap_get_lep_set_from_numlist(numlist);
        
-       g_free(imapset);
-       imap_seq_set_free(seq_list);
-       g_free(cmd);
-
-       return ok;
+       for(cur = seq_list ; cur != NULL ; cur = g_slist_next(cur)) {
+               struct mailimap_set * imapset;
+               
+               imapset = cur->data;
+               
+               ok = imap_cmd_store(session, imapset,
+                                   flags, is_set);
+       }
+       
+       imap_lep_set_free(seq_list);
+       
+       return IMAP_SUCCESS;
 }
 
 typedef struct _select_data {
@@ -2923,23 +2077,6 @@ typedef struct _select_data {
        gboolean done;
 } select_data;
 
-static void *imap_select_thread(void *data)
-{
-       select_data *stuff = (select_data *)data;
-       IMAPSession *session = stuff->session;
-       gchar *real_path = stuff->real_path;
-       gint *exists = stuff->exists;
-       gint *recent = stuff->recent;
-       gint *unseen = stuff->unseen;
-       guint32 *uid_validity = stuff->uid_validity;
-       gint ok;
-       
-       ok = imap_cmd_select(session, real_path,
-                            exists, recent, unseen, uid_validity, TRUE);
-       stuff->done = TRUE;
-       return GINT_TO_POINTER(ok);
-}
-               
 static gint imap_select(IMAPSession *session, IMAPFolder *folder,
                        const gchar *path,
                        gint *exists, gint *recent, gint *unseen,
@@ -2963,46 +2100,9 @@ static gint imap_select(IMAPSession *session, IMAPFolder *folder,
        session->mbox = NULL;
 
        real_path = imap_get_real_path(folder, path);
-       
-#if (defined USE_PTHREAD && defined __GLIBC__ && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)))
 
-       if (block == FALSE) {
-               select_data *data = g_new0(select_data, 1);
-               void *tmp;
-               pthread_t pt;
-               data->session = session;
-               data->real_path = real_path;
-               data->exists = exists;
-               data->recent = recent;
-               data->unseen = unseen;
-               data->uid_validity = uid_validity;
-               data->done = FALSE;
-               
-               if (pthread_create(&pt, PTHREAD_CREATE_JOINABLE,
-                               imap_select_thread, data) != 0) {
-                       ok = GPOINTER_TO_INT(imap_select_thread(data));
-                       g_free(data);
-               } else {
-                       debug_print("+++waiting for imap_select_thread...\n");
-                       while(!data->done) {
-                               /* don't let the interface freeze while waiting */
-                               sylpheed_do_idle();
-                       }
-                       debug_print("---imap_select_thread done\n");
-
-                       /* get the thread's return value and clean its resources */
-                       pthread_join(pt, &tmp);
-                       ok = GPOINTER_TO_INT(tmp);
-                       g_free(data);
-               }
-       } else {
-               ok = imap_cmd_select(session, real_path,
-                            exists, recent, unseen, uid_validity, block);
-       }
-#else
        ok = imap_cmd_select(session, real_path,
                             exists, recent, unseen, uid_validity, block);
-#endif
        if (ok != IMAP_SUCCESS)
                log_warning(_("can't select folder: %s\n"), real_path);
        else {
@@ -3014,86 +2114,66 @@ static gint imap_select(IMAPSession *session, IMAPFolder *folder,
        return ok;
 }
 
-#define THROW(err) { ok = err; goto catch; }
-
 static gint imap_status(IMAPSession *session, IMAPFolder *folder,
                        const gchar *path,
                        gint *messages, gint *recent,
                        guint32 *uid_next, guint32 *uid_validity,
                        gint *unseen, gboolean block)
 {
-       gchar *real_path;
-       gchar *real_path_;
-       gint ok;
-       GPtrArray *argbuf = NULL;
-       gchar *str;
-
-       if (messages && recent && uid_next && uid_validity && unseen) {
-               *messages = *recent = *uid_next = *uid_validity = *unseen = 0;
-               argbuf = g_ptr_array_new();
+       int r;
+       clistiter * iter;
+       struct mailimap_mailbox_data_status * data_status;
+       int got_values;
+       
+       r = imap_threaded_status(FOLDER(folder), path, &data_status);
+       if (r != MAILIMAP_NO_ERROR)
+               return IMAP_ERROR;
+       
+       if (data_status->st_info_list == NULL) {
+               mailimap_mailbox_data_status_free(data_status);
+               return IMAP_ERROR;
        }
-
-       real_path = imap_get_real_path(folder, path);
-       QUOTE_IF_REQUIRED(real_path_, real_path);
-       imap_gen_send(session, "STATUS %s "
-                         "(MESSAGES RECENT UIDNEXT UIDVALIDITY UNSEEN)",
-                         real_path_);
-
-       ok = imap_cmd_ok_with_block(session, argbuf, block);
-       if (ok != IMAP_SUCCESS || !argbuf) THROW(ok);
-
-       str = search_array_str(argbuf, "STATUS");
-       if (!str) THROW(IMAP_ERROR);
-
-       str = strrchr(str, '(');
-       if (!str) THROW(IMAP_ERROR);
-       str++;
-       while (*str != '\0' && *str != ')') {
-               while (*str == ' ') str++;
-
-               if (!strncmp(str, "MESSAGES ", 9)) {
-                       str += 9;
-                       *messages = strtol(str, &str, 10);
-               } else if (!strncmp(str, "RECENT ", 7)) {
-                       str += 7;
-                       *recent = strtol(str, &str, 10);
-               } else if (!strncmp(str, "UIDNEXT ", 8)) {
-                       str += 8;
-                       *uid_next = strtoul(str, &str, 10);
-               } else if (!strncmp(str, "UIDVALIDITY ", 12)) {
-                       str += 12;
-                       *uid_validity = strtoul(str, &str, 10);
-               } else if (!strncmp(str, "UNSEEN ", 7)) {
-                       str += 7;
-                       *unseen = strtol(str, &str, 10);
-               } else {
-                       g_warning("invalid STATUS response: %s\n", str);
+       
+       got_values = 0;
+       for(iter = clist_begin(data_status->st_info_list) ; iter != NULL ;
+           iter = clist_next(iter)) {
+               struct mailimap_status_info * info;             
+               
+               info = clist_content(iter);
+               switch (info->st_att) {
+               case MAILIMAP_STATUS_ATT_MESSAGES:
+                       * messages = info->st_value;
+                       got_values |= 1 << 0;
+                       break;
+                       
+               case MAILIMAP_STATUS_ATT_RECENT:
+                       * recent = info->st_value;
+                       got_values |= 1 << 1;
+                       break;
+                       
+               case MAILIMAP_STATUS_ATT_UIDNEXT:
+                       * uid_next = info->st_value;
+                       got_values |= 1 << 2;
+                       break;
+                       
+               case MAILIMAP_STATUS_ATT_UIDVALIDITY:
+                       * uid_validity = info->st_value;
+                       got_values |= 1 << 3;
+                       break;
+                       
+               case MAILIMAP_STATUS_ATT_UNSEEN:
+                       * unseen = info->st_value;
+                       got_values |= 1 << 4;
                        break;
                }
        }
-
-catch:
-       g_free(real_path);
-       if (argbuf) {
-               ptr_array_free_strings(argbuf);
-               g_ptr_array_free(argbuf, TRUE);
-       }
-
-       return ok;
-}
-
-#undef THROW
-
-static gboolean imap_has_capability(IMAPSession *session, const gchar *cap)
-{
-       gchar **p;
+       mailimap_mailbox_data_status_free(data_status);
        
-       for (p = session->capability; *p != NULL; ++p) {
-               if (!g_ascii_strcasecmp(*p, cap))
-                       return TRUE;
-       }
-
-       return FALSE;
+       if (got_values != ((1 << 4) + (1 << 3) +
+                          (1 << 2) + (1 << 1) + (1 << 0)))
+               return IMAP_ERROR;
+       
+       return IMAP_SUCCESS;
 }
 
 static void imap_free_capabilities(IMAPSession *session)
@@ -3104,6 +2184,7 @@ static void imap_free_capabilities(IMAPSession *session)
 
 /* low-level IMAP4rev1 commands */
 
+#if 0
 static gint imap_cmd_authenticate(IMAPSession *session, const gchar *user,
                                  const gchar *pass, IMAPAuthType type)
 {
@@ -3148,848 +2229,248 @@ static gint imap_cmd_authenticate(IMAPSession *session, const gchar *user,
 
        return ok;
 }
-
-static gint imap_cmd_login(IMAPSession *session,
-                          const gchar *user, const gchar *pass)
-{
-       gchar *ans;
-       gint ok;
-
-       imap_gen_send(session, "LOGIN {%d}\r\n%s {%d}\r\n%s", 
-                               strlen(user), user, 
-                               strlen(pass), pass);
-                               
-       ok = imap_gen_recv_with_block(session, &ans, TRUE);
-       if (ok != IMAP_SUCCESS || ans[0] != '+' || ans[1] != ' ') {
-               g_free(ans);
-               return IMAP_ERROR;
-       }
-       g_free(ans);
-       ok = imap_gen_recv_with_block(session, &ans, TRUE);
-       if (ok != IMAP_SUCCESS || ans[0] != '+' || ans[1] != ' ') {
-               g_free(ans);
-               return IMAP_ERROR;
-       }
-       g_free(ans);
-       ok = imap_cmd_ok(session, NULL);
-       if (ok != IMAP_SUCCESS)
-               log_warning(_("IMAP4 login failed.\n"));
-
-       return ok;
-}
-
-static gint imap_cmd_logout(IMAPSession *session)
-{
-       imap_gen_send(session, "LOGOUT");
-       return imap_cmd_ok(session, NULL);
-}
-
-static gint imap_cmd_noop(IMAPSession *session)
-{
-       imap_gen_send(session, "NOOP");
-       return imap_cmd_ok(session, NULL);
-}
-
-#if USE_OPENSSL
-static gint imap_cmd_starttls(IMAPSession *session)
-{
-       imap_gen_send(session, "STARTTLS");
-       return imap_cmd_ok(session, NULL);
-}
 #endif
 
-#define THROW(err) { ok = err; goto catch; }
-
-static gint imap_cmd_namespace(IMAPSession *session, gchar **ns_str)
-{
-       gint ok;
-       GPtrArray *argbuf;
-       gchar *str;
-
-       argbuf = g_ptr_array_new();
-
-       imap_gen_send(session, "NAMESPACE");
-       if ((ok = imap_cmd_ok(session, argbuf)) != IMAP_SUCCESS) THROW(ok);
-
-       str = search_array_str(argbuf, "NAMESPACE");
-       if (!str) THROW(IMAP_ERROR);
-
-       *ns_str = g_strdup(str);
-
-catch:
-       ptr_array_free_strings(argbuf);
-       g_ptr_array_free(argbuf, TRUE);
-
-       return ok;
-}
-
-#undef THROW
-
-static gint imap_cmd_list(IMAPSession *session, const gchar *ref,
-                         const gchar *mailbox, GPtrArray *argbuf)
-{
-       gchar *ref_, *mailbox_;
-
-       if (!ref) ref = "\"\"";
-       if (!mailbox) mailbox = "\"\"";
-
-       QUOTE_IF_REQUIRED(ref_, ref);
-       QUOTE_IF_REQUIRED(mailbox_, mailbox);
-       imap_gen_send(session, "LIST %s %s", ref_, mailbox_);
-
-       return imap_cmd_ok(session, argbuf);
-}
-
-#define THROW goto catch
-
-static gint imap_cmd_do_select(IMAPSession *session, const gchar *folder,
-                              gboolean examine,
-                              gint *exists, gint *recent, gint *unseen,
-                              guint32 *uid_validity, gboolean block)
-{
-       gint ok;
-       gchar *resp_str;
-       GPtrArray *argbuf;
-       gchar *select_cmd;
-       gchar *folder_;
-       unsigned int uid_validity_;
-
-       *exists = *recent = *unseen = *uid_validity = 0;
-       argbuf = g_ptr_array_new();
-
-       if (examine)
-               select_cmd = "EXAMINE";
-       else
-               select_cmd = "SELECT";
-
-       QUOTE_IF_REQUIRED(folder_, folder);
-       imap_gen_send(session, "%s %s", select_cmd, folder_);
-
-       if ((ok = imap_cmd_ok_with_block(session, argbuf, block)) != IMAP_SUCCESS) THROW;
-
-       resp_str = search_array_contain_str(argbuf, "EXISTS");
-       if (resp_str) {
-               if (sscanf(resp_str,"%d EXISTS", exists) != 1) {
-                       g_warning("imap_cmd_select(): invalid EXISTS line.\n");
-                       THROW;
-               }
-       }
-
-       resp_str = search_array_contain_str(argbuf, "RECENT");
-       if (resp_str) {
-               if (sscanf(resp_str, "%d RECENT", recent) != 1) {
-                       g_warning("imap_cmd_select(): invalid RECENT line.\n");
-                       THROW;
-               }
-       }
-
-       resp_str = search_array_contain_str(argbuf, "UIDVALIDITY");
-       if (resp_str) {
-               if (sscanf(resp_str, "OK [UIDVALIDITY %u] ", &uid_validity_)
-                   != 1) {
-                       g_warning("imap_cmd_select(): invalid UIDVALIDITY line.\n");
-                       THROW;
-               }
-               *uid_validity = uid_validity_;
-       }
-
-       resp_str = search_array_contain_str(argbuf, "UNSEEN");
-       if (resp_str) {
-               if (sscanf(resp_str, "OK [UNSEEN %d] ", unseen) != 1) {
-                       g_warning("imap_cmd_select(): invalid UNSEEN line.\n");
-                       THROW;
-               }
-       }
-
-catch:
-       ptr_array_free_strings(argbuf);
-       g_ptr_array_free(argbuf, TRUE);
-
-       return ok;
-}
-
-static gint imap_cmd_select(IMAPSession *session, const gchar *folder,
-                           gint *exists, gint *recent, gint *unseen,
-                           guint32 *uid_validity, gboolean block)
-{
-       return imap_cmd_do_select(session, folder, FALSE,
-                                 exists, recent, unseen, uid_validity, block);
-}
-
-static gint imap_cmd_examine(IMAPSession *session, const gchar *folder,
-                            gint *exists, gint *recent, gint *unseen,
-                            guint32 *uid_validity, gboolean block)
-{
-       return imap_cmd_do_select(session, folder, TRUE,
-                                 exists, recent, unseen, uid_validity, block);
-}
-
-#undef THROW
-
-static gint imap_cmd_create(IMAPSession *session, const gchar *folder)
-{
-       gchar *folder_;
-
-       QUOTE_IF_REQUIRED(folder_, folder);
-       imap_gen_send(session, "CREATE %s", folder_);
-
-       return imap_cmd_ok(session, NULL);
-}
-
-static gint imap_cmd_rename(IMAPSession *session, const gchar *old_folder,
-                           const gchar *new_folder)
-{
-       gchar *old_folder_, *new_folder_;
-
-       QUOTE_IF_REQUIRED(old_folder_, old_folder);
-       QUOTE_IF_REQUIRED(new_folder_, new_folder);
-       imap_gen_send(session, "RENAME %s %s", old_folder_, new_folder_);
-
-       return imap_cmd_ok(session, NULL);
-}
-
-static gint imap_cmd_delete(IMAPSession *session, const gchar *folder)
-{
-       gchar *folder_;
-
-       QUOTE_IF_REQUIRED(folder_, folder);
-       imap_gen_send(session, "DELETE %s", folder_);
-
-       return imap_cmd_ok(session, NULL);
-}
-
-static gint imap_cmd_search(IMAPSession *session, const gchar *criteria, 
-                           GSList **list, gboolean block)
-{
-       gint ok;
-       gchar *uidlist;
-       GPtrArray *argbuf;
-
-       g_return_val_if_fail(criteria != NULL, IMAP_ERROR);
-       g_return_val_if_fail(list != NULL, IMAP_ERROR);
-
-       *list = NULL;
-       
-       argbuf = g_ptr_array_new();
-       imap_gen_send(session, "UID SEARCH %s", criteria);
-
-       ok = imap_cmd_ok_with_block(session, argbuf, block);
-       if (ok != IMAP_SUCCESS) {
-               ptr_array_free_strings(argbuf);
-               g_ptr_array_free(argbuf, TRUE);
-               return ok;
-       }
-
-       if ((uidlist = search_array_str(argbuf, "SEARCH ")) != NULL) {
-               gchar **strlist, **p;
-
-               strlist = g_strsplit(uidlist + 7, " ", 0);
-               for (p = strlist; *p != NULL; ++p) {
-                       guint msgnum;
-
-                       if (sscanf(*p, "%u", &msgnum) == 1)
-                               *list = g_slist_append(*list, GINT_TO_POINTER(msgnum));
-               }
-               g_strfreev(strlist);
-       }
-       ptr_array_free_strings(argbuf);
-       g_ptr_array_free(argbuf, TRUE);
-
-       return IMAP_SUCCESS;
-}
-
-typedef struct _fetch_data {
-       IMAPSession *session;
-       guint32 uid;
-       const gchar *filename;
-       gboolean headers;
-       gboolean body;
-       gboolean done;
-} fetch_data;
-
-static void *imap_cmd_fetch_thread(void *data)
-{
-       fetch_data *stuff = (fetch_data *)data;
-       IMAPSession *session = stuff->session;
-       guint32 uid = stuff->uid;
-       const gchar *filename = stuff->filename;
-       
-       gint ok;
-       gchar *buf = NULL;
-       gchar *cur_pos;
-       gchar size_str[32];
-       glong size_num;
-
-       if (filename == NULL) {
-               stuff->done = TRUE;
-               return GINT_TO_POINTER(IMAP_ERROR);
-       }
-       
-       if (stuff->body)
-               imap_gen_send(session, "UID FETCH %d BODY.PEEK[]", uid);
-       else
-               imap_gen_send(session, "UID FETCH %d BODY.PEEK[HEADER]",
-                               uid);
-       while ((ok = imap_gen_recv_block(session, &buf)) == IMAP_SUCCESS) {
-               if (buf[0] != '*' || buf[1] != ' ') {
-                       g_free(buf);
-                       stuff->done = TRUE;
-                       return GINT_TO_POINTER(IMAP_ERROR);
-               }
-               if (strstr(buf, "FETCH") != NULL) break;
-               g_free(buf);
-       }
-       if (ok != IMAP_SUCCESS) {
-               g_free(buf);
-               stuff->done = TRUE;
-               return GINT_TO_POINTER(ok);
-       }
-
-#define RETURN_ERROR_IF_FAIL(cond)     \
-       if (!(cond)) {                  \
-               g_free(buf);            \
-               stuff->done = TRUE;     \
-               return GINT_TO_POINTER(IMAP_ERROR);     \
-       }
-
-       cur_pos = strchr(buf, '{');
-       RETURN_ERROR_IF_FAIL(cur_pos != NULL);
-       cur_pos = strchr_cpy(cur_pos + 1, '}', size_str, sizeof(size_str));
-       RETURN_ERROR_IF_FAIL(cur_pos != NULL);
-       size_num = atol(size_str);
-       RETURN_ERROR_IF_FAIL(size_num >= 0);
-
-       RETURN_ERROR_IF_FAIL(*cur_pos == '\0');
-
-#undef RETURN_ERROR_IF_FAIL
-
-       g_free(buf);
-
-       if (recv_bytes_write_to_file(SESSION(session)->sock,
-                                    size_num, filename) != 0) {
-               stuff->done = TRUE;
-               return GINT_TO_POINTER(IMAP_ERROR);
-       }
-       if (imap_gen_recv_block(session, &buf) != IMAP_SUCCESS) {
-               g_free(buf);
-               stuff->done = TRUE;
-               return GINT_TO_POINTER(IMAP_ERROR);
-       }
-
-       if (buf[0] == '\0' || buf[strlen(buf) - 1] != ')') {
-               g_free(buf);
-               stuff->done = TRUE;
-               return GINT_TO_POINTER(IMAP_ERROR);
-       }
-       g_free(buf);
-
-       ok = imap_cmd_ok_block(session, NULL);
-
-       stuff->done = TRUE;
-       return GINT_TO_POINTER(ok);
-}
-
-static gint imap_cmd_fetch(IMAPSession *session, guint32 uid,
-                               const gchar *filename, gboolean headers,
-                               gboolean body)
-{
-       fetch_data *data = g_new0(fetch_data, 1);
-       int result = 0;
-#ifdef USE_PTHREAD
-       void *tmp;
-       pthread_t pt;
-#endif
-       data->done = FALSE;
-       data->session = session;
-       data->uid = uid;
-       data->filename = filename;
-       data->headers = headers;
-       data->body = body;
-
-       if (prefs_common.work_offline && !imap_gtk_should_override()) {
-               g_free(data);
-               return -1;
-       }
-
-#if (defined USE_PTHREAD && defined __GLIBC__ && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)))
-       MUTEX_TRYLOCK_OR_RETURN_VAL(-1);
-       if (pthread_create(&pt, PTHREAD_CREATE_JOINABLE,
-                       imap_cmd_fetch_thread, data) != 0) {
-               result = GPOINTER_TO_INT(imap_cmd_fetch_thread(data));
-               g_free(data);
-               MUTEX_UNLOCK();
-               return result;
-       }
-       debug_print("+++waiting for imap_cmd_fetch_thread...\n");
-       while(!data->done) {
-               /* don't let the interface freeze while waiting */
-               sylpheed_do_idle();
-       }
-       debug_print("---imap_cmd_fetch_thread done\n");
-
-       /* get the thread's return value and clean its resources */
-       pthread_join(pt, &tmp);
-       result = GPOINTER_TO_INT(tmp);
-       MUTEX_UNLOCK();
-#else
-       result = GPOINTER_TO_INT(imap_cmd_fetch_thread(data));
-#endif
-       g_free(data);
-       return result;
-}
-
-static gint imap_cmd_append(IMAPSession *session, const gchar *destfolder,
-                           const gchar *file, IMAPFlags flags, 
-                           guint32 *new_uid)
-{
-       gint ok;
-       gint size;
-       gchar *destfolder_;
-       gchar *flag_str;
-       unsigned int new_uid_;
-       gchar *ret = NULL;
-       gchar buf[BUFFSIZE];
-       FILE *fp;
-       GPtrArray *argbuf;
-       gchar *resp_str;
-
-       g_return_val_if_fail(file != NULL, IMAP_ERROR);
-
-       size = get_file_size_as_crlf(file);
-       if ((fp = fopen(file, "rb")) == NULL) {
-               FILE_OP_ERROR(file, "fopen");
-               return -1;
-       }
-       QUOTE_IF_REQUIRED(destfolder_, destfolder);
-       flag_str = imap_get_flag_str(flags);
-       imap_gen_send(session, "APPEND %s (%s) {%d}", 
-                     destfolder_, flag_str, size);
-       g_free(flag_str);
-
-       ok = imap_gen_recv(session, &ret);
-       if (ok != IMAP_SUCCESS || ret[0] != '+' || ret[1] != ' ') {
-               log_warning(_("can't append %s to %s\n"), file, destfolder_);
-               g_free(ret);
-               fclose(fp);
-               return IMAP_ERROR;
-       }
-       g_free(ret);
-
-       log_print("IMAP4> %s\n", "(sending file...)");
-
-       while (fgets(buf, sizeof(buf), fp) != NULL) {
-               strretchomp(buf);
-               if (sock_puts(SESSION(session)->sock, buf) < 0) {
-                       fclose(fp);
-                       return -1;
-               }
-       }
-
-       if (ferror(fp)) {
-               FILE_OP_ERROR(file, "fgets");
-               fclose(fp);
-               return -1;
-       }
-
-       sock_puts(SESSION(session)->sock, "");
-
-       fclose(fp);
-
-       if (new_uid != NULL)
-               *new_uid = 0;
-
-       if (new_uid != NULL && session->uidplus) {
-               argbuf = g_ptr_array_new();
-
-               ok = imap_cmd_ok(session, argbuf);
-               if ((ok == IMAP_SUCCESS) && (argbuf->len > 0)) {
-                       resp_str = g_ptr_array_index(argbuf, argbuf->len - 1);
-                       if (resp_str &&
-                           sscanf(resp_str, "%*u OK [APPENDUID %*u %u]",
-                                  &new_uid_) == 1) {
-                               *new_uid = new_uid_;
-                       }
-               }
-
-               ptr_array_free_strings(argbuf);
-               g_ptr_array_free(argbuf, TRUE);
-       } else
-               ok = imap_cmd_ok(session, NULL);
-
-       if (ok != IMAP_SUCCESS)
-               log_warning(_("can't append message to %s\n"),
-                           destfolder_);
+static gint imap_cmd_login(IMAPSession *session,
+                          const gchar *user, const gchar *pass)
+{
+       int r;
+       gint ok;
 
+       r = imap_threaded_login(session->folder, user, pass);
+       if (r != MAILIMAP_NO_ERROR)
+               ok = IMAP_ERROR;
+       else
+               ok = IMAP_SUCCESS;
+       
        return ok;
 }
 
-static MsgNumberList *imapset_to_numlist(IMAPSet imapset)
+static gint imap_cmd_logout(IMAPSession *session)
 {
-       gchar **ranges, **range;
-       unsigned int low, high;
-       MsgNumberList *uids = NULL;
+       imap_threaded_disconnect(session->folder);
        
-       ranges = g_strsplit(imapset, ",", 0);
-       for (range = ranges; *range != NULL; range++) {
-               if (sscanf(*range, "%u:%u", &low, &high) == 1)
-                       uids = g_slist_prepend(uids, GINT_TO_POINTER(low));
-               else {
-                       int i;
-                       for (i = low; i <= high; i++)
-                               uids = g_slist_prepend(uids, GINT_TO_POINTER(i));
-               }
-       }
-       uids = g_slist_reverse(uids);
-       g_strfreev(ranges);
-
-       return uids;
+       return IMAP_SUCCESS;
 }
 
-static gint imap_cmd_copy(IMAPSession *session, const gchar *seq_set,
-                         const gchar *destfolder, GRelation *uid_mapping)
+static gint imap_cmd_noop(IMAPSession *session)
 {
-       gint ok;
-       gchar *destfolder_;
+       int r;
        
-       g_return_val_if_fail(session != NULL, IMAP_ERROR);
-       g_return_val_if_fail(seq_set != NULL, IMAP_ERROR);
-       g_return_val_if_fail(destfolder != NULL, IMAP_ERROR);
+       r = imap_threaded_noop(session->folder);
+       if (r != MAILIMAP_NO_ERROR)
+               return IMAP_ERROR;
+       
+       return IMAP_SUCCESS;
+}
 
-       QUOTE_IF_REQUIRED(destfolder_, destfolder);
-       imap_gen_send(session, "UID COPY %s %s", seq_set, destfolder_);
-
-       if (uid_mapping != NULL && session->uidplus) {
-               GPtrArray *reply;               
-               gchar *resp_str = NULL, *olduids_str, *newuids_str;
-               MsgNumberList *olduids, *old_cur, *newuids, *new_cur;
-
-               reply = g_ptr_array_new();
-               ok = imap_cmd_ok(session, reply);
-               if ((ok == IMAP_SUCCESS) && (reply->len > 0)) {
-                       resp_str = g_ptr_array_index(reply, reply->len - 1);
-                       if (resp_str) {
-                               olduids_str = g_new0(gchar, strlen(resp_str));
-                               newuids_str = g_new0(gchar, strlen(resp_str));
-                               if (sscanf(resp_str, "%*s OK [COPYUID %*u %[0-9,:] %[0-9,:]]",
-                                          olduids_str, newuids_str) == 2) {
-                                       olduids = imapset_to_numlist(olduids_str);
-                                       newuids = imapset_to_numlist(newuids_str);
-
-                                       old_cur = olduids;
-                                       new_cur = newuids;
-                                       while(old_cur != NULL && new_cur != NULL) {
-                                               g_relation_insert(uid_mapping, 
-                                                                 GPOINTER_TO_INT(old_cur->data),
-                                                                 GPOINTER_TO_INT(new_cur->data));
-                                               old_cur = g_slist_next(old_cur);
-                                               new_cur = g_slist_next(new_cur);
-                                       }
+#if USE_OPENSSL
+static gint imap_cmd_starttls(IMAPSession *session)
+{
+       int r;
 
-                                       g_slist_free(olduids);
-                                       g_slist_free(newuids);
-                               }
-                               g_free(olduids_str);
-                               g_free(newuids_str);
-                       }
-               }
-               ptr_array_free_strings(reply);
-               g_ptr_array_free(reply, TRUE);
-       } else
-               ok = imap_cmd_ok(session, NULL);
+       r = imap_threaded_starttls(session->folder);
+       if (r != MAILIMAP_NO_ERROR)
+               return IMAP_ERROR;
+       
+       return IMAP_SUCCESS;
+}
+#endif
 
-       if (ok != IMAP_SUCCESS)
-               log_warning(_("can't copy %s to %s\n"), seq_set, destfolder_);
+static gint imap_cmd_select(IMAPSession *session, const gchar *folder,
+                           gint *exists, gint *recent, gint *unseen,
+                           guint32 *uid_validity, gboolean block)
+{
+       int r;
 
-       return ok;
+       r = imap_threaded_select(session->folder, folder,
+                                exists, recent, unseen, uid_validity);
+       if (r != MAILIMAP_NO_ERROR) {
+               return IMAP_ERROR;
+       }
+       
+       return IMAP_SUCCESS;
 }
 
-gint imap_cmd_envelope(IMAPSession *session, IMAPSet set)
+static gint imap_cmd_examine(IMAPSession *session, const gchar *folder,
+                            gint *exists, gint *recent, gint *unseen,
+                            guint32 *uid_validity, gboolean block)
 {
-       static gchar *header_fields = 
-               "Date From To Cc Subject Message-ID References In-Reply-To" ;
-
-       imap_gen_send
-               (session, "UID FETCH %s (UID FLAGS RFC822.SIZE BODY.PEEK[HEADER.FIELDS (%s)])",
-                set, header_fields);
+       int r;
 
+       r = imap_threaded_examine(session->folder, folder,
+                                 exists, recent, unseen, uid_validity);
+       if (r != MAILIMAP_NO_ERROR) {
+               return IMAP_ERROR;
+       }
+       
        return IMAP_SUCCESS;
 }
 
-static gint imap_cmd_store(IMAPSession *session, IMAPSet seq_set,
-                          gchar *sub_cmd)
+static gint imap_cmd_create(IMAPSession *session, const gchar *folder)
 {
-       gint ok;
-
-       imap_gen_send(session, "UID STORE %s %s", seq_set, sub_cmd);
+       int r;
+       
+       r = imap_threaded_create(session->folder, folder);
+       if (r != MAILIMAP_NO_ERROR)
+               return IMAP_ERROR;
+       
+       return IMAP_SUCCESS;
+}
 
-       if ((ok = imap_cmd_ok(session, NULL)) != IMAP_SUCCESS) {
-               log_warning(_("error while imap command: STORE %s %s\n"),
-                           seq_set, sub_cmd);
-               return ok;
-       }
+static gint imap_cmd_rename(IMAPSession *session, const gchar *old_folder,
+                           const gchar *new_folder)
+{
+       int r;
+       
+       r = imap_threaded_rename(session->folder, old_folder,
+                                new_folder);
+       if (r != MAILIMAP_NO_ERROR)
+               return IMAP_ERROR;
+       
+       return IMAP_SUCCESS;
+}
 
+static gint imap_cmd_delete(IMAPSession *session, const gchar *folder)
+{
+       int r;
+       
+       r = imap_threaded_delete(session->folder, folder);
+       if (r != MAILIMAP_NO_ERROR)
+               return IMAP_ERROR;
+       
        return IMAP_SUCCESS;
 }
 
-typedef struct _expunge_data {
+typedef struct _fetch_data {
        IMAPSession *session;
-       IMAPSet seq_set;
+       guint32 uid;
+       const gchar *filename;
+       gboolean headers;
+       gboolean body;
        gboolean done;
-} expunge_data;
+} fetch_data;
 
-static void *imap_cmd_expunge_thread(void *data)
+static void *imap_cmd_fetch_thread(void *data)
 {
-       expunge_data *stuff = (expunge_data *)data;
+       fetch_data *stuff = (fetch_data *)data;
        IMAPSession *session = stuff->session;
-       IMAPSet seq_set = stuff->seq_set;
-
-       gint ok;
-
-       if (seq_set && session->uidplus)
-               imap_gen_send(session, "UID EXPUNGE %s", seq_set);
-       else    
-               imap_gen_send(session, "EXPUNGE");
-       if ((ok = imap_cmd_ok_with_block(session, NULL, TRUE)) != IMAP_SUCCESS) {
-               log_warning(_("error while imap command: EXPUNGE\n"));
-               stuff->done = TRUE;
-               return GINT_TO_POINTER(ok);
+       guint32 uid = stuff->uid;
+       const gchar *filename = stuff->filename;
+       int r;
+       
+       if (stuff->body) {
+               r = imap_threaded_fetch_content(session->folder,
+                                              uid, 1, filename);
        }
-
-       stuff->done = TRUE;
+       else {
+               r = imap_threaded_fetch_content(session->folder,
+                                               uid, 0, filename);
+       }
+       if (r != MAILIMAP_NO_ERROR)
+               return GINT_TO_POINTER(IMAP_ERROR);
+       
        return GINT_TO_POINTER(IMAP_SUCCESS);
 }
 
-static gint imap_cmd_expunge(IMAPSession *session, IMAPSet seq_set)
+static gint imap_cmd_fetch(IMAPSession *session, guint32 uid,
+                               const gchar *filename, gboolean headers,
+                               gboolean body)
 {
-       expunge_data *data = g_new0(expunge_data, 1);
-       int result;
-#ifdef USE_PTHREAD
-       void *tmp;
-       pthread_t pt;
-#endif
+       fetch_data *data = g_new0(fetch_data, 1);
+       int result = 0;
        data->done = FALSE;
        data->session = session;
-       data->seq_set = seq_set;
+       data->uid = uid;
+       data->filename = filename;
+       data->headers = headers;
+       data->body = body;
 
        if (prefs_common.work_offline && !imap_gtk_should_override()) {
                g_free(data);
                return -1;
        }
 
-#if (defined USE_PTHREAD && defined __GLIBC__ && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)))
-       if (pthread_create(&pt, PTHREAD_CREATE_JOINABLE,
-                       imap_cmd_expunge_thread, data) != 0) {
-               result = GPOINTER_TO_INT(imap_cmd_expunge_thread(data));
-               g_free(data);
-               return result;
-       }
-       debug_print("+++waiting for imap_cmd_expunge_thread...\n");
-       while(!data->done) {
-               /* don't let the interface freeze while waiting */
-               sylpheed_do_idle();
-       }
-       debug_print("---imap_cmd_expunge_thread done\n");
-
-       /* get the thread's return value and clean its resources */
-       pthread_join(pt, &tmp);
-       result = GPOINTER_TO_INT(tmp);
-#else
-       result = GPOINTER_TO_INT(imap_cmd_expunge_thread(data));
-#endif
+       result = GPOINTER_TO_INT(imap_cmd_fetch_thread(data));
        g_free(data);
        return result;
 }
 
-static gint imap_cmd_close(IMAPSession *session)
-{
-       gint ok;
-
-       imap_gen_send(session, "CLOSE");
-       if ((ok = imap_cmd_ok(session, NULL)) != IMAP_SUCCESS)
-               log_warning(_("error while imap command: CLOSE\n"));
-
-       return ok;
-}
-
-static gint imap_cmd_ok_with_block(IMAPSession *session, GPtrArray *argbuf, gboolean block)
-{
-       gint ok = IMAP_SUCCESS;
-       gchar *buf;
-       gint cmd_num;
-       gchar *data;
-
-       while ((ok = imap_gen_recv_with_block(session, &buf, block))
-              == IMAP_SUCCESS) {
-               /* make sure data is long enough for any substring of buf */
-               data = alloca(strlen(buf) + 1);
-
-               /* untagged line read */
-               if (buf[0] == '*' && buf[1] == ' ') {
-                       gint num;
-                       if (argbuf)
-                               g_ptr_array_add(argbuf, g_strdup(buf + 2));
-
-                       if (sscanf(buf + 2, "%d %s", &num, data) >= 2) {
-                               if (!strcmp(data, "EXISTS")) {
-                                       session->exists = num;
-                                       session->folder_content_changed = TRUE;
-                               }
-
-                               if(!strcmp(data, "EXPUNGE")) {
-                                       session->exists--;
-                                       session->folder_content_changed = TRUE;
-                               }
-                       }
-               /* tagged line with correct tag and OK response found */
-               } else if ((sscanf(buf, "%d %s", &cmd_num, data) >= 2) &&
-                          (cmd_num == session->cmd_count) &&
-                          !strcmp(data, "OK")) {
-                       if (argbuf)
-                               g_ptr_array_add(argbuf, g_strdup(buf));
-                       break;
-               /* everything else */
-               } else {
-                       ok = IMAP_ERROR;
-                       break;
-               }
-               g_free(buf);
-       }
-       g_free(buf);
-
-       return ok;
-}
-static gint imap_cmd_ok(IMAPSession *session, GPtrArray *argbuf)
-{
-       return imap_cmd_ok_with_block(session, argbuf, FALSE);
-}
-static gint imap_cmd_ok_block(IMAPSession *session, GPtrArray *argbuf)
-{
-       return imap_cmd_ok_with_block(session, argbuf, TRUE);
-}
-static void imap_gen_send(IMAPSession *session, const gchar *format, ...)
-{
-       gchar *buf;
-       gchar *tmp;
-       gchar *p;
-       va_list args;
-
-       va_start(args, format);
-       tmp = g_strdup_vprintf(format, args);
-       va_end(args);
-
-       session->cmd_count++;
-
-       buf = g_strdup_printf("%d %s\r\n", session->cmd_count, tmp);
-       if (!g_ascii_strncasecmp(tmp, "LOGIN ", 6) && (p = strchr(tmp + 6, ' '))) {
-               *p = '\0';
-               log_print("IMAP4> %d %s ********\n", session->cmd_count, tmp);
-       } else
-               log_print("IMAP4> %d %s\n", session->cmd_count, tmp);
-
-       sock_write_all(SESSION(session)->sock, buf, strlen(buf));
-       g_free(tmp);
-       g_free(buf);
-}
 
-static gint imap_gen_recv_with_block(IMAPSession *session, gchar **ret, gboolean block)
+static gint imap_cmd_append(IMAPSession *session, const gchar *destfolder,
+                           const gchar *file, IMAPFlags flags, 
+                           guint32 *new_uid)
 {
-       if (!block) {
-               if ((*ret = imap_getline(SESSION(session)->sock)) == NULL)
-                       return IMAP_SOCKET;
-       } else {
-               if ((*ret = sock_getline(SESSION(session)->sock)) == NULL)
-                       return IMAP_SOCKET;
-       }
-       strretchomp(*ret);
+       struct mailimap_flag_list * flag_list;
+       int r;
+       
+       g_return_val_if_fail(file != NULL, IMAP_ERROR);
 
-       log_print("IMAP4< %s\n", *ret);
+       flag_list = imap_flag_to_lep(flags);
+       r = imap_threaded_append(session->folder, destfolder,
+                        file, flag_list);
        
-       session_set_access_time(SESSION(session));
+       if (new_uid != NULL)
+               *new_uid = 0;
 
+       if (r != MAILIMAP_NO_ERROR)
+               return IMAP_ERROR;
+       
        return IMAP_SUCCESS;
 }
 
-static gint imap_gen_recv_block(IMAPSession *session, gchar **ret)
-{
-       return imap_gen_recv_with_block(session, ret, TRUE);
-}
-
-static gint imap_gen_recv(IMAPSession *session, gchar **ret)
-{
-       return imap_gen_recv_with_block(session, ret, FALSE);
-}
-/* misc utility functions */
-
-static gchar *strchr_cpy(const gchar *src, gchar ch, gchar *dest, gint len)
-{
-       gchar *tmp;
-
-       dest[0] = '\0';
-       tmp = strchr(src, ch);
-       if (!tmp)
-               return NULL;
-
-       memcpy(dest, src, MIN(tmp - src, len - 1));
-       dest[MIN(tmp - src, len - 1)] = '\0';
-
-       return tmp + 1;
-}
-
-static gchar *get_quoted(const gchar *src, gchar ch, gchar *dest, gint len)
+static gint imap_cmd_copy(IMAPSession *session, struct mailimap_set * set,
+                         const gchar *destfolder, GRelation *uid_mapping)
 {
-       const gchar *p = src;
-       gint n = 0;
-
-       g_return_val_if_fail(*p == ch, NULL);
-
-       *dest = '\0';
-       p++;
-
-       while (*p != '\0' && *p != ch) {
-               if (n < len - 1) {
-                       if (*p == '\\' && *(p + 1) != '\0')
-                               p++;
-                       *dest++ = *p++;
-               } else
-                       p++;
-               n++;
-       }
+       int r;
+       
+       g_return_val_if_fail(session != NULL, IMAP_ERROR);
+       g_return_val_if_fail(set != NULL, IMAP_ERROR);
+       g_return_val_if_fail(destfolder != NULL, IMAP_ERROR);
 
-       *dest = '\0';
-       return (gchar *)(*p == ch ? p + 1 : p);
+       r = imap_threaded_copy(session->folder, set, destfolder);
+       if (r != MAILIMAP_NO_ERROR)
+               return IMAP_ERROR;
+       
+       return IMAP_SUCCESS;
 }
 
-static gchar *search_array_contain_str(GPtrArray *array, const gchar *str)
+static gint imap_cmd_store(IMAPSession *session, struct mailimap_set * set,
+                          IMAPFlags flags, int do_add)
 {
-       gint i;
-
-       for (i = 0; i < array->len; i++) {
-               gchar *tmp;
-
-               tmp = g_ptr_array_index(array, i);
-               if (strstr(tmp, str) != NULL)
-                       return tmp;
-       }
-
-       return NULL;
+       int r;
+       struct mailimap_flag_list * flag_list;
+       struct mailimap_store_att_flags * store_att_flags;
+       
+       flag_list = imap_flag_to_lep(flags);
+       
+       if (do_add)
+               store_att_flags =
+                       mailimap_store_att_flags_new_add_flags_silent(flag_list);
+       else
+               store_att_flags =
+                       mailimap_store_att_flags_new_remove_flags_silent(flag_list);
+       
+       r = imap_threaded_store(session->folder, set, store_att_flags);
+       if (r != MAILIMAP_NO_ERROR)
+               return IMAP_ERROR;
+       
+       return IMAP_SUCCESS;
 }
 
-static gchar *search_array_str(GPtrArray *array, const gchar *str)
+static gint imap_cmd_expunge(IMAPSession *session)
 {
-       gint i;
-       gint len;
-
-       len = strlen(str);
-
-       for (i = 0; i < array->len; i++) {
-               gchar *tmp;
-
-               tmp = g_ptr_array_index(array, i);
-               if (!strncmp(tmp, str, len))
-                       return tmp;
+       int r;
+       
+       if (prefs_common.work_offline && !imap_gtk_should_override()) {
+               return -1;
        }
-
-       return NULL;
+       
+       r = imap_threaded_expunge(session->folder);
+       if (r != MAILIMAP_NO_ERROR)
+               return IMAP_ERROR;
+       
+       return IMAP_SUCCESS;
 }
 
 static void imap_path_separator_subst(gchar *str, gchar separator)
@@ -4171,104 +2652,23 @@ static gchar *imap_utf8_to_modified_utf7(const gchar *from)
                        g_string_append_c(to_str, ',');
                } else if (in_escape && *p == '-') {
                        g_string_append_c(to_str, '-');
-                       in_escape = FALSE;
-               } else {
-                       g_string_append_c(to_str, *p);
-               }
-       }
-
-       if (in_escape) {
-               in_escape = FALSE;
-               g_string_append_c(to_str, '-');
-       }
-
-       to = to_str->str;
-       g_string_free(to_str, FALSE);
-
-       return to;
-}
-
-static GSList *imap_get_seq_set_from_numlist(MsgNumberList *numlist)
-{
-       GString *str;
-       GSList *sorted_list, *cur;
-       guint first, last, next;
-       gchar *ret_str;
-       GSList *ret_list = NULL;
-
-       if (numlist == NULL)
-               return NULL;
-
-       str = g_string_sized_new(256);
-
-       sorted_list = g_slist_copy(numlist);
-       sorted_list = g_slist_sort(sorted_list, g_int_compare);
-
-       first = GPOINTER_TO_INT(sorted_list->data);
-
-       for (cur = sorted_list; cur != NULL; cur = g_slist_next(cur)) {
-               if (GPOINTER_TO_INT(cur->data) == 0)
-                       continue;
-
-               last = GPOINTER_TO_INT(cur->data);
-               if (cur->next)
-                       next = GPOINTER_TO_INT(cur->next->data);
-               else
-                       next = 0;
-
-               if (last + 1 != next || next == 0) {
-                       if (str->len > 0)
-                               g_string_append_c(str, ',');
-                       if (first == last)
-                               g_string_append_printf(str, "%u", first);
-                       else
-                               g_string_append_printf(str, "%u:%u", first, last);
-
-                       first = next;
-
-                       if (str->len > IMAP_CMD_LIMIT) {
-                               ret_str = g_strdup(str->str);
-                               ret_list = g_slist_append(ret_list, ret_str);
-                               g_string_truncate(str, 0);
-                       }
+                       in_escape = FALSE;
+               } else {
+                       g_string_append_c(to_str, *p);
                }
        }
 
-       if (str->len > 0) {
-               ret_str = g_strdup(str->str);
-               ret_list = g_slist_append(ret_list, ret_str);
-       }
-
-       g_slist_free(sorted_list);
-       g_string_free(str, TRUE);
-
-       return ret_list;
-}
-
-static GSList *imap_get_seq_set_from_msglist(MsgInfoList *msglist)
-{
-       MsgNumberList *numlist = NULL;
-       MsgInfoList *cur;
-       GSList *seq_list;
-
-       for (cur = msglist; cur != NULL; cur = g_slist_next(cur)) {
-               MsgInfo *msginfo = (MsgInfo *) cur->data;
-
-               numlist = g_slist_append(numlist, GINT_TO_POINTER(msginfo->msgnum));
+       if (in_escape) {
+               in_escape = FALSE;
+               g_string_append_c(to_str, '-');
        }
-       seq_list = imap_get_seq_set_from_numlist(numlist);
-       g_slist_free(numlist);
 
-       return seq_list;
-}
+       to = to_str->str;
+       g_string_free(to_str, FALSE);
 
-static void imap_seq_set_free(GSList *seq_list)
-{
-       slist_free_strings(seq_list);
-       g_slist_free(seq_list);
+       return to;
 }
 
-
 static gboolean imap_rename_folder_func(GNode *node, gpointer data)
 {
        FolderItem *item = node->data;
@@ -4314,8 +2714,10 @@ static void *get_list_of_uids_thread(void *data)
        gint ok, nummsgs = 0, lastuid_old;
        IMAPSession *session;
        GSList *uidlist, *elem;
-       gchar *cmd_buf;
-
+       struct mailimap_set * set;
+       clist * lep_uidlist;
+       int r;
+       
        session = imap_session_get(folder);
        if (session == NULL) {
                stuff->done = TRUE;
@@ -4329,45 +2731,31 @@ static void *get_list_of_uids_thread(void *data)
                return GINT_TO_POINTER(-1);
        }
 
-       cmd_buf = g_strdup_printf("UID %d:*", item->lastuid + 1);
-       ok = imap_cmd_search(session, cmd_buf, &uidlist, TRUE);
-       g_free(cmd_buf);
-
-       if (ok == IMAP_SOCKET) {
-               session_destroy((Session *)session);
-               ((RemoteFolder *)folder)->session = NULL;
-               stuff->done = TRUE;
-               return GINT_TO_POINTER(-1);
-       }
-
-       if (ok != IMAP_SUCCESS) {
-               gint i;
-               GPtrArray *argbuf;
-
-               argbuf = g_ptr_array_new();
-
-               cmd_buf = g_strdup_printf("UID FETCH %d:* (UID)", item->lastuid + 1);
-               imap_gen_send(session, cmd_buf);
-               g_free(cmd_buf);
-               ok = imap_cmd_ok_block(session, argbuf);
-               if (ok != IMAP_SUCCESS) {
-                       ptr_array_free_strings(argbuf);
-                       g_ptr_array_free(argbuf, TRUE);
-                       stuff->done = TRUE;
-                       return GINT_TO_POINTER(-1);
-               }
-       
-               for(i = 0; i < argbuf->len; i++) {
-                       int ret, msgnum;
+       uidlist = NULL;
        
-                       if((ret = sscanf(g_ptr_array_index(argbuf, i), 
-                                   "%*d FETCH (UID %d)", &msgnum)) == 1)
-                               uidlist = g_slist_prepend(uidlist, GINT_TO_POINTER(msgnum));
+       set = mailimap_set_new_interval(item->lastuid + 1, 0);
+       r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_SIMPLE, set,
+                                &lep_uidlist);
+       if (r == MAILIMAP_NO_ERROR) {
+               GSList * fetchuid_list;
+               
+               fetchuid_list =
+                       imap_uid_list_from_lep(lep_uidlist);
+               uidlist = g_slist_concat(fetchuid_list, uidlist);
+       }
+       else {
+               GSList * fetchuid_list;
+               carray * lep_uidtab;
+               
+               r = imap_threaded_fetch_uid(folder, item->lastuid + 1,
+                                           &lep_uidtab);
+               if (r == MAILIMAP_NO_ERROR) {
+                       fetchuid_list =
+                               imap_uid_list_from_lep_tab(lep_uidtab);
+                       uidlist = g_slist_concat(fetchuid_list, uidlist);
                }
-               ptr_array_free_strings(argbuf);
-               g_ptr_array_free(argbuf, TRUE);
        }
-
+       
        lastuid_old = item->lastuid;
        *msgnum_list = g_slist_copy(item->uid_list);
        nummsgs = g_slist_length(*msgnum_list);
@@ -4396,10 +2784,6 @@ static gint get_list_of_uids(Folder *folder, IMAPFolderItem *item, GSList **msgn
 {
        gint result;
        get_list_uid_data *data = g_new0(get_list_uid_data, 1);
-#ifdef USE_PTHREAD
-       void *tmp;
-       pthread_t pt;
-#endif
        data->done = FALSE;
        data->folder = folder;
        data->item = item;
@@ -4410,26 +2794,7 @@ static gint get_list_of_uids(Folder *folder, IMAPFolderItem *item, GSList **msgn
                return -1;
        }
 
-#if (defined USE_PTHREAD && defined __GLIBC__ && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)))
-       if (pthread_create(&pt, PTHREAD_CREATE_JOINABLE,
-                       get_list_of_uids_thread, data) != 0) {
-               result = GPOINTER_TO_INT(get_list_of_uids_thread(data));
-               g_free(data);
-               return result;
-       }
-       debug_print("+++waiting for get_list_of_uids_thread...\n");
-       while(!data->done) {
-               /* don't let the interface freeze while waiting */
-               sylpheed_do_idle();
-       }
-       debug_print("---get_list_of_uids_thread done\n");
-
-       /* get the thread's return value and clean its resources */
-       pthread_join(pt, &tmp);
-       result = GPOINTER_TO_INT(tmp);
-#else
        result = GPOINTER_TO_INT(get_list_of_uids_thread(data));
-#endif
        g_free(data);
        return result;
 
@@ -4444,6 +2809,8 @@ gint imap_get_num_list(Folder *folder, FolderItem *_item, GSList **msgnum_list,
        gchar *dir;
        gboolean selected_folder;
        
+       debug_print("get_num_list\n");
+       
        g_return_val_if_fail(folder != NULL, -1);
        g_return_val_if_fail(item != NULL, -1);
        g_return_val_if_fail(item->item.path != NULL, -1);
@@ -4550,7 +2917,9 @@ gint imap_get_num_list(Folder *folder, FolderItem *_item, GSList **msgnum_list,
        remove_numbered_files_not_in_list(dir, *msgnum_list);
        g_free(dir);
        MUTEX_UNLOCK();
-
+       
+       debug_print("get_num_list - ok - %i\n", nummsgs);
+       
        return nummsgs;
 }
 
@@ -4580,12 +2949,15 @@ static MsgInfo *imap_parse_msg(const gchar *file, FolderItem *item)
        return msginfo;
 }
 
-GSList *imap_get_msginfos(Folder *folder, FolderItem *item, GSList *msgnum_list)
+GSList *imap_get_msginfos(Folder *folder, FolderItem *item,
+                         GSList *msgnum_list)
 {
        IMAPSession *session;
        MsgInfoList *ret = NULL;
        gint ok;
-
+       
+       debug_print("get_msginfos\n");
+       
        g_return_val_if_fail(folder != NULL, NULL);
        g_return_val_if_fail(item != NULL, NULL);
        g_return_val_if_fail(msgnum_list != NULL, NULL);
@@ -4601,8 +2973,8 @@ GSList *imap_get_msginfos(Folder *folder, FolderItem *item, GSList *msgnum_list)
 
        if (!(item->stype == F_QUEUE || item->stype == F_DRAFT)) {
                ret = g_slist_concat(ret,
-                       imap_get_uncached_messages(
-                       session, item, msgnum_list));
+                       imap_get_uncached_messages(session, item,
+                                                  msgnum_list));
        } else {
                MsgNumberList *sorted_list, *elem;
                gint startnum, lastnum;
@@ -4834,12 +3206,12 @@ static gint imap_remove_msg(Folder *folder, FolderItem *item, gint uid)
        }
 
        if (!session->uidplus) {
-               ok = imap_cmd_expunge(session, NULL);
+               ok = imap_cmd_expunge(session);
        } else {
                gchar *uidstr;
 
                uidstr = g_strdup_printf("%u", uid);
-               ok = imap_cmd_expunge(session, uidstr);
+               ok = imap_cmd_expunge(session);
                g_free(uidstr);
        }
        if (ok != IMAP_SUCCESS) {
@@ -4940,31 +3312,65 @@ static /*gint*/ void *imap_get_flags_thread(void *data)
                        return GINT_TO_POINTER(-1);
                }
 
+               if (unseen_cnt > exists_cnt / 2)
+                       reverse_seen = TRUE;
        } 
-
-       if (unseen_cnt > exists_cnt / 2)
-               reverse_seen = TRUE;
+       else {
+               if (item->unread_msgs > item->total_msgs / 2)
+                       reverse_seen = TRUE;
+       }
 
        cmd_buf = g_string_new(NULL);
 
        sorted_list = g_slist_sort(g_slist_copy(msginfo_list), compare_msginfo);
 
-       seq_list = imap_get_seq_set_from_msglist(msginfo_list);
+       seq_list = imap_get_lep_set_from_msglist(msginfo_list);
 
        for (cur = seq_list; cur != NULL; cur = g_slist_next(cur)) {
-               IMAPSet imapset = cur->data;
-
-               g_string_sprintf(cmd_buf, "%sSEEN UID %s", reverse_seen ? "" : "UN", imapset);
-               imap_cmd_search(session, cmd_buf->str, &p_unseen, TRUE);
-               unseen = g_slist_concat(unseen, p_unseen);
-
-               g_string_sprintf(cmd_buf, "ANSWERED UID %s", imapset);
-               imap_cmd_search(session, cmd_buf->str, &p_answered, TRUE);
-               answered = g_slist_concat(answered, p_answered);
+               struct mailimap_set * imapset;
+               clist * lep_uidlist;
+               int r;
+               
+               imapset = cur->data;
+               if (reverse_seen) {
+                       r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_SEEN,
+                                                imapset, &lep_uidlist);
+               }
+               else {
+                       r = imap_threaded_search(folder,
+                                                IMAP_SEARCH_TYPE_UNSEEN,
+                                                imapset, &lep_uidlist);
+               }
+               if (r == MAILIMAP_NO_ERROR) {
+                       GSList * uidlist;
+                       
+                       uidlist = imap_uid_list_from_lep(lep_uidlist);
+                       mailimap_search_result_free(lep_uidlist);
+                       
+                       unseen = g_slist_concat(unseen, uidlist);
+               }
+               
+               r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_ANSWERED,
+                                        imapset, &lep_uidlist);
+               if (r == MAILIMAP_NO_ERROR) {
+                       GSList * uidlist;
+                       
+                       uidlist = imap_uid_list_from_lep(lep_uidlist);
+                       mailimap_search_result_free(lep_uidlist);
+                       
+                       answered = g_slist_concat(answered, uidlist);
+               }
 
-               g_string_sprintf(cmd_buf, "FLAGGED UID %s", imapset);
-               imap_cmd_search(session, cmd_buf->str, &p_flagged, TRUE);
-               flagged = g_slist_concat(flagged, p_flagged);
+               r = imap_threaded_search(folder, IMAP_SEARCH_TYPE_FLAGGED,
+                                        imapset, &lep_uidlist);
+               if (r == MAILIMAP_NO_ERROR) {
+                       GSList * uidlist;
+                       
+                       uidlist = imap_uid_list_from_lep(lep_uidlist);
+                       mailimap_search_result_free(lep_uidlist);
+                       
+                       flagged = g_slist_concat(flagged, uidlist);
+               }
        }
 
        p_unseen = unseen;
@@ -4996,7 +3402,7 @@ static /*gint*/ void *imap_get_flags_thread(void *data)
                g_relation_insert(msgflags, msginfo, GINT_TO_POINTER(flags));
        }
 
-       imap_seq_set_free(seq_list);
+       imap_lep_set_free(seq_list);
        g_slist_free(flagged);
        g_slist_free(answered);
        g_slist_free(unseen);
@@ -5012,10 +3418,6 @@ static gint imap_get_flags(Folder *folder, FolderItem *item,
 {
        gint result;
        get_flags_data *data = g_new0(get_flags_data, 1);
-#ifdef USE_PTHREAD
-       void *tmp;
-       pthread_t pt;
-#endif
        data->done = FALSE;
        data->folder = folder;
        data->item = item;
@@ -5027,29 +3429,8 @@ static gint imap_get_flags(Folder *folder, FolderItem *item,
                return -1;
        }
 
-#if (defined USE_PTHREAD && defined __GLIBC__ && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)))
-       MUTEX_TRYLOCK_OR_RETURN_VAL(-1);
-       if (pthread_create(&pt, PTHREAD_CREATE_JOINABLE,
-                       imap_get_flags_thread, data) != 0) {
-               result = GPOINTER_TO_INT(imap_get_flags_thread(data));
-               g_free(data);
-               MUTEX_UNLOCK();
-               return result;
-       }
-       debug_print("+++waiting for imap_get_flags_thread...\n");
-       while(!data->done) {
-               /* don't let the interface freeze while waiting */
-               sylpheed_do_idle();
-       }
-       debug_print("---imap_get_flags_thread done\n");
-
-       /* get the thread's return value and clean its resources */
-       pthread_join(pt, &tmp);
-       result = GPOINTER_TO_INT(tmp);
-       MUTEX_UNLOCK();
-#else
        result = GPOINTER_TO_INT(imap_get_flags_thread(data));
-#endif
+       
        g_free(data);
        return result;
 
@@ -5128,3 +3509,299 @@ static void imap_set_batch (Folder *folder, FolderItem *_item, gboolean batch)
                process_hashtable();
        }
 }
+
+
+
+/* data types conversion libetpan <-> sylpheed */
+
+
+
+#define ETPAN_IMAP_MB_MARKED      1
+#define ETPAN_IMAP_MB_UNMARKED    2
+#define ETPAN_IMAP_MB_NOSELECT    4
+#define ETPAN_IMAP_MB_NOINFERIORS 8
+
+static int imap_flags_to_flags(struct mailimap_mbx_list_flags * imap_flags)
+{
+  int flags;
+  clistiter * cur;
+  
+  flags = 0;
+  if (imap_flags->mbf_type == MAILIMAP_MBX_LIST_FLAGS_SFLAG) {
+    switch (imap_flags->mbf_sflag) {
+    case MAILIMAP_MBX_LIST_SFLAG_MARKED:
+      flags |= ETPAN_IMAP_MB_MARKED;
+      break;
+    case MAILIMAP_MBX_LIST_SFLAG_NOSELECT:
+      flags |= ETPAN_IMAP_MB_NOSELECT;
+      break;
+    case MAILIMAP_MBX_LIST_SFLAG_UNMARKED:
+      flags |= ETPAN_IMAP_MB_UNMARKED;
+      break;
+    }
+  }
+  
+  for(cur = clist_begin(imap_flags->mbf_oflags) ; cur != NULL ;
+      cur = clist_next(cur)) {
+    struct mailimap_mbx_list_oflag * oflag;
+    
+    oflag = clist_content(cur);
+    
+    switch (oflag->of_type) {
+    case MAILIMAP_MBX_LIST_OFLAG_NOINFERIORS:
+      flags |= ETPAN_IMAP_MB_NOINFERIORS;
+      break;
+    }
+  }
+  
+  return flags;
+}
+
+static GSList * imap_list_from_lep(IMAPFolder * folder,
+                                  clist * list, const gchar * real_path)
+{
+       clistiter * iter;
+       GSList * item_list;
+       
+       item_list = NULL;
+       
+       for(iter = clist_begin(list) ; iter != NULL ;
+           iter = clist_next(iter)) {
+               struct mailimap_mailbox_list * mb;
+               int flags;
+               char delimiter;
+               char * name;
+               char * dup_name;
+               gchar * base;
+               gchar * loc_name;
+               gchar * loc_path;
+               FolderItem *new_item;
+               
+               mb = clist_content(iter);
+               
+               flags = 0;
+               if (mb->mb_flag != NULL)
+                       flags = imap_flags_to_flags(mb->mb_flag);
+               
+               delimiter = mb->mb_delimiter;
+               name = mb->mb_name;
+               
+               dup_name = strdup(name);                
+               if (delimiter != '\0')
+                       subst_char(dup_name, delimiter, '/');
+               
+               base = g_path_get_basename(dup_name);
+               if (base[0] == '.') {
+                       g_free(base);
+                       free(dup_name);
+                       continue;
+               }
+               
+               if (strcmp(dup_name, real_path) == 0) {
+                       g_free(base);
+                       free(dup_name);
+                       continue;
+               }
+               
+               loc_name = imap_modified_utf7_to_utf8(base);
+               loc_path = imap_modified_utf7_to_utf8(dup_name);
+               
+               new_item = folder_item_new(FOLDER(folder), loc_name, loc_path);
+               if ((flags & ETPAN_IMAP_MB_NOINFERIORS) != 0)
+                       new_item->no_sub = TRUE;
+               if (strcmp(dup_name, "INBOX") != 0 &&
+                   ((flags & ETPAN_IMAP_MB_NOSELECT) != 0))
+                       new_item->no_select = TRUE;
+               
+               item_list = g_slist_append(item_list, new_item);
+               
+               debug_print("folder '%s' found.\n", loc_path);
+               g_free(base);
+               g_free(loc_path);
+               g_free(loc_name);
+               
+               free(dup_name);
+       }
+       
+       return item_list;
+}
+
+static GSList * imap_get_lep_set_from_numlist(MsgNumberList *numlist)
+{
+       GSList *sorted_list, *cur;
+       guint first, last, next;
+       GSList *ret_list = NULL;
+       unsigned int count;
+       struct mailimap_set * current_set;
+       unsigned int item_count;
+       
+       if (numlist == NULL)
+               return NULL;
+       
+       count = 0;
+       current_set = mailimap_set_new_empty();
+       
+       sorted_list = g_slist_copy(numlist);
+       sorted_list = g_slist_sort(sorted_list, g_int_compare);
+
+       first = GPOINTER_TO_INT(sorted_list->data);
+       
+       item_count = 0;
+       for (cur = sorted_list; cur != NULL; cur = g_slist_next(cur)) {
+               if (GPOINTER_TO_INT(cur->data) == 0)
+                       continue;
+               
+               item_count ++;
+               
+               last = GPOINTER_TO_INT(cur->data);
+               if (cur->next)
+                       next = GPOINTER_TO_INT(cur->next->data);
+               else
+                       next = 0;
+
+               if (last + 1 != next || next == 0) {
+
+                       struct mailimap_set_item * item;
+                       item = mailimap_set_item_new(first, last);
+                       mailimap_set_add(current_set, item);
+                       count ++;
+                       
+                       first = next;
+                       
+                       if (count >= IMAP_SET_MAX_COUNT) {
+                               ret_list = g_slist_append(ret_list,
+                                                         current_set);
+                               current_set = mailimap_set_new_empty();
+                               count = 0;
+                               item_count = 0;
+                       }
+               }
+       }
+       
+       if (clist_count(current_set->set_list) > 0) {
+               ret_list = g_slist_append(ret_list,
+                                         current_set);
+       }
+       
+       g_slist_free(sorted_list);
+
+       return ret_list;
+}
+
+static GSList * imap_get_lep_set_from_msglist(MsgInfoList *msglist)
+{
+       MsgNumberList *numlist = NULL;
+       MsgInfoList *cur;
+       GSList *seq_list;
+
+       for (cur = msglist; cur != NULL; cur = g_slist_next(cur)) {
+               MsgInfo *msginfo = (MsgInfo *) cur->data;
+
+               numlist = g_slist_append(numlist, GINT_TO_POINTER(msginfo->msgnum));
+       }
+       seq_list = imap_get_lep_set_from_numlist(numlist);
+       g_slist_free(numlist);
+
+       return seq_list;
+}
+
+static GSList * imap_uid_list_from_lep(clist * list)
+{
+       clistiter * iter;
+       GSList * result;
+       
+       result = NULL;
+       
+       for(iter = clist_begin(list) ; iter != NULL ;
+           iter = clist_next(iter)) {
+               uint32_t * puid;
+               
+               puid = clist_content(iter);
+               result = g_slist_append(result, GINT_TO_POINTER(* puid));
+       }
+       
+       return result;
+}
+
+static GSList * imap_uid_list_from_lep_tab(carray * list)
+{
+       unsigned int i;
+       GSList * result;
+       
+       result = NULL;
+       
+       for(i = 0 ; i < carray_count(list) ; i ++) {
+               uint32_t * puid;
+               
+               puid = carray_get(list, i);
+               result = g_slist_append(result, GINT_TO_POINTER(* puid));
+       }
+       
+       return result;
+}
+
+static MsgInfo *imap_envelope_from_lep(struct imap_fetch_env_info * info,
+                                      FolderItem *item)
+{
+       MsgInfo *msginfo = NULL;
+       guint32 uid = 0;
+       size_t size = 0;
+       MsgFlags flags = {0, 0};
+       
+       MSG_SET_TMP_FLAGS(flags, MSG_IMAP);
+       if (item->stype == F_QUEUE) {
+               MSG_SET_TMP_FLAGS(flags, MSG_QUEUED);
+       } else if (item->stype == F_DRAFT) {
+               MSG_SET_TMP_FLAGS(flags, MSG_DRAFT);
+       }
+       flags.perm_flags = info->flags;
+       
+       uid = info->uid;
+       size = info->size;
+       msginfo = procheader_parse_str(info->headers, flags, FALSE, FALSE);
+       
+       if (msginfo) {
+               msginfo->msgnum = uid;
+               msginfo->size = size;
+       }
+
+       return msginfo;
+}
+
+static void imap_lep_set_free(GSList *seq_list)
+{
+       GSList * cur;
+       
+       for(cur = seq_list ; cur != NULL ; cur = g_slist_next(cur)) {
+               struct mailimap_set * imapset;
+               
+               imapset = cur->data;
+               mailimap_set_free(imapset);
+       }
+       g_slist_free(seq_list);
+}
+
+static struct mailimap_flag_list * imap_flag_to_lep(IMAPFlags flags)
+{
+       struct mailimap_flag_list * flag_list;
+       
+       flag_list = mailimap_flag_list_new_empty();
+       
+       if (IMAP_IS_SEEN(flags))
+               mailimap_flag_list_add(flag_list,
+                                      mailimap_flag_new_seen());
+       if (IMAP_IS_ANSWERED(flags))
+               mailimap_flag_list_add(flag_list,
+                                      mailimap_flag_new_answered());
+       if (IMAP_IS_FLAGGED(flags))
+               mailimap_flag_list_add(flag_list,
+                                      mailimap_flag_new_flagged());
+       if (IMAP_IS_DELETED(flags))
+               mailimap_flag_list_add(flag_list,
+                                      mailimap_flag_new_deleted());
+       if (IMAP_IS_DRAFT(flags))
+               mailimap_flag_list_add(flag_list,
+                                      mailimap_flag_new_draft());
+       
+       return flag_list;
+}
index 6aa62eb..b769df4 100644 (file)
@@ -89,6 +89,7 @@
 #include "imap_gtk.h"
 #include "news_gtk.h"
 #include "matcher.h"
+#include "imap-thread.h"
 
 #if USE_OPENSSL
 #  include "ssl.h"
@@ -334,7 +335,8 @@ int main(int argc, char *argv[])
 #endif
        
        sock_set_io_timeout(prefs_common.io_timeout_secs);
-
+       imap_main_set_timeout(prefs_common.io_timeout_secs);
+       
        prefs_actions_read_config();
        prefs_display_header_read_config();
        /* prefs_filtering_read_config(); */
@@ -375,6 +377,8 @@ int main(int argc, char *argv[])
                        exit_sylpheed(mainwin);
        }
 
+       imap_main_init();
+       
        account_set_missing_folder();
        folder_set_missing_folders();
        folderview_set(folderview);
@@ -468,6 +472,8 @@ static void exit_sylpheed(MainWindow *mainwin)
 
        debug_print("shutting down\n");
 
+       imap_main_done();
+       
        inc_autocheck_timer_remove();
 
        if (prefs_common.clean_on_exit)
index d8aa7bf..1225720 100644 (file)
@@ -38,6 +38,7 @@
 #include "gtk/prefswindow.h"
 
 #include "manage_window.h"
+#include "imap-thread.h"
 
 typedef struct _OtherPage
 {
@@ -235,6 +236,7 @@ void prefs_other_save(PrefsPage *_page)
        prefs_common.io_timeout_secs = gtk_spin_button_get_value_as_int(
                GTK_SPIN_BUTTON(page->spinbtn_iotimeout));
        sock_set_io_timeout(prefs_common.io_timeout_secs);
+       imap_main_set_timeout(prefs_common.io_timeout_secs);
        mainwindow = mainwindow_get_mainwindow();
        log_window_set_clipping(mainwindow->logwin, prefs_common.cliplog,
                                prefs_common.loglength);