1 /* notmuch - Not much of an email program, (just index and search)
3 * Copyright © 2013 Peter Wang
5 * Based in part on notmuch-deliver
6 * Copyright © 2010 Ali Polatel
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.
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.
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/ .
21 * Author: Peter Wang <novalazy@gmail.com>
24 #include "notmuch-client.h"
27 #include <sys/types.h>
31 static volatile sig_atomic_t interrupted;
34 handle_sigint (unused (int sig))
36 static char msg[] = "Stopping... \n";
38 /* This write is "opportunistic", so it's okay to ignore the
39 * result. It is not required for correctness, and if it does
40 * fail or produce a short write, we want to get out of the signal
41 * handler as quickly as possible, not retry it. */
42 IGNORE_RESULT (write (2, msg, sizeof (msg) - 1));
46 /* Like gethostname but guarantees that a null-terminated hostname is
47 * returned, even if it has to make one up. Invalid characters are
48 * substituted such that the hostname can be used within a filename.
51 safe_gethostname (char *hostname, size_t len)
55 if (gethostname (hostname, len) == -1) {
56 strncpy (hostname, "unknown", len);
58 hostname[len - 1] = '\0';
60 for (p = hostname; *p != '\0'; p++) {
61 if (*p == '/' || *p == ':')
66 /* Call fsync() on a directory path. */
68 sync_dir (const char *dir)
72 fd = open (dir, O_RDONLY);
74 fprintf (stderr, "Error: open %s: %s\n", dir, strerror (errno));
80 fprintf (stderr, "Error: fsync %s: %s\n", dir, strerror (errno));
88 * Check the specified folder name does not contain a directory
89 * component ".." to prevent writes outside of the Maildir
90 * hierarchy. Return TRUE on valid folder name, FALSE otherwise.
93 is_valid_folder_name (const char *folder)
95 const char *p = folder;
98 if ((p[0] == '.') && (p[1] == '.') && (p[2] == '\0' || p[2] == '/'))
108 * Make the given directory and its parents as necessary, using the
109 * given mode. Return TRUE on success, FALSE otherwise. Partial
110 * results are not cleaned up on errors.
112 static notmuch_bool_t
113 mkdir_recursive (const void *ctx, const char *path, int mode)
117 char *parent = NULL, *slash;
119 /* First check the common case: directory already exists. */
120 r = stat (path, &st);
122 if (! S_ISDIR (st.st_mode)) {
123 fprintf (stderr, "Error: '%s' is not a directory: %s\n",
124 path, strerror (EEXIST));
129 } else if (errno != ENOENT) {
130 fprintf (stderr, "Error: stat '%s': %s\n", path, strerror (errno));
134 /* mkdir parents, if any */
135 slash = strrchr (path, '/');
136 if (slash && slash != path) {
137 parent = talloc_strndup (ctx, path, slash - path);
139 fprintf (stderr, "Error: %s\n", strerror (ENOMEM));
143 if (! mkdir_recursive (ctx, parent, mode))
147 if (mkdir (path, mode)) {
148 fprintf (stderr, "Error: mkdir '%s': %s\n", path, strerror (errno));
152 return parent ? sync_dir (parent) : TRUE;
156 * Create the given maildir folder, i.e. maildir and its
157 * subdirectories cur/new/tmp. Return TRUE on success, FALSE
158 * otherwise. Partial results are not cleaned up on errors.
160 static notmuch_bool_t
161 maildir_create_folder (const void *ctx, const char *maildir)
163 const char *subdirs[] = { "cur", "new", "tmp" };
164 const int mode = 0700;
168 for (i = 0; i < ARRAY_SIZE (subdirs); i++) {
169 subdir = talloc_asprintf (ctx, "%s/%s", maildir, subdirs[i]);
171 fprintf (stderr, "Error: %s\n", strerror (ENOMEM));
175 if (! mkdir_recursive (ctx, subdir, mode))
183 * Generate a temporary file basename, no path, do not create an
184 * actual file. Return the basename, or NULL on errors.
187 tempfilename (const void *ctx)
194 /* We follow the Dovecot file name generation algorithm. */
196 safe_gethostname (hostname, sizeof (hostname));
197 gettimeofday (&tv, NULL);
199 filename = talloc_asprintf (ctx, "%ld.M%ldP%d.%s",
200 (long) tv.tv_sec, (long) tv.tv_usec, pid, hostname);
202 fprintf (stderr, "Error: %s\n", strerror (ENOMEM));
208 * Create a unique temporary file in maildir/tmp, return fd and full
209 * path to file in *path_out, or -1 on errors (in which case *path_out
213 maildir_mktemp (const void *ctx, const char *maildir, char **path_out)
215 char *filename, *path;
219 filename = tempfilename (ctx);
223 path = talloc_asprintf (ctx, "%s/tmp/%s", maildir, filename);
225 fprintf (stderr, "Error: %s\n", strerror (ENOMEM));
229 fd = open (path, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, 0600);
230 } while (fd == -1 && errno == EEXIST);
233 fprintf (stderr, "Error: open '%s': %s\n", path, strerror (errno));
243 * Copy fdin to fdout, return TRUE on success, and FALSE on errors and
246 static notmuch_bool_t
247 copy_fd (int fdout, int fdin)
249 notmuch_bool_t empty = TRUE;
251 while (! interrupted) {
256 remain = read (fdin, buf, sizeof (buf));
262 fprintf (stderr, "Error: reading from standard input: %s\n",
269 ssize_t written = write (fdout, p, remain);
270 if (written < 0 && errno == EINTR)
273 fprintf (stderr, "Error: writing to temporary file: %s",
280 } while (remain > 0);
283 return (!interrupted && !empty);
287 * Write fdin to a new temp file in maildir/tmp, return full path to
288 * the file, or NULL on errors.
291 maildir_write_tmp (const void *ctx, int fdin, const char *maildir)
296 fdout = maildir_mktemp (ctx, maildir, &path);
300 if (! copy_fd (fdout, fdin))
304 fprintf (stderr, "Error: fsync '%s': %s\n", path, strerror (errno));
320 * Write fdin to a new file in maildir/new, using an intermediate temp
321 * file in maildir/tmp, return full path to the new file, or NULL on
325 maildir_write_new (const void *ctx, int fdin, const char *maildir)
327 char *cleanpath, *tmppath, *newpath, *newdir;
329 tmppath = maildir_write_tmp (ctx, fdin, maildir);
334 newpath = talloc_strdup (ctx, tmppath);
336 fprintf (stderr, "Error: %s\n", strerror (ENOMEM));
340 /* sanity checks needed? */
341 memcpy (newpath + strlen (maildir) + 1, "new", 3);
343 if (rename (tmppath, newpath)) {
344 fprintf (stderr, "Error: rename '%s' '%s': %s\n",
345 tmppath, newpath, strerror (errno));
350 newdir = talloc_asprintf (ctx, "%s/%s", maildir, "new");
352 fprintf (stderr, "Error: %s\n", strerror (ENOMEM));
356 if (! sync_dir (newdir))
368 * Add the specified message file to the notmuch database, applying
369 * tags in tag_ops. If synchronize_flags is TRUE, the tags are
370 * synchronized to maildir flags (which may result in message file
373 * Return NOTMUCH_STATUS_SUCCESS on success, errors otherwise. If keep
374 * is TRUE, errors in tag changes and flag syncing are ignored and
375 * success status is returned; otherwise such errors cause the message
376 * to be removed from the database. Failure to add the message to the
377 * database results in error status regardless of keep.
379 static notmuch_status_t
380 add_file (notmuch_database_t *notmuch, const char *path, tag_op_list_t *tag_ops,
381 notmuch_bool_t synchronize_flags, notmuch_bool_t keep)
383 notmuch_message_t *message;
384 notmuch_status_t status;
386 status = notmuch_database_add_message (notmuch, path, &message);
387 if (status == NOTMUCH_STATUS_SUCCESS) {
388 status = tag_op_list_apply (message, tag_ops, 0);
390 fprintf (stderr, "%s: failed to apply tags to file '%s': %s\n",
391 keep ? "Warning" : "Error",
392 path, notmuch_status_to_string (status));
395 } else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) {
396 status = NOTMUCH_STATUS_SUCCESS;
397 } else if (status == NOTMUCH_STATUS_FILE_NOT_EMAIL) {
398 fprintf (stderr, "Error: delivery of non-mail file: '%s'\n", path);
401 fprintf (stderr, "Error: failed to add '%s' to notmuch database: %s\n",
402 path, notmuch_status_to_string (status));
406 if (synchronize_flags) {
407 status = notmuch_message_tags_to_maildir_flags (message);
408 if (status != NOTMUCH_STATUS_SUCCESS)
409 fprintf (stderr, "%s: failed to sync tags to maildir flags for '%s': %s\n",
410 keep ? "Warning" : "Error",
411 path, notmuch_status_to_string (status));
414 * Note: Unfortunately a failed maildir flag sync might
415 * already have renamed the file, in which case the cleanup
421 notmuch_message_destroy (message);
425 status = NOTMUCH_STATUS_SUCCESS;
427 notmuch_status_t cleanup_status;
429 cleanup_status = notmuch_database_remove_message (notmuch, path);
430 if (cleanup_status != NOTMUCH_STATUS_SUCCESS &&
431 cleanup_status != NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) {
432 fprintf (stderr, "Warning: failed to remove '%s' from database "
433 "after errors: %s. Please run 'notmuch new' to fix.\n",
434 path, notmuch_status_to_string (cleanup_status));
444 notmuch_insert_command (notmuch_config_t *config, int argc, char *argv[])
446 notmuch_status_t status, close_status;
447 notmuch_database_t *notmuch;
448 struct sigaction action;
450 const char **new_tags;
451 size_t new_tags_length;
452 tag_op_list_t *tag_ops;
453 char *query_string = NULL;
454 const char *folder = NULL;
455 notmuch_bool_t create_folder = FALSE;
456 notmuch_bool_t keep = FALSE;
457 notmuch_bool_t no_hooks = FALSE;
458 notmuch_bool_t synchronize_flags;
464 notmuch_opt_desc_t options[] = {
465 { NOTMUCH_OPT_STRING, &folder, "folder", 0, 0 },
466 { NOTMUCH_OPT_BOOLEAN, &create_folder, "create-folder", 0, 0 },
467 { NOTMUCH_OPT_BOOLEAN, &keep, "keep", 0, 0 },
468 { NOTMUCH_OPT_BOOLEAN, &no_hooks, "no-hooks", 'n', 0 },
469 { NOTMUCH_OPT_INHERIT, (void *) ¬much_shared_options, NULL, 0, 0 },
470 { NOTMUCH_OPT_END, 0, 0, 0, 0 }
473 opt_index = parse_arguments (argc, argv, options, 1);
477 notmuch_process_shared_options (argv[0]);
479 db_path = notmuch_config_get_database_path (config);
480 new_tags = notmuch_config_get_new_tags (config, &new_tags_length);
481 synchronize_flags = notmuch_config_get_maildir_synchronize_flags (config);
483 tag_ops = tag_op_list_create (config);
484 if (tag_ops == NULL) {
485 fprintf (stderr, "Out of memory.\n");
488 for (i = 0; i < new_tags_length; i++) {
489 const char *error_msg;
491 error_msg = illegal_tag (new_tags[i], FALSE);
493 fprintf (stderr, "Error: tag '%s' in new.tags: %s\n",
494 new_tags[i], error_msg);
498 if (tag_op_list_append (tag_ops, new_tags[i], FALSE))
502 if (parse_tag_command_line (config, argc - opt_index, argv + opt_index,
503 &query_string, tag_ops))
506 if (*query_string != '\0') {
507 fprintf (stderr, "Error: unexpected query string: %s\n", query_string);
511 if (folder == NULL) {
514 if (! is_valid_folder_name (folder)) {
515 fprintf (stderr, "Error: invalid folder name: '%s'\n", folder);
518 maildir = talloc_asprintf (config, "%s/%s", db_path, folder);
520 fprintf (stderr, "Out of memory\n");
523 if (create_folder && ! maildir_create_folder (config, maildir))
527 /* Set up our handler for SIGINT. We do not set SA_RESTART so that copying
528 * from standard input may be interrupted. */
529 memset (&action, 0, sizeof (struct sigaction));
530 action.sa_handler = handle_sigint;
531 sigemptyset (&action.sa_mask);
533 sigaction (SIGINT, &action, NULL);
535 /* Write the message to the Maildir new directory. */
536 newpath = maildir_write_new (config, STDIN_FILENO, maildir);
541 status = notmuch_database_open (notmuch_config_get_database_path (config),
542 NOTMUCH_DATABASE_MODE_READ_WRITE, ¬much);
544 return keep ? NOTMUCH_STATUS_SUCCESS : status_to_exit (status);
546 notmuch_exit_if_unmatched_db_uuid (notmuch);
549 /* Index the message. */
550 status = add_file (notmuch, newpath, tag_ops, synchronize_flags, keep);
552 /* Commit changes. */
553 close_status = notmuch_database_destroy (notmuch);
555 /* Hold on to the first error, if any. */
557 status = close_status;
558 fprintf (stderr, "%s: failed to commit database changes: %s\n",
559 keep ? "Warning" : "Error",
560 notmuch_status_to_string (close_status));
565 status = NOTMUCH_STATUS_SUCCESS;
567 /* If maildir flag sync failed, this might fail. */
568 if (unlink (newpath)) {
569 fprintf (stderr, "Warning: failed to remove '%s' from maildir "
570 "after errors: %s. Please run 'notmuch new' to fix.\n",
571 newpath, strerror (errno));
576 if (! no_hooks && status == NOTMUCH_STATUS_SUCCESS) {
577 /* Ignore hook failures. */
578 notmuch_run_hook (db_path, "post-insert");
581 return status_to_exit (status);