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>
30 #include "string-util.h"
32 static volatile sig_atomic_t interrupted;
35 handle_sigint (unused (int sig))
37 static const char msg[] = "Stopping... \n";
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));
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.
52 safe_gethostname (char *hostname, size_t len)
56 if (gethostname (hostname, len) == -1) {
57 strncpy (hostname, "unknown", len);
59 hostname[len - 1] = '\0';
61 for (p = hostname; *p != '\0'; p++) {
62 if (*p == '/' || *p == ':')
67 /* Call fsync() on a directory path. */
69 sync_dir (const char *dir)
73 fd = open (dir, O_RDONLY);
75 fprintf (stderr, "Error: open %s: %s\n", dir, strerror (errno));
81 fprintf (stderr, "Error: fsync %s: %s\n", dir, strerror (errno));
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.
94 is_valid_folder_name (const char *folder)
96 const char *p = folder;
99 if ((p[0] == '.') && (p[1] == '.') && (p[2] == '\0' || p[2] == '/'))
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.
114 mkdir_recursive (const void *ctx, const char *path, int mode)
118 char *parent = NULL, *slash;
120 /* First check the common case: directory already exists. */
121 r = stat (path, &st);
123 if (! S_ISDIR (st.st_mode)) {
124 fprintf (stderr, "Error: '%s' is not a directory: %s\n",
125 path, strerror (EEXIST));
130 } else if (errno != ENOENT) {
131 fprintf (stderr, "Error: stat '%s': %s\n", path, strerror (errno));
135 /* mkdir parents, if any */
136 slash = strrchr (path, '/');
137 if (slash && slash != path) {
138 parent = talloc_strndup (ctx, path, slash - path);
140 fprintf (stderr, "Error: %s\n", strerror (ENOMEM));
144 if (! mkdir_recursive (ctx, parent, mode))
148 if (mkdir (path, mode)) {
149 fprintf (stderr, "Error: mkdir '%s': %s\n", path, strerror (errno));
153 return parent ? sync_dir (parent) : true;
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.
162 maildir_create_folder (const void *ctx, const char *maildir, bool world_readable)
164 const char *subdirs[] = { "cur", "new", "tmp" };
165 const int mode = (world_readable ? 0755 : 0700);
169 for (i = 0; i < ARRAY_SIZE (subdirs); i++) {
170 subdir = talloc_asprintf (ctx, "%s/%s", maildir, subdirs[i]);
172 fprintf (stderr, "Error: %s\n", strerror (ENOMEM));
176 if (! mkdir_recursive (ctx, subdir, mode))
184 * Generate a temporary file basename, no path, do not create an
185 * actual file. Return the basename, or NULL on errors.
188 tempfilename (const void *ctx)
195 /* We follow the Dovecot file name generation algorithm. */
197 safe_gethostname (hostname, sizeof (hostname));
198 gettimeofday (&tv, NULL);
200 filename = talloc_asprintf (ctx, "%ld.M%ldP%d.%s",
201 (long) tv.tv_sec, (long) tv.tv_usec, pid, hostname);
203 fprintf (stderr, "Error: %s\n", strerror (ENOMEM));
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
214 maildir_mktemp (const void *ctx, const char *maildir, bool world_readable, char **path_out)
216 char *filename, *path;
218 const int mode = (world_readable ? 0644 : 0600);
221 filename = tempfilename (ctx);
225 path = talloc_asprintf (ctx, "%s/tmp/%s", maildir, filename);
227 fprintf (stderr, "Error: %s\n", strerror (ENOMEM));
231 fd = open (path, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, mode);
232 } while (fd == -1 && errno == EEXIST);
235 fprintf (stderr, "Error: open '%s': %s\n", path, strerror (errno));
245 write_buf (const char *buf, int fdout, ssize_t remain)
250 ssize_t written = write (fdout, p, remain);
251 if (written < 0 && errno == EINTR)
254 fprintf (stderr, "Error: writing to temporary file: %s",
260 } while (remain > 0);
265 * Copy fdin to fdout, return true on success, and false on errors and
269 copy_fd (int fdout, int fdin)
273 const char *header = "X-Envelope-From: ";
275 while (! interrupted) {
280 remain = read (fdin, buf, sizeof (buf));
286 fprintf (stderr, "Error: reading from standard input: %s\n",
291 if (first && remain >= 5 && 0 == strncmp (buf, "From ", 5)) {
292 if (! write_buf (header, fdout, strlen (header)))
300 if (! write_buf (p, fdout, remain))
305 return (! interrupted && ! empty);
309 * Write fdin to a new temp file in maildir/tmp, return full path to
310 * the file, or NULL on errors.
313 maildir_write_tmp (const void *ctx, int fdin, const char *maildir, bool world_readable)
318 fdout = maildir_mktemp (ctx, maildir, world_readable, &path);
322 if (! copy_fd (fdout, fdin))
326 fprintf (stderr, "Error: fsync '%s': %s\n", path, strerror (errno));
342 * Write fdin to a new file in maildir/new, using an intermediate temp
343 * file in maildir/tmp, return full path to the new file, or NULL on
347 maildir_write_new (const void *ctx, int fdin, const char *maildir, bool world_readable)
349 char *cleanpath, *tmppath, *newpath, *newdir;
351 tmppath = maildir_write_tmp (ctx, fdin, maildir, world_readable);
356 newpath = talloc_strdup (ctx, tmppath);
358 fprintf (stderr, "Error: %s\n", strerror (ENOMEM));
362 /* sanity checks needed? */
363 memcpy (newpath + strlen (maildir) + 1, "new", 3);
365 if (rename (tmppath, newpath)) {
366 fprintf (stderr, "Error: rename '%s' '%s': %s\n",
367 tmppath, newpath, strerror (errno));
372 newdir = talloc_asprintf (ctx, "%s/%s", maildir, "new");
374 fprintf (stderr, "Error: %s\n", strerror (ENOMEM));
378 if (! sync_dir (newdir))
390 * Add the specified message file to the notmuch database, applying
391 * tags in tag_ops. If synchronize_flags is true, the tags are
392 * synchronized to maildir flags (which may result in message file
395 * Return NOTMUCH_STATUS_SUCCESS on success, errors otherwise. If keep
396 * is true, errors in tag changes and flag syncing are ignored and
397 * success status is returned; otherwise such errors cause the message
398 * to be removed from the database. Failure to add the message to the
399 * database results in error status regardless of keep.
401 static notmuch_status_t
402 add_file (notmuch_database_t *notmuch, const char *path, tag_op_list_t *tag_ops,
403 bool synchronize_flags, bool keep,
404 notmuch_indexopts_t *indexopts)
406 notmuch_message_t *message;
407 notmuch_status_t status;
409 status = notmuch_database_index_file (notmuch, path, indexopts, &message);
410 if (status == NOTMUCH_STATUS_SUCCESS) {
411 status = tag_op_list_apply (message, tag_ops, 0);
413 fprintf (stderr, "%s: failed to apply tags to file '%s': %s\n",
414 keep ? "Warning" : "Error",
415 path, notmuch_status_to_string (status));
418 } else if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) {
419 status = NOTMUCH_STATUS_SUCCESS;
420 } else if (status == NOTMUCH_STATUS_FILE_NOT_EMAIL) {
421 fprintf (stderr, "Error: delivery of non-mail file: '%s'\n", path);
424 fprintf (stderr, "Error: failed to add '%s' to notmuch database: %s\n",
425 path, notmuch_status_to_string (status));
429 if (synchronize_flags) {
430 status = notmuch_message_tags_to_maildir_flags (message);
431 if (status != NOTMUCH_STATUS_SUCCESS)
432 fprintf (stderr, "%s: failed to sync tags to maildir flags for '%s': %s\n",
433 keep ? "Warning" : "Error",
434 path, notmuch_status_to_string (status));
437 * Note: Unfortunately a failed maildir flag sync might
438 * already have renamed the file, in which case the cleanup
444 notmuch_message_destroy (message);
448 status = NOTMUCH_STATUS_SUCCESS;
450 notmuch_status_t cleanup_status;
452 cleanup_status = notmuch_database_remove_message (notmuch, path);
453 if (cleanup_status != NOTMUCH_STATUS_SUCCESS &&
454 cleanup_status != NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) {
455 fprintf (stderr, "Warning: failed to remove '%s' from database "
456 "after errors: %s. Please run 'notmuch new' to fix.\n",
457 path, notmuch_status_to_string (cleanup_status));
467 notmuch_insert_command (notmuch_database_t *notmuch, int argc, char *argv[])
469 notmuch_status_t status, close_status;
470 struct sigaction action;
471 const char *mail_root;
472 notmuch_config_values_t *new_tags = NULL;
473 tag_op_list_t *tag_ops;
474 char *query_string = NULL;
475 const char *folder = "";
476 bool create_folder = false;
479 bool world_readable = false;
480 notmuch_bool_t synchronize_flags;
484 notmuch_indexopts_t *indexopts = notmuch_database_get_default_indexopts (notmuch);
486 void *local = talloc_new (NULL);
488 notmuch_opt_desc_t options[] = {
489 { .opt_string = &folder, .name = "folder", .allow_empty = true },
490 { .opt_bool = &create_folder, .name = "create-folder" },
491 { .opt_bool = &keep, .name = "keep" },
492 { .opt_bool = &hooks, .name = "hooks" },
493 { .opt_bool = &world_readable, .name = "world-readable" },
494 { .opt_inherit = notmuch_shared_indexing_options },
495 { .opt_inherit = notmuch_shared_options },
499 opt_index = parse_arguments (argc, argv, options, 1);
503 notmuch_process_shared_options (notmuch, argv[0]);
505 mail_root = notmuch_config_get (notmuch, NOTMUCH_CONFIG_MAIL_ROOT);
507 new_tags = notmuch_config_get_values (notmuch, NOTMUCH_CONFIG_NEW_TAGS);
509 if (print_status_database (
512 notmuch_config_get_bool (notmuch, NOTMUCH_CONFIG_SYNC_MAILDIR_FLAGS,
513 &synchronize_flags)))
516 tag_ops = tag_op_list_create (local);
517 if (tag_ops == NULL) {
518 fprintf (stderr, "Out of memory.\n");
522 notmuch_config_values_valid (new_tags);
523 notmuch_config_values_move_to_next (new_tags)) {
524 const char *error_msg;
525 const char *tag = notmuch_config_values_get (new_tags);
526 error_msg = illegal_tag (tag, false);
528 fprintf (stderr, "Error: tag '%s' in new.tags: %s\n",
533 if (tag_op_list_append (tag_ops, tag, false))
537 if (parse_tag_command_line (local, argc - opt_index, argv + opt_index,
538 &query_string, tag_ops))
541 if (*query_string != '\0') {
542 fprintf (stderr, "Error: unexpected query string: %s\n", query_string);
546 if (! is_valid_folder_name (folder)) {
547 fprintf (stderr, "Error: invalid folder name: '%s'\n", folder);
551 maildir = talloc_asprintf (local, "%s/%s", mail_root, folder);
553 fprintf (stderr, "Out of memory\n");
557 strip_trailing (maildir, '/');
558 if (create_folder && ! maildir_create_folder (local, maildir, world_readable))
561 /* Set up our handler for SIGINT. We do not set SA_RESTART so that copying
562 * from standard input may be interrupted. */
563 memset (&action, 0, sizeof (struct sigaction));
564 action.sa_handler = handle_sigint;
565 sigemptyset (&action.sa_mask);
567 sigaction (SIGINT, &action, NULL);
569 /* Write the message to the Maildir new directory. */
570 newpath = maildir_write_new (local, STDIN_FILENO, maildir, world_readable);
575 status = notmuch_process_shared_indexing_options (indexopts);
576 if (status != NOTMUCH_STATUS_SUCCESS) {
577 fprintf (stderr, "Error: Failed to process index options. (%s)\n",
578 notmuch_status_to_string (status));
582 /* Index the message. */
583 status = add_file (notmuch, newpath, tag_ops, synchronize_flags, keep, indexopts);
585 /* Commit changes. */
586 close_status = notmuch_database_close (notmuch);
588 /* Hold on to the first error, if any. */
590 status = close_status;
591 fprintf (stderr, "%s: failed to commit database changes: %s\n",
592 keep ? "Warning" : "Error",
593 notmuch_status_to_string (close_status));
598 status = NOTMUCH_STATUS_SUCCESS;
600 /* If maildir flag sync failed, this might fail. */
601 if (unlink (newpath)) {
602 fprintf (stderr, "Warning: failed to remove '%s' from maildir "
603 "after errors: %s. Please run 'notmuch new' to fix.\n",
604 newpath, strerror (errno));
609 if (hooks && status == NOTMUCH_STATUS_SUCCESS) {
610 /* Ignore hook failures. */
611 notmuch_run_hook (notmuch, "post-insert");
614 notmuch_database_destroy (notmuch);
618 return status_to_exit (status);