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