]> git.notmuchmail.org Git - notmuch/blob - notmuch-insert.c
CLI/new: support maildir synced tags in new.tags
[notmuch] / notmuch-insert.c
1 /* notmuch - Not much of an email program, (just index and search)
2  *
3  * Copyright © 2013 Peter Wang
4  *
5  * Based in part on notmuch-deliver
6  * Copyright © 2010 Ali Polatel
7  *
8  * This program is free software: you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation, either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program.  If not, see https://www.gnu.org/licenses/ .
20  *
21  * Author: Peter Wang <novalazy@gmail.com>
22  */
23
24 #include "notmuch-client.h"
25 #include "tag-util.h"
26
27 #include <sys/types.h>
28 #include <sys/stat.h>
29 #include <fcntl.h>
30 #include "string-util.h"
31
32 static volatile sig_atomic_t interrupted;
33
34 static void
35 handle_sigint (unused (int sig))
36 {
37     static char msg[] = "Stopping...         \n";
38
39     /* This write is "opportunistic", so it's okay to ignore the
40      * result.  It is not required for correctness, and if it does
41      * fail or produce a short write, we want to get out of the signal
42      * handler as quickly as possible, not retry it. */
43     IGNORE_RESULT (write (2, msg, sizeof (msg) - 1));
44     interrupted = 1;
45 }
46
47 /* Like gethostname but guarantees that a null-terminated hostname is
48  * returned, even if it has to make one up. Invalid characters are
49  * substituted such that the hostname can be used within a filename.
50  */
51 static void
52 safe_gethostname (char *hostname, size_t len)
53 {
54     char *p;
55
56     if (gethostname (hostname, len) == -1) {
57         strncpy (hostname, "unknown", len);
58     }
59     hostname[len - 1] = '\0';
60
61     for (p = hostname; *p != '\0'; p++) {
62         if (*p == '/' || *p == ':')
63             *p = '_';
64     }
65 }
66
67 /* Call fsync() on a directory path. */
68 static notmuch_bool_t
69 sync_dir (const char *dir)
70 {
71     int fd, r;
72
73     fd = open (dir, O_RDONLY);
74     if (fd == -1) {
75         fprintf (stderr, "Error: open %s: %s\n", dir, strerror (errno));
76         return FALSE;
77     }
78
79     r = fsync (fd);
80     if (r)
81         fprintf (stderr, "Error: fsync %s: %s\n", dir, strerror (errno));
82
83     close (fd);
84
85     return r == 0;
86 }
87
88 /*
89  * Check the specified folder name does not contain a directory
90  * component ".." to prevent writes outside of the Maildir
91  * hierarchy. Return TRUE on valid folder name, FALSE otherwise.
92  */
93 static notmuch_bool_t
94 is_valid_folder_name (const char *folder)
95 {
96     const char *p = folder;
97
98     for (;;) {
99         if ((p[0] == '.') && (p[1] == '.') && (p[2] == '\0' || p[2] == '/'))
100             return FALSE;
101         p = strchr (p, '/');
102         if (!p)
103             return TRUE;
104         p++;
105     }
106 }
107
108 /*
109  * Make the given directory and its parents as necessary, using the
110  * given mode. Return TRUE on success, FALSE otherwise. Partial
111  * results are not cleaned up on errors.
112  */
113 static notmuch_bool_t
114 mkdir_recursive (const void *ctx, const char *path, int mode)
115 {
116     struct stat st;
117     int r;
118     char *parent = NULL, *slash;
119
120     /* First check the common case: directory already exists. */
121     r = stat (path, &st);
122     if (r == 0) {
123         if (! S_ISDIR (st.st_mode)) {
124             fprintf (stderr, "Error: '%s' is not a directory: %s\n",
125                      path, strerror (EEXIST));
126             return FALSE;
127         }
128
129         return TRUE;
130     } else if (errno != ENOENT) {
131         fprintf (stderr, "Error: stat '%s': %s\n", path, strerror (errno));
132         return FALSE;
133     }
134
135     /* mkdir parents, if any */
136     slash = strrchr (path, '/');
137     if (slash && slash != path) {
138         parent = talloc_strndup (ctx, path, slash - path);
139         if (! parent) {
140             fprintf (stderr, "Error: %s\n", strerror (ENOMEM));
141             return FALSE;
142         }
143
144         if (! mkdir_recursive (ctx, parent, mode))
145             return FALSE;
146     }
147
148     if (mkdir (path, mode)) {
149         fprintf (stderr, "Error: mkdir '%s': %s\n", path, strerror (errno));
150         return FALSE;
151     }
152
153     return parent ? sync_dir (parent) : TRUE;
154 }
155
156 /*
157  * Create the given maildir folder, i.e. maildir and its
158  * subdirectories cur/new/tmp. Return TRUE on success, FALSE
159  * otherwise. Partial results are not cleaned up on errors.
160  */
161 static notmuch_bool_t
162 maildir_create_folder (const void *ctx, const char *maildir)
163 {
164     const char *subdirs[] = { "cur", "new", "tmp" };
165     const int mode = 0700;
166     char *subdir;
167     unsigned int i;
168
169     for (i = 0; i < ARRAY_SIZE (subdirs); i++) {
170         subdir = talloc_asprintf (ctx, "%s/%s", maildir, subdirs[i]);
171         if (! subdir) {
172             fprintf (stderr, "Error: %s\n", strerror (ENOMEM));
173             return FALSE;
174         }
175
176         if (! mkdir_recursive (ctx, subdir, mode))
177             return FALSE;
178     }
179
180     return TRUE;
181 }
182
183 /*
184  * Generate a temporary file basename, no path, do not create an
185  * actual file. Return the basename, or NULL on errors.
186  */
187 static char *
188 tempfilename (const void *ctx)
189 {
190     char *filename;
191     char hostname[256];
192     struct timeval tv;
193     pid_t pid;
194
195     /* We follow the Dovecot file name generation algorithm. */
196     pid = getpid ();
197     safe_gethostname (hostname, sizeof (hostname));
198     gettimeofday (&tv, NULL);
199
200     filename = talloc_asprintf (ctx, "%ld.M%ldP%d.%s",
201                                 (long) tv.tv_sec, (long) tv.tv_usec, pid, hostname);
202     if (! filename)
203         fprintf (stderr, "Error: %s\n", strerror (ENOMEM));
204
205     return filename;
206 }
207
208 /*
209  * Create a unique temporary file in maildir/tmp, return fd and full
210  * path to file in *path_out, or -1 on errors (in which case *path_out
211  * is not touched).
212  */
213 static int
214 maildir_mktemp (const void *ctx, const char *maildir, char **path_out)
215 {
216     char *filename, *path;
217     int fd;
218
219     do {
220         filename = tempfilename (ctx);
221         if (! filename)
222             return -1;
223
224         path = talloc_asprintf (ctx, "%s/tmp/%s", maildir, filename);
225         if (! path) {
226             fprintf (stderr, "Error: %s\n", strerror (ENOMEM));
227             return -1;
228         }
229
230         fd = open (path, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, 0600);
231     } while (fd == -1 && errno == EEXIST);
232
233     if (fd == -1) {
234         fprintf (stderr, "Error: open '%s': %s\n", path, strerror (errno));
235         return -1;
236     }
237
238     *path_out = path;
239
240     return fd;
241 }
242
243 /*
244  * Copy fdin to fdout, return TRUE on success, and FALSE on errors and
245  * empty input.
246  */
247 static notmuch_bool_t
248 copy_fd (int fdout, int fdin)
249 {
250     notmuch_bool_t empty = TRUE;
251
252     while (! interrupted) {
253         ssize_t remain;
254         char buf[4096];
255         char *p;
256
257         remain = read (fdin, buf, sizeof (buf));
258         if (remain == 0)
259             break;
260         if (remain < 0) {
261             if (errno == EINTR)
262                 continue;
263             fprintf (stderr, "Error: reading from standard input: %s\n",
264                      strerror (errno));
265             return FALSE;
266         }
267
268         p = buf;
269         do {
270             ssize_t written = write (fdout, p, remain);
271             if (written < 0 && errno == EINTR)
272                 continue;
273             if (written <= 0) {
274                 fprintf (stderr, "Error: writing to temporary file: %s",
275                          strerror (errno));
276                 return FALSE;
277             }
278             p += written;
279             remain -= written;
280             empty = FALSE;
281         } while (remain > 0);
282     }
283
284     return (!interrupted && !empty);
285 }
286
287 /*
288  * Write fdin to a new temp file in maildir/tmp, return full path to
289  * the file, or NULL on errors.
290  */
291 static char *
292 maildir_write_tmp (const void *ctx, int fdin, const char *maildir)
293 {
294     char *path;
295     int fdout;
296
297     fdout = maildir_mktemp (ctx, maildir, &path);
298     if (fdout < 0)
299         return NULL;
300
301     if (! copy_fd (fdout, fdin))
302         goto FAIL;
303
304     if (fsync (fdout)) {
305         fprintf (stderr, "Error: fsync '%s': %s\n", path, strerror (errno));
306         goto FAIL;
307     }
308
309     close (fdout);
310
311     return path;
312
313 FAIL:
314     close (fdout);
315     unlink (path);
316
317     return NULL;
318 }
319
320 /*
321  * Write fdin to a new file in maildir/new, using an intermediate temp
322  * file in maildir/tmp, return full path to the new file, or NULL on
323  * errors.
324  */
325 static char *
326 maildir_write_new (const void *ctx, int fdin, const char *maildir)
327 {
328     char *cleanpath, *tmppath, *newpath, *newdir;
329
330     tmppath = maildir_write_tmp (ctx, fdin, maildir);
331     if (! tmppath)
332         return NULL;
333     cleanpath = tmppath;
334
335     newpath = talloc_strdup (ctx, tmppath);
336     if (! newpath) {
337         fprintf (stderr, "Error: %s\n", strerror (ENOMEM));
338         goto FAIL;
339     }
340
341     /* sanity checks needed? */
342     memcpy (newpath + strlen (maildir) + 1, "new", 3);
343
344     if (rename (tmppath, newpath)) {
345         fprintf (stderr, "Error: rename '%s' '%s': %s\n",
346                  tmppath, newpath, strerror (errno));
347         goto FAIL;
348     }
349     cleanpath = newpath;
350
351     newdir = talloc_asprintf (ctx, "%s/%s", maildir, "new");
352     if (! newdir) {
353         fprintf (stderr, "Error: %s\n", strerror (ENOMEM));
354         goto FAIL;
355     }
356
357     if (! sync_dir (newdir))
358         goto FAIL;
359
360     return newpath;
361
362 FAIL:
363     unlink (cleanpath);
364
365     return NULL;
366 }
367
368 /*
369  * Add the specified message file to the notmuch database, applying
370  * tags in tag_ops. If synchronize_flags is TRUE, the tags are
371  * synchronized to maildir flags (which may result in message file
372  * rename).
373  *
374  * Return NOTMUCH_STATUS_SUCCESS on success, errors otherwise. If keep
375  * is TRUE, errors in tag changes and flag syncing are ignored and
376  * success status is returned; otherwise such errors cause the message
377  * to be removed from the database. Failure to add the message to the
378  * database results in error status regardless of keep.
379  */
380 static notmuch_status_t
381 add_file (notmuch_database_t *notmuch, const char *path, tag_op_list_t *tag_ops,
382           notmuch_bool_t synchronize_flags, notmuch_bool_t keep)
383 {
384     notmuch_message_t *message;
385     notmuch_status_t status;
386
387     status = notmuch_database_index_file (notmuch, path, NULL, &message);
388     if (status == NOTMUCH_STATUS_SUCCESS) {
389         status = tag_op_list_apply (message, tag_ops, 0);
390         if (status) {
391             fprintf (stderr, "%s: failed to apply tags to file '%s': %s\n",
392                      keep ? "Warning" : "Error",
393                      path, notmuch_status_to_string (status));
394             goto DONE;
395         }
396     } else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) {
397         status = NOTMUCH_STATUS_SUCCESS;
398     } else if (status == NOTMUCH_STATUS_FILE_NOT_EMAIL) {
399         fprintf (stderr, "Error: delivery of non-mail file: '%s'\n", path);
400         goto FAIL;
401     } else {
402         fprintf (stderr, "Error: failed to add '%s' to notmuch database: %s\n",
403                  path, notmuch_status_to_string (status));
404         goto FAIL;
405     }
406
407     if (synchronize_flags) {
408         status = notmuch_message_tags_to_maildir_flags (message);
409         if (status != NOTMUCH_STATUS_SUCCESS)
410             fprintf (stderr, "%s: failed to sync tags to maildir flags for '%s': %s\n",
411                      keep ? "Warning" : "Error",
412                      path, notmuch_status_to_string (status));
413
414         /*
415          * Note: Unfortunately a failed maildir flag sync might
416          * already have renamed the file, in which case the cleanup
417          * path may fail.
418          */
419     }
420
421   DONE:
422     notmuch_message_destroy (message);
423
424     if (status) {
425         if (keep) {
426             status = NOTMUCH_STATUS_SUCCESS;
427         } else {
428             notmuch_status_t cleanup_status;
429
430             cleanup_status = notmuch_database_remove_message (notmuch, path);
431             if (cleanup_status != NOTMUCH_STATUS_SUCCESS &&
432                 cleanup_status != NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) {
433                 fprintf (stderr, "Warning: failed to remove '%s' from database "
434                          "after errors: %s. Please run 'notmuch new' to fix.\n",
435                          path, notmuch_status_to_string (cleanup_status));
436             }
437         }
438     }
439
440   FAIL:
441     return status;
442 }
443
444 int
445 notmuch_insert_command (notmuch_config_t *config, int argc, char *argv[])
446 {
447     notmuch_status_t status, close_status;
448     notmuch_database_t *notmuch;
449     struct sigaction action;
450     const char *db_path;
451     const char **new_tags;
452     size_t new_tags_length;
453     tag_op_list_t *tag_ops;
454     char *query_string = NULL;
455     char *folder = NULL;
456     notmuch_bool_t create_folder = FALSE;
457     notmuch_bool_t keep = FALSE;
458     notmuch_bool_t no_hooks = FALSE;
459     notmuch_bool_t synchronize_flags;
460     const char *maildir;
461     char *newpath;
462     int opt_index;
463     unsigned int i;
464
465     notmuch_opt_desc_t options[] = {
466         { NOTMUCH_OPT_STRING, &folder, "folder", 0, 0 },
467         { NOTMUCH_OPT_BOOLEAN, &create_folder, "create-folder", 0, 0 },
468         { NOTMUCH_OPT_BOOLEAN, &keep, "keep", 0, 0 },
469         { NOTMUCH_OPT_BOOLEAN,  &no_hooks, "no-hooks", 'n', 0 },
470         { NOTMUCH_OPT_INHERIT, (void *) &notmuch_shared_options, NULL, 0, 0 },
471         { NOTMUCH_OPT_END, 0, 0, 0, 0 }
472     };
473
474     opt_index = parse_arguments (argc, argv, options, 1);
475     if (opt_index < 0)
476         return EXIT_FAILURE;
477
478     notmuch_process_shared_options (argv[0]);
479
480     db_path = notmuch_config_get_database_path (config);
481     new_tags = notmuch_config_get_new_tags (config, &new_tags_length);
482     synchronize_flags = notmuch_config_get_maildir_synchronize_flags (config);
483
484     tag_ops = tag_op_list_create (config);
485     if (tag_ops == NULL) {
486         fprintf (stderr, "Out of memory.\n");
487         return EXIT_FAILURE;
488     }
489     for (i = 0; i < new_tags_length; i++) {
490         const char *error_msg;
491
492         error_msg = illegal_tag (new_tags[i], FALSE);
493         if (error_msg) {
494             fprintf (stderr, "Error: tag '%s' in new.tags: %s\n",
495                      new_tags[i],  error_msg);
496             return EXIT_FAILURE;
497         }
498
499         if (tag_op_list_append (tag_ops, new_tags[i], FALSE))
500             return EXIT_FAILURE;
501     }
502
503     if (parse_tag_command_line (config, argc - opt_index, argv + opt_index,
504                                 &query_string, tag_ops))
505         return EXIT_FAILURE;
506
507     if (*query_string != '\0') {
508         fprintf (stderr, "Error: unexpected query string: %s\n", query_string);
509         return EXIT_FAILURE;
510     }
511
512     if (folder == NULL) {
513         maildir = db_path;
514     } else {
515         strip_trailing (folder, '/');
516         if (! is_valid_folder_name (folder)) {
517             fprintf (stderr, "Error: invalid folder name: '%s'\n", folder);
518             return EXIT_FAILURE;
519         }
520         maildir = talloc_asprintf (config, "%s/%s", db_path, folder);
521         if (! maildir) {
522             fprintf (stderr, "Out of memory\n");
523             return EXIT_FAILURE;
524         }
525         if (create_folder && ! maildir_create_folder (config, maildir))
526             return EXIT_FAILURE;
527     }
528
529     /* Set up our handler for SIGINT. We do not set SA_RESTART so that copying
530      * from standard input may be interrupted. */
531     memset (&action, 0, sizeof (struct sigaction));
532     action.sa_handler = handle_sigint;
533     sigemptyset (&action.sa_mask);
534     action.sa_flags = 0;
535     sigaction (SIGINT, &action, NULL);
536
537     /* Write the message to the Maildir new directory. */
538     newpath = maildir_write_new (config, STDIN_FILENO, maildir);
539     if (! newpath) {
540         return EXIT_FAILURE;
541     }
542
543     status = notmuch_database_open (notmuch_config_get_database_path (config),
544                                     NOTMUCH_DATABASE_MODE_READ_WRITE, &notmuch);
545     if (status)
546         return keep ? NOTMUCH_STATUS_SUCCESS : status_to_exit (status);
547
548     notmuch_exit_if_unmatched_db_uuid (notmuch);
549
550
551     /* Index the message. */
552     status = add_file (notmuch, newpath, tag_ops, synchronize_flags, keep);
553
554     /* Commit changes. */
555     close_status = notmuch_database_destroy (notmuch);
556     if (close_status) {
557         /* Hold on to the first error, if any. */
558         if (! status)
559             status = close_status;
560         fprintf (stderr, "%s: failed to commit database changes: %s\n",
561                  keep ? "Warning" : "Error",
562                  notmuch_status_to_string (close_status));
563     }
564
565     if (status) {
566         if (keep) {
567             status = NOTMUCH_STATUS_SUCCESS;
568         } else {
569             /* If maildir flag sync failed, this might fail. */
570             if (unlink (newpath)) {
571                 fprintf (stderr, "Warning: failed to remove '%s' from maildir "
572                          "after errors: %s. Please run 'notmuch new' to fix.\n",
573                          newpath, strerror (errno));
574             }
575         }
576     }
577
578     if (! no_hooks && status == NOTMUCH_STATUS_SUCCESS) {
579         /* Ignore hook failures. */
580         notmuch_run_hook (db_path, "post-insert");
581     }
582
583     return status_to_exit (status);
584 }