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