Fix CID 1491365: resource leak.
[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                         g_free(socket_dir);
2370                         return filename;
2371                 }
2372
2373                 if (!is_dir_exist(socket_dir) && make_dir(socket_dir) < 0) {
2374                         g_print("Error creating socket_dir %s: %s\n",
2375                                 socket_dir, g_strerror(errno));
2376                 }
2377
2378                 md5_hex_digest(md5sum, get_rc_dir());
2379
2380                 filename = g_strdup_printf("%s%c%s", socket_dir, G_DIR_SEPARATOR,
2381                                            md5sum);
2382                 g_free(socket_dir);
2383                 debug_print("Using control socket %s\n", filename);
2384         }
2385
2386         return filename;
2387 }
2388 #endif
2389
2390 static gchar *get_crashfile_name(void)
2391 {
2392         static gchar *filename = NULL;
2393
2394         if (filename == NULL) {
2395                 filename = g_strdup_printf("%s%cclaws-crashed",
2396                                            get_tmp_dir(), G_DIR_SEPARATOR);
2397         }
2398
2399         return filename;
2400 }
2401
2402 static gint prohibit_duplicate_launch(void)
2403 {
2404         gint sock;
2405         GList *curr;
2406 #ifdef G_OS_UNIX
2407         gchar *path;
2408
2409         path = claws_get_socket_name();
2410         /* Try to connect to the control socket */
2411         sock = fd_connect_unix(path);
2412         
2413         if (x_display == NULL)
2414                 x_display = g_strdup(g_getenv("DISPLAY"));
2415
2416         if (sock < 0) {
2417                 gint ret;
2418 #if HAVE_FLOCK
2419                 gchar *socket_lock;
2420                 gint lock_fd;
2421                 /* If connect failed, no other process is running.
2422                  * Unlink the potentially existing socket, then
2423                  * open it. This has to be done locking a temporary
2424                  * file to avoid the race condition where another
2425                  * process could have created the socket just in
2426                  * between.
2427                  */
2428                 socket_lock = g_strconcat(path, ".lock",
2429                                           NULL);
2430                 lock_fd = g_open(socket_lock, O_RDWR|O_CREAT, 0);
2431                 if (lock_fd < 0) {
2432                         debug_print("Couldn't open %s: %s (%d)\n", socket_lock,
2433                                 g_strerror(errno), errno);
2434                         g_free(socket_lock);
2435                         return -1;
2436                 }
2437                 if (flock(lock_fd, LOCK_EX) < 0) {
2438                         debug_print("Couldn't lock %s: %s (%d)\n", socket_lock,
2439                                 g_strerror(errno), errno);
2440                         close(lock_fd);
2441                         g_free(socket_lock);
2442                         return -1;
2443                 }
2444 #endif
2445
2446                 claws_unlink(path);
2447                 debug_print("Opening socket %s\n", path);
2448                 ret = fd_open_unix(path);
2449 #if HAVE_FLOCK
2450                 flock(lock_fd, LOCK_UN);
2451                 close(lock_fd);
2452                 claws_unlink(socket_lock);
2453                 g_free(socket_lock);
2454 #endif
2455                 return ret;
2456         }
2457 #else
2458         HANDLE hmutex;
2459
2460         hmutex = CreateMutexA(NULL, FALSE, "ClawsMail");
2461         if (!hmutex) {
2462                 debug_print("cannot create Mutex\n");
2463                 return -1;
2464         }
2465         if (GetLastError() != ERROR_ALREADY_EXISTS) {
2466                 sock = fd_open_inet(50216);
2467                 if (sock < 0)
2468                         return 0;
2469                 return sock;
2470         }
2471
2472         sock = fd_connect_inet(50216);
2473         if (sock < 0)
2474                 return -1;
2475 #endif
2476         /* remote command mode */
2477
2478         debug_print("another Claws Mail instance is already running.\n");
2479
2480         if (cmd.receive_all) {
2481                 CM_FD_WRITE_ALL("receive_all\n");
2482         } else if (cmd.receive) {
2483                 CM_FD_WRITE_ALL("receive\n");
2484         } else if (cmd.cancel_receiving) {
2485                 CM_FD_WRITE_ALL("cancel_receiving\n");
2486         } else if (cmd.cancel_sending) {
2487                 CM_FD_WRITE_ALL("cancel_sending\n");
2488         } else if (cmd.compose && cmd.attach_files) {
2489                 gchar *str, *compose_str;
2490
2491                 if (cmd.compose_mailto) {
2492                         compose_str = g_strdup_printf("compose_attach %s\n",
2493                                                       cmd.compose_mailto);
2494                 } else {
2495                         compose_str = g_strdup("compose_attach\n");
2496                 }
2497
2498                 CM_FD_WRITE_ALL(compose_str);
2499                 g_free(compose_str);
2500
2501                 for (curr = cmd.attach_files; curr != NULL ; curr = curr->next) {
2502                         str = (gchar *) ((AttachInfo *)curr->data)->file;
2503                         if (((AttachInfo *)curr->data)->insert)
2504                                 CM_FD_WRITE_ALL("insert ");
2505                         else
2506                                 CM_FD_WRITE_ALL("attach ");
2507                         CM_FD_WRITE_ALL(str);
2508                         CM_FD_WRITE_ALL("\n");
2509                 }
2510
2511                 CM_FD_WRITE_ALL(".\n");
2512         } else if (cmd.compose) {
2513                 gchar *compose_str;
2514
2515                 if (cmd.compose_mailto) {
2516                         compose_str = g_strdup_printf
2517                                 ("compose %s\n", cmd.compose_mailto);
2518                 } else {
2519                         compose_str = g_strdup("compose\n");
2520                 }
2521
2522                 CM_FD_WRITE_ALL(compose_str);
2523                 g_free(compose_str);
2524         } else if (cmd.subscribe) {
2525                 gchar *str = g_strdup_printf("subscribe %s\n", cmd.subscribe_uri);
2526                 CM_FD_WRITE_ALL(str);
2527                 g_free(str);
2528         } else if (cmd.send) {
2529                 CM_FD_WRITE_ALL("send\n");
2530         } else if (cmd.online_mode == ONLINE_MODE_ONLINE) {
2531                 CM_FD_WRITE("online\n");
2532         } else if (cmd.online_mode == ONLINE_MODE_OFFLINE) {
2533                 CM_FD_WRITE("offline\n");
2534         } else if (cmd.debug) {
2535                 CM_FD_WRITE("debug\n");
2536         } else if (cmd.status || cmd.status_full) {
2537                 gchar buf[BUFFSIZE];
2538                 gint i;
2539                 const gchar *command;
2540                 GPtrArray *folders;
2541                 gchar *folder;
2542  
2543                 command = cmd.status_full ? "status-full\n" : "status\n";
2544                 folders = cmd.status_full ? cmd.status_full_folders :
2545                         cmd.status_folders;
2546  
2547                 CM_FD_WRITE_ALL(command);
2548                 for (i = 0; folders && i < folders->len; ++i) {
2549                         folder = g_ptr_array_index(folders, i);
2550                         CM_FD_WRITE_ALL(folder);
2551                         CM_FD_WRITE_ALL("\n");
2552                 }
2553                 CM_FD_WRITE_ALL(".\n");
2554                 for (;;) {
2555                         fd_gets(sock, buf, sizeof(buf) - 1);
2556                         buf[sizeof(buf) - 1] = '\0';
2557                         if (!STRNCMP(buf, ".\n")) break;
2558                         if (claws_fputs(buf, stdout) == EOF) {
2559                                 g_warning("writing to stdout failed");
2560                                 break;
2561                         }
2562                 }
2563         } else if (cmd.exit) {
2564                 CM_FD_WRITE_ALL("exit\n");
2565         } else if (cmd.statistics) {
2566                 gchar buf[BUFSIZ];
2567                 CM_FD_WRITE("statistics\n");
2568                 for (;;) {
2569                         fd_gets(sock, buf, sizeof(buf) - 1);
2570                         buf[sizeof(buf) - 1] = '\0';
2571                         if (!STRNCMP(buf, ".\n")) break;
2572                         if (claws_fputs(buf, stdout) == EOF) {
2573                                 g_warning("writing to stdout failed");
2574                                 break;
2575                         }
2576                 }
2577         } else if (cmd.reset_statistics) {
2578                 CM_FD_WRITE("reset_statistics\n");
2579         } else if (cmd.target) {
2580                 gchar *str = g_strdup_printf("select %s\n", cmd.target);
2581                 CM_FD_WRITE_ALL(str);
2582                 g_free(str);
2583         } else if (cmd.search) {
2584                 gchar buf[BUFFSIZE];
2585                 gchar *str =
2586                         g_strdup_printf("search %s\n%s\n%s\n%c\n",
2587                                                         cmd.search_folder, cmd.search_type, cmd.search_request,
2588                                                         (cmd.search_recursive==TRUE)?'1':'0');
2589                 CM_FD_WRITE_ALL(str);
2590                 g_free(str);
2591                 for (;;) {
2592                         fd_gets(sock, buf, sizeof(buf) - 1);
2593                         buf[sizeof(buf) - 1] = '\0';
2594                         if (!STRNCMP(buf, ".\n")) break;
2595                         if (claws_fputs(buf, stdout) == EOF) {
2596                                 g_warning("writing to stdout failed");
2597                                 break;
2598                         }
2599                 }
2600         } else {
2601 #ifdef G_OS_UNIX
2602                 gchar buf[BUFSIZ];
2603                 CM_FD_WRITE_ALL("get_display\n");
2604                 memset(buf, 0, sizeof(buf));
2605                 fd_gets(sock, buf, sizeof(buf) - 1);
2606                 buf[sizeof(buf) - 1] = '\0';
2607                 if (g_strcmp0(buf, x_display)) {
2608                         g_print("Claws Mail is already running on display %s.\n",
2609                                 buf);
2610                 } else {
2611                         fd_close(sock);
2612                         sock = fd_connect_unix(path);
2613                         CM_FD_WRITE_ALL("popup\n");
2614                 }
2615 #else
2616                 CM_FD_WRITE_ALL("popup\n");
2617 #endif
2618         }
2619
2620         fd_close(sock);
2621         return -1;
2622 }
2623
2624 static gint lock_socket_remove(void)
2625 {
2626 #ifdef G_OS_UNIX
2627         gchar *filename, *dirname;
2628 #endif
2629         if (lock_socket < 0) {
2630                 return -1;
2631         }
2632
2633         if (lock_socket_tag > 0) {
2634                 g_source_remove(lock_socket_tag);
2635         }
2636         fd_close(lock_socket);
2637
2638 #ifdef G_OS_UNIX
2639         filename = claws_get_socket_name();
2640         dirname = g_path_get_dirname(filename);
2641         if (claws_unlink(filename) < 0)
2642                 FILE_OP_ERROR(filename, "claws_unlink");
2643         g_rmdir(dirname);
2644         g_free(dirname);
2645 #endif
2646
2647         return 0;
2648 }
2649
2650 static GPtrArray *get_folder_item_list(gint sock)
2651 {
2652         gchar buf[BUFFSIZE];
2653         FolderItem *item;
2654         GPtrArray *folders = NULL;
2655
2656         for (;;) {
2657                 fd_gets(sock, buf, sizeof(buf) - 1);
2658                 buf[sizeof(buf) - 1] = '\0';
2659                 if (!STRNCMP(buf, ".\n")) {
2660                         break;
2661                 }
2662                 strretchomp(buf);
2663                 if (!folders) {
2664                         folders = g_ptr_array_new();
2665                 }
2666                 item = folder_find_item_from_identifier(buf);
2667                 if (item) {
2668                         g_ptr_array_add(folders, item);
2669                 } else {
2670                         g_warning("no such folder: %s", buf);
2671                 }
2672         }
2673
2674         return folders;
2675 }
2676
2677 static void lock_socket_input_cb(gpointer data,
2678                                  gint source,
2679                                  GIOCondition condition)
2680 {
2681         MainWindow *mainwin = (MainWindow *)data;
2682         gint sock;
2683         gchar buf[BUFFSIZE];
2684
2685         sock = fd_accept(source);
2686         if (sock < 0)
2687                 return;
2688
2689         fd_gets(sock, buf, sizeof(buf) - 1);
2690         buf[sizeof(buf) - 1] = '\0';
2691
2692         if (!STRNCMP(buf, "popup")) {
2693                 main_window_popup(mainwin);
2694 #ifdef G_OS_UNIX
2695         } else if (!STRNCMP(buf, "get_display")) {
2696                 CM_FD_WRITE_ALL(x_display);
2697 #endif
2698         } else if (!STRNCMP(buf, "receive_all")) {
2699                 inc_all_account_mail(mainwin, FALSE, FALSE,
2700                                      prefs_common.newmail_notify_manu);
2701         } else if (!STRNCMP(buf, "receive")) {
2702                 inc_mail(mainwin, prefs_common.newmail_notify_manu);
2703         } else if (!STRNCMP(buf, "cancel_receiving")) {
2704                 inc_cancel_all();
2705                 imap_cancel_all();
2706         } else if (!STRNCMP(buf, "cancel_sending")) {
2707                 send_cancel();
2708         } else if (!STRNCMP(buf, "compose_attach")) {
2709                 GList *files = NULL, *curr;
2710                 AttachInfo *ainfo;
2711                 gchar *mailto;
2712
2713                 mailto = g_strdup(buf + strlen("compose_attach") + 1);
2714                 while (fd_gets(sock, buf, sizeof(buf) - 1) > 0) {
2715                         buf[sizeof(buf) - 1] = '\0';
2716                         strretchomp(buf);
2717                         if (!g_strcmp0(buf, "."))
2718                                 break;
2719
2720                         ainfo = g_new0(AttachInfo, 1);
2721                         ainfo->file = g_strdup(strstr(buf, " ") + 1);
2722                         ainfo->insert = !STRNCMP(buf, "insert ");
2723                         files = g_list_append(files, ainfo);
2724                 }
2725                 open_compose_new(mailto, files);
2726                 
2727                 curr = g_list_first(files);
2728                 while (curr != NULL) {
2729                         ainfo = (AttachInfo *)curr->data;
2730                         g_free(ainfo->file);
2731                         g_free(ainfo);
2732                         curr = curr->next;
2733                 }
2734                 g_list_free(files);
2735                 g_free(mailto);
2736         } else if (!STRNCMP(buf, "compose")) {
2737                 open_compose_new(buf + strlen("compose") + 1, NULL);
2738         } else if (!STRNCMP(buf, "subscribe")) {
2739                 main_window_popup(mainwin);
2740                 folder_subscribe(buf + strlen("subscribe") + 1);
2741         } else if (!STRNCMP(buf, "send")) {
2742                 send_queue();
2743         } else if (!STRNCMP(buf, "online")) {
2744                 main_window_toggle_work_offline(mainwin, FALSE, FALSE);
2745         } else if (!STRNCMP(buf, "offline")) {
2746                 main_window_toggle_work_offline(mainwin, TRUE, FALSE);
2747         } else if (!STRNCMP(buf, "debug")) {
2748                 debug_set_mode(debug_get_mode() ? FALSE : TRUE);
2749         } else if (!STRNCMP(buf, "status-full") ||
2750                    !STRNCMP(buf, "status")) {
2751                 gchar *status;
2752                 GPtrArray *folders;
2753  
2754                 folders = get_folder_item_list(sock);
2755                 status = folder_get_status
2756                         (folders, !STRNCMP(buf, "status-full"));
2757                 CM_FD_WRITE_ALL(status);
2758                 CM_FD_WRITE_ALL(".\n");
2759                 g_free(status);
2760                 if (folders) g_ptr_array_free(folders, TRUE);
2761         } else if (!STRNCMP(buf, "statistics")) {
2762                 gchar tmp[BUFSIZ];
2763
2764                 g_snprintf(tmp, sizeof(tmp), _("Session statistics\n"));
2765                 CM_FD_WRITE_ALL(tmp);
2766
2767                 if (prefs_common.date_format) {
2768                         struct tm *lt;
2769                         gint len = 100;
2770                         gchar date[len];
2771
2772                         lt = localtime(&session_stats.time_started);
2773                         fast_strftime(date, len, prefs_common.date_format, lt);
2774                         g_snprintf(tmp, sizeof(tmp), _("Started: %s\n"),
2775                                         lt ? date : ctime(&session_stats.time_started));
2776                 } else
2777                         g_snprintf(tmp, sizeof(tmp), _("Started: %s\n"),
2778                                         ctime(&session_stats.time_started));
2779                 CM_FD_WRITE_ALL(tmp);
2780
2781                 CM_FD_WRITE_ALL("\n");
2782
2783                 g_snprintf(tmp, sizeof(tmp), _("Incoming traffic\n"));
2784                 CM_FD_WRITE_ALL(tmp);
2785
2786                 g_snprintf(tmp, sizeof(tmp), _("Received messages: %d\n"),
2787                                 session_stats.received);
2788                 CM_FD_WRITE_ALL(tmp);
2789
2790                 CM_FD_WRITE_ALL("\n");
2791
2792                 g_snprintf(tmp, sizeof(tmp), _("Outgoing traffic\n"));
2793                 CM_FD_WRITE_ALL(tmp);
2794
2795                 g_snprintf(tmp, sizeof(tmp), _("New/redirected messages: %d\n"),
2796                                 session_stats.sent);
2797                 CM_FD_WRITE_ALL(tmp);
2798
2799                 g_snprintf(tmp, sizeof(tmp), _("Replied messages: %d\n"),
2800                                 session_stats.replied);
2801                 CM_FD_WRITE_ALL(tmp);
2802
2803                 g_snprintf(tmp, sizeof(tmp), _("Forwarded messages: %d\n"),
2804                                 session_stats.forwarded);
2805                 CM_FD_WRITE_ALL(tmp);
2806
2807                 g_snprintf(tmp, sizeof(tmp), _("Total outgoing messages: %d\n"),
2808                                 (session_stats.sent + session_stats.replied +
2809                                  session_stats.forwarded));
2810                 CM_FD_WRITE_ALL(tmp);
2811
2812                 CM_FD_WRITE_ALL(".\n");
2813         } else if (!STRNCMP(buf, "reset_statistics")) {
2814                 reset_statistics();
2815         } else if (!STRNCMP(buf, "select ")) {
2816                 const gchar *target = buf+7;
2817                 mainwindow_jump_to(target, TRUE);
2818         } else if (!STRNCMP(buf, "search ")) {
2819                 FolderItem* folderItem = NULL;
2820                 GSList *messages = NULL;
2821                 gchar *folder_name = NULL;
2822                 gchar *request = NULL;
2823                 AdvancedSearch *search;
2824                 gboolean recursive;
2825                 AdvancedSearchType searchType = ADVANCED_SEARCH_EXTENDED;
2826                 
2827                 search = advsearch_new();
2828
2829                 folder_name = g_strdup(buf+7);
2830                 strretchomp(folder_name);
2831
2832                 if (fd_gets(sock, buf, sizeof(buf) - 1) <= 0) 
2833                         goto search_exit;
2834                 buf[sizeof(buf) - 1] = '\0';
2835
2836                 switch (toupper(buf[0])) {
2837                 case 'S': searchType = ADVANCED_SEARCH_SUBJECT; break;
2838                 case 'F': searchType = ADVANCED_SEARCH_FROM; break;
2839                 case 'T': searchType = ADVANCED_SEARCH_TO; break;
2840                 case 'M': searchType = ADVANCED_SEARCH_MIXED; break;
2841                 case 'G': searchType = ADVANCED_SEARCH_TAG; break;
2842                 case 'E': searchType = ADVANCED_SEARCH_EXTENDED; break;
2843                 }
2844
2845                 if (fd_gets(sock, buf, sizeof(buf) - 1) <= 0) 
2846                         goto search_exit;
2847
2848                 buf[sizeof(buf) - 1] = '\0';
2849                 request = g_strdup(buf);
2850                 strretchomp(request);
2851
2852                 recursive = TRUE;
2853                 if (fd_gets(sock, buf, sizeof(buf) - 1) > 0)
2854                         recursive = buf[0] != '0';
2855
2856                 buf[sizeof(buf) - 1] = '\0';
2857
2858                 debug_print("search: %s %i %s %i\n", folder_name, searchType, request, recursive);
2859
2860                 folderItem = folder_find_item_from_identifier(folder_name);
2861
2862                 if (folderItem == NULL) {
2863                         debug_print("Unknown folder item : '%s', searching folder\n",folder_name);
2864                         Folder* folder = folder_find_from_path(folder_name);
2865                         if (folder != NULL)
2866                                 folderItem = FOLDER_ITEM(folder->node->data);
2867                         else
2868                                 debug_print("Unknown folder: '%s'\n",folder_name);
2869                 } else {
2870                         debug_print("%s %s\n",folderItem->name, folderItem->path);
2871                 }
2872
2873                 if (folderItem != NULL) {
2874                         advsearch_set(search, searchType, request);
2875                         advsearch_search_msgs_in_folders(search, &messages, folderItem, recursive);
2876                 } else {
2877                         g_print("Folder '%s' not found.\n'", folder_name);
2878                 }
2879
2880                 GSList *cur;
2881                 for (cur = messages; cur != NULL; cur = cur->next) {
2882                         MsgInfo* msg = (MsgInfo *)cur->data;
2883                         gchar *file = procmsg_get_message_file_path(msg);
2884                         CM_FD_WRITE_ALL(file);
2885                         CM_FD_WRITE_ALL("\n");
2886                         g_free(file);
2887                 }
2888                 CM_FD_WRITE_ALL(".\n");
2889
2890 search_exit:
2891                 g_free(folder_name);
2892                 g_free(request);
2893                 advsearch_free(search);
2894                 if (messages != NULL)
2895                         procmsg_msg_list_free(messages);
2896         } else if (!STRNCMP(buf, "exit")) {
2897                 if (prefs_common.clean_on_exit && !prefs_common.ask_on_clean) {
2898                         procmsg_empty_all_trash();
2899                 }
2900                 app_will_exit(NULL, mainwin);
2901         }
2902         fd_close(sock);
2903
2904 }
2905
2906 static void open_compose_new(const gchar *address, GList *attach_files)
2907 {
2908         gchar *addr = NULL;
2909
2910         if (address) {
2911                 Xstrdup_a(addr, address, return);
2912                 g_strstrip(addr);
2913         }
2914
2915         compose_new(NULL, addr, attach_files);
2916 }
2917
2918 static void send_queue(void)
2919 {
2920         GList *list;
2921         gchar *errstr = NULL;
2922         gboolean error = FALSE;
2923         for (list = folder_get_list(); list != NULL; list = list->next) {
2924                 Folder *folder = list->data;
2925
2926                 if (folder->queue) {
2927                         gint res = procmsg_send_queue
2928                                 (folder->queue, prefs_common.savemsg,
2929                                 &errstr);
2930
2931                         if (res) {
2932                                 folder_item_scan(folder->queue);
2933                         }
2934                         
2935                         if (res < 0)
2936                                 error = TRUE;
2937                 }
2938         }
2939         if (errstr) {
2940                 alertpanel_error_log(_("Some errors occurred "
2941                                 "while sending queued messages:\n%s"), errstr);
2942                 g_free(errstr);
2943         } else if (error) {
2944                 alertpanel_error_log("Some errors occurred "
2945                                 "while sending queued messages.");
2946         }
2947 }
2948
2949 static void quit_signal_handler(int sig)
2950 {
2951         debug_print("Quitting on signal %d\n", sig);
2952
2953         g_timeout_add(0, clean_quit, NULL);
2954 }
2955
2956 static void install_basic_sighandlers()
2957 {
2958 #ifndef G_OS_WIN32
2959         sigset_t    mask;
2960         struct sigaction act;
2961
2962         sigemptyset(&mask);
2963
2964 #ifdef SIGTERM
2965         sigaddset(&mask, SIGTERM);
2966 #endif
2967 #ifdef SIGINT
2968         sigaddset(&mask, SIGINT);
2969 #endif
2970 #ifdef SIGHUP
2971         sigaddset(&mask, SIGHUP);
2972 #endif
2973
2974         act.sa_handler = quit_signal_handler;
2975         act.sa_mask    = mask;
2976         act.sa_flags   = 0;
2977
2978 #ifdef SIGTERM
2979         sigaction(SIGTERM, &act, 0);
2980 #endif
2981 #ifdef SIGINT
2982         sigaction(SIGINT, &act, 0);
2983 #endif  
2984 #ifdef SIGHUP
2985         sigaction(SIGHUP, &act, 0);
2986 #endif  
2987
2988         sigprocmask(SIG_UNBLOCK, &mask, 0);
2989 #endif /* !G_OS_WIN32 */
2990 }
2991
2992 #if (defined linux && defined SIGIO)
2993 static int mem_notify_fd = 0;
2994
2995 static gboolean clean_caches(gpointer unused)
2996 {
2997         if (static_mainwindow && static_mainwindow->lock_count > 0)
2998                 return TRUE;
2999         debug_print("/dev/mem_notify: callback: Freeing some memory now!\n");
3000         folder_clean_cache_memory_force();
3001         return FALSE;
3002 }
3003
3004 static void memory_signal_handler(int sig)
3005 {
3006         debug_print("/dev/mem_notify: Kernel says we should free up some memory!\n");
3007         g_timeout_add(10, clean_caches, NULL); 
3008 }
3009
3010 static void install_memory_sighandler()
3011 {
3012         sigset_t    mask;
3013         struct sigaction act;
3014         int flags;
3015
3016         mem_notify_fd = g_open("/dev/mem_notify", O_RDONLY|O_NONBLOCK, 0);
3017         if (mem_notify_fd == -1) {
3018                 debug_print("/dev/mem_notify not available (%s)\n", 
3019                         g_strerror(errno));
3020                 return;
3021         }
3022         
3023         fcntl(mem_notify_fd, F_SETOWN, getpid());
3024         flags = fcntl(mem_notify_fd, F_GETFL);
3025         fcntl(mem_notify_fd, flags|FASYNC);
3026
3027         sigemptyset(&mask);
3028
3029         sigaddset(&mask, SIGIO);
3030
3031         act.sa_handler = memory_signal_handler;
3032         act.sa_mask    = mask;
3033         act.sa_flags   = 0;
3034
3035         sigaction(SIGIO, &act, 0);
3036
3037         sigprocmask(SIG_UNBLOCK, &mask, 0);
3038
3039         debug_print("/dev/mem_notify: installed handler\n");
3040 }
3041 #endif /* linux && SIGIO */
3042
3043 #ifdef HAVE_NETWORKMANAGER_SUPPORT
3044 static void networkmanager_state_change_cb(DBusGProxy *proxy, gchar *dev,
3045                                          gpointer data)
3046 {
3047         MainWindow *mainWin;
3048
3049         mainWin = NULL;
3050         if (static_mainwindow)
3051                 mainWin = static_mainwindow;
3052         else if (data)
3053                 mainWin = (MainWindow*)data;
3054         
3055         if (!prefs_common.use_networkmanager)
3056                 return;
3057
3058         if (mainWin) {
3059                 GError *error = NULL;
3060                 gboolean online;
3061
3062                 online = networkmanager_is_online(&error);
3063                 if(!error) {
3064                         if(online && went_offline_nm) {
3065                                 went_offline_nm = FALSE;
3066                                 main_window_toggle_work_offline(mainWin, FALSE, FALSE);
3067                                 debug_print("NetworkManager: Went online\n");
3068                                 log_message(LOG_PROTOCOL, _("NetworkManager: network is online.\n"));
3069                         }
3070                         else if(!online) {
3071                                 went_offline_nm = TRUE;
3072                                 main_window_toggle_work_offline(mainWin, TRUE, FALSE);
3073                                 debug_print("NetworkManager: Went offline\n");
3074                                 log_message(LOG_PROTOCOL, _("NetworkManager: network is offline.\n"));
3075                         }
3076                 }
3077                 else {
3078                         debug_print("Failed to get online information from NetworkManager: %s\n",
3079                                                          error->message);
3080                         g_error_free(error);
3081                 }
3082         }
3083         else
3084                 debug_print("NetworkManager: Cannot change connection state because "
3085                                                  "main window does not exist\n");
3086 }
3087
3088 /* Returns true (and sets error appropriately, if given) in case of error */
3089 gboolean networkmanager_is_online(GError **error)
3090 {
3091         DBusGConnection *connection;
3092         DBusGProxy *proxy;
3093         GError *tmp_error = NULL;
3094         gboolean retVal;
3095         guint32 state;
3096
3097         if (!prefs_common.use_networkmanager)
3098                 return TRUE;
3099
3100         tmp_error = NULL;
3101         proxy = NULL;
3102         connection = dbus_g_bus_get(DBUS_BUS_SYSTEM, &tmp_error);
3103
3104         if(!connection) {
3105                 /* If calling code doesn't do error checking, at least print some debug */
3106                 if((error == NULL) || (*error == NULL))
3107                         debug_print("Failed to open connection to system bus: %s\n",
3108                                                          tmp_error->message);
3109                 g_propagate_error(error, tmp_error);
3110                 return TRUE;
3111         }
3112
3113         proxy = dbus_g_proxy_new_for_name(connection,
3114                         "org.freedesktop.NetworkManager",
3115                         "/org/freedesktop/NetworkManager",
3116                         "org.freedesktop.NetworkManager");
3117
3118         retVal = dbus_g_proxy_call(proxy,"state",&tmp_error, G_TYPE_INVALID,
3119                         G_TYPE_UINT, &state, G_TYPE_INVALID);
3120
3121         if(proxy)
3122                 g_object_unref(proxy);
3123         if(connection)
3124                 dbus_g_connection_unref(connection);
3125
3126         if(!retVal) {
3127                 /* If calling code doesn't do error checking, at least print some debug */
3128                 if((error == NULL) || (*error == NULL))
3129                         debug_print("Failed to get state info from NetworkManager: %s\n",
3130                                                          tmp_error->message);
3131                 g_propagate_error(error, tmp_error);
3132                 return TRUE;
3133         }
3134         return (state == NM_STATE_CONNECTED_LOCAL ||
3135                 state == NM_STATE_CONNECTED_SITE ||
3136                 state == NM_STATE_CONNECTED_GLOBAL ||
3137                 state == NM_STATE_UNKNOWN);
3138 }
3139 #endif