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 http://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)
73 fd = open (dir, O_RDONLY);
75 fprintf (stderr, "Error: open() dir failed: %s\n", strerror (errno));
78 ret = (fsync (fd) == 0);
80 fprintf (stderr, "Error: fsync() dir failed: %s\n", strerror (errno));
87 * Check the specified folder name does not contain a directory
88 * component ".." to prevent writes outside of the Maildir
89 * hierarchy. Return TRUE on valid folder name, FALSE otherwise.
92 is_valid_folder_name (const char *folder)
94 const char *p = folder;
97 if ((p[0] == '.') && (p[1] == '.') && (p[2] == '\0' || p[2] == '/'))
106 /* Make the given directory, succeeding if it already exists. */
107 static notmuch_bool_t
108 make_directory (char *path, int mode)
113 if (mkdir (path, mode) != 0)
114 return (errno == EEXIST);
116 /* Sync the parent directory for durability. */
118 slash = strrchr (path, '/');
121 ret = sync_dir (path);
127 /* Make the given directory including its parent directories as necessary.
128 * Return TRUE on success, FALSE on error. */
129 static notmuch_bool_t
130 make_directory_and_parents (char *path, int mode)
137 /* First check the common case: directory already exists. */
138 if (stat (path, &st) == 0)
139 return S_ISDIR (st.st_mode) ? TRUE : FALSE;
141 for (start = path; *start != '\0'; start = end + 1) {
142 /* start points to the first unprocessed character.
143 * Find the next slash from start onwards. */
144 end = strchr (start, '/');
146 /* If there are no more slashes then all the parent directories
147 * have been made. Now attempt to make the whole path. */
149 return make_directory (path, mode);
151 /* Make the path up to the next slash, unless the current
152 * directory component is actually empty. */
155 ret = make_directory (path, mode);
165 /* Create the given maildir folder, i.e. dir and its subdirectories
166 * 'cur', 'new', 'tmp'. */
167 static notmuch_bool_t
168 maildir_create_folder (void *ctx, const char *dir)
170 const int mode = 0700;
174 /* Create 'cur' directory, including parent directories. */
175 subdir = talloc_asprintf (ctx, "%s/cur", dir);
177 fprintf (stderr, "Out of memory.\n");
180 if (! make_directory_and_parents (subdir, mode))
183 tail = subdir + strlen (subdir) - 3;
185 /* Create 'new' directory. */
186 strcpy (tail, "new");
187 if (! make_directory (subdir, mode))
190 /* Create 'tmp' directory. */
191 strcpy (tail, "tmp");
192 if (! make_directory (subdir, mode))
195 talloc_free (subdir);
199 /* Open a unique file in the 'tmp' sub-directory of dir.
200 * Returns the file descriptor on success, or -1 on failure.
201 * On success, file paths for the message in the 'tmp' and 'new'
202 * directories are returned via tmppath and newpath,
203 * and the path of the 'new' directory itself in newdir. */
205 maildir_open_tmp_file (void *ctx, const char *dir,
206 char **tmppath, char **newpath, char **newdir)
214 /* We follow the Dovecot file name generation algorithm. */
216 safe_gethostname (hostname, sizeof (hostname));
218 gettimeofday (&tv, NULL);
219 filename = talloc_asprintf (ctx, "%ld.M%ldP%d.%s",
220 tv.tv_sec, tv.tv_usec, pid, hostname);
222 fprintf (stderr, "Out of memory\n");
226 *tmppath = talloc_asprintf (ctx, "%s/tmp/%s", dir, filename);
228 fprintf (stderr, "Out of memory\n");
232 fd = open (*tmppath, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, 0600);
233 } while (fd == -1 && errno == EEXIST);
236 fprintf (stderr, "Error: opening %s: %s\n", *tmppath, strerror (errno));
240 *newdir = talloc_asprintf (ctx, "%s/new", dir);
241 *newpath = talloc_asprintf (ctx, "%s/new/%s", dir, filename);
242 if (! *newdir || ! *newpath) {
243 fprintf (stderr, "Out of memory\n");
249 talloc_free (filename);
255 * Copy fdin to fdout, return TRUE on success, and FALSE on errors and
258 static notmuch_bool_t
259 copy_fd (int fdout, int fdin)
261 notmuch_bool_t empty = TRUE;
263 while (! interrupted) {
268 remain = read (fdin, buf, sizeof (buf));
274 fprintf (stderr, "Error: reading from standard input: %s\n",
281 ssize_t written = write (fdout, p, remain);
282 if (written < 0 && errno == EINTR)
285 fprintf (stderr, "Error: writing to temporary file: %s",
292 } while (remain > 0);
295 return (!interrupted && !empty);
298 static notmuch_bool_t
299 write_message (void *ctx, int fdin, const char *dir, char **newpath)
306 fdout = maildir_open_tmp_file (ctx, dir, &tmppath, newpath, &newdir);
310 cleanup_path = tmppath;
312 if (! copy_fd (fdout, fdin))
315 if (fsync (fdout) != 0) {
316 fprintf (stderr, "Error: fsync failed: %s\n", strerror (errno));
323 /* Atomically move the new message file from the Maildir 'tmp' directory
324 * to the 'new' directory. We follow the Dovecot recommendation to
325 * simply use rename() instead of link() and unlink().
326 * See also: http://wiki.dovecot.org/MailboxFormat/Maildir#Mail_delivery
328 if (rename (tmppath, *newpath) != 0) {
329 fprintf (stderr, "Error: rename() failed: %s\n", strerror (errno));
333 cleanup_path = *newpath;
335 if (! sync_dir (newdir))
343 unlink (cleanup_path);
347 /* Add the specified message file to the notmuch database, applying tags.
348 * The file is renamed to encode notmuch tags as maildir flags. */
350 add_file_to_database (notmuch_database_t *notmuch, const char *path,
351 tag_op_list_t *tag_ops, notmuch_bool_t synchronize_flags)
353 notmuch_message_t *message;
354 notmuch_status_t status;
356 status = notmuch_database_add_message (notmuch, path, &message);
358 case NOTMUCH_STATUS_SUCCESS:
359 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
362 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
363 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
364 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
365 case NOTMUCH_STATUS_OUT_OF_MEMORY:
366 case NOTMUCH_STATUS_FILE_ERROR:
367 case NOTMUCH_STATUS_NULL_POINTER:
368 case NOTMUCH_STATUS_TAG_TOO_LONG:
369 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
370 case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
371 case NOTMUCH_STATUS_LAST_STATUS:
372 fprintf (stderr, "Error: failed to add `%s' to notmuch database: %s\n",
373 path, notmuch_status_to_string (status));
377 if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) {
378 /* Don't change tags of an existing message. */
379 if (synchronize_flags) {
380 status = notmuch_message_tags_to_maildir_flags (message);
381 if (status != NOTMUCH_STATUS_SUCCESS)
382 fprintf (stderr, "Error: failed to sync tags to maildir flags\n");
385 tag_op_flag_t flags = synchronize_flags ? TAG_FLAG_MAILDIR_SYNC : 0;
387 tag_op_list_apply (message, tag_ops, flags);
390 notmuch_message_destroy (message);
394 notmuch_insert_command (notmuch_config_t *config, int argc, char *argv[])
396 notmuch_database_t *notmuch;
397 struct sigaction action;
399 const char **new_tags;
400 size_t new_tags_length;
401 tag_op_list_t *tag_ops;
402 char *query_string = NULL;
403 const char *folder = NULL;
404 notmuch_bool_t create_folder = FALSE;
405 notmuch_bool_t synchronize_flags;
411 notmuch_opt_desc_t options[] = {
412 { NOTMUCH_OPT_STRING, &folder, "folder", 0, 0 },
413 { NOTMUCH_OPT_BOOLEAN, &create_folder, "create-folder", 0, 0 },
414 { NOTMUCH_OPT_END, 0, 0, 0, 0 }
417 opt_index = parse_arguments (argc, argv, options, 1);
421 db_path = notmuch_config_get_database_path (config);
422 new_tags = notmuch_config_get_new_tags (config, &new_tags_length);
423 synchronize_flags = notmuch_config_get_maildir_synchronize_flags (config);
425 tag_ops = tag_op_list_create (config);
426 if (tag_ops == NULL) {
427 fprintf (stderr, "Out of memory.\n");
430 for (i = 0; i < new_tags_length; i++) {
431 const char *error_msg;
433 error_msg = illegal_tag (new_tags[i], FALSE);
435 fprintf (stderr, "Error: tag '%s' in new.tags: %s\n",
436 new_tags[i], error_msg);
440 if (tag_op_list_append (tag_ops, new_tags[i], FALSE))
444 if (parse_tag_command_line (config, argc - opt_index, argv + opt_index,
445 &query_string, tag_ops))
448 if (*query_string != '\0') {
449 fprintf (stderr, "Error: unexpected query string: %s\n", query_string);
453 if (folder == NULL) {
456 if (! is_valid_folder_name (folder)) {
457 fprintf (stderr, "Error: invalid folder name: '%s'\n", folder);
460 maildir = talloc_asprintf (config, "%s/%s", db_path, folder);
462 fprintf (stderr, "Out of memory\n");
465 if (create_folder && ! maildir_create_folder (config, maildir)) {
466 fprintf (stderr, "Error: creating maildir %s: %s\n",
467 maildir, strerror (errno));
472 /* Setup our handler for SIGINT. We do not set SA_RESTART so that copying
473 * from standard input may be interrupted. */
474 memset (&action, 0, sizeof (struct sigaction));
475 action.sa_handler = handle_sigint;
476 sigemptyset (&action.sa_mask);
478 sigaction (SIGINT, &action, NULL);
480 if (notmuch_database_open (notmuch_config_get_database_path (config),
481 NOTMUCH_DATABASE_MODE_READ_WRITE, ¬much))
484 /* Write the message to the Maildir new directory. */
485 if (! write_message (config, STDIN_FILENO, maildir, &newpath)) {
486 notmuch_database_destroy (notmuch);
490 /* Add the message to the index.
491 * Even if adding the message to the notmuch database fails,
492 * the message is on disk and we consider the delivery completed. */
493 add_file_to_database (notmuch, newpath, tag_ops,
496 notmuch_database_destroy (notmuch);