]> git.notmuchmail.org Git - notmuch/blob - contrib/notmuch-deliver/src/main.c
f7a4eaa6576bd1ec544d54c54b0e3d6e158388d0
[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 #ifdef HAVE_UNISTD_H
30 #include <unistd.h>
31 #endif
32 #ifdef HAVE_SPLICE
33 #include <fcntl.h>
34 #endif
35
36 #ifdef HAVE_SYSEXITS_H
37 #include <sysexits.h>
38 #endif
39
40 #include <glib.h>
41 #include <notmuch.h>
42
43 #include "maildircreate.h"
44 #include "maildirmisc.h"
45
46 #ifndef EX_USAGE
47 #define EX_USAGE 64
48 #endif
49
50 #ifndef EX_SOFTWARE
51 #define EX_SOFTWARE 70
52 #endif
53
54 #ifndef EX_OSERR
55 #define EX_OSERR 71
56 #endif
57
58 #ifndef EX_IOERR
59 #define EX_IOERR 74
60 #endif
61
62 #ifndef EX_TEMPFAIL
63 #define EX_TEMPFAIL 75
64 #endif
65
66 #ifndef EX_NOPERM
67 #define EX_NOPERM 77
68 #endif
69
70 #ifndef EX_CONFIG
71 #define EX_CONFIG 78
72 #endif
73
74 static gboolean opt_create, opt_fatal, opt_folder, opt_version;
75 static gboolean opt_verbose = FALSE;
76 static gchar **opt_tags = NULL;
77 static gchar **opt_rtags = NULL;
78
79 static GOptionEntry options[] = {
80         {"version", 'V', 0, G_OPTION_ARG_NONE, &opt_version,
81                 "Display version", NULL},
82         {"verbose", 'v', 0, G_OPTION_ARG_NONE, &opt_verbose,
83                 "Be verbose (useful for debugging)", NULL},
84         {"create", 'c', 0, G_OPTION_ARG_NONE, &opt_create,
85                 "Create the maildir if it doesn't exist", NULL},
86         {"folder", 'f', 0, G_OPTION_ARG_NONE, &opt_folder,
87                 "Add a dot before FOLDER, e.g: Local => $MAILDIR/.Local", NULL},
88         {"tag", 't', 0, G_OPTION_ARG_STRING_ARRAY, &opt_tags,
89                 "Add a tag to the message, may be specified multiple times", "TAG"},
90         {"remove-tag", 'r', 0, G_OPTION_ARG_STRING_ARRAY, &opt_rtags,
91                 "Remove a tag from the message, may be specified multiple times", "TAG"},
92         {"fatal-add", 0, 0, G_OPTION_ARG_NONE, &opt_fatal,
93                 "If adding the mail to the database fails, unlink it and return non-zero", NULL},
94         {NULL, 0, 0, 0, NULL, NULL, NULL},
95 };
96
97 static void
98 about(void)
99 {
100         printf(PACKAGE"-"VERSION GITHEAD "\n");
101 }
102
103 static void
104 log_handler(G_GNUC_UNUSED const gchar *domain, GLogLevelFlags level,
105         const gchar *message, G_GNUC_UNUSED gpointer user_data)
106 {
107         g_return_if_fail(message != NULL && message[0] != '\0');
108
109         if (!opt_verbose && (level & G_LOG_LEVEL_DEBUG))
110                 return;
111
112         g_printerr(PACKAGE": %s\n", message);
113 }
114
115 static gboolean
116 load_keyfile(const gchar *path, gchar **db_path, gchar ***tags)
117 {
118         GKeyFile *fd;
119         GError *error;
120
121         fd = g_key_file_new();
122         error = NULL;
123         if (!g_key_file_load_from_file(fd, path, G_KEY_FILE_NONE, &error)) {
124                 g_printerr("Failed to parse `%s': %s", path, error->message);
125                 g_error_free(error);
126                 g_key_file_free(fd);
127                 return FALSE;
128         }
129
130         *db_path = g_key_file_get_string(fd, "database", "path", &error);
131         if (*db_path == NULL) {
132                 g_critical("Failed to parse database.path from `%s': %s", path, error->message);
133                 g_error_free(error);
134                 g_key_file_free(fd);
135                 return FALSE;
136         }
137
138         *tags = g_key_file_get_string_list(fd, "new", "tags", NULL, NULL);
139
140         g_key_file_free(fd);
141         return TRUE;
142 }
143
144 #ifdef HAVE_SPLICE
145 static int
146 save_splice(int fdin, int fdout)
147 {
148         int ret, written, pfd[2];
149
150         if (pipe(pfd) < 0) {
151                 g_critical("Failed to create pipe: %s", g_strerror(errno));
152                 return EX_IOERR;
153         }
154
155         for (;;) {
156                 ret = splice(fdin, NULL, pfd[1], NULL, 4096, 0);
157                 if (!ret)
158                         break;
159                 if (ret < 0) {
160                         g_critical("Splicing data from standard input failed: %s",
161                                 g_strerror(errno));
162                         close(pfd[0]);
163                         close(pfd[1]);
164                         return EX_IOERR;
165                 }
166
167                 do {
168                         written = splice(pfd[0], NULL, fdout, NULL, ret, 0);
169                         if (!written) {
170                                 g_critical("Splicing data to temporary file failed: internal error");
171                                 close(pfd[0]);
172                                 close(pfd[1]);
173                                 return EX_IOERR;
174                         }
175                         if (written < 0) {
176                                 g_critical("Splicing data to temporary file failed: %s",
177                                         g_strerror(errno));
178                                 close(pfd[0]);
179                                 close(pfd[1]);
180                                 return EX_IOERR;
181                         }
182                         ret -= written;
183                 } while (ret);
184         }
185
186         close(pfd[0]);
187         close(pfd[1]);
188         return 0;
189 }
190 #endif /* HAVE_SPLICE */
191
192 static int
193 save_readwrite(int fdin, int fdout)
194 {
195         int ret, written;
196         char buf[4096], *p;
197
198         for (;;) {
199                 ret = read(fdin, buf, 4096);
200                 if (!ret)
201                         break;
202                 if (ret < 0) {
203                         if (errno == EINTR)
204                                 continue;
205                         g_critical("Reading from standard input failed: %s",
206                                 g_strerror(errno));
207                         return EX_IOERR;
208                 }
209                 p = buf;
210                 do {
211                         written = write(fdout, p, ret);
212                         if (!written)
213                                 return EX_IOERR;
214                         if (written < 0) {
215                                 if (errno == EINTR)
216                                         continue;
217                                 g_critical("Writing to temporary file failed: %s",
218                                         g_strerror(errno));
219                                 return EX_IOERR;
220                         }
221                         p += written;
222                         ret -= written;
223                 } while (ret);
224         }
225
226         return 0;
227 }
228
229 static int
230 save_maildir(int fdin, const char *dir, int auto_create, char **path)
231 {
232         int fdout, ret;
233         struct maildir_tmpcreate_info info;
234
235         maildir_tmpcreate_init(&info);
236         info.openmode = 0666;
237         info.maildir = dir;
238         info.doordie = 1;
239
240         while ((fdout = maildir_tmpcreate_fd(&info)) < 0)
241         {
242                 if (errno == ENOENT && auto_create && maildir_mkdir(dir) == 0)
243                 {
244                         auto_create = 0;
245                         continue;
246                 }
247
248                 g_critical("Failed to create temporary file `%s': %s",
249                         info.tmpname, g_strerror(errno));
250                 return EX_TEMPFAIL;
251         }
252
253         g_debug("Reading from standard input and writing to `%s'", info.tmpname);
254 #ifdef HAVE_SPLICE
255         ret = g_getenv("NOTMUCH_DELIVER_NO_SPLICE")
256                 ? save_readwrite(fdin, fdout)
257                 : save_splice(fdin, fdout);
258 #else
259         ret = save_readwrite(fdin, fdout);
260 #endif /* HAVE_SPLICE */
261         if (ret)
262                 goto fail;
263
264         close(fdout);
265         g_debug("Moving `%s' to `%s'", info.tmpname, info.newname);
266         if (maildir_movetmpnew(info.tmpname, info.newname)) {
267                 g_critical("Moving `%s' to `%s' failed: %s",
268                         info.tmpname, info.newname, g_strerror(errno));
269                 unlink(info.tmpname);
270                 return EX_IOERR;
271         }
272
273         if (path)
274                 *path = g_strdup(info.newname);
275
276         maildir_tmpcreate_free(&info);
277
278         return 0;
279
280 fail:
281         g_debug("Unlinking `%s'", info.tmpname);
282         unlink(info.tmpname);
283         return EX_IOERR;
284 }
285
286 static int
287 add_tags(notmuch_message_t *message, char **tags)
288 {
289         unsigned i;
290         notmuch_status_t ret;
291
292         if (!tags)
293                 return 0;
294
295         for (i = 0; tags[i]; i++) {
296                 ret = notmuch_message_add_tag(message, tags[i]);
297                 if (ret != NOTMUCH_STATUS_SUCCESS)
298                         g_warning("Failed to add tag `%s': %s",
299                                 tags[i], notmuch_status_to_string(ret));
300         }
301
302         return i;
303 }
304
305 static int
306 rm_tags(notmuch_message_t *message, char **tags)
307 {
308         unsigned i;
309         notmuch_status_t ret;
310
311         if (!tags)
312                 return 0;
313
314         for (i = 0; tags[i]; i++) {
315                 ret = notmuch_message_remove_tag(message, tags[i]);
316                 if (ret != NOTMUCH_STATUS_SUCCESS)
317                         g_warning("Failed to remove tag `%s': %s",
318                                 tags[i], notmuch_status_to_string(ret));
319         }
320
321         return i;
322 }
323
324 static int
325 save_database(notmuch_database_t *db, const char *path, char **default_tags)
326 {
327         notmuch_status_t ret;
328         notmuch_message_t *message;
329
330         g_debug("Adding `%s' to notmuch database", path);
331         ret = notmuch_database_add_message(db, path, &message);
332         switch (ret) {
333         case NOTMUCH_STATUS_SUCCESS:
334                 break;
335         case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
336                 g_debug("Message is a duplicate, not adding tags");
337                 return 0;
338         default:
339                 g_warning("Failed to add `%s' to notmuch database: %s",
340                         path, notmuch_status_to_string(ret));
341                 return EX_SOFTWARE;
342         }
343
344         g_debug("Message isn't a duplicate, adding tags");
345         add_tags(message, default_tags);
346         add_tags(message, opt_tags);
347         rm_tags(message, opt_rtags);
348
349         return 0;
350 }
351
352 int
353 main(int argc, char **argv)
354 {
355         int ret;
356         gchar *conf_path, *db_path, *folder, *maildir, *mail;
357         gchar **conf_tags;
358         GOptionContext *ctx;
359         GError *error = NULL;
360         notmuch_database_t *db;
361
362         ctx = g_option_context_new("[FOLDER]");
363         g_option_context_add_main_entries(ctx, options, PACKAGE);
364         g_option_context_set_summary(ctx, PACKAGE"-"VERSION GITHEAD" - notmuch delivery tool");
365         g_option_context_set_description(ctx,
366                 "\nConfiguration:\n"
367                 "  "PACKAGE" uses notmuch's configuration file to determine database path and\n"
368                 "  initial tags to add to new messages. You may set NOTMUCH_CONFIG environment\n"
369                 "  variable to specify an alternative configuration file.\n"
370                 "\nEnvironment:\n"
371                 "  NOTMUCH_CONFIG: Path to notmuch configuration file\n"
372                 "  NOTMUCH_DELIVER_NO_SPLICE: Don't use splice() even if it's available\n"
373                 "\nExit codes:\n"
374                 "  0   => Successful run\n"
375                 "  64  => Usage error\n"
376                 "  70  => Failed to open the database\n"
377                 "         (or to add to the database if --fatal-add is specified)\n"
378                 "  71  => Input output errors\n"
379                 "         (failed to read from standard input)\n"
380                 "         (failed to write to temporary file)\n"
381                 "  76  => Failed to open/create maildir\n"
382                 "  78  => Configuration error (wrt .notmuch-config)\n");
383
384         g_log_set_default_handler(log_handler, NULL);
385
386         if (!g_option_context_parse(ctx, &argc, &argv, &error)) {
387                 g_critical("Option parsing failed: %s", error->message);
388                 g_option_context_free(ctx);
389                 g_error_free(error);
390                 return EX_USAGE;
391         }
392         g_option_context_free(ctx);
393
394         if (opt_version) {
395                 about();
396                 return 0;
397         }
398
399         if (g_getenv("NOTMUCH_CONFIG"))
400                 conf_path = g_strdup(g_getenv("NOTMUCH_CONFIG"));
401         else if (g_getenv("HOME"))
402                 conf_path = g_build_filename(g_getenv("HOME"), ".notmuch-config", NULL);
403         else {
404                 g_critical("Neither NOTMUCH_CONFIG nor HOME set");
405                 return EX_USAGE;
406         }
407
408         db_path = NULL;
409         conf_tags = NULL;
410         g_debug("Parsing configuration from `%s'", conf_path);
411         if (!load_keyfile(conf_path, &db_path, &conf_tags)) {
412                 g_free(conf_path);
413                 return EX_CONFIG;
414         }
415         g_free(conf_path);
416
417         if ((argc - 1) > 1) {
418                 g_critical("Won't deliver to %d folders", argc - 1);
419                 return EX_USAGE;
420         }
421
422         if (argc > 1) {
423                 folder = g_strdup_printf("%s%s", opt_folder ? "." : "", argv[1]);
424                 maildir = g_build_filename(db_path, folder, NULL);
425                 g_free(folder);
426         }
427         else
428                 maildir = g_strdup(db_path);
429
430         g_debug("Opening notmuch database `%s'", db_path);
431         db = notmuch_database_open(db_path, NOTMUCH_DATABASE_MODE_READ_WRITE);
432         g_free(db_path);
433         if (db == NULL)
434                 return EX_SOFTWARE;
435         if (notmuch_database_needs_upgrade(db)) {
436                 g_message("Upgrading database");
437                 notmuch_database_upgrade(db, NULL, NULL);
438         }
439
440         g_debug("Opening maildir `%s'", maildir);
441         if ((ret = save_maildir(STDIN_FILENO, maildir, opt_create, &mail)) != 0) {
442                 g_free(maildir);
443                 return ret;
444         }
445         g_free(maildir);
446
447         if ((ret = save_database(db, mail, conf_tags)) != 0 && opt_fatal) {
448                 g_warning("Unlinking `%s'", mail);
449                 unlink(mail);
450                 return ret;
451         }
452         g_strfreev(conf_tags);
453         g_strfreev(opt_tags);
454         g_strfreev(opt_rtags);
455         g_free(mail);
456
457         notmuch_database_close(db);
458
459         return 0;
460 }