Since we depend on GLib 2.28, make real use of GList/GSList's _free_full
[claws.git] / src / main.c
1 /*
2  * Claws Mail -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2016 Hiroyuki Yamamoto and the Claws Mail team
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  */
18
19 #ifdef HAVE_CONFIG_H
20 #  include "config.h"
21 #include "claws-features.h"
22 #endif
23
24 #include "defs.h"
25
26 #include <glib.h>
27 #include <glib/gi18n.h>
28 #include <gtk/gtk.h>
29
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <ctype.h>
34 #include <unistd.h>
35 #include <time.h>
36 #include <sys/stat.h>
37 #include <sys/types.h>
38 #ifdef G_OS_UNIX
39 #  include <signal.h>
40 #  include <errno.h>
41 #  include <fcntl.h>
42 #endif
43 #ifdef HAVE_LIBSM
44 #include <X11/SM/SMlib.h>
45 #endif
46
47 #if HAVE_FLOCK
48 #include <sys/file.h>
49 #endif
50
51 #include "file_checker.h"
52 #include "wizard.h"
53 #ifdef HAVE_STARTUP_NOTIFICATION
54 # define SN_API_NOT_YET_FROZEN
55 # include <libsn/sn-launchee.h>
56 # include <gdk/gdkx.h>
57 #endif
58
59 #ifdef HAVE_DBUS_GLIB
60 #include <dbus/dbus-glib.h>
61 #endif
62 #ifdef HAVE_NETWORKMANAGER_SUPPORT
63 #include <NetworkManager.h>
64 #endif
65 #ifdef HAVE_VALGRIND
66 #include <valgrind.h>
67 #endif
68 #ifdef HAVE_SVG
69 #include <librsvg/rsvg.h>
70 #endif
71
72 #include "claws.h"
73 #include "main.h"
74 #include "mainwindow.h"
75 #include "folderview.h"
76 #include "image_viewer.h"
77 #include "summaryview.h"
78 #include "prefs_common.h"
79 #include "prefs_account.h"
80 #include "prefs_actions.h"
81 #include "prefs_ext_prog.h"
82 #include "prefs_fonts.h"
83 #include "prefs_image_viewer.h"
84 #include "prefs_message.h"
85 #include "prefs_migration.h"
86 #include "prefs_receive.h"
87 #include "prefs_msg_colors.h"
88 #include "prefs_quote.h"
89 #include "prefs_spelling.h"
90 #include "prefs_summaries.h"
91 #include "prefs_themes.h"
92 #include "prefs_other.h"
93 #include "prefs_logging.h"
94 #include "prefs_send.h"
95 #include "prefs_wrapping.h"
96 #include "prefs_compose_writing.h"
97 #include "prefs_display_header.h"
98 #include "account.h"
99 #include "procmsg.h"
100 #include "inc.h"
101 #include "imap.h"
102 #include "send_message.h"
103 #include "md5.h"
104 #include "import.h"
105 #include "manage_window.h"
106 #include "alertpanel.h"
107 #include "statusbar.h"
108 #ifndef USE_ALT_ADDRBOOK
109         #include "addressbook.h"
110 #else
111         #include "addressbook-dbus.h"
112 #endif
113 #include "compose.h"
114 #include "folder.h"
115 #include "folder_item_prefs.h"
116 #include "setup.h"
117 #include "utils.h"
118 #include "gtkutils.h"
119 #include "socket.h"
120 #include "log.h"
121 #include "prefs_toolbar.h"
122 #include "plugin.h"
123 #include "mh_gtk.h"
124 #include "imap_gtk.h"
125 #include "news_gtk.h"
126 #include "matcher.h"
127 #include "tags.h"
128 #include "hooks.h"
129 #include "menu.h"
130 #include "quicksearch.h"
131 #include "advsearch.h"
132 #include "avatars.h"
133 #include "passwordstore.h"
134
135 #ifdef HAVE_LIBETPAN
136 #include "imap-thread.h"
137 #include "nntp-thread.h"
138 #endif
139 #include "stock_pixmap.h"
140 #ifdef USE_GNUTLS
141 #  include "ssl.h"
142 #endif
143
144 #include "version.h"
145
146 #include "crash.h"
147
148 #include "timing.h"
149
150 #ifdef HAVE_NETWORKMANAGER_SUPPORT
151 /* Went offline due to NetworkManager */
152 static gboolean went_offline_nm;
153 #endif
154
155
156 #ifdef HAVE_DBUS_GLIB
157 static DBusGProxy *awn_proxy = NULL;
158 #endif
159
160 gchar *prog_version;
161 #if (defined HAVE_LIBSM || defined CRASH_DIALOG)
162 gchar *argv0;
163 #endif
164
165 #ifdef HAVE_STARTUP_NOTIFICATION
166 static SnLauncheeContext *sn_context = NULL;
167 static SnDisplay *sn_display = NULL;
168 #endif
169
170 static gint lock_socket = -1;
171 static gint lock_socket_tag = 0;
172 static gchar *x_display = NULL;
173 typedef enum 
174 {
175         ONLINE_MODE_DONT_CHANGE,
176         ONLINE_MODE_ONLINE,
177         ONLINE_MODE_OFFLINE
178 } OnlineMode;
179
180 static struct RemoteCmd {
181         gboolean receive;
182         gboolean receive_all;
183         gboolean cancel_receiving;
184         gboolean cancel_sending;
185         gboolean compose;
186         const gchar *compose_mailto;
187         GList *attach_files;
188         gboolean search;
189         const gchar *search_folder;
190         const gchar *search_type;
191         const gchar *search_request;
192         gboolean search_recursive;
193         gboolean status;
194         gboolean status_full;
195         gboolean statistics;
196         gboolean reset_statistics;
197         GPtrArray *status_folders;
198         GPtrArray *status_full_folders;
199         gboolean send;
200         gboolean crash;
201         int online_mode;
202         gchar   *crash_params;
203         gboolean exit;
204         gboolean subscribe;
205         const gchar *subscribe_uri;
206         const gchar *target;
207         gboolean debug;
208         const gchar *geometry;
209 } cmd;
210
211 SessionStats session_stats;
212
213 static void reset_statistics(void);
214                 
215 static void parse_cmd_opt(int argc, char *argv[]);
216
217 static gint prohibit_duplicate_launch   (void);
218 static gchar * get_crashfile_name       (void);
219 static gint lock_socket_remove          (void);
220 static void lock_socket_input_cb        (gpointer          data,
221                                          gint              source,
222                                          GIOCondition      condition);
223
224 static void open_compose_new            (const gchar    *address,
225                                          GList          *attach_files);
226
227 static void send_queue                  (void);
228 static void initial_processing          (FolderItem *item, gpointer data);
229 static void quit_signal_handler         (int sig);
230 static void install_basic_sighandlers   (void);
231 #if (defined linux && defined SIGIO)
232 static void install_memory_sighandler   (void);
233 #endif
234 static void exit_claws                  (MainWindow *mainwin);
235
236 #ifdef HAVE_NETWORKMANAGER_SUPPORT
237 static void networkmanager_state_change_cb(DBusGProxy *proxy, gchar *dev,
238                                                                                                                                                                          gpointer data);
239 #endif
240
241 #define MAKE_DIR_IF_NOT_EXIST(dir) \
242 { \
243         if (!is_dir_exist(dir)) { \
244                 if (is_file_exist(dir)) { \
245                         alertpanel_warning \
246                                 (_("File '%s' already exists.\n" \
247                                    "Can't create folder."), \
248                                  dir); \
249                         return 1; \
250                 } \
251                 if (make_dir(dir) < 0) \
252                         return 1; \
253         } \
254 }
255
256 static MainWindow *static_mainwindow;
257
258 static gboolean emergency_exit = FALSE;
259
260 #ifdef HAVE_STARTUP_NOTIFICATION
261 static void sn_error_trap_push(SnDisplay *display, Display *xdisplay)
262 {
263         gdk_error_trap_push();
264 }
265
266 static void sn_error_trap_pop(SnDisplay *display, Display *xdisplay)
267 {
268         gdk_error_trap_pop();
269 }
270
271 static void startup_notification_complete(gboolean with_window)
272 {
273         Display *xdisplay;
274         GtkWidget *hack = NULL;
275
276         if (with_window) {
277                 /* this is needed to make the startup notification leave,
278                  * if we have been launched from a menu.
279                  * We have to display a window, so let it be very little */
280                 hack = gtk_window_new(GTK_WINDOW_POPUP);
281                 gtk_window_move(GTK_WINDOW(hack), 0, 0);
282                 gtk_widget_set_size_request(hack, 1, 1);
283                 gtk_widget_show(hack);
284         }
285
286         xdisplay = GDK_DISPLAY_XDISPLAY(gdk_display_get_default());
287         sn_display = sn_display_new(xdisplay,
288                                 sn_error_trap_push,
289                                 sn_error_trap_pop);
290         sn_context = sn_launchee_context_new_from_environment(sn_display,
291                                                  DefaultScreen(xdisplay));
292
293         if (sn_context != NULL) {
294                 sn_launchee_context_complete(sn_context);
295                 sn_launchee_context_unref(sn_context);
296                 sn_display_unref(sn_display);
297         }
298         if (with_window) {
299                 gtk_widget_destroy(hack);
300         }
301 }
302 #endif /* HAVE_STARTUP_NOTIFICATION */
303
304 static void claws_gtk_idle(void) 
305 {
306         while(gtk_events_pending()) {
307                 gtk_main_iteration();
308         }
309         g_usleep(50000);
310 }
311
312 static gboolean sc_starting = FALSE;
313
314 static gboolean defer_check_all(void *data)
315 {
316         gboolean autochk = GPOINTER_TO_INT(data);
317
318         inc_all_account_mail(static_mainwindow, autochk, 
319                         prefs_common.newmail_notify_manu);
320
321         if (sc_starting) {
322                 sc_starting = FALSE;
323                 main_window_set_menu_sensitive(static_mainwindow);
324                 toolbar_main_set_sensitive(static_mainwindow);
325         }
326         return FALSE;
327 }
328
329 static gboolean defer_check(void *data)
330 {
331         inc_mail(static_mainwindow, prefs_common.newmail_notify_manu);
332
333         if (sc_starting) {
334                 sc_starting = FALSE;
335                 main_window_set_menu_sensitive(static_mainwindow);
336                 toolbar_main_set_sensitive(static_mainwindow);
337         }
338         return FALSE;
339 }
340
341 static gboolean defer_jump(void *data)
342 {
343         if (cmd.receive_all) {
344                 defer_check_all(GINT_TO_POINTER(FALSE));
345         } else if (prefs_common.chk_on_startup) {
346                 defer_check_all(GINT_TO_POINTER(TRUE));
347         } else if (cmd.receive) {
348                 defer_check(NULL);
349         } 
350         mainwindow_jump_to(data, FALSE);
351         if (sc_starting) {
352                 sc_starting = FALSE;
353                 main_window_set_menu_sensitive(static_mainwindow);
354                 toolbar_main_set_sensitive(static_mainwindow);
355         }
356         return FALSE;
357 }
358
359 static void chk_update_val(GtkWidget *widget, gpointer data)
360 {
361         gboolean *val = (gboolean *)data;
362         *val = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget));
363 }
364
365 static gboolean migrate_old_config(const gchar *old_cfg_dir, const gchar *new_cfg_dir, const gchar *oldversion)
366 {
367         gchar *message = g_strdup_printf(_("Configuration for %s found.\n"
368                          "Do you want to migrate this configuration?"), oldversion);
369         gchar *message2 = g_strdup_printf(_("\n\nYour Sylpheed filtering rules can be converted by a\n"
370                              "script available at %s."), TOOLS_URI);
371
372         if (!strcmp(oldversion, "Sylpheed"))
373                 message = g_strconcat(message, message2, NULL);
374         g_free(message2);
375
376         gint r = 0;
377         GtkWidget *window = NULL;
378         GtkWidget *keep_backup_chk;
379         gboolean backup = TRUE;
380
381         keep_backup_chk = gtk_check_button_new_with_label (_("Keep old configuration"));
382         gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(keep_backup_chk), TRUE);
383         CLAWS_SET_TIP(keep_backup_chk,
384                              _("Keeping a backup will allow you to go back to an "
385                                "older version, but may take a while if you have "
386                                "cached IMAP or News data, and will take some extra "
387                                "room on your disk."));
388
389         g_signal_connect(G_OBJECT(keep_backup_chk), "toggled", 
390                         G_CALLBACK(chk_update_val), &backup);
391
392         if (alertpanel_full(_("Migration of configuration"), message,
393                         GTK_STOCK_NO, GTK_STOCK_YES, NULL, ALERTFOCUS_SECOND, FALSE,
394                         keep_backup_chk, ALERT_QUESTION) != G_ALERTALTERNATE) {
395                 return FALSE;
396         }
397         
398         /* we can either do a fast migration requiring not any extra disk
399          * space, or a slow one that copies the old configuration and leaves
400          * it in place. */
401         if (backup) {
402 backup_mode:
403                 window = label_window_create(_("Copying configuration... This may take a while..."));
404                 GTK_EVENTS_FLUSH();
405                 
406                 r = copy_dir(old_cfg_dir, new_cfg_dir);
407                 label_window_destroy(window);
408                 
409                 /* if copy failed, we'll remove the partially copied
410                  * new directory */
411                 if (r != 0) {
412                         alertpanel_error(_("Migration failed!"));
413                         remove_dir_recursive(new_cfg_dir);
414                 } else {
415                         if (!backup) {
416                                 /* fast mode failed, but we don't want backup */
417                                 remove_dir_recursive(old_cfg_dir);
418                         }
419                 }
420         } else {
421                 window = label_window_create(_("Migrating configuration..."));
422                 GTK_EVENTS_FLUSH();
423                 
424                 r = g_rename(old_cfg_dir, new_cfg_dir);
425                 label_window_destroy(window);
426                 
427                 /* if g_rename failed, we'll try to copy */
428                 if (r != 0) {
429                         FILE_OP_ERROR(new_cfg_dir, "g_rename");
430                         debug_print("rename failed, trying copy\n");
431                         goto backup_mode;
432                 }
433         }
434         return (r == 0);
435 }
436
437 static int migrate_common_rc(const gchar *old_rc, const gchar *new_rc)
438 {
439         FILE *oldfp, *newfp;
440         gchar *plugin_path, *old_plugin_path, *new_plugin_path;
441         gchar buf[BUFFSIZE];
442         gboolean err = FALSE;
443
444         oldfp = g_fopen(old_rc, "r");
445         if (!oldfp)
446                 return -1;
447         newfp = g_fopen(new_rc, "w");
448         if (!newfp) {
449                 fclose(oldfp);
450                 return -1;
451         }
452         
453         plugin_path = g_strdup(get_plugin_dir());
454         new_plugin_path = g_strdup(plugin_path);
455         
456         if (strstr(plugin_path, "/claws-mail/")) {
457                 gchar *end = g_strdup(strstr(plugin_path, "/claws-mail/")+strlen("/claws-mail/"));
458                 *(strstr(plugin_path, "/claws-mail/")) = '\0';
459                 old_plugin_path = g_strconcat(plugin_path, "/sylpheed-claws/", end, NULL);
460                 g_free(end);
461         } else {
462                 old_plugin_path = g_strdup(new_plugin_path);
463         }
464         debug_print("replacing %s with %s\n", old_plugin_path, new_plugin_path);
465         while (fgets(buf, sizeof(buf), oldfp)) {
466                 if (strncmp(buf, old_plugin_path, strlen(old_plugin_path))) {
467                         err |= (fputs(buf, newfp) == EOF);
468                 } else {
469                         debug_print("->replacing %s\n", buf);
470                         debug_print("  with %s%s\n", new_plugin_path, buf+strlen(old_plugin_path));
471                         err |= (fputs(new_plugin_path, newfp) == EOF);
472                         err |= (fputs(buf+strlen(old_plugin_path), newfp) == EOF);
473                 }
474         }
475         g_free(plugin_path);
476         g_free(new_plugin_path);
477         g_free(old_plugin_path);
478         fclose(oldfp);
479         if (fclose(newfp) == EOF)
480                 err = TRUE;
481         
482         return (err ? -1:0);
483 }
484
485 #ifdef HAVE_LIBSM
486 static void
487 sc_client_set_value (MainWindow *mainwin,
488                   gchar       *name,
489                   char        *type,
490                   int          num_vals,
491                   SmPropValue *vals)
492 {
493         SmProp *proplist[1];
494         SmProp prop;
495
496         prop.name = name;
497         prop.type = type;
498         prop.num_vals = num_vals;
499         prop.vals = vals;
500
501         proplist[0]= &prop;
502         if (mainwin->smc_conn)
503                 SmcSetProperties ((SmcConn) mainwin->smc_conn, 1, proplist);
504 }
505
506 static void sc_die_callback (SmcConn smc_conn, SmPointer client_data)
507 {
508         clean_quit(NULL);
509 }
510
511 static void sc_save_complete_callback(SmcConn smc_conn, SmPointer client_data)
512 {
513 }
514
515 static void sc_shutdown_cancelled_callback (SmcConn smc_conn, SmPointer client_data)
516 {
517         MainWindow *mainwin = (MainWindow *)client_data;
518         if (mainwin->smc_conn)
519                 SmcSaveYourselfDone ((SmcConn) mainwin->smc_conn, TRUE);
520 }
521
522 static void sc_save_yourself_callback (SmcConn   smc_conn,
523                                SmPointer client_data,
524                                int       save_style,
525                                gboolean  shutdown,
526                                int       interact_style,
527                                gboolean  fast) {
528
529         MainWindow *mainwin = (MainWindow *)client_data;
530         if (mainwin->smc_conn)
531                 SmcSaveYourselfDone ((SmcConn) mainwin->smc_conn, TRUE);
532 }
533
534 static IceIOErrorHandler sc_ice_installed_handler;
535
536 static void sc_ice_io_error_handler (IceConn connection)
537 {
538         if (sc_ice_installed_handler)
539                 (*sc_ice_installed_handler) (connection);
540 }
541 static gboolean sc_process_ice_messages (GIOChannel   *source,
542                                          GIOCondition  condition,
543                                          gpointer      data)
544 {
545         IceConn connection = (IceConn) data;
546         IceProcessMessagesStatus status;
547
548         status = IceProcessMessages (connection, NULL, NULL);
549
550         if (status == IceProcessMessagesIOError) {
551                 IcePointer context = IceGetConnectionContext (connection);
552
553                 if (context && G_IS_OBJECT(context)) {
554                 guint disconnect_id = g_signal_lookup ("disconnect", G_OBJECT_TYPE (context));
555
556                 if (disconnect_id > 0)
557                         g_signal_emit (context, disconnect_id, 0);
558                 } else {
559                         IceSetShutdownNegotiation (connection, False);
560                         IceCloseConnection (connection);
561                 }
562         }
563
564         return TRUE;
565 }
566
567 static void new_ice_connection (IceConn connection, IcePointer client_data, Bool opening,
568                     IcePointer *watch_data)
569 {
570         guint input_id;
571
572         if (opening) {
573                 GIOChannel *channel;
574                 /* Make sure we don't pass on these file descriptors to any
575                 exec'ed children */
576                 fcntl(IceConnectionNumber(connection),F_SETFD,
577                 fcntl(IceConnectionNumber(connection),F_GETFD,0) | FD_CLOEXEC);
578
579                 channel = g_io_channel_unix_new (IceConnectionNumber (connection));
580                 input_id = g_io_add_watch (channel,
581                 G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_PRI,
582                 sc_process_ice_messages,
583                 connection);
584                 g_io_channel_unref (channel);
585
586                 *watch_data = (IcePointer) GUINT_TO_POINTER (input_id);
587         } else {
588                 input_id = GPOINTER_TO_UINT ((gpointer) *watch_data);
589                 g_source_remove (input_id);
590         }
591 }
592
593 static void sc_session_manager_connect(MainWindow *mainwin)
594 {
595         static gboolean connected = FALSE;
596         SmcCallbacks      callbacks;
597         gchar            *client_id;
598         IceIOErrorHandler default_handler;
599
600         if (connected)
601                 return;
602         connected = TRUE;
603
604
605         sc_ice_installed_handler = IceSetIOErrorHandler (NULL);
606         default_handler = IceSetIOErrorHandler (sc_ice_io_error_handler);
607
608         if (sc_ice_installed_handler == default_handler)
609                 sc_ice_installed_handler = NULL;
610
611         IceAddConnectionWatch (new_ice_connection, NULL);
612       
613       
614         callbacks.save_yourself.callback      = sc_save_yourself_callback;
615         callbacks.die.callback                = sc_die_callback;
616         callbacks.save_complete.callback      = sc_save_complete_callback;
617         callbacks.shutdown_cancelled.callback = sc_shutdown_cancelled_callback;
618
619         callbacks.save_yourself.client_data =
620                 callbacks.die.client_data =
621                 callbacks.save_complete.client_data =
622                 callbacks.shutdown_cancelled.client_data = (SmPointer) mainwin;
623         if (g_getenv ("SESSION_MANAGER")) {
624                 gchar error_string_ret[256] = "";
625
626                 mainwin->smc_conn = (gpointer)
627                         SmcOpenConnection (NULL, mainwin,
628                                 SmProtoMajor, SmProtoMinor,
629                                 SmcSaveYourselfProcMask | SmcDieProcMask |
630                                 SmcSaveCompleteProcMask |
631                                 SmcShutdownCancelledProcMask,
632                                 &callbacks,
633                                 NULL, &client_id,
634                                 256, error_string_ret);
635
636                 if (error_string_ret[0] || mainwin->smc_conn == NULL)
637                         g_warning ("While connecting to session manager: %s.",
638                                 error_string_ret);
639                 else {
640                         SmPropValue *vals;
641                         vals = g_new (SmPropValue, 1);
642                         vals[0].length = strlen(argv0);
643                         vals[0].value = argv0;
644                         sc_client_set_value (mainwin, SmCloneCommand, SmLISTofARRAY8, 1, vals);
645                         sc_client_set_value (mainwin, SmRestartCommand, SmLISTofARRAY8, 1, vals);
646                         sc_client_set_value (mainwin, SmProgram, SmARRAY8, 1, vals);
647
648                         vals[0].length = strlen(g_get_user_name()?g_get_user_name():"");
649                         vals[0].value = g_strdup(g_get_user_name()?g_get_user_name():"");
650                         sc_client_set_value (mainwin, SmUserID, SmARRAY8, 1, vals);
651
652                         g_free(vals[0].value);
653                         g_free(vals);
654                 }
655         }
656 }
657 #endif
658
659 static gboolean sc_exiting = FALSE;
660 static gboolean show_at_startup = TRUE;
661 static gboolean claws_crashed_bool = FALSE;
662
663 gboolean claws_crashed(void) {
664         return claws_crashed_bool;
665 }
666
667 void main_set_show_at_startup(gboolean show)
668 {
669         show_at_startup = show;
670 }
671
672 #ifdef G_OS_WIN32
673 static FILE* win32_debug_fp=NULL;
674 static guint win32_log_handler_app_id;
675 static guint win32_log_handler_glib_id;
676 static guint win32_log_handler_gtk_id;
677
678 static void win32_print_stdout(const gchar *string)
679 {
680         if (win32_debug_fp) {
681                 fprintf(win32_debug_fp, "%s", string);
682                 fflush(win32_debug_fp);
683         }
684 }
685
686 static void win32_print_stderr(const gchar *string)
687 {
688         if (win32_debug_fp) {
689                 fprintf(win32_debug_fp, "%s", string);
690                 fflush(win32_debug_fp);
691         }
692 }
693
694 static void win32_log(const gchar *log_domain, GLogLevelFlags log_level, const gchar* message, gpointer user_data)
695 {
696         if (win32_debug_fp) {
697                 const gchar* type;
698
699                 switch(log_level & G_LOG_LEVEL_MASK)
700                 {
701                         case G_LOG_LEVEL_ERROR:
702                                 type="error";
703                                 break;
704                         case G_LOG_LEVEL_CRITICAL:
705                                 type="critical";
706                                 break;
707                         case G_LOG_LEVEL_WARNING:
708                                 type="warning";
709                                 break;
710                         case G_LOG_LEVEL_MESSAGE:
711                                 type="message";
712                                 break;
713                         case G_LOG_LEVEL_INFO:
714                                 type="info";
715                                 break;
716                         case G_LOG_LEVEL_DEBUG:
717                                 type="debug";
718                                 break;
719                         default:
720                                 type="N/A";
721                 }
722                 if (log_domain)
723                         fprintf(win32_debug_fp, "%s: %s: %s", log_domain, type, message);
724                 else
725                         fprintf(win32_debug_fp, "%s: %s", type, message);
726                 fflush(win32_debug_fp);
727         }
728 }
729
730 static void win32_open_log(void)
731 {
732         gchar *logfile = g_strconcat(g_get_tmp_dir(), G_DIR_SEPARATOR_S, "claws-win32.log", NULL);
733         gchar *oldlogfile = g_strconcat(g_get_tmp_dir(), G_DIR_SEPARATOR_S, "claws-win32.log.bak", NULL);
734
735         if (is_file_exist(logfile)) {
736                 if (rename_force(logfile, oldlogfile) < 0)
737                         FILE_OP_ERROR(logfile, "rename");
738         }
739         win32_debug_fp = g_fopen(logfile, "w");
740         g_free(logfile);
741         g_free(oldlogfile);
742         if (win32_debug_fp)
743         {
744                 g_set_print_handler(win32_print_stdout);
745                 g_set_printerr_handler(win32_print_stdout);
746                 win32_log_handler_app_id = g_log_set_handler(NULL, G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL
747                      | G_LOG_FLAG_RECURSION, win32_log, NULL);
748                 win32_log_handler_glib_id = g_log_set_handler("GLib", G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL
749                      | G_LOG_FLAG_RECURSION, win32_log, NULL);
750                 win32_log_handler_gtk_id = g_log_set_handler("Gtk", G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL
751                      | G_LOG_FLAG_RECURSION, win32_log, NULL);
752         }
753 }
754
755 static void win32_close_log(void)
756 {
757         if (win32_debug_fp)
758         {
759                 g_log_remove_handler("", win32_log_handler_app_id);
760                 g_log_remove_handler("GLib", win32_log_handler_glib_id);
761                 g_log_remove_handler("Gtk", win32_log_handler_gtk_id);
762                 fclose(win32_debug_fp);
763                 win32_debug_fp=NULL;
764         }
765 }               
766 #endif
767
768 static void main_dump_features_list(gboolean show_debug_only)
769 /* display compiled-in features list */
770 {
771         if (show_debug_only && !debug_get_mode())
772                 return;
773
774         if (show_debug_only)
775                 debug_print("runtime GTK+ %d.%d.%d / GLib %d.%d.%d\n",
776                            gtk_major_version, gtk_minor_version, gtk_micro_version,
777                            glib_major_version, glib_minor_version, glib_micro_version);
778         else
779                 g_print("runtime GTK+ %d.%d.%d / GLib %d.%d.%d\n",
780                            gtk_major_version, gtk_minor_version, gtk_micro_version,
781                            glib_major_version, glib_minor_version, glib_micro_version);
782         if (show_debug_only)
783                 debug_print("buildtime GTK+ %d.%d.%d / GLib %d.%d.%d\n",
784                            GTK_MAJOR_VERSION, GTK_MINOR_VERSION, GTK_MICRO_VERSION,
785                            GLIB_MAJOR_VERSION, GLIB_MINOR_VERSION, GLIB_MICRO_VERSION);
786         else
787                 g_print("buildtime GTK+ %d.%d.%d / GLib %d.%d.%d\n",
788                            GTK_MAJOR_VERSION, GTK_MINOR_VERSION, GTK_MICRO_VERSION,
789                            GLIB_MAJOR_VERSION, GLIB_MINOR_VERSION, GLIB_MICRO_VERSION);
790         
791         if (show_debug_only)
792                 debug_print("Compiled-in features:\n");
793         else
794                 g_print("Compiled-in features:\n");
795 #if HAVE_LIBCOMPFACE
796         if (show_debug_only)
797                 debug_print(" compface\n");
798         else
799                 g_print(" compface\n");
800 #endif
801 #if USE_ENCHANT
802         if (show_debug_only)
803                 debug_print(" Enchant\n");
804         else
805                 g_print(" Enchant\n");
806 #endif
807 #if USE_GNUTLS
808         if (show_debug_only)
809                 debug_print(" GnuTLS\n");
810         else
811                 g_print(" GnuTLS\n");
812 #endif
813 #if INET6
814         if (show_debug_only)
815                 debug_print(" IPv6\n");
816         else
817                 g_print(" IPv6\n");
818 #endif
819 #if HAVE_ICONV
820         if (show_debug_only)
821                 debug_print(" iconv\n");
822         else
823                 g_print(" iconv\n");
824 #endif
825 #if USE_JPILOT
826         if (show_debug_only)
827                 debug_print(" JPilot\n");
828         else
829                 g_print(" JPilot\n");
830 #endif
831 #if USE_LDAP
832         if (show_debug_only)
833                 debug_print(" LDAP\n");
834         else
835                 g_print(" LDAP\n");
836 #endif
837 #if HAVE_LIBETPAN
838         if (show_debug_only)
839                 debug_print(" libetpan %d.%d\n", LIBETPAN_VERSION_MAJOR, LIBETPAN_VERSION_MINOR);
840         else
841                 g_print(" libetpan %d.%d\n", LIBETPAN_VERSION_MAJOR, LIBETPAN_VERSION_MINOR);
842 #endif
843 #if HAVE_LIBSM
844         if (show_debug_only)
845                 debug_print(" libSM\n");
846         else
847                 g_print(" libSM\n");
848 #endif
849 #if HAVE_NETWORKMANAGER_SUPPORT
850         if (show_debug_only)
851                 debug_print(" NetworkManager\n");
852         else
853                 g_print(" NetworkManager\n");
854 #endif
855 #if HAVE_SVG
856         if (show_debug_only)
857                 debug_print(" librSVG " LIBRSVG_VERSION "\n");
858         else
859                 g_print(" librSVG " LIBRSVG_VERSION "\n");
860 #endif
861 }
862
863 #ifdef HAVE_DBUS_GLIB
864 static gulong dbus_item_hook_id = HOOK_NONE;
865 static gulong dbus_folder_hook_id = HOOK_NONE;
866
867 static void uninstall_dbus_status_handler(void)
868 {
869         if(awn_proxy)
870                 g_object_unref(awn_proxy);
871         awn_proxy = NULL;
872         if (dbus_item_hook_id != HOOK_NONE)
873                 hooks_unregister_hook(FOLDER_ITEM_UPDATE_HOOKLIST, dbus_item_hook_id);
874         if (dbus_folder_hook_id != HOOK_NONE)
875                 hooks_unregister_hook(FOLDER_UPDATE_HOOKLIST, dbus_folder_hook_id);
876 }
877
878 static void dbus_update(FolderItem *removed_item)
879 {
880         guint new, unread, unreadmarked, marked, total;
881         guint replied, forwarded, locked, ignored, watched;
882         gchar *buf;
883         GError *error = NULL;
884
885         folder_count_total_msgs(&new, &unread, &unreadmarked, &marked, &total,
886                                 &replied, &forwarded, &locked, &ignored,
887                                 &watched);
888         if (removed_item) {
889                 total -= removed_item->total_msgs;
890                 new -= removed_item->new_msgs;
891                 unread -= removed_item->unread_msgs;
892         }
893
894         if (new > 0) {
895                 buf = g_strdup_printf("%d", new);
896                 dbus_g_proxy_call(awn_proxy, "SetInfoByName", &error,
897                         G_TYPE_STRING, "claws-mail",
898                         G_TYPE_STRING, buf,
899                         G_TYPE_INVALID, G_TYPE_INVALID);
900                 g_free(buf);
901                 
902         } else {
903                 dbus_g_proxy_call(awn_proxy, "UnsetInfoByName", &error, G_TYPE_STRING,
904                         "claws-mail", G_TYPE_INVALID, G_TYPE_INVALID);
905         }
906         if (error) {
907                 debug_print("%s\n", error->message);
908                 g_error_free(error);
909         }
910 }
911
912 static gboolean dbus_status_update_folder_hook(gpointer source, gpointer data)
913 {
914         FolderUpdateData *hookdata;
915         hookdata = source;
916         if (hookdata->update_flags & FOLDER_REMOVE_FOLDERITEM)
917                 dbus_update(hookdata->item);
918         else
919                 dbus_update(NULL);
920
921         return FALSE;
922 }
923
924 static gboolean dbus_status_update_item_hook(gpointer source, gpointer data)
925 {
926         dbus_update(NULL);
927
928         return FALSE;
929 }
930
931 static void install_dbus_status_handler(void)
932 {
933         GError *tmp_error = NULL;
934         DBusGConnection *connection = dbus_g_bus_get(DBUS_BUS_SESSION, &tmp_error);
935         
936         if(!connection) {
937                 /* If calling code doesn't do error checking, at least print some debug */
938                 debug_print("Failed to open connection to session bus: %s\n",
939                                  tmp_error->message);
940                 g_error_free(tmp_error);
941                 return;
942         }
943         awn_proxy = dbus_g_proxy_new_for_name(connection,
944                         "com.google.code.Awn",
945                         "/com/google/code/Awn",
946                         "com.google.code.Awn");
947         dbus_item_hook_id = hooks_register_hook (FOLDER_ITEM_UPDATE_HOOKLIST, dbus_status_update_item_hook, NULL);
948         if (dbus_item_hook_id == HOOK_NONE) {
949                 g_warning("Failed to register folder item update hook");
950                 uninstall_dbus_status_handler();
951                 return;
952         }
953
954         dbus_folder_hook_id = hooks_register_hook (FOLDER_UPDATE_HOOKLIST, dbus_status_update_folder_hook, NULL);
955         if (dbus_folder_hook_id == HOOK_NONE) {
956                 g_warning("Failed to register folder update hook");
957                 uninstall_dbus_status_handler();
958                 return;
959         }
960 }
961 #endif
962
963 static void reset_statistics(void)
964 {
965         /* (re-)initialize session statistics */
966         session_stats.received = 0;
967         session_stats.sent = 0;
968         session_stats.replied = 0;
969         session_stats.forwarded = 0;
970         session_stats.time_started = time(NULL);
971 }
972
973 int main(int argc, char *argv[])
974 {
975 #ifdef HAVE_DBUS_GLIB
976         DBusGConnection *connection;
977         GError *error;
978 #endif
979 #ifdef HAVE_NETWORKMANAGER_SUPPORT
980         DBusGProxy *nm_proxy;
981 #endif
982         gchar *userrc;
983         MainWindow *mainwin;
984         FolderView *folderview;
985         GdkPixbuf *icon;
986         gboolean crash_file_present = FALSE;
987         guint num_folder_class = 0;
988         gboolean asked_for_migration = FALSE;
989         gboolean start_done = TRUE;
990         GSList *plug_list = NULL;
991         gboolean never_ran = FALSE;
992         gboolean mainwin_shown = FALSE;
993         gint ret;
994
995         START_TIMING("startup");
996
997         sc_starting = TRUE;
998
999 #ifdef G_OS_WIN32
1000         win32_open_log();
1001 #endif
1002         if (!claws_init(&argc, &argv)) {
1003 #ifdef G_OS_WIN32
1004                 win32_close_log();
1005 #endif
1006                 return 0;
1007         }
1008
1009         prog_version = PROG_VERSION;
1010 #if (defined HAVE_LIBSM || defined CRASH_DIALOG)
1011         argv0 = g_strdup(argv[0]);
1012 #endif
1013
1014         parse_cmd_opt(argc, argv);
1015
1016         sock_init();
1017
1018         /* check and create unix domain socket for remote operation */
1019         lock_socket = prohibit_duplicate_launch();
1020         if (lock_socket < 0) {
1021 #ifdef HAVE_STARTUP_NOTIFICATION
1022                 if(gtk_init_check(&argc, &argv))
1023                         startup_notification_complete(TRUE);
1024 #endif
1025                 return 0;
1026         }
1027
1028         main_dump_features_list(TRUE);
1029         prefs_prepare_cache();
1030
1031 #ifdef CRASH_DIALOG
1032         if (cmd.crash) {
1033 #if !GTK_CHECK_VERSION(3, 0, 0)
1034                 gtk_set_locale();
1035 #endif
1036                 gtk_init(&argc, &argv);
1037                 crash_main(cmd.crash_params);
1038 #ifdef G_OS_WIN32
1039                 win32_close_log();
1040 #endif
1041                 return 0;
1042         }
1043         crash_install_handlers();
1044 #endif
1045         install_basic_sighandlers();
1046 #if (defined linux && defined SIGIO)
1047         install_memory_sighandler();
1048 #endif
1049
1050         if (cmd.status || cmd.status_full || cmd.search ||
1051                 cmd.statistics || cmd.reset_statistics || 
1052                 cmd.cancel_receiving || cmd.cancel_sending ||
1053                 cmd.debug) {
1054                 puts("0 Claws Mail not running.");
1055                 lock_socket_remove();
1056                 return 0;
1057         }
1058         
1059         if (cmd.exit)
1060                 return 0;
1061 #if !GLIB_CHECK_VERSION(2,32,0)
1062         if (!g_thread_supported())
1063                 g_thread_init(NULL);
1064 #endif
1065
1066         reset_statistics();
1067         
1068 #if !GTK_CHECK_VERSION(3, 0, 0)
1069         gtk_set_locale();
1070 #endif
1071         gtk_init(&argc, &argv);
1072
1073 #ifdef G_OS_WIN32
1074         gtk_settings_set_string_property(gtk_settings_get_default(),
1075                         "gtk-theme-name",
1076                         "MS-Windows",
1077                         "XProperty");
1078         gtk_settings_set_long_property(gtk_settings_get_default(),
1079                         "gtk-auto-mnemonics",
1080                         TRUE,
1081                         "XProperty");
1082         gtk_settings_set_long_property(gtk_settings_get_default(),
1083                         "gtk-button-images",
1084                         TRUE,
1085                         "XProperty");
1086 #endif
1087
1088 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1089         went_offline_nm = FALSE;
1090         nm_proxy = NULL;
1091 #endif
1092 #ifdef HAVE_DBUS_GLIB
1093         error = NULL;
1094         connection = dbus_g_bus_get(DBUS_BUS_SYSTEM, &error);
1095
1096         if(!connection) {
1097                 debug_print("Failed to open connection to system bus: %s\n", error->message);
1098                 g_error_free(error);
1099         }
1100         else {
1101 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1102                 nm_proxy = dbus_g_proxy_new_for_name(connection,
1103                         "org.freedesktop.NetworkManager",
1104                         "/org/freedesktop/NetworkManager",
1105                         "org.freedesktop.NetworkManager");
1106                 if (nm_proxy) {
1107                         dbus_g_proxy_add_signal(nm_proxy, "StateChanged", G_TYPE_UINT, G_TYPE_INVALID);
1108                         dbus_g_proxy_connect_signal(nm_proxy, "StateChanged",
1109                                 G_CALLBACK(networkmanager_state_change_cb),
1110                                 NULL,NULL);
1111                 }
1112 #endif
1113                 install_dbus_status_handler();
1114         }
1115 #endif
1116
1117 #if !GTK_CHECK_VERSION(3, 0, 0)
1118         gtk_widget_set_default_colormap(
1119                 gdk_screen_get_system_colormap(
1120                         gdk_screen_get_default()));
1121 #endif
1122
1123         gtkut_create_ui_manager();
1124
1125         /* Create container for all the menus we will be adding */
1126         MENUITEM_ADDUI("/", "Menus", NULL, GTK_UI_MANAGER_MENUBAR);
1127
1128         if (!g_thread_supported()) {
1129                 g_error(_("g_thread is not supported by glib.\n"));
1130         }
1131
1132 #ifdef G_OS_WIN32
1133         CHDIR_EXEC_CODE_RETURN_VAL_IF_FAIL(get_home_dir(), 1, win32_close_log(););
1134 #else
1135         CHDIR_RETURN_VAL_IF_FAIL(get_home_dir(), 1);
1136 #endif
1137         
1138         /* no config dir exists. See if we can migrate an old config. */
1139         if (!is_dir_exist(get_rc_dir())) {
1140                 prefs_destroy_cache();
1141                 gboolean r = FALSE;
1142                 
1143                 /* if one of the old dirs exist, we'll ask if the user 
1144                  * want to migrates, and r will be TRUE if he said yes
1145                  * and migration succeeded, and FALSE otherwise.
1146                  */
1147                 if (is_dir_exist(OLD_GTK2_RC_DIR)) {
1148                         r = migrate_old_config(OLD_GTK2_RC_DIR, get_rc_dir(),
1149                                                g_strconcat("Sylpheed-Claws 2.6.0 ", _("(or older)"), NULL));
1150                         asked_for_migration = TRUE;
1151                 } else if (is_dir_exist(OLDER_GTK2_RC_DIR)) {
1152                         r = migrate_old_config(OLDER_GTK2_RC_DIR, get_rc_dir(),
1153                                                g_strconcat("Sylpheed-Claws 1.9.15 ",_("(or older)"), NULL));
1154                         asked_for_migration = TRUE;
1155                 } else if (is_dir_exist(OLD_GTK1_RC_DIR)) {
1156                         r = migrate_old_config(OLD_GTK1_RC_DIR, get_rc_dir(),
1157                                                g_strconcat("Sylpheed-Claws 1.0.5 ",_("(or older)"), NULL));
1158                         asked_for_migration = TRUE;
1159                 } else if (is_dir_exist(SYLPHEED_RC_DIR)) {
1160                         r = migrate_old_config(SYLPHEED_RC_DIR, get_rc_dir(), "Sylpheed");
1161                         asked_for_migration = TRUE;
1162                 }
1163                 
1164                 /* If migration failed or the user didn't want to do it,
1165                  * we create a new one (and we'll hit wizard later). 
1166                  */
1167                 if (r == FALSE && !is_dir_exist(get_rc_dir())) {
1168 #ifdef G_OS_UNIX
1169                         if (copy_dir(SYSCONFDIR "/skel/.claws-mail", get_rc_dir()) < 0) {
1170 #endif
1171                                 if (!is_dir_exist(get_rc_dir()) && make_dir(get_rc_dir()) < 0) {
1172 #ifdef G_OS_WIN32
1173                                         win32_close_log();
1174 #endif
1175                                         exit(1);
1176                                 }
1177 #ifdef G_OS_UNIX
1178                         }
1179 #endif
1180                 }
1181         }
1182         
1183
1184         if (!is_file_exist(RC_DIR G_DIR_SEPARATOR_S COMMON_RC) &&
1185             is_file_exist(RC_DIR G_DIR_SEPARATOR_S OLD_COMMON_RC)) {
1186                 /* post 2.6 name change */
1187                 migrate_common_rc(RC_DIR G_DIR_SEPARATOR_S OLD_COMMON_RC,
1188                           RC_DIR G_DIR_SEPARATOR_S COMMON_RC);
1189         }
1190
1191         if (!cmd.exit)
1192                 plugin_load_all("Common");
1193
1194         userrc = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, "gtkrc-2.0", NULL);
1195         gtk_rc_parse(userrc);
1196         g_free(userrc);
1197
1198         userrc = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MENU_RC, NULL);
1199         gtk_accel_map_load (userrc);
1200         g_free(userrc);
1201
1202 #ifdef G_OS_WIN32
1203         CHDIR_EXEC_CODE_RETURN_VAL_IF_FAIL(get_rc_dir(), 1, win32_close_log(););
1204 #else
1205         CHDIR_RETURN_VAL_IF_FAIL(get_rc_dir(), 1);
1206 #endif
1207
1208         MAKE_DIR_IF_NOT_EXIST(get_mail_base_dir());
1209         MAKE_DIR_IF_NOT_EXIST(get_imap_cache_dir());
1210         MAKE_DIR_IF_NOT_EXIST(get_news_cache_dir());
1211         MAKE_DIR_IF_NOT_EXIST(get_mime_tmp_dir());
1212         MAKE_DIR_IF_NOT_EXIST(get_tmp_dir());
1213         MAKE_DIR_IF_NOT_EXIST(UIDL_DIR);
1214
1215         crash_file_present = is_file_exist(get_crashfile_name());
1216         /* remove temporary files */
1217         remove_all_files(get_tmp_dir());
1218         remove_all_files(get_mime_tmp_dir());
1219
1220         if (!cmd.crash && crash_file_present)
1221                 claws_crashed_bool = TRUE;
1222
1223         if (is_file_exist("claws.log")) {
1224                 if (rename_force("claws.log", "claws.log.bak") < 0)
1225                         FILE_OP_ERROR("claws.log", "rename");
1226         }
1227         set_log_file(LOG_PROTOCOL, "claws.log");
1228
1229         if (is_file_exist("filtering.log")) {
1230                 if (rename_force("filtering.log", "filtering.log.bak") < 0)
1231                         FILE_OP_ERROR("filtering.log", "rename");
1232         }
1233         set_log_file(LOG_DEBUG_FILTERING, "filtering.log");
1234
1235 #ifdef G_OS_WIN32
1236         CHDIR_EXEC_CODE_RETURN_VAL_IF_FAIL(get_home_dir(), 1, win32_close_log(););
1237 #else
1238         CHDIR_RETURN_VAL_IF_FAIL(get_home_dir(), 1);
1239 #endif
1240
1241         folder_system_init();
1242         prefs_common_read_config();
1243
1244         if (prefs_update_config_version_common() < 0) {
1245                 debug_print("Main configuration file version upgrade failed, exiting\n");
1246 #ifdef G_OS_WIN32
1247                 win32_close_log();
1248 #endif
1249                 exit(200);
1250         }
1251
1252         prefs_themes_init();
1253         prefs_fonts_init();
1254         prefs_ext_prog_init();
1255         prefs_wrapping_init();
1256         prefs_compose_writing_init();
1257         prefs_msg_colors_init();
1258         image_viewer_init();
1259         prefs_image_viewer_init();
1260         prefs_quote_init();
1261         prefs_summaries_init();
1262         prefs_message_init();
1263         prefs_other_init();
1264         prefs_logging_init();
1265         prefs_receive_init();
1266         prefs_send_init();
1267         tags_read_tags();
1268         matcher_init();
1269 #ifdef USE_ENCHANT
1270         gtkaspell_checkers_init();
1271         prefs_spelling_init();
1272 #endif
1273
1274 #ifdef G_OS_WIN32
1275         if(prefs_common.gtk_theme && strcmp(prefs_common.gtk_theme, DEFAULT_W32_GTK_THEME))
1276                 gtk_settings_set_string_property(gtk_settings_get_default(),
1277                         "gtk-theme-name",
1278                         prefs_common.gtk_theme,
1279                         "XProperty");
1280 #endif
1281
1282
1283         sock_set_io_timeout(prefs_common.io_timeout_secs);
1284         prefs_actions_read_config();
1285         prefs_display_header_read_config();
1286         /* prefs_filtering_read_config(); */
1287 #ifndef USE_ALT_ADDRBOOK
1288         addressbook_read_file();
1289 #else
1290         g_clear_error(&error);
1291         if (! addressbook_start_service(&error)) {
1292                 g_warning("%s", error->message);
1293                 g_clear_error(&error);
1294         }
1295         else {
1296                 addressbook_install_hooks(&error);
1297         }
1298 #endif
1299         gtkut_widget_init();
1300         stock_pixbuf_gdk(STOCK_PIXMAP_CLAWS_MAIL_ICON, &icon);
1301         gtk_window_set_default_icon(icon);
1302
1303         folderview_initialize();
1304
1305         mh_gtk_init();
1306         imap_gtk_init();
1307         news_gtk_init();
1308
1309         mainwin = main_window_create();
1310
1311         if (!check_file_integrity())
1312                 exit(1);
1313
1314 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1315         networkmanager_state_change_cb(nm_proxy,NULL,mainwin);
1316 #endif
1317
1318         manage_window_focus_in(mainwin->window, NULL, NULL);
1319         folderview = mainwin->folderview;
1320
1321         folderview_freeze(mainwin->folderview);
1322         folder_item_update_freeze();
1323
1324         if ((ret = passwd_store_read_config()) < 0) {
1325                 debug_print("Password store configuration file version upgrade failed (%d), exiting\n", ret);
1326 #ifdef G_OS_WIN32
1327                 win32_close_log();
1328 #endif
1329                 exit(202);
1330         }
1331
1332         prefs_account_init();
1333         account_read_config_all();
1334
1335         if (prefs_update_config_version_accounts() < 0) {
1336                 debug_print("Accounts configuration file version upgrade failed, exiting\n");
1337 #ifdef G_OS_WIN32
1338                 win32_close_log();
1339 #endif
1340                 exit(201);
1341         }
1342
1343 #ifdef HAVE_LIBETPAN
1344         imap_main_init(prefs_common.skip_ssl_cert_check);
1345         imap_main_set_timeout(prefs_common.io_timeout_secs);
1346         nntp_main_init(prefs_common.skip_ssl_cert_check);
1347 #endif  
1348         /* If we can't read a folder list or don't have accounts,
1349          * it means the configuration's not done. Either this is
1350          * a brand new install, a failed/refused migration,
1351          * or a failed config_version upgrade.
1352          */
1353         if ((ret = folder_read_list()) < 0) {
1354                 debug_print("Folderlist read failed (%d)\n", ret);
1355                 prefs_destroy_cache();
1356                 
1357                 if (ret == -2) {
1358                         /* config_version update failed in folder_read_list(). We
1359                          * do not want to run the wizard, just exit. */
1360                         debug_print("Folderlist version upgrade failed, exiting\n");
1361 #ifdef G_OS_WIN32
1362                         win32_close_log();
1363 #endif
1364                         exit(203);
1365                 }
1366
1367                 /* if run_wizard returns FALSE it's because it's
1368                  * been cancelled. We can't do much but exit.
1369                  * however, if the user was asked for a migration,
1370                  * we remove the newly created directory so that
1371                  * he's asked again for migration on next launch.*/
1372                 if (!run_wizard(mainwin, TRUE)) {
1373                         if (asked_for_migration)
1374                                 remove_dir_recursive(RC_DIR);
1375 #ifdef G_OS_WIN32
1376                         win32_close_log();
1377 #endif
1378                         exit(1);
1379                 }
1380                 main_window_reflect_prefs_all_now();
1381                 folder_write_list();
1382                 never_ran = TRUE;
1383         }
1384
1385         if (!account_get_list()) {
1386                 prefs_destroy_cache();
1387                 if (!run_wizard(mainwin, FALSE)) {
1388                         if (asked_for_migration)
1389                                 remove_dir_recursive(RC_DIR);
1390 #ifdef G_OS_WIN32
1391                         win32_close_log();
1392 #endif
1393                         exit(1);
1394                 }
1395                 if(!account_get_list()) {
1396                         exit_claws(mainwin);
1397 #ifdef G_OS_WIN32
1398                         win32_close_log();
1399 #endif
1400                         exit(1);
1401                 }
1402                 never_ran = TRUE;
1403         }
1404
1405         
1406         toolbar_main_set_sensitive(mainwin);
1407         main_window_set_menu_sensitive(mainwin);
1408
1409         /* if crashed, show window early so that the user
1410          * sees what's happening */
1411         if (claws_crashed()) {
1412                 main_window_popup(mainwin);
1413                 mainwin_shown = TRUE;
1414         }
1415
1416         account_set_missing_folder();
1417         folder_set_missing_folders();
1418         folderview_set(folderview);
1419
1420         prefs_matcher_read_config();
1421         quicksearch_set_search_strings(mainwin->summaryview->quicksearch);
1422
1423         /* make one all-folder processing before using claws */
1424         main_window_cursor_wait(mainwin);
1425         folder_func_to_all_folders(initial_processing, (gpointer *)mainwin);
1426
1427         /* if claws crashed, rebuild caches */
1428         if (claws_crashed()) {
1429                 GTK_EVENTS_FLUSH();
1430                 debug_print("Claws Mail crashed, checking for new messages in local folders\n");
1431                 folder_item_update_thaw();
1432                 folderview_check_new(NULL);
1433                 folder_clean_cache_memory_force();
1434                 folder_item_update_freeze();
1435         }
1436         /* make the crash-indicator file */
1437         str_write_to_file("foo", get_crashfile_name());
1438
1439         inc_autocheck_timer_init(mainwin);
1440
1441         /* ignore SIGPIPE signal for preventing sudden death of program */
1442 #ifdef G_OS_UNIX
1443         signal(SIGPIPE, SIG_IGN);
1444 #endif
1445         if (cmd.online_mode == ONLINE_MODE_OFFLINE) {
1446                 main_window_toggle_work_offline(mainwin, TRUE, FALSE);
1447         }
1448         if (cmd.online_mode == ONLINE_MODE_ONLINE) {
1449                 main_window_toggle_work_offline(mainwin, FALSE, FALSE);
1450         }
1451
1452         if (cmd.status_folders) {
1453                 g_ptr_array_free(cmd.status_folders, TRUE);
1454                 cmd.status_folders = NULL;
1455         }
1456         if (cmd.status_full_folders) {
1457                 g_ptr_array_free(cmd.status_full_folders, TRUE);
1458                 cmd.status_full_folders = NULL;
1459         }
1460
1461         claws_register_idle_function(claws_gtk_idle);
1462
1463         avatars_init();
1464         prefs_toolbar_init();
1465
1466         num_folder_class = g_list_length(folder_get_list());
1467
1468         plugin_load_all("GTK2");
1469
1470         if (g_list_length(folder_get_list()) != num_folder_class) {
1471                 debug_print("new folders loaded, reloading processing rules\n");
1472                 prefs_matcher_read_config();
1473         }
1474         
1475         if ((plug_list = plugin_get_unloaded_list()) != NULL) {
1476                 GSList *cur;
1477                 gchar *list = NULL;
1478                 gint num_plugins = 0;
1479                 for (cur = plug_list; cur; cur = cur->next) {
1480                         Plugin *plugin = (Plugin *)cur->data;
1481                         gchar *tmp = g_strdup_printf("%s\n%s",
1482                                 list? list:"",
1483                                 plugin_get_name(plugin));
1484                         g_free(list);
1485                         list = tmp;
1486                         num_plugins++;
1487                 }
1488                 main_window_cursor_normal(mainwin);
1489                 main_window_popup(mainwin);
1490                 mainwin_shown = TRUE;
1491                 alertpanel_warning(ngettext(
1492                                      "The following plugin failed to load. "
1493                                      "Check the Plugins configuration "
1494                                      "for more information:\n%s",
1495                                      "The following plugins failed to load. "
1496                                      "Check the Plugins configuration "
1497                                      "for more information:\n%s", 
1498                                      num_plugins), 
1499                                      list);
1500                 main_window_cursor_wait(mainwin);
1501                 g_free(list);
1502                 g_slist_free(plug_list);
1503         }
1504
1505         if (never_ran) {
1506                 prefs_common_write_config();
1507                 plugin_load_standard_plugins ();
1508         }
1509
1510         /* if not crashed, show window now */
1511         if (!mainwin_shown) {
1512                 /* apart if something told not to show */
1513                 if (show_at_startup)
1514                         main_window_popup(mainwin);
1515         }
1516
1517         if (cmd.geometry != NULL) {
1518                 if (!gtk_window_parse_geometry(GTK_WINDOW(mainwin->window), cmd.geometry))
1519                         g_warning("failed to parse geometry '%s'", cmd.geometry);
1520                 else {
1521                         int width, height;
1522
1523                         if (sscanf(cmd.geometry, "%ux%u+", &width, &height) == 2)
1524                                 gtk_window_resize(GTK_WINDOW(mainwin->window), width, height);
1525                         else
1526                                 g_warning("failed to parse geometry's width/height");
1527                 }
1528         }
1529
1530         if (!folder_have_mailbox()) {
1531                 prefs_destroy_cache();
1532                 main_window_cursor_normal(mainwin);
1533                 if (folder_get_list() != NULL) {
1534                         alertpanel_error(_("Claws Mail has detected a configured "
1535                                    "mailbox, but it is incomplete. It is "
1536                                    "possibly due to a failing IMAP account. Use "
1537                                    "\"Rebuild folder tree\" on the mailbox parent "
1538                                    "folder's context menu to try to fix it."));
1539                 } else {
1540                         alertpanel_error(_("Claws Mail has detected a configured "
1541                                    "mailbox, but could not load it. It is "
1542                                    "probably provided by an out-of-date "
1543                                    "external plugin. Please reinstall the "
1544                                    "plugin and try again."));
1545                         exit_claws(mainwin);
1546 #ifdef G_OS_WIN32
1547                         win32_close_log();
1548 #endif
1549                         exit(1);
1550                 }
1551         }
1552         
1553         static_mainwindow = mainwin;
1554
1555 #ifdef HAVE_STARTUP_NOTIFICATION
1556         startup_notification_complete(FALSE);
1557 #endif
1558 #ifdef HAVE_LIBSM
1559         sc_session_manager_connect(mainwin);
1560 #endif
1561
1562         folder_item_update_thaw();
1563         folderview_thaw(mainwin->folderview);
1564         main_window_cursor_normal(mainwin);
1565
1566         if (!cmd.target && prefs_common.goto_last_folder_on_startup &&
1567             folder_find_item_from_identifier(prefs_common.last_opened_folder) != NULL &&
1568             !claws_crashed()) {
1569                 cmd.target = prefs_common.last_opened_folder;
1570         }
1571
1572         if (cmd.receive_all && !cmd.target) {
1573                 start_done = FALSE;
1574                 g_timeout_add(1000, defer_check_all, GINT_TO_POINTER(FALSE));
1575         } else if (prefs_common.chk_on_startup && !cmd.target) {
1576                 start_done = FALSE;
1577                 g_timeout_add(1000, defer_check_all, GINT_TO_POINTER(TRUE));
1578         } else if (cmd.receive && !cmd.target) {
1579                 start_done = FALSE;
1580                 g_timeout_add(1000, defer_check, NULL);
1581         }
1582         folderview_grab_focus(folderview);
1583
1584         if (cmd.compose) {
1585                 open_compose_new(cmd.compose_mailto, cmd.attach_files);
1586         }
1587         if (cmd.attach_files) {
1588                 list_free_strings_full(cmd.attach_files);
1589                 cmd.attach_files = NULL;
1590         }
1591         if (cmd.subscribe) {
1592                 folder_subscribe(cmd.subscribe_uri);
1593         }
1594
1595         if (cmd.send) {
1596                 send_queue();
1597         }
1598         
1599         if (cmd.target) {
1600                 start_done = FALSE;
1601                 g_timeout_add(500, defer_jump, (gpointer)cmd.target);
1602         }
1603
1604         prefs_destroy_cache();
1605         
1606         compose_reopen_exit_drafts();
1607
1608         if (start_done) {
1609                 sc_starting = FALSE;
1610                 main_window_set_menu_sensitive(mainwin);
1611                 toolbar_main_set_sensitive(mainwin);
1612         }
1613
1614         /* register the callback of unix domain socket input */
1615         lock_socket_tag = claws_input_add(lock_socket,
1616                                         G_IO_IN | G_IO_HUP | G_IO_ERR | G_IO_PRI,
1617                                         lock_socket_input_cb,
1618                                         mainwin, TRUE);
1619
1620         END_TIMING();
1621
1622         gtk_main();
1623
1624 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1625         if(nm_proxy)
1626                 g_object_unref(nm_proxy);
1627 #endif
1628 #ifdef HAVE_DBUS_GLIB
1629         uninstall_dbus_status_handler();
1630         if(connection)
1631                 dbus_g_connection_unref(connection);
1632 #endif
1633 #ifdef G_OS_WIN32
1634         win32_close_log();
1635 #endif
1636         utils_free_regex();
1637         exit_claws(mainwin);
1638
1639         return 0;
1640 }
1641
1642 static void save_all_caches(FolderItem *item, gpointer data)
1643 {
1644         if (!item->cache) {
1645                 return;
1646         }
1647
1648         if (item->opened) {
1649                 folder_item_close(item);
1650         }
1651
1652         folder_item_free_cache(item, TRUE);
1653 }
1654
1655 static void exit_claws(MainWindow *mainwin)
1656 {
1657         gchar *filename;
1658         gboolean have_connectivity;
1659         FolderItem *item;
1660
1661         sc_exiting = TRUE;
1662
1663         debug_print("shutting down\n");
1664         inc_autocheck_timer_remove();
1665
1666 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1667         if (prefs_common.work_offline && went_offline_nm)
1668                 prefs_common.work_offline = FALSE;
1669 #endif
1670
1671         /* save prefs for opened folder */
1672         if((item = folderview_get_opened_item(mainwin->folderview)) != NULL) {
1673                 summary_save_prefs_to_folderitem(
1674                         mainwin->summaryview, item);
1675                 prefs_common.last_opened_folder =
1676                         folder_item_get_identifier(item);
1677         }
1678
1679         /* save all state before exiting */
1680         folder_func_to_all_folders(save_all_caches, NULL);
1681         folder_write_list();
1682
1683         main_window_get_size(mainwin);
1684         main_window_get_position(mainwin);
1685
1686         prefs_common_write_config();
1687         account_write_config_all();
1688         passwd_store_write_config();
1689 #ifndef USE_ALT_ADDRBOOK
1690         addressbook_export_to_file();
1691 #endif
1692         filename = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S, MENU_RC, NULL);
1693         gtk_accel_map_save(filename);
1694         g_free(filename);
1695
1696         /* delete temporary files */
1697         remove_all_files(get_tmp_dir());
1698         remove_all_files(get_mime_tmp_dir());
1699
1700         close_log_file(LOG_PROTOCOL);
1701         close_log_file(LOG_DEBUG_FILTERING);
1702
1703 #ifdef HAVE_NETWORKMANAGER_SUPPORT
1704         have_connectivity = networkmanager_is_online(NULL); 
1705 #else
1706         have_connectivity = TRUE;
1707 #endif
1708 #ifdef HAVE_LIBETPAN
1709         imap_main_done(have_connectivity);
1710         nntp_main_done(have_connectivity);
1711 #endif
1712         /* delete crashfile */
1713         if (!cmd.crash)
1714                 claws_unlink(get_crashfile_name());
1715
1716         lock_socket_remove();
1717
1718 #ifdef HAVE_LIBSM
1719         if (mainwin->smc_conn)
1720                 SmcCloseConnection ((SmcConn)mainwin->smc_conn, 0, NULL);
1721         mainwin->smc_conn = NULL;
1722 #endif
1723
1724         main_window_destroy_all();
1725         
1726         plugin_unload_all("GTK2");
1727
1728         matcher_done();
1729         prefs_toolbar_done();
1730         avatars_done();
1731
1732 #ifndef USE_ALT_ADDRBOOK
1733         addressbook_destroy();
1734 #endif
1735         prefs_themes_done();
1736         prefs_fonts_done();
1737         prefs_ext_prog_done();
1738         prefs_wrapping_done();
1739         prefs_compose_writing_done();
1740         prefs_msg_colors_done();
1741         prefs_image_viewer_done();
1742         image_viewer_done();
1743         prefs_quote_done();
1744         prefs_summaries_done();
1745         prefs_message_done();
1746         prefs_other_done();
1747         prefs_receive_done();
1748         prefs_logging_done();
1749         prefs_send_done();
1750         tags_write_tags();
1751 #ifdef USE_ENCHANT       
1752         prefs_spelling_done();
1753         gtkaspell_checkers_quit();
1754 #endif
1755         plugin_unload_all("Common");
1756         claws_done();
1757 }
1758
1759 #define G_STRING_APPEND_ENCODED_URI(gstring,source)     \
1760         {                                               \
1761                 gchar tmpbuf[BUFFSIZE];                 \
1762                 encode_uri(tmpbuf, BUFFSIZE, (source)); \
1763                 g_string_append((gstring), tmpbuf);     \
1764         }
1765
1766 #define G_PRINT_EXIT(msg)       \
1767         {                       \
1768                 g_print(msg);   \
1769                 exit(1);        \
1770         }
1771
1772 static GString * parse_cmd_compose_from_file(const gchar *fn)
1773 {
1774         GString *headers = g_string_new(NULL);
1775         GString *body = g_string_new(NULL);
1776         gchar *to = NULL;
1777         gchar *h;
1778         gchar *v;
1779         gchar fb[BUFFSIZE];
1780         FILE *fp;
1781         gboolean isstdin;
1782
1783         if (fn == NULL || *fn == '\0')
1784                 G_PRINT_EXIT(_("Missing filename\n"));
1785         isstdin = (*fn == '-' && *(fn + 1) == '\0');
1786         if (isstdin)
1787                 fp = stdin;
1788         else {
1789                 fp = g_fopen(fn, "r");
1790                 if (!fp)
1791                         G_PRINT_EXIT(_("Cannot open filename for reading\n"));
1792         }
1793
1794         while (fgets(fb, sizeof(fb), fp)) {
1795                 gchar *tmp;     
1796                 strretchomp(fb);
1797                 if (*fb == '\0')
1798                         break;
1799                 h = fb;
1800                 while (*h && *h != ':') { ++h; } /* search colon */
1801                 if (*h == '\0')
1802                         G_PRINT_EXIT(_("Malformed header\n"));
1803                 v = h + 1;
1804                 while (*v && *v == ' ') { ++v; } /* trim value start */
1805                 *h = '\0';
1806                 tmp = g_ascii_strdown(fb, -1); /* get header name */
1807                 if (!strcmp(tmp, "to")) {
1808                         if (to != NULL)
1809                                 G_PRINT_EXIT(_("Duplicated 'To:' header\n"));
1810                         to = g_strdup(v);
1811                 } else {
1812                         g_string_append_c(headers, '&');
1813                         g_string_append(headers, tmp);
1814                         g_string_append_c(headers, '=');
1815                         g_string_append_uri_escaped(headers, v, NULL, TRUE);
1816                 }
1817                 g_free(tmp);
1818         }
1819         if (to == NULL)
1820                 G_PRINT_EXIT(_("Missing required 'To:' header\n"));
1821         g_string_append(body, to);
1822         g_free(to);
1823         g_string_append(body, "?body=");
1824         while (fgets(fb, sizeof(fb), fp)) {
1825                 g_string_append_uri_escaped(body, fb, NULL, TRUE);
1826         }
1827         if (!isstdin)
1828                 fclose(fp);
1829         /* append the remaining headers */
1830         g_string_append(body, headers->str);
1831         g_string_free(headers, TRUE);
1832
1833         return body;
1834 }
1835
1836 #undef G_STRING_APPEND_ENCODED_URI
1837 #undef G_PRINT_EXIT
1838
1839 static void parse_cmd_opt(int argc, char *argv[])
1840 {
1841         AttachInfo *ainfo;
1842         gint i;
1843
1844         for (i = 1; i < argc; i++) {
1845                 if (!strncmp(argv[i], "--receive-all", 13)) {
1846                         cmd.receive_all = TRUE;
1847                 } else if (!strncmp(argv[i], "--receive", 9)) {
1848                         cmd.receive = TRUE;
1849                 } else if (!strncmp(argv[i], "--cancel-receiving", 18)) {
1850                         cmd.cancel_receiving = TRUE;
1851                 } else if (!strncmp(argv[i], "--cancel-sending", 16)) {
1852                         cmd.cancel_sending = TRUE;
1853                 } else if (!strncmp(argv[i], "--compose-from-file", 19)) {
1854                         const gchar *p = (i+1 < argc)?argv[i+1]:NULL;
1855
1856                         GString *mailto = parse_cmd_compose_from_file(p);
1857                         cmd.compose = TRUE;
1858                         cmd.compose_mailto = mailto->str;
1859                         i++;
1860                 } else if (!strncmp(argv[i], "--compose", 9)) {
1861                         const gchar *p = (i+1 < argc)?argv[i+1]:NULL;
1862
1863                         cmd.compose = TRUE;
1864                         cmd.compose_mailto = NULL;
1865                         if (p && *p != '\0' && *p != '-') {
1866                                 if (!strncmp(p, "mailto:", 7)) {
1867                                         cmd.compose_mailto = p + 7;
1868                                 } else {
1869                                         cmd.compose_mailto = p;
1870                                 }
1871                                 i++;
1872                         }
1873                 } else if (!strncmp(argv[i], "--subscribe", 11)) {
1874                         const gchar *p = (i+1 < argc)?argv[i+1]:NULL;
1875                         if (p && *p != '\0' && *p != '-') {
1876                                 cmd.subscribe = TRUE;
1877                                 cmd.subscribe_uri = p;
1878                         }
1879                 } else if (!strncmp(argv[i], "--attach", 8) || !strncmp(argv[i], "--insert", 8)) {
1880                         const gchar *p = (i+1 < argc)?argv[i+1]:NULL;
1881                         gchar *file = NULL;
1882                         gboolean insert = !strncmp(argv[i], "--insert", 8);
1883
1884                         while (p && *p != '\0' && *p != '-') {
1885                                 if ((file = g_filename_from_uri(p, NULL, NULL)) != NULL) {
1886                                         if (!is_file_exist(file)) {
1887                                                 g_free(file);
1888                                                 file = NULL;
1889                                         }
1890                                 }
1891                                 if (file == NULL && *p != G_DIR_SEPARATOR) {
1892                                         file = g_strconcat(claws_get_startup_dir(),
1893                                                            G_DIR_SEPARATOR_S,
1894                                                            p, NULL);
1895                                 } else if (file == NULL) {
1896                                         file = g_strdup(p);
1897                                 }
1898
1899                                 ainfo = g_new0(AttachInfo, 1);
1900                                 ainfo->file = file;
1901                                 ainfo->insert = insert;
1902                                 cmd.attach_files = g_list_append(cmd.attach_files, ainfo);
1903                                 i++;
1904                                 p = (i+1 < argc)?argv[i+1]:NULL;
1905                         }
1906                 } else if (!strncmp(argv[i], "--send", 6)) {
1907                         cmd.send = TRUE;
1908                 } else if (!strncmp(argv[i], "--version-full", 14) ||
1909                            !strncmp(argv[i], "-V", 2)) {
1910                         g_print("Claws Mail version " VERSION_GIT_FULL "\n");
1911                         main_dump_features_list(FALSE);
1912                         exit(0);
1913                 } else if (!strncmp(argv[i], "--version", 9) ||
1914                            !strncmp(argv[i], "-v", 2)) {
1915                         g_print("Claws Mail version " VERSION "\n");
1916                         exit(0);
1917                 } else if (!strncmp(argv[i], "--status-full", 13)) {
1918                         const gchar *p = (i+1 < argc)?argv[i+1]:NULL;
1919  
1920                         cmd.status_full = TRUE;
1921                         while (p && *p != '\0' && *p != '-') {
1922                                 if (!cmd.status_full_folders) {
1923                                         cmd.status_full_folders =
1924                                                 g_ptr_array_new();
1925                                 }
1926                                 g_ptr_array_add(cmd.status_full_folders,
1927                                                 g_strdup(p));
1928                                 i++;
1929                                 p = (i+1 < argc)?argv[i+1]:NULL;
1930                         }
1931                 } else if (!strncmp(argv[i], "--status", 8)) {
1932                         const gchar *p = (i+1 < argc)?argv[i+1]:NULL;
1933  
1934                         cmd.status = TRUE;
1935                         while (p && *p != '\0' && *p != '-') {
1936                                 if (!cmd.status_folders)
1937                                         cmd.status_folders = g_ptr_array_new();
1938                                 g_ptr_array_add(cmd.status_folders,
1939                                                 g_strdup(p));
1940                                 i++;
1941                                 p = (i+1 < argc)?argv[i+1]:NULL;
1942                         }
1943                 } else if (!strncmp(argv[i], "--search", 8)) {
1944                         cmd.search_folder    = (i+1 < argc)?argv[i+1]:NULL;
1945                         cmd.search_type      = (i+2 < argc)?argv[i+2]:NULL;
1946                         cmd.search_request   = (i+3 < argc)?argv[i+3]:NULL;
1947                         const char* rec      = (i+4 < argc)?argv[i+4]:NULL;
1948                         cmd.search_recursive = TRUE;
1949                         if (rec && (tolower(*rec)=='n' || tolower(*rec)=='f' || *rec=='0'))
1950                                 cmd.search_recursive = FALSE;
1951                         if (cmd.search_folder && cmd.search_type && cmd.search_request)
1952                                 cmd.search = TRUE;
1953                 } else if (!strncmp(argv[i], "--online", 8)) {
1954                         cmd.online_mode = ONLINE_MODE_ONLINE;
1955                 } else if (!strncmp(argv[i], "--offline", 9)) {
1956                         cmd.online_mode = ONLINE_MODE_OFFLINE;
1957                 } else if (!strncmp(argv[i], "--toggle-debug", 14)) {
1958                         cmd.debug = TRUE;
1959                 } else if (!strncmp(argv[i], "--statistics", 12)) {
1960                         cmd.statistics = TRUE;
1961                 } else if (!strncmp(argv[i], "--reset-statistics", 18)) {
1962                         cmd.reset_statistics = TRUE;
1963                 } else if (!strncmp(argv[i], "--help", 6) ||
1964                            !strncmp(argv[i], "-h", 2)) {
1965                         gchar *base = g_path_get_basename(argv[0]);
1966                         g_print(_("Usage: %s [OPTION]...\n"), base);
1967
1968                         g_print("%s\n", _("  --compose [address]    open composition window"));
1969                         g_print("%s\n", _("  --compose-from-file file\n"
1970                                           "                         open composition window with data from given file;\n"
1971                                           "                         use - as file name for reading from standard input;\n"
1972                                           "                         content format: headers first (To: required) until an\n"
1973                                           "                         empty line, then mail body until end of file."));
1974                         g_print("%s\n", _("  --subscribe [uri]      subscribe to the given URI if possible"));
1975                         g_print("%s\n", _("  --attach file1 [file2]...\n"
1976                                           "                         open composition window with specified files\n"
1977                                           "                         attached"));
1978                         g_print("%s\n", _("  --insert file1 [file2]...\n"
1979                                           "                         open composition window with specified files\n"
1980                                           "                         inserted"));
1981                         g_print("%s\n", _("  --receive              receive new messages"));
1982                         g_print("%s\n", _("  --receive-all          receive new messages of all accounts"));
1983                         g_print("%s\n", _("  --cancel-receiving     cancel receiving of messages"));
1984                         g_print("%s\n", _("  --cancel-sending       cancel sending of messages"));
1985                         g_print("%s\n", _("  --search folder type request [recursive]\n"
1986                                           "                         searches mail\n"
1987                                           "                         folder ex.: \"#mh/Mailbox/inbox\" or \"Mail\"\n"
1988                                           "                         type: s[ubject],f[rom],t[o],e[xtended],m[ixed] or g: tag\n"
1989                                           "                         request: search string\n"
1990                                           "                         recursive: false if arg. starts with 0, n, N, f or F"));
1991
1992                         g_print("%s\n", _("  --send                 send all queued messages"));
1993                         g_print("%s\n", _("  --status [folder]...   show the total number of messages"));
1994                         g_print("%s\n", _("  --status-full [folder]...\n"
1995                                           "                         show the status of each folder"));
1996                         g_print("%s\n", _("  --statistics           show session statistics"));
1997                         g_print("%s\n", _("  --reset-statistics     reset session statistics"));
1998                         g_print("%s\n", _("  --select folder[/msg]  jumps to the specified folder/message\n" 
1999                                           "                         folder is a folder id like 'folder/sub_folder'"));
2000                         g_print("%s\n", _("  --online               switch to online mode"));
2001                         g_print("%s\n", _("  --offline              switch to offline mode"));
2002                         g_print("%s\n", _("  --exit --quit -q       exit Claws Mail"));
2003                         g_print("%s\n", _("  --debug                debug mode"));
2004                         g_print("%s\n", _("  --toggle-debug         toggle debug mode"));
2005                         g_print("%s\n", _("  --help -h              display this help and exit"));
2006                         g_print("%s\n", _("  --version -v           output version information and exit"));
2007                         g_print("%s\n", _("  --version-full -V      output version and built-in features information and exit"));
2008                         g_print("%s\n", _("  --config-dir           output configuration directory"));
2009                         g_print("%s\n", _("  --alternate-config-dir [dir]\n"
2010                                           "                         use specified configuration directory"));
2011                         g_print("%s\n", _("  --geometry -geometry WxH+X+Y\n"
2012                                           "                         set geometry for main window"));
2013
2014                         g_free(base);
2015                         exit(1);
2016                 } else if (!strncmp(argv[i], "--crash", 7)) {
2017                         cmd.crash = TRUE;
2018                         cmd.crash_params = g_strdup((i+1 < argc)?argv[i+1]:NULL);
2019                         i++;
2020                 } else if (!strncmp(argv[i], "--config-dir", sizeof "--config-dir" - 1)) {
2021                         g_print(RC_DIR "\n");
2022                         exit(0);
2023                 } else if (!strncmp(argv[i], "--alternate-config-dir", sizeof "--alternate-config-dir" - 1) && i+1 < argc) {
2024                         set_rc_dir(argv[i+1]);
2025                 } else if (!strncmp(argv[i], "--geometry", sizeof "--geometry" - 1)
2026                           || !strncmp(argv[i], "-geometry", sizeof "-geometry" - 1)) {
2027                         cmd.geometry = (i+1 < argc)? argv[i+1]: NULL;
2028                 } else if (!strncmp(argv[i], "--exit", 6) ||
2029                            !strncmp(argv[i], "--quit", 6) ||
2030                            !strncmp(argv[i], "-q", 2)) {
2031                         cmd.exit = TRUE;
2032                 } else if (!strncmp(argv[i], "--select", 8) && i+1 < argc) {
2033                         cmd.target = argv[i+1];
2034                 } else if (i == 1 && argc == 2) {
2035                         /* only one parameter. Do something intelligent about it */
2036                         if ((strstr(argv[i], "@")||!strncmp(argv[i], "mailto:", 7)) && !strstr(argv[i], "://")) {
2037                                 const gchar *p = argv[i];
2038
2039                                 cmd.compose = TRUE;
2040                                 cmd.compose_mailto = NULL;
2041                                 if (p && *p != '\0' && *p != '-') {
2042                                         if (!strncmp(p, "mailto:", 7)) {
2043                                                 cmd.compose_mailto = p + 7;
2044                                         } else {
2045                                                 cmd.compose_mailto = p;
2046                                         }
2047                                 }
2048                         } else if (!strncmp(argv[i], "file://", 7)) {
2049                                 cmd.target = argv[i];
2050                         } else if (!strncmp(argv[i], "?attach=file://", strlen("?attach=file://"))) {
2051                                 cmd.compose = TRUE;
2052                                 cmd.compose_mailto = argv[i];
2053                         } else if (strstr(argv[i], "://")) {
2054                                 const gchar *p = argv[i];
2055                                 if (p && *p != '\0' && *p != '-') {
2056                                         cmd.subscribe = TRUE;
2057                                         cmd.subscribe_uri = p;
2058                                 }
2059                         } else if (!strcmp(argv[i], "--sync")) {
2060                                 /* gtk debug */
2061                         } else if (is_dir_exist(argv[i]) || is_file_exist(argv[i])) {
2062                                 cmd.target = argv[i];
2063                         } else {
2064                                 g_print(_("Unknown option\n"));
2065                                 exit(1);
2066                         }
2067                 }
2068         }
2069
2070         if (cmd.attach_files && cmd.compose == FALSE) {
2071                 cmd.compose = TRUE;
2072                 cmd.compose_mailto = NULL;
2073         }
2074 }
2075
2076 static void initial_processing(FolderItem *item, gpointer data)
2077 {
2078         MainWindow *mainwin = (MainWindow *)data;
2079         gchar *buf;
2080
2081         cm_return_if_fail(item);
2082         buf = g_strdup_printf(_("Processing (%s)..."), 
2083                               item->path 
2084                               ? item->path 
2085                               : _("top level folder"));
2086         g_free(buf);
2087
2088         if (folder_item_parent(item) != NULL && item->prefs->enable_processing) {
2089                 item->processing_pending = TRUE;
2090                 folder_item_apply_processing(item);
2091                 item->processing_pending = FALSE;
2092         }
2093
2094         STATUSBAR_POP(mainwin);
2095 }
2096
2097 static gboolean draft_all_messages(void)
2098 {
2099         const GList *compose_list = NULL;
2100         
2101         compose_clear_exit_drafts();
2102         compose_list = compose_get_compose_list();
2103         while (compose_list != NULL) {
2104                 Compose *c = (Compose*)compose_list->data;
2105                 if (!compose_draft(c, COMPOSE_DRAFT_FOR_EXIT))
2106                         return FALSE;
2107                 compose_list = compose_get_compose_list();
2108         }
2109         return TRUE;
2110 }
2111 gboolean clean_quit(gpointer data)
2112 {
2113         static gboolean firstrun = TRUE;
2114
2115         if (!firstrun) {
2116                 return FALSE;
2117         }
2118         firstrun = FALSE;
2119
2120         /*!< Good idea to have the main window stored in a 
2121          *   static variable so we can check that variable
2122          *   to see if we're really allowed to do things
2123          *   that actually the spawner is supposed to 
2124          *   do (like: sending mail, composing messages).
2125          *   Because, really, if we're the spawnee, and
2126          *   we touch GTK stuff, we're hosed. See the 
2127          *   next fixme. */
2128
2129         /* FIXME: Use something else to signal that we're
2130          * in the original spawner, and not in a spawned
2131          * child. */
2132         if (!static_mainwindow) {
2133                 return FALSE;
2134         }
2135                 
2136         draft_all_messages();
2137         emergency_exit = TRUE;
2138         exit_claws(static_mainwindow);
2139         exit(0);
2140
2141         return FALSE;
2142 }
2143
2144 void app_will_exit(GtkWidget *widget, gpointer data)
2145 {
2146         MainWindow *mainwin = data;
2147         
2148         if (gtk_main_level() == 0) {
2149                 debug_print("not even started\n");
2150                 return;
2151         }
2152         if (sc_exiting == TRUE) {
2153                 debug_print("exit pending\n");
2154                 return;
2155         }
2156         sc_exiting = TRUE;
2157         debug_print("exiting\n");
2158         if (compose_get_compose_list()) {
2159                 if (!draft_all_messages()) {
2160                         main_window_popup(mainwin);
2161                         sc_exiting = FALSE;
2162                         return;
2163                 }
2164         }
2165
2166         if (prefs_common.warn_queued_on_exit && procmsg_have_queued_mails_fast()) {
2167                 if (alertpanel(_("Queued messages"),
2168                                _("Some unsent messages are queued. Exit now?"),
2169                                GTK_STOCK_CANCEL, GTK_STOCK_OK, NULL, ALERTFOCUS_FIRST)
2170                     != G_ALERTALTERNATE) {
2171                         main_window_popup(mainwin);
2172                         sc_exiting = FALSE;
2173                         return;
2174                 }
2175                 manage_window_focus_in(mainwin->window, NULL, NULL);
2176         }
2177
2178         sock_cleanup();
2179 #ifdef HAVE_VALGRIND
2180         if (RUNNING_ON_VALGRIND) {
2181                 summary_clear_list(mainwin->summaryview);
2182         }
2183 #endif
2184         if (folderview_get_selected_item(mainwin->folderview))
2185                 folder_item_close(folderview_get_selected_item(mainwin->folderview));
2186         gtk_main_quit();
2187 }
2188
2189 gboolean claws_is_exiting(void)
2190 {
2191         return sc_exiting;
2192 }
2193
2194 gboolean claws_is_starting(void)
2195 {
2196         return sc_starting;
2197 }
2198
2199 #ifdef G_OS_UNIX
2200 /*
2201  * CLAWS: want this public so crash dialog can delete the
2202  * lock file too
2203  */
2204 gchar *claws_get_socket_name(void)
2205 {
2206         static gchar *filename = NULL;
2207         gchar *socket_dir = NULL;
2208         gchar md5sum[33];
2209
2210         if (filename == NULL) {
2211                 GStatBuf st;
2212                 gint stat_ok;
2213
2214                 socket_dir = g_strdup_printf("%s%cclaws-mail-%d",
2215                                            g_get_tmp_dir(), G_DIR_SEPARATOR,
2216 #if HAVE_GETUID
2217                                            getuid());
2218 #else
2219                                            0);
2220 #endif
2221                 stat_ok = g_stat(socket_dir, &st);
2222                 if (stat_ok < 0 && errno != ENOENT) {
2223                         g_print("Error stat'ing socket_dir %s: %s\n",
2224                                 socket_dir, g_strerror(errno));
2225                 } else if (stat_ok == 0 && S_ISSOCK(st.st_mode)) {
2226                         /* old versions used a sock in $TMPDIR/claws-mail-$UID */
2227                         debug_print("Using legacy socket %s\n", socket_dir);
2228                         filename = g_strdup(socket_dir);
2229                         return filename;
2230                 }
2231
2232                 if (!is_dir_exist(socket_dir) && make_dir(socket_dir) < 0) {
2233                         g_print("Error creating socket_dir %s: %s\n",
2234                                 socket_dir, g_strerror(errno));
2235                 }
2236
2237                 md5_hex_digest(md5sum, get_rc_dir());
2238
2239                 filename = g_strdup_printf("%s%c%s", socket_dir, G_DIR_SEPARATOR,
2240                                            md5sum);
2241                 g_free(socket_dir);
2242                 debug_print("Using control socket %s\n", filename);
2243         }
2244
2245         return filename;
2246 }
2247 #endif
2248
2249 static gchar *get_crashfile_name(void)
2250 {
2251         static gchar *filename = NULL;
2252
2253         if (filename == NULL) {
2254                 filename = g_strdup_printf("%s%cclaws-crashed",
2255                                            get_tmp_dir(), G_DIR_SEPARATOR);
2256         }
2257
2258         return filename;
2259 }
2260
2261 static gint prohibit_duplicate_launch(void)
2262 {
2263         gint uxsock;
2264         GList *curr;
2265 #ifdef G_OS_UNIX
2266         gchar *path;
2267
2268         path = claws_get_socket_name();
2269         /* Try to connect to the control socket */
2270         uxsock = fd_connect_unix(path);
2271         
2272         if (x_display == NULL)
2273                 x_display = g_strdup(g_getenv("DISPLAY"));
2274
2275         if (uxsock < 0) {
2276                 gint ret;
2277 #if HAVE_FLOCK
2278                 gchar *socket_lock;
2279                 gint lock_fd;
2280                 /* If connect failed, no other process is running.
2281                  * Unlink the potentially existing socket, then
2282                  * open it. This has to be done locking a temporary
2283                  * file to avoid the race condition where another
2284                  * process could have created the socket just in
2285                  * between.
2286                  */
2287                 socket_lock = g_strconcat(path, ".lock",
2288                                           NULL);
2289                 lock_fd = g_open(socket_lock, O_RDWR|O_CREAT, 0);
2290                 if (lock_fd < 0) {
2291                         debug_print("Couldn't open %s: %s (%d)\n", socket_lock,
2292                                 g_strerror(errno), errno);
2293                         g_free(socket_lock);
2294                         return -1;
2295                 }
2296                 if (flock(lock_fd, LOCK_EX) < 0) {
2297                         debug_print("Couldn't lock %s: %s (%d)\n", socket_lock,
2298                                 g_strerror(errno), errno);
2299                         close(lock_fd);
2300                         g_free(socket_lock);
2301                         return -1;
2302                 }
2303 #endif
2304
2305                 claws_unlink(path);
2306                 debug_print("Opening socket %s\n", path);
2307                 ret = fd_open_unix(path);
2308 #if HAVE_FLOCK
2309                 flock(lock_fd, LOCK_UN);
2310                 close(lock_fd);
2311                 claws_unlink(socket_lock);
2312                 g_free(socket_lock);
2313 #endif
2314                 return ret;
2315         }
2316 #else
2317         HANDLE hmutex;
2318
2319         hmutex = CreateMutexA(NULL, FALSE, "ClawsMail");
2320         if (!hmutex) {
2321                 debug_print("cannot create Mutex\n");
2322                 return -1;
2323         }
2324         if (GetLastError() != ERROR_ALREADY_EXISTS) {
2325                 uxsock = fd_open_inet(50216);
2326                 if (uxsock < 0)
2327                         return 0;
2328                 return uxsock;
2329         }
2330
2331         uxsock = fd_connect_inet(50216);
2332         if (uxsock < 0)
2333                 return -1;
2334 #endif
2335         /* remote command mode */
2336
2337         debug_print("another Claws Mail instance is already running.\n");
2338
2339         if (cmd.receive_all) {
2340                 fd_write_all(uxsock, "receive_all\n", 12);
2341         } else if (cmd.receive) {
2342                 fd_write_all(uxsock, "receive\n", 8);
2343         } else if (cmd.cancel_receiving) {
2344                 fd_write_all(uxsock, "cancel_receiving\n", 17);
2345         } else if (cmd.cancel_sending) {
2346                 fd_write_all(uxsock, "cancel_sending\n", 15);
2347         } else if (cmd.compose && cmd.attach_files) {
2348                 gchar *str, *compose_str;
2349
2350                 if (cmd.compose_mailto) {
2351                         compose_str = g_strdup_printf("compose_attach %s\n",
2352                                                       cmd.compose_mailto);
2353                 } else {
2354                         compose_str = g_strdup("compose_attach\n");
2355                 }
2356
2357                 fd_write_all(uxsock, compose_str, strlen(compose_str));
2358                 g_free(compose_str);
2359
2360                 for (curr = cmd.attach_files; curr != NULL ; curr = curr->next) {
2361                         str = (gchar *) ((AttachInfo *)curr->data)->file;
2362                         if (((AttachInfo *)curr->data)->insert)
2363                                 fd_write_all(uxsock, "insert ", strlen("insert "));
2364                         else
2365                                 fd_write_all(uxsock, "attach ", strlen("attach "));
2366                         fd_write_all(uxsock, str, strlen(str));
2367                         fd_write_all(uxsock, "\n", 1);
2368                 }
2369
2370                 fd_write_all(uxsock, ".\n", 2);
2371         } else if (cmd.compose) {
2372                 gchar *compose_str;
2373
2374                 if (cmd.compose_mailto) {
2375                         compose_str = g_strdup_printf
2376                                 ("compose %s\n", cmd.compose_mailto);
2377                 } else {
2378                         compose_str = g_strdup("compose\n");
2379                 }
2380
2381                 fd_write_all(uxsock, compose_str, strlen(compose_str));
2382                 g_free(compose_str);
2383         } else if (cmd.subscribe) {
2384                 gchar *str = g_strdup_printf("subscribe %s\n", cmd.subscribe_uri);
2385                 fd_write_all(uxsock, str, strlen(str));
2386                 g_free(str);
2387         } else if (cmd.send) {
2388                 fd_write_all(uxsock, "send\n", 5);
2389         } else if (cmd.online_mode == ONLINE_MODE_ONLINE) {
2390                 fd_write(uxsock, "online\n", 6);
2391         } else if (cmd.online_mode == ONLINE_MODE_OFFLINE) {
2392                 fd_write(uxsock, "offline\n", 7);
2393         } else if (cmd.debug) {
2394                 fd_write(uxsock, "debug\n", 7);
2395         } else if (cmd.status || cmd.status_full) {
2396                 gchar buf[BUFFSIZE];
2397                 gint i;
2398                 const gchar *command;
2399                 GPtrArray *folders;
2400                 gchar *folder;
2401  
2402                 command = cmd.status_full ? "status-full\n" : "status\n";
2403                 folders = cmd.status_full ? cmd.status_full_folders :
2404                         cmd.status_folders;
2405  
2406                 fd_write_all(uxsock, command, strlen(command));
2407                 for (i = 0; folders && i < folders->len; ++i) {
2408                         folder = g_ptr_array_index(folders, i);
2409                         fd_write_all(uxsock, folder, strlen(folder));
2410                         fd_write_all(uxsock, "\n", 1);
2411                 }
2412                 fd_write_all(uxsock, ".\n", 2);
2413                 for (;;) {
2414                         fd_gets(uxsock, buf, sizeof(buf) - 1);
2415                         buf[sizeof(buf) - 1] = '\0';
2416                         if (!strncmp(buf, ".\n", 2)) break;
2417                         fputs(buf, stdout);
2418                 }
2419         } else if (cmd.exit) {
2420                 fd_write_all(uxsock, "exit\n", 5);
2421         } else if (cmd.statistics) {
2422                 gchar buf[BUFSIZ];
2423                 fd_write(uxsock, "statistics\n", 11);
2424                 for (;;) {
2425                         fd_gets(uxsock, buf, sizeof(buf) - 1);
2426                         buf[sizeof(buf) - 1] = '\0';
2427                         if (!strncmp(buf, ".\n", 2)) break;
2428                         fputs(buf, stdout);
2429                 }
2430         } else if (cmd.reset_statistics) {
2431                 fd_write(uxsock, "reset_statistics\n", 17);
2432         } else if (cmd.target) {
2433                 gchar *str = g_strdup_printf("select %s\n", cmd.target);
2434                 fd_write_all(uxsock, str, strlen(str));
2435                 g_free(str);
2436         } else if (cmd.search) {
2437                 gchar buf[BUFFSIZE];
2438                 gchar *str =
2439                         g_strdup_printf("search %s\n%s\n%s\n%c\n",
2440                                                         cmd.search_folder, cmd.search_type, cmd.search_request,
2441                                                         (cmd.search_recursive==TRUE)?'1':'0');
2442                 fd_write_all(uxsock, str, strlen(str));
2443                 g_free(str);
2444                 for (;;) {
2445                         fd_gets(uxsock, buf, sizeof(buf) - 1);
2446                         buf[sizeof(buf) - 1] = '\0';
2447                         if (!strncmp(buf, ".\n", 2)) break;
2448                         fputs(buf, stdout);
2449                 }
2450         } else {
2451 #ifndef G_OS_WIN32
2452                 gchar buf[BUFSIZ];
2453                 fd_write_all(uxsock, "get_display\n", 12);
2454                 memset(buf, 0, sizeof(buf));
2455                 fd_gets(uxsock, buf, sizeof(buf) - 1);
2456                 buf[sizeof(buf) - 1] = '\0';
2457                 if (strcmp2(buf, x_display)) {
2458                         g_print("Claws Mail is already running on display %s.\n",
2459                                 buf);
2460                 } else {
2461                         fd_close(uxsock);
2462                         uxsock = fd_connect_unix(path);
2463                         fd_write_all(uxsock, "popup\n", 6);
2464                 }
2465 #else
2466                 fd_write_all(uxsock, "popup\n", 6);
2467 #endif
2468         }
2469
2470         fd_close(uxsock);
2471         return -1;
2472 }
2473
2474 static gint lock_socket_remove(void)
2475 {
2476 #ifdef G_OS_UNIX
2477         gchar *filename, *dirname;
2478 #endif
2479         if (lock_socket < 0) {
2480                 return -1;
2481         }
2482
2483         if (lock_socket_tag > 0) {
2484                 g_source_remove(lock_socket_tag);
2485         }
2486         fd_close(lock_socket);
2487
2488 #ifdef G_OS_UNIX
2489         filename = claws_get_socket_name();
2490         dirname = g_path_get_dirname(filename);
2491         claws_unlink(filename);
2492         g_rmdir(dirname);
2493         g_free(dirname);
2494 #endif
2495
2496         return 0;
2497 }
2498
2499 static GPtrArray *get_folder_item_list(gint sock)
2500 {
2501         gchar buf[BUFFSIZE];
2502         FolderItem *item;
2503         GPtrArray *folders = NULL;
2504
2505         for (;;) {
2506                 fd_gets(sock, buf, sizeof(buf) - 1);
2507                 buf[sizeof(buf) - 1] = '\0';
2508                 if (!strncmp(buf, ".\n", 2)) {
2509                         break;
2510                 }
2511                 strretchomp(buf);
2512                 if (!folders) {
2513                         folders = g_ptr_array_new();
2514                 }
2515                 item = folder_find_item_from_identifier(buf);
2516                 if (item) {
2517                         g_ptr_array_add(folders, item);
2518                 } else {
2519                         g_warning("no such folder: %s", buf);
2520                 }
2521         }
2522
2523         return folders;
2524 }
2525
2526 static void lock_socket_input_cb(gpointer data,
2527                                  gint source,
2528                                  GIOCondition condition)
2529 {
2530         MainWindow *mainwin = (MainWindow *)data;
2531         gint sock;
2532         gchar buf[BUFFSIZE];
2533
2534         sock = fd_accept(source);
2535         if (sock < 0)
2536                 return;
2537
2538         fd_gets(sock, buf, sizeof(buf) - 1);
2539         buf[sizeof(buf) - 1] = '\0';
2540
2541         if (!strncmp(buf, "popup", 5)) {
2542                 main_window_popup(mainwin);
2543         } else if (!strncmp(buf, "get_display", 11)) {
2544                 fd_write_all(sock, x_display, strlen(x_display));
2545         } else if (!strncmp(buf, "receive_all", 11)) {
2546                 inc_all_account_mail(mainwin, FALSE,
2547                                      prefs_common.newmail_notify_manu);
2548         } else if (!strncmp(buf, "receive", 7)) {
2549                 inc_mail(mainwin, prefs_common.newmail_notify_manu);
2550         } else if (!strncmp(buf, "cancel_receiving", 16)) {
2551                 inc_cancel_all();
2552                 imap_cancel_all();
2553         } else if (!strncmp(buf, "cancel_sending", 14)) {
2554                 send_cancel();
2555         } else if (!strncmp(buf, "compose_attach", 14)) {
2556                 GList *files = NULL, *curr;
2557                 AttachInfo *ainfo;
2558                 gchar *mailto;
2559
2560                 mailto = g_strdup(buf + strlen("compose_attach") + 1);
2561                 while (fd_gets(sock, buf, sizeof(buf) - 1) > 0) {
2562                         buf[sizeof(buf) - 1] = '\0';
2563                         strretchomp(buf);
2564                         if (!strcmp2(buf, "."))
2565                                 break;
2566
2567                         ainfo = g_new0(AttachInfo, 1);
2568                         ainfo->file = g_strdup(strstr(buf, " ") + 1);
2569                         ainfo->insert = !strncmp(buf, "insert ", 7);
2570                         files = g_list_append(files, ainfo);
2571                 }
2572                 open_compose_new(mailto, files);
2573                 
2574                 curr = g_list_first(files);
2575                 while (curr != NULL) {
2576                         ainfo = (AttachInfo *)curr->data;
2577                         g_free(ainfo->file);
2578                         g_free(ainfo);
2579                         curr = curr->next;
2580                 }
2581                 g_list_free(files);
2582                 g_free(mailto);
2583         } else if (!strncmp(buf, "compose", 7)) {
2584                 open_compose_new(buf + strlen("compose") + 1, NULL);
2585         } else if (!strncmp(buf, "subscribe", 9)) {
2586                 main_window_popup(mainwin);
2587                 folder_subscribe(buf + strlen("subscribe") + 1);
2588         } else if (!strncmp(buf, "send", 4)) {
2589                 send_queue();
2590         } else if (!strncmp(buf, "online", 6)) {
2591                 main_window_toggle_work_offline(mainwin, FALSE, FALSE);
2592         } else if (!strncmp(buf, "offline", 7)) {
2593                 main_window_toggle_work_offline(mainwin, TRUE, FALSE);
2594         } else if (!strncmp(buf, "debug", 5)) {
2595                 debug_set_mode(debug_get_mode() ? FALSE : TRUE);
2596         } else if (!strncmp(buf, "status-full", 11) ||
2597                    !strncmp(buf, "status", 6)) {
2598                 gchar *status;
2599                 GPtrArray *folders;
2600  
2601                 folders = get_folder_item_list(sock);
2602                 status = folder_get_status
2603                         (folders, !strncmp(buf, "status-full", 11));
2604                 fd_write_all(sock, status, strlen(status));
2605                 fd_write_all(sock, ".\n", 2);
2606                 g_free(status);
2607                 if (folders) g_ptr_array_free(folders, TRUE);
2608         } else if (!strncmp(buf, "statistics", 10)) {
2609                 gchar tmp[BUFSIZ];
2610
2611                 g_snprintf(tmp, sizeof(tmp), _("Session statistics\n"));
2612                 fd_write_all(sock, tmp, strlen(tmp));
2613
2614                 if (prefs_common.date_format) {
2615                         struct tm *lt;
2616                         gint len = 100;
2617                         gchar date[len];
2618
2619                         lt = localtime(&session_stats.time_started);
2620                         fast_strftime(date, len, prefs_common.date_format, lt);
2621                         g_snprintf(tmp, sizeof(tmp), _("Started: %s\n"),
2622                                         lt ? date : ctime(&session_stats.time_started));
2623                 } else
2624                         g_snprintf(tmp, sizeof(tmp), _("Started: %s\n"),
2625                                         ctime(&session_stats.time_started));
2626                 fd_write_all(sock, tmp, strlen(tmp));
2627
2628                 fd_write_all(sock, "\n", 1);
2629
2630                 g_snprintf(tmp, sizeof(tmp), _("Incoming traffic\n"));
2631                 fd_write_all(sock, tmp, strlen(tmp));
2632
2633                 g_snprintf(tmp, sizeof(tmp), _("Received messages: %d\n"),
2634                                 session_stats.received);
2635                 fd_write_all(sock, tmp, strlen(tmp));
2636
2637                 fd_write_all(sock, "\n", 1);
2638
2639                 g_snprintf(tmp, sizeof(tmp), _("Outgoing traffic\n"));
2640                 fd_write_all(sock, tmp, strlen(tmp));
2641
2642                 g_snprintf(tmp, sizeof(tmp), _("New/redirected messages: %d\n"),
2643                                 session_stats.sent);
2644                 fd_write_all(sock, tmp, strlen(tmp));
2645
2646                 g_snprintf(tmp, sizeof(tmp), _("Replied messages: %d\n"),
2647                                 session_stats.replied);
2648                 fd_write_all(sock, tmp, strlen(tmp));
2649
2650                 g_snprintf(tmp, sizeof(tmp), _("Forwarded messages: %d\n"),
2651                                 session_stats.forwarded);
2652                 fd_write_all(sock, tmp, strlen(tmp));
2653
2654                 g_snprintf(tmp, sizeof(tmp), _("Total outgoing messages: %d\n"),
2655                                 (session_stats.sent + session_stats.replied +
2656                                  session_stats.forwarded));
2657                 fd_write_all(sock, tmp, strlen(tmp));
2658
2659                 fd_write_all(sock, ".\n", 2);
2660         } else if (!strncmp(buf, "reset_statistics", 16)) {
2661                 reset_statistics();
2662         } else if (!strncmp(buf, "select ", 7)) {
2663                 const gchar *target = buf+7;
2664                 mainwindow_jump_to(target, TRUE);
2665         } else if (!strncmp(buf, "search ", 7)) {
2666                 FolderItem* folderItem = NULL;
2667                 GSList *messages = NULL;
2668                 gchar *folder_name = NULL;
2669                 gchar *request = NULL;
2670                 AdvancedSearch *search;
2671                 gboolean recursive;
2672                 AdvancedSearchType searchType = ADVANCED_SEARCH_EXTENDED;
2673                 
2674                 search = advsearch_new();
2675
2676                 folder_name = g_strdup(buf+7);
2677                 strretchomp(folder_name);
2678
2679                 if (fd_gets(sock, buf, sizeof(buf) - 1) <= 0) 
2680                         goto search_exit;
2681                 buf[sizeof(buf) - 1] = '\0';
2682
2683                 switch (toupper(buf[0])) {
2684                 case 'S': searchType = ADVANCED_SEARCH_SUBJECT; break;
2685                 case 'F': searchType = ADVANCED_SEARCH_FROM; break;
2686                 case 'T': searchType = ADVANCED_SEARCH_TO; break;
2687                 case 'M': searchType = ADVANCED_SEARCH_MIXED; break;
2688                 case 'G': searchType = ADVANCED_SEARCH_TAG; break;
2689                 case 'E': searchType = ADVANCED_SEARCH_EXTENDED; break;
2690                 }
2691
2692                 if (fd_gets(sock, buf, sizeof(buf) - 1) <= 0) 
2693                         goto search_exit;
2694
2695                 buf[sizeof(buf) - 1] = '\0';
2696                 request = g_strdup(buf);
2697                 strretchomp(request);
2698
2699                 recursive = TRUE;
2700                 if (fd_gets(sock, buf, sizeof(buf) - 1) > 0)
2701                         recursive = buf[0] != '0';
2702
2703                 buf[sizeof(buf) - 1] = '\0';
2704
2705                 debug_print("search: %s %i %s %i\n", folder_name, searchType, request, recursive);
2706
2707                 folderItem = folder_find_item_from_identifier(folder_name);
2708
2709                 if (folderItem == NULL) {
2710                         debug_print("Unknown folder item : '%s', searching folder\n",folder_name);
2711                         Folder* folder = folder_find_from_path(folder_name);
2712                         if (folder != NULL)
2713                                 folderItem = FOLDER_ITEM(folder->node->data);
2714                         else
2715                                 debug_print("Unknown folder: '%s'\n",folder_name);
2716                 } else {
2717                         debug_print("%s %s\n",folderItem->name, folderItem->path);
2718                 }
2719
2720                 if (folderItem != NULL) {
2721                         advsearch_set(search, searchType, request);
2722                         advsearch_search_msgs_in_folders(search, &messages, folderItem, recursive);
2723                 } else {
2724                         g_print("Folder '%s' not found.\n'", folder_name);
2725                 }
2726
2727                 GSList *cur;
2728                 for (cur = messages; cur != NULL; cur = cur->next) {
2729                         MsgInfo* msg = (MsgInfo *)cur->data;
2730                         gchar *file = procmsg_get_message_file_path(msg);
2731                         fd_write_all(sock, file, strlen(file));
2732                         fd_write_all(sock, "\n", 1);
2733                         g_free(file);
2734                 }
2735                 fd_write_all(sock, ".\n", 2);
2736
2737 search_exit:
2738                 g_free(folder_name);
2739                 g_free(request);
2740                 advsearch_free(search);
2741                 if (messages != NULL)
2742                         procmsg_msg_list_free(messages);
2743         } else if (!strncmp(buf, "exit", 4)) {
2744                 if (prefs_common.clean_on_exit && !prefs_common.ask_on_clean) {
2745                         procmsg_empty_all_trash();
2746                 }
2747                 app_will_exit(NULL, mainwin);
2748         }
2749         fd_close(sock);
2750
2751 }
2752
2753 static void open_compose_new(const gchar *address, GList *attach_files)
2754 {
2755         gchar *addr = NULL;
2756
2757         if (address) {
2758                 Xstrdup_a(addr, address, return);
2759                 g_strstrip(addr);
2760         }
2761
2762         compose_new(NULL, addr, attach_files);
2763 }
2764
2765 static void send_queue(void)
2766 {
2767         GList *list;
2768         gchar *errstr = NULL;
2769         gboolean error = FALSE;
2770         for (list = folder_get_list(); list != NULL; list = list->next) {
2771                 Folder *folder = list->data;
2772
2773                 if (folder->queue) {
2774                         gint res = procmsg_send_queue
2775                                 (folder->queue, prefs_common.savemsg,
2776                                 &errstr);
2777
2778                         if (res) {
2779                                 folder_item_scan(folder->queue);
2780                         }
2781                         
2782                         if (res < 0)
2783                                 error = TRUE;
2784                 }
2785         }
2786         if (errstr) {
2787                 alertpanel_error_log(_("Some errors occurred "
2788                                 "while sending queued messages:\n%s"), errstr);
2789                 g_free(errstr);
2790         } else if (error) {
2791                 alertpanel_error_log("Some errors occurred "
2792                                 "while sending queued messages.");
2793         }
2794 }
2795
2796 static void quit_signal_handler(int sig)
2797 {
2798         debug_print("Quitting on signal %d\n", sig);
2799
2800         g_timeout_add(0, clean_quit, NULL);
2801 }
2802
2803 static void install_basic_sighandlers()
2804 {
2805 #ifndef G_OS_WIN32
2806         sigset_t    mask;
2807         struct sigaction act;
2808
2809         sigemptyset(&mask);
2810
2811 #ifdef SIGTERM
2812         sigaddset(&mask, SIGTERM);
2813 #endif
2814 #ifdef SIGINT
2815         sigaddset(&mask, SIGINT);
2816 #endif
2817 #ifdef SIGHUP
2818         sigaddset(&mask, SIGHUP);
2819 #endif
2820
2821         act.sa_handler = quit_signal_handler;
2822         act.sa_mask    = mask;
2823         act.sa_flags   = 0;
2824
2825 #ifdef SIGTERM
2826         sigaction(SIGTERM, &act, 0);
2827 #endif
2828 #ifdef SIGINT
2829         sigaction(SIGINT, &act, 0);
2830 #endif  
2831 #ifdef SIGHUP
2832         sigaction(SIGHUP, &act, 0);
2833 #endif  
2834
2835         sigprocmask(SIG_UNBLOCK, &mask, 0);
2836 #endif /* !G_OS_WIN32 */
2837 }
2838
2839 #if (defined linux && defined SIGIO)
2840 static int mem_notify_fd = 0;
2841
2842 static gboolean clean_caches(gpointer unused)
2843 {
2844         if (static_mainwindow && static_mainwindow->lock_count > 0)
2845                 return TRUE;
2846         debug_print("/dev/mem_notify: callback: Freeing some memory now!\n");
2847         folder_clean_cache_memory_force();
2848         return FALSE;
2849 }
2850
2851 static void memory_signal_handler(int sig)
2852 {
2853         debug_print("/dev/mem_notify: Kernel says we should free up some memory!\n");
2854         g_timeout_add(10, clean_caches, NULL); 
2855 }
2856
2857 static void install_memory_sighandler()
2858 {
2859         sigset_t    mask;
2860         struct sigaction act;
2861         int flags;
2862
2863         mem_notify_fd = g_open("/dev/mem_notify", O_RDONLY|O_NONBLOCK, 0);
2864         if (mem_notify_fd == -1) {
2865                 debug_print("/dev/mem_notify not available (%s)\n", 
2866                         g_strerror(errno));
2867                 return;
2868         }
2869         
2870         fcntl(mem_notify_fd, F_SETOWN, getpid());
2871         flags = fcntl(mem_notify_fd, F_GETFL);
2872         fcntl(mem_notify_fd, flags|FASYNC);
2873
2874         sigemptyset(&mask);
2875
2876         sigaddset(&mask, SIGIO);
2877
2878         act.sa_handler = memory_signal_handler;
2879         act.sa_mask    = mask;
2880         act.sa_flags   = 0;
2881
2882         sigaction(SIGIO, &act, 0);
2883
2884         sigprocmask(SIG_UNBLOCK, &mask, 0);
2885
2886         debug_print("/dev/mem_notify: installed handler\n");
2887 }
2888 #endif /* linux && SIGIO */
2889
2890 #ifdef HAVE_NETWORKMANAGER_SUPPORT
2891 static void networkmanager_state_change_cb(DBusGProxy *proxy, gchar *dev,
2892                                          gpointer data)
2893 {
2894         MainWindow *mainWin;
2895
2896         mainWin = NULL;
2897         if (static_mainwindow)
2898                 mainWin = static_mainwindow;
2899         else if (data)
2900                 mainWin = (MainWindow*)data;
2901         
2902         if (!prefs_common.use_networkmanager)
2903                 return;
2904
2905         if (mainWin) {
2906                 GError *error = NULL;
2907                 gboolean online;
2908
2909                 online = networkmanager_is_online(&error);
2910                 if(!error) {
2911                         if(online && went_offline_nm) {
2912                                 went_offline_nm = FALSE;
2913                                 main_window_toggle_work_offline(mainWin, FALSE, FALSE);
2914                                 debug_print("NetworkManager: Went online\n");
2915                                 log_message(LOG_PROTOCOL, _("NetworkManager: network is online.\n"));
2916                         }
2917                         else if(!online) {
2918                                 went_offline_nm = TRUE;
2919                                 main_window_toggle_work_offline(mainWin, TRUE, FALSE);
2920                                 debug_print("NetworkManager: Went offline\n");
2921                                 log_message(LOG_PROTOCOL, _("NetworkManager: network is offline.\n"));
2922                         }
2923                 }
2924                 else {
2925                         debug_print("Failed to get online information from NetworkManager: %s\n",
2926                                                          error->message);
2927                         g_error_free(error);
2928                 }
2929         }
2930         else
2931                 debug_print("NetworkManager: Cannot change connection state because "
2932                                                  "main window does not exist\n");
2933 }
2934
2935 /* Returns true (and sets error appropriately, if given) in case of error */
2936 gboolean networkmanager_is_online(GError **error)
2937 {
2938         DBusGConnection *connection;
2939         DBusGProxy *proxy;
2940         GError *tmp_error = NULL;
2941         gboolean retVal;
2942         guint32 state;
2943
2944         if (!prefs_common.use_networkmanager)
2945                 return TRUE;
2946
2947         tmp_error = NULL;
2948         proxy = NULL;
2949         connection = dbus_g_bus_get(DBUS_BUS_SYSTEM, &tmp_error);
2950
2951         if(!connection) {
2952                 /* If calling code doesn't do error checking, at least print some debug */
2953                 if((error == NULL) || (*error == NULL))
2954                         debug_print("Failed to open connection to system bus: %s\n",
2955                                                          tmp_error->message);
2956                 g_propagate_error(error, tmp_error);
2957                 return TRUE;
2958         }
2959
2960         proxy = dbus_g_proxy_new_for_name(connection,
2961                         "org.freedesktop.NetworkManager",
2962                         "/org/freedesktop/NetworkManager",
2963                         "org.freedesktop.NetworkManager");
2964
2965         retVal = dbus_g_proxy_call(proxy,"state",&tmp_error, G_TYPE_INVALID,
2966                         G_TYPE_UINT, &state, G_TYPE_INVALID);
2967
2968         if(proxy)
2969                 g_object_unref(proxy);
2970         if(connection)
2971                 dbus_g_connection_unref(connection);
2972
2973         if(!retVal) {
2974                 /* If calling code doesn't do error checking, at least print some debug */
2975                 if((error == NULL) || (*error == NULL))
2976                         debug_print("Failed to get state info from NetworkManager: %s\n",
2977                                                          tmp_error->message);
2978                 g_propagate_error(error, tmp_error);
2979                 return TRUE;
2980         }
2981         return (state == NM_STATE_CONNECTED_LOCAL ||
2982                 state == NM_STATE_CONNECTED_SITE ||
2983                 state == NM_STATE_CONNECTED_GLOBAL ||
2984                 state == NM_STATE_UNKNOWN);
2985 }
2986 #endif