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