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