]> git.cworth.org Git - notmuch/blob - notmuch-insert.c
CLI/insert: split copy_fd
[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 const 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 bool
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 bool
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 bool
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 bool
162 maildir_create_folder (const void *ctx, const char *maildir, bool world_readable)
163 {
164     const char *subdirs[] = { "cur", "new", "tmp" };
165     const int mode = (world_readable ? 0755 : 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, bool world_readable, char **path_out)
215 {
216     char *filename, *path;
217     int fd;
218     const int mode = (world_readable ? 0644 : 0600);
219
220     do {
221         filename = tempfilename (ctx);
222         if (! filename)
223             return -1;
224
225         path = talloc_asprintf (ctx, "%s/tmp/%s", maildir, filename);
226         if (! path) {
227             fprintf (stderr, "Error: %s\n", strerror (ENOMEM));
228             return -1;
229         }
230
231         fd = open (path, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, mode);
232     } while (fd == -1 && errno == EEXIST);
233
234     if (fd == -1) {
235         fprintf (stderr, "Error: open '%s': %s\n", path, strerror (errno));
236         return -1;
237     }
238
239     *path_out = path;
240
241     return fd;
242 }
243
244 static bool
245 write_buf (const char *buf, int fdout, ssize_t remain)
246 {
247     const char *p = buf;
248
249     do {
250         ssize_t written = write (fdout, p, remain);
251         if (written < 0 && errno == EINTR)
252             continue;
253         if (written <= 0) {
254             fprintf (stderr, "Error: writing to temporary file: %s",
255                      strerror (errno));
256             return false;
257         }
258         p += written;
259         remain -= written;
260     } while (remain > 0);
261     return true;
262 }
263
264 /*
265  * Copy fdin to fdout, return true on success, and false on errors and
266  * empty input.
267  */
268 static bool
269 copy_fd (int fdout, int fdin)
270 {
271     bool empty = true;
272
273     while (! interrupted) {
274         ssize_t remain;
275         char buf[4096];
276
277         remain = read (fdin, buf, sizeof (buf));
278         if (remain == 0)
279             break;
280         if (remain < 0) {
281             if (errno == EINTR)
282                 continue;
283             fprintf (stderr, "Error: reading from standard input: %s\n",
284                      strerror (errno));
285             return false;
286         }
287         if (! write_buf (buf, fdout, remain))
288             return false;
289         empty = false;
290     }
291
292     return (! interrupted && ! empty);
293 }
294
295 /*
296  * Write fdin to a new temp file in maildir/tmp, return full path to
297  * the file, or NULL on errors.
298  */
299 static char *
300 maildir_write_tmp (const void *ctx, int fdin, const char *maildir, bool world_readable)
301 {
302     char *path;
303     int fdout;
304
305     fdout = maildir_mktemp (ctx, maildir, world_readable, &path);
306     if (fdout < 0)
307         return NULL;
308
309     if (! copy_fd (fdout, fdin))
310         goto FAIL;
311
312     if (fsync (fdout)) {
313         fprintf (stderr, "Error: fsync '%s': %s\n", path, strerror (errno));
314         goto FAIL;
315     }
316
317     close (fdout);
318
319     return path;
320
321   FAIL:
322     close (fdout);
323     unlink (path);
324
325     return NULL;
326 }
327
328 /*
329  * Write fdin to a new file in maildir/new, using an intermediate temp
330  * file in maildir/tmp, return full path to the new file, or NULL on
331  * errors.
332  */
333 static char *
334 maildir_write_new (const void *ctx, int fdin, const char *maildir, bool world_readable)
335 {
336     char *cleanpath, *tmppath, *newpath, *newdir;
337
338     tmppath = maildir_write_tmp (ctx, fdin, maildir, world_readable);
339     if (! tmppath)
340         return NULL;
341     cleanpath = tmppath;
342
343     newpath = talloc_strdup (ctx, tmppath);
344     if (! newpath) {
345         fprintf (stderr, "Error: %s\n", strerror (ENOMEM));
346         goto FAIL;
347     }
348
349     /* sanity checks needed? */
350     memcpy (newpath + strlen (maildir) + 1, "new", 3);
351
352     if (rename (tmppath, newpath)) {
353         fprintf (stderr, "Error: rename '%s' '%s': %s\n",
354                  tmppath, newpath, strerror (errno));
355         goto FAIL;
356     }
357     cleanpath = newpath;
358
359     newdir = talloc_asprintf (ctx, "%s/%s", maildir, "new");
360     if (! newdir) {
361         fprintf (stderr, "Error: %s\n", strerror (ENOMEM));
362         goto FAIL;
363     }
364
365     if (! sync_dir (newdir))
366         goto FAIL;
367
368     return newpath;
369
370   FAIL:
371     unlink (cleanpath);
372
373     return NULL;
374 }
375
376 /*
377  * Add the specified message file to the notmuch database, applying
378  * tags in tag_ops. If synchronize_flags is true, the tags are
379  * synchronized to maildir flags (which may result in message file
380  * rename).
381  *
382  * Return NOTMUCH_STATUS_SUCCESS on success, errors otherwise. If keep
383  * is true, errors in tag changes and flag syncing are ignored and
384  * success status is returned; otherwise such errors cause the message
385  * to be removed from the database. Failure to add the message to the
386  * database results in error status regardless of keep.
387  */
388 static notmuch_status_t
389 add_file (notmuch_database_t *notmuch, const char *path, tag_op_list_t *tag_ops,
390           bool synchronize_flags, bool keep,
391           notmuch_indexopts_t *indexopts)
392 {
393     notmuch_message_t *message;
394     notmuch_status_t status;
395
396     status = notmuch_database_index_file (notmuch, path, indexopts, &message);
397     if (status == NOTMUCH_STATUS_SUCCESS) {
398         status = tag_op_list_apply (message, tag_ops, 0);
399         if (status) {
400             fprintf (stderr, "%s: failed to apply tags to file '%s': %s\n",
401                      keep ? "Warning" : "Error",
402                      path, notmuch_status_to_string (status));
403             goto DONE;
404         }
405     } else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) {
406         status = NOTMUCH_STATUS_SUCCESS;
407     } else if (status == NOTMUCH_STATUS_FILE_NOT_EMAIL) {
408         fprintf (stderr, "Error: delivery of non-mail file: '%s'\n", path);
409         goto FAIL;
410     } else {
411         fprintf (stderr, "Error: failed to add '%s' to notmuch database: %s\n",
412                  path, notmuch_status_to_string (status));
413         goto FAIL;
414     }
415
416     if (synchronize_flags) {
417         status = notmuch_message_tags_to_maildir_flags (message);
418         if (status != NOTMUCH_STATUS_SUCCESS)
419             fprintf (stderr, "%s: failed to sync tags to maildir flags for '%s': %s\n",
420                      keep ? "Warning" : "Error",
421                      path, notmuch_status_to_string (status));
422
423         /*
424          * Note: Unfortunately a failed maildir flag sync might
425          * already have renamed the file, in which case the cleanup
426          * path may fail.
427          */
428     }
429
430   DONE:
431     notmuch_message_destroy (message);
432
433     if (status) {
434         if (keep) {
435             status = NOTMUCH_STATUS_SUCCESS;
436         } else {
437             notmuch_status_t cleanup_status;
438
439             cleanup_status = notmuch_database_remove_message (notmuch, path);
440             if (cleanup_status != NOTMUCH_STATUS_SUCCESS &&
441                 cleanup_status != NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) {
442                 fprintf (stderr, "Warning: failed to remove '%s' from database "
443                          "after errors: %s. Please run 'notmuch new' to fix.\n",
444                          path, notmuch_status_to_string (cleanup_status));
445             }
446         }
447     }
448
449   FAIL:
450     return status;
451 }
452
453 int
454 notmuch_insert_command (notmuch_database_t *notmuch, int argc, char *argv[])
455 {
456     notmuch_status_t status, close_status;
457     struct sigaction action;
458     const char *mail_root;
459     notmuch_config_values_t *new_tags = NULL;
460     tag_op_list_t *tag_ops;
461     char *query_string = NULL;
462     const char *folder = "";
463     bool create_folder = false;
464     bool keep = false;
465     bool hooks = true;
466     bool world_readable = false;
467     notmuch_bool_t synchronize_flags;
468     char *maildir;
469     char *newpath;
470     int opt_index;
471     notmuch_indexopts_t *indexopts = notmuch_database_get_default_indexopts (notmuch);
472
473     void *local = talloc_new (NULL);
474
475     notmuch_opt_desc_t options[] = {
476         { .opt_string = &folder, .name = "folder", .allow_empty = true },
477         { .opt_bool = &create_folder, .name = "create-folder" },
478         { .opt_bool = &keep, .name = "keep" },
479         { .opt_bool = &hooks, .name = "hooks" },
480         { .opt_bool = &world_readable, .name = "world-readable" },
481         { .opt_inherit = notmuch_shared_indexing_options },
482         { .opt_inherit = notmuch_shared_options },
483         { }
484     };
485
486     opt_index = parse_arguments (argc, argv, options, 1);
487     if (opt_index < 0)
488         return EXIT_FAILURE;
489
490     notmuch_process_shared_options (notmuch, argv[0]);
491
492     mail_root = notmuch_config_get (notmuch, NOTMUCH_CONFIG_MAIL_ROOT);
493
494     new_tags = notmuch_config_get_values (notmuch, NOTMUCH_CONFIG_NEW_TAGS);
495
496     if (print_status_database (
497             "notmuch insert",
498             notmuch,
499             notmuch_config_get_bool (notmuch, NOTMUCH_CONFIG_SYNC_MAILDIR_FLAGS,
500                                      &synchronize_flags)))
501         return EXIT_FAILURE;
502
503     tag_ops = tag_op_list_create (local);
504     if (tag_ops == NULL) {
505         fprintf (stderr, "Out of memory.\n");
506         return EXIT_FAILURE;
507     }
508     for (;
509          notmuch_config_values_valid (new_tags);
510          notmuch_config_values_move_to_next (new_tags)) {
511         const char *error_msg;
512         const char *tag = notmuch_config_values_get (new_tags);
513         error_msg = illegal_tag (tag, false);
514         if (error_msg) {
515             fprintf (stderr, "Error: tag '%s' in new.tags: %s\n",
516                      tag,  error_msg);
517             return EXIT_FAILURE;
518         }
519
520         if (tag_op_list_append (tag_ops, tag, false))
521             return EXIT_FAILURE;
522     }
523
524     if (parse_tag_command_line (local, argc - opt_index, argv + opt_index,
525                                 &query_string, tag_ops))
526         return EXIT_FAILURE;
527
528     if (*query_string != '\0') {
529         fprintf (stderr, "Error: unexpected query string: %s\n", query_string);
530         return EXIT_FAILURE;
531     }
532
533     if (! is_valid_folder_name (folder)) {
534         fprintf (stderr, "Error: invalid folder name: '%s'\n", folder);
535         return EXIT_FAILURE;
536     }
537
538     maildir = talloc_asprintf (local, "%s/%s", mail_root, folder);
539     if (! maildir) {
540         fprintf (stderr, "Out of memory\n");
541         return EXIT_FAILURE;
542     }
543
544     strip_trailing (maildir, '/');
545     if (create_folder && ! maildir_create_folder (local, maildir, world_readable))
546         return EXIT_FAILURE;
547
548     /* Set up our handler for SIGINT. We do not set SA_RESTART so that copying
549      * from standard input may be interrupted. */
550     memset (&action, 0, sizeof (struct sigaction));
551     action.sa_handler = handle_sigint;
552     sigemptyset (&action.sa_mask);
553     action.sa_flags = 0;
554     sigaction (SIGINT, &action, NULL);
555
556     /* Write the message to the Maildir new directory. */
557     newpath = maildir_write_new (local, STDIN_FILENO, maildir, world_readable);
558     if (! newpath) {
559         return EXIT_FAILURE;
560     }
561
562     status = notmuch_process_shared_indexing_options (indexopts);
563     if (status != NOTMUCH_STATUS_SUCCESS) {
564         fprintf (stderr, "Error: Failed to process index options. (%s)\n",
565                  notmuch_status_to_string (status));
566         return EXIT_FAILURE;
567     }
568
569     /* Index the message. */
570     status = add_file (notmuch, newpath, tag_ops, synchronize_flags, keep, indexopts);
571
572     /* Commit changes. */
573     close_status = notmuch_database_close (notmuch);
574     if (close_status) {
575         /* Hold on to the first error, if any. */
576         if (! status)
577             status = close_status;
578         fprintf (stderr, "%s: failed to commit database changes: %s\n",
579                  keep ? "Warning" : "Error",
580                  notmuch_status_to_string (close_status));
581     }
582
583     if (status) {
584         if (keep) {
585             status = NOTMUCH_STATUS_SUCCESS;
586         } else {
587             /* If maildir flag sync failed, this might fail. */
588             if (unlink (newpath)) {
589                 fprintf (stderr, "Warning: failed to remove '%s' from maildir "
590                          "after errors: %s. Please run 'notmuch new' to fix.\n",
591                          newpath, strerror (errno));
592             }
593         }
594     }
595
596     if (hooks && status == NOTMUCH_STATUS_SUCCESS) {
597         /* Ignore hook failures. */
598         notmuch_run_hook (notmuch, "post-insert");
599     }
600
601     notmuch_database_destroy (notmuch);
602
603     talloc_free (local);
604
605     return status_to_exit (status);
606 }