]> git.notmuchmail.org Git - notmuch/blob - contrib/notmuch-deliver/src/main.c
More debug messages
[notmuch] / contrib / notmuch-deliver / src / main.c
1 /* vim: set cino= fo=croql sw=8 ts=8 sts=0 noet cin fdm=syntax : */
2
3 /*
4  * Copyright (c) 2010 Ali Polatel <alip@exherbo.org>
5  * Based in part upon deliverquota of maildrop which is:
6  *   Copyright 1998 - 2009 Double Precision, Inc.
7  *
8  * This file is part of the notmuch-deliver. notmuch-deliver is free software;
9  * you can redistribute it and/or modify it under the terms of the GNU General
10  * Public License version 2, as published by the Free Software Foundation.
11  *
12  * notmuch-deliver is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
15  * more details.
16  *
17  * You should have received a copy of the GNU General Public License along with
18  * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
19  * Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21
22 #ifdef HAVE_CONFIG_H
23 #include "config.h"
24 #endif
25
26 #include <errno.h>
27 #include <stdio.h>
28 #include <string.h>
29 #include <unistd.h>
30
31 #ifdef HAVE_SYSEXITS_H
32 #include <sysexits.h>
33 #endif
34
35 #include <glib.h>
36 #include <notmuch.h>
37
38 #include "maildircreate.h"
39 #include "maildirmisc.h"
40
41 #ifndef EX_USAGE
42 #define EX_USAGE 64
43 #endif
44
45 #ifndef EX_SOFTWARE
46 #define EX_SOFTWARE 70
47 #endif
48
49 #ifndef EX_OSERR
50 #define EX_OSERR 71
51 #endif
52
53 #ifndef EX_IOERR
54 #define EX_IOERR 74
55 #endif
56
57 #ifndef EX_TEMPFAIL
58 #define EX_TEMPFAIL 75
59 #endif
60
61 #ifndef EX_NOPERM
62 #define EX_NOPERM 77
63 #endif
64
65 #ifndef EX_CONFIG
66 #define EX_CONFIG 78
67 #endif
68
69 static gboolean opt_create, opt_fatal, opt_folder, opt_version;
70 static gboolean opt_verbose = FALSE;
71 static gchar **opt_tags = NULL;
72 static gchar **opt_rtags = NULL;
73
74 static GOptionEntry options[] = {
75         {"version", 'V', 0, G_OPTION_ARG_NONE, &opt_version,
76                 "Display version", NULL},
77         {"verbose", 'v', 0, G_OPTION_ARG_NONE, &opt_verbose,
78                 "Be verbose (useful for debugging)", NULL},
79         {"create", 'c', 0, G_OPTION_ARG_NONE, &opt_create,
80                 "Create the maildir if it doesn't exist", NULL},
81         {"folder", 'f', 0, G_OPTION_ARG_NONE, &opt_folder,
82                 "Add a dot before FOLDER, e.g: Local => $MAILDIR/.Local", NULL},
83         {"tag", 't', 0, G_OPTION_ARG_STRING_ARRAY, &opt_tags,
84                 "Add a tag to the message, may be specified multiple times", "TAG"},
85         {"remove-tag", 'r', 0, G_OPTION_ARG_STRING_ARRAY, &opt_rtags,
86                 "Remove a tag from the message, may be specified multiple times", "TAG"},
87         {"fatal-add", 0, 0, G_OPTION_ARG_NONE, &opt_fatal,
88                 "If adding the mail to the database fails, unlink it and return non-zero", NULL},
89         {NULL, 0, 0, 0, NULL, NULL, NULL},
90 };
91
92 static void
93 about(void)
94 {
95         printf(PACKAGE"-"VERSION GITHEAD "\n");
96 }
97
98 static void
99 log_handler(G_GNUC_UNUSED const gchar *domain, GLogLevelFlags level,
100         const gchar *message, G_GNUC_UNUSED gpointer user_data)
101 {
102         g_return_if_fail(message != NULL && message[0] != '\0');
103
104         if (!opt_verbose && (level & G_LOG_LEVEL_DEBUG))
105                 return;
106
107         g_printerr(PACKAGE": %s\n", message);
108 }
109
110 static gboolean
111 load_keyfile(const gchar *path, gchar **db_path, gchar ***tags)
112 {
113         GKeyFile *fd;
114         GError *error;
115
116         fd = g_key_file_new();
117         error = NULL;
118         if (!g_key_file_load_from_file(fd, path, G_KEY_FILE_NONE, &error)) {
119                 g_printerr("Failed to parse `%s': %s", path, error->message);
120                 g_error_free(error);
121                 g_key_file_free(fd);
122                 return FALSE;
123         }
124
125         *db_path = g_key_file_get_string(fd, "database", "path", &error);
126         if (*db_path == NULL) {
127                 g_critical("Failed to parse database.path from `%s': %s", path, error->message);
128                 g_error_free(error);
129                 g_key_file_free(fd);
130                 return FALSE;
131         }
132
133         *tags = g_key_file_get_string_list(fd, "new", "tags", NULL, NULL);
134
135         g_key_file_free(fd);
136         return TRUE;
137 }
138
139 static int
140 save_maildir(int fdin, const char *dir, int auto_create, char **path)
141 {
142         int fd, ret, written;
143         char buf[4096], *p;
144         struct maildir_tmpcreate_info info;
145
146         maildir_tmpcreate_init(&info);
147         info.openmode = 0666;
148         info.maildir = dir;
149         info.doordie = 1;
150
151         while ((fd = maildir_tmpcreate_fd(&info)) < 0)
152         {
153                 if (errno == ENOENT && auto_create && maildir_mkdir(dir) == 0)
154                 {
155                         auto_create = 0;
156                         continue;
157                 }
158
159                 g_critical("Failed to create temporary file `%s': %s",
160                         info.tmpname, g_strerror(errno));
161                 return EX_TEMPFAIL;
162         }
163
164         g_debug("Reading from standard input and writing to `%s'", info.tmpname);
165         for (;;) {
166                 ret = read(fdin, buf, 4096);
167                 if (!ret)
168                         break;
169                 if (ret < 0) {
170                         if (errno == EINTR)
171                                 continue;
172                         g_critical("Reading from standard input failed: %s", g_strerror(errno));
173                         goto fail;
174                 }
175                 p = buf;
176                 do {
177                         written = write(fd, p, ret);
178                         if (!written)
179                                 goto fail;
180                         if (written < 0) {
181                                 if (errno == EINTR)
182                                         continue;
183                                 g_critical("Writing to temporary file `%s' failed: %s",
184                                         info.tmpname, g_strerror(errno));
185                                 goto fail;
186                         }
187                         p += written;
188                         ret -= written;
189                 } while (ret);
190         }
191
192         close(fd);
193         g_debug("Moving `%s' to `%s'", info.tmpname, info.newname);
194         if (maildir_movetmpnew(info.tmpname, info.newname)) {
195                 g_critical("Moving `%s' to `%s' failed: %s",
196                         info.tmpname, info.newname, g_strerror(errno));
197                 unlink(info.tmpname);
198                 return EX_IOERR;
199         }
200
201         if (path)
202                 *path = g_strdup(info.newname);
203
204         maildir_tmpcreate_free(&info);
205
206         return 0;
207
208 fail:
209         g_debug("Unlinking `%s'", info.tmpname);
210         unlink(info.tmpname);
211         return EX_IOERR;
212 }
213
214 static int
215 add_tags(notmuch_message_t *message, char **tags)
216 {
217         unsigned i;
218         notmuch_status_t ret;
219
220         if (!tags)
221                 return 0;
222
223         for (i = 0; tags[i]; i++) {
224                 ret = notmuch_message_add_tag(message, tags[i]);
225                 if (ret != NOTMUCH_STATUS_SUCCESS)
226                         g_warning("Failed to add tag `%s': %s",
227                                 tags[i], notmuch_status_to_string(ret));
228         }
229
230         return i;
231 }
232
233 static int
234 rm_tags(notmuch_message_t *message, char **tags)
235 {
236         unsigned i;
237         notmuch_status_t ret;
238
239         if (!tags)
240                 return 0;
241
242         for (i = 0; tags[i]; i++) {
243                 ret = notmuch_message_remove_tag(message, tags[i]);
244                 if (ret != NOTMUCH_STATUS_SUCCESS)
245                         g_warning("Failed to remove tag `%s': %s",
246                                 tags[i], notmuch_status_to_string(ret));
247         }
248
249         return i;
250 }
251
252 static int
253 save_database(notmuch_database_t *db, const char *path, char **default_tags)
254 {
255         notmuch_status_t ret;
256         notmuch_message_t *message;
257
258         g_debug("Adding `%s' to notmuch database", path);
259         ret = notmuch_database_add_message(db, path, &message);
260         switch (ret) {
261         case NOTMUCH_STATUS_SUCCESS:
262                 break;
263         case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
264                 g_debug("Message is a duplicate, not adding tags");
265                 return 0;
266         default:
267                 g_warning("Failed to add `%s' to notmuch database: %s",
268                         path, notmuch_status_to_string(ret));
269                 return EX_SOFTWARE;
270         }
271
272         g_debug("Message isn't a duplicate, adding tags");
273         add_tags(message, default_tags);
274         add_tags(message, opt_tags);
275         rm_tags(message, opt_rtags);
276
277         return 0;
278 }
279
280 int
281 main(int argc, char **argv)
282 {
283         int ret;
284         gchar *conf_path, *db_path, *folder, *maildir, *mail;
285         gchar **conf_tags;
286         GOptionContext *ctx;
287         GError *error = NULL;
288         notmuch_database_t *db;
289
290         ctx = g_option_context_new("[FOLDER]");
291         g_option_context_add_main_entries(ctx, options, PACKAGE);
292         g_option_context_set_summary(ctx, PACKAGE"-"VERSION GITHEAD" - notmuch delivery tool");
293         g_option_context_set_description(ctx,
294                 "\nConfiguration:\n"
295                 "  "PACKAGE" uses notmuch's configuration file to determine database path and\n"
296                 "  initial tags to add to new messages. You may set NOTMUCH_CONFIG environment\n"
297                 "  variable to specify an alternative configuration file.\n"
298                 "\nExit codes:\n"
299                 "  0   => Successful run\n"
300                 "  64  => Usage error\n"
301                 "  70  => Failed to open the database\n"
302                 "         (or to add to the database if --fatal-add is specified)\n"
303                 "  71  => Input output errors\n"
304                 "         (failed to read from standard input)\n"
305                 "         (failed to write to temporary file)\n"
306                 "  76  => Failed to open/create maildir\n"
307                 "  78  => Configuration error (wrt .notmuch-config)\n");
308
309         g_log_set_default_handler(log_handler, NULL);
310
311         if (!g_option_context_parse(ctx, &argc, &argv, &error)) {
312                 g_critical("Option parsing failed: %s", error->message);
313                 g_option_context_free(ctx);
314                 g_error_free(error);
315                 return EX_USAGE;
316         }
317         g_option_context_free(ctx);
318
319         if (opt_version) {
320                 about();
321                 return 0;
322         }
323
324         if (g_getenv("NOTMUCH_CONFIG"))
325                 conf_path = g_strdup(g_getenv("NOTMUCH_CONFIG"));
326         else if (g_getenv("HOME"))
327                 conf_path = g_build_filename(g_getenv("HOME"), ".notmuch-config", NULL);
328         else {
329                 g_critical("Neither NOTMUCH_CONFIG nor HOME set");
330                 return EX_USAGE;
331         }
332
333         db_path = NULL;
334         conf_tags = NULL;
335         g_debug("Parsing configuration from `%s'", conf_path);
336         if (!load_keyfile(conf_path, &db_path, &conf_tags)) {
337                 g_free(conf_path);
338                 return EX_CONFIG;
339         }
340         g_free(conf_path);
341
342         if (argc > 1) {
343                 folder = g_strdup_printf("%s%s", opt_folder ? "." : "", argv[1]);
344                 maildir = g_build_filename(db_path, folder, NULL);
345                 g_free(folder);
346         }
347         else
348                 maildir = g_strdup(db_path);
349
350         g_debug("Opening notmuch database `%s'", db_path);
351         db = notmuch_database_open(db_path, NOTMUCH_DATABASE_MODE_READ_WRITE);
352         g_free(db_path);
353         if (db == NULL)
354                 return EX_SOFTWARE;
355         if (notmuch_database_needs_upgrade(db)) {
356                 g_message("Upgrading database");
357                 notmuch_database_upgrade(db, NULL, NULL);
358         }
359
360         g_debug("Opening maildir `%s'", maildir);
361         if ((ret = save_maildir(STDIN_FILENO, maildir, opt_create, &mail)) != 0) {
362                 g_free(maildir);
363                 return ret;
364         }
365         g_free(maildir);
366
367         if ((ret = save_database(db, mail, conf_tags)) != 0 && opt_fatal) {
368                 g_warning("Unlinking `%s'", mail);
369                 unlink(mail);
370                 return ret;
371         }
372         g_strfreev(conf_tags);
373         g_strfreev(opt_tags);
374         g_strfreev(opt_rtags);
375         g_free(mail);
376
377         notmuch_database_close(db);
378
379         return 0;
380 }