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)
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 tv.tv_sec, tv.tv_usec, pid, hostname);
202 fprintf (stderr, "Error: %s\n", strerror (ENOMEM));
207 /* Open a unique file in the 'tmp' sub-directory of dir.
208 * Returns the file descriptor on success, or -1 on failure.
209 * On success, file paths for the message in the 'tmp' and 'new'
210 * directories are returned via tmppath and newpath,
211 * and the path of the 'new' directory itself in newdir. */
213 maildir_open_tmp_file (void *ctx, const char *dir,
214 char **tmppath, char **newpath, char **newdir)
220 filename = tempfilename (ctx);
224 *tmppath = talloc_asprintf (ctx, "%s/tmp/%s", dir, filename);
226 fprintf (stderr, "Out of memory\n");
230 fd = open (*tmppath, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, 0600);
231 } while (fd == -1 && errno == EEXIST);
234 fprintf (stderr, "Error: opening %s: %s\n", *tmppath, strerror (errno));
238 *newdir = talloc_asprintf (ctx, "%s/new", dir);
239 *newpath = talloc_asprintf (ctx, "%s/new/%s", dir, filename);
240 if (! *newdir || ! *newpath) {
241 fprintf (stderr, "Out of memory\n");
247 talloc_free (filename);
253 * Copy fdin to fdout, return TRUE on success, and FALSE on errors and
256 static notmuch_bool_t
257 copy_fd (int fdout, int fdin)
259 notmuch_bool_t empty = TRUE;
261 while (! interrupted) {
266 remain = read (fdin, buf, sizeof (buf));
272 fprintf (stderr, "Error: reading from standard input: %s\n",
279 ssize_t written = write (fdout, p, remain);
280 if (written < 0 && errno == EINTR)
283 fprintf (stderr, "Error: writing to temporary file: %s",
290 } while (remain > 0);
293 return (!interrupted && !empty);
296 static notmuch_bool_t
297 write_message (void *ctx, int fdin, const char *dir, char **newpath)
304 fdout = maildir_open_tmp_file (ctx, dir, &tmppath, newpath, &newdir);
308 cleanup_path = tmppath;
310 if (! copy_fd (fdout, fdin))
313 if (fsync (fdout) != 0) {
314 fprintf (stderr, "Error: fsync failed: %s\n", strerror (errno));
321 /* Atomically move the new message file from the Maildir 'tmp' directory
322 * to the 'new' directory. We follow the Dovecot recommendation to
323 * simply use rename() instead of link() and unlink().
324 * See also: http://wiki.dovecot.org/MailboxFormat/Maildir#Mail_delivery
326 if (rename (tmppath, *newpath) != 0) {
327 fprintf (stderr, "Error: rename() failed: %s\n", strerror (errno));
331 cleanup_path = *newpath;
333 if (! sync_dir (newdir))
341 unlink (cleanup_path);
345 /* Add the specified message file to the notmuch database, applying tags.
346 * The file is renamed to encode notmuch tags as maildir flags. */
348 add_file_to_database (notmuch_database_t *notmuch, const char *path,
349 tag_op_list_t *tag_ops, notmuch_bool_t synchronize_flags)
351 notmuch_message_t *message;
352 notmuch_status_t status;
354 status = notmuch_database_add_message (notmuch, path, &message);
356 case NOTMUCH_STATUS_SUCCESS:
357 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
360 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
361 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
362 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
363 case NOTMUCH_STATUS_OUT_OF_MEMORY:
364 case NOTMUCH_STATUS_FILE_ERROR:
365 case NOTMUCH_STATUS_NULL_POINTER:
366 case NOTMUCH_STATUS_TAG_TOO_LONG:
367 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
368 case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
369 case NOTMUCH_STATUS_LAST_STATUS:
370 fprintf (stderr, "Error: failed to add `%s' to notmuch database: %s\n",
371 path, notmuch_status_to_string (status));
375 if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) {
376 /* Don't change tags of an existing message. */
377 if (synchronize_flags) {
378 status = notmuch_message_tags_to_maildir_flags (message);
379 if (status != NOTMUCH_STATUS_SUCCESS)
380 fprintf (stderr, "Error: failed to sync tags to maildir flags\n");
383 tag_op_flag_t flags = synchronize_flags ? TAG_FLAG_MAILDIR_SYNC : 0;
385 tag_op_list_apply (message, tag_ops, flags);
388 notmuch_message_destroy (message);
392 notmuch_insert_command (notmuch_config_t *config, int argc, char *argv[])
394 notmuch_database_t *notmuch;
395 struct sigaction action;
397 const char **new_tags;
398 size_t new_tags_length;
399 tag_op_list_t *tag_ops;
400 char *query_string = NULL;
401 const char *folder = NULL;
402 notmuch_bool_t create_folder = FALSE;
403 notmuch_bool_t synchronize_flags;
409 notmuch_opt_desc_t options[] = {
410 { NOTMUCH_OPT_STRING, &folder, "folder", 0, 0 },
411 { NOTMUCH_OPT_BOOLEAN, &create_folder, "create-folder", 0, 0 },
412 { NOTMUCH_OPT_END, 0, 0, 0, 0 }
415 opt_index = parse_arguments (argc, argv, options, 1);
419 db_path = notmuch_config_get_database_path (config);
420 new_tags = notmuch_config_get_new_tags (config, &new_tags_length);
421 synchronize_flags = notmuch_config_get_maildir_synchronize_flags (config);
423 tag_ops = tag_op_list_create (config);
424 if (tag_ops == NULL) {
425 fprintf (stderr, "Out of memory.\n");
428 for (i = 0; i < new_tags_length; i++) {
429 const char *error_msg;
431 error_msg = illegal_tag (new_tags[i], FALSE);
433 fprintf (stderr, "Error: tag '%s' in new.tags: %s\n",
434 new_tags[i], error_msg);
438 if (tag_op_list_append (tag_ops, new_tags[i], FALSE))
442 if (parse_tag_command_line (config, argc - opt_index, argv + opt_index,
443 &query_string, tag_ops))
446 if (*query_string != '\0') {
447 fprintf (stderr, "Error: unexpected query string: %s\n", query_string);
451 if (folder == NULL) {
454 if (! is_valid_folder_name (folder)) {
455 fprintf (stderr, "Error: invalid folder name: '%s'\n", folder);
458 maildir = talloc_asprintf (config, "%s/%s", db_path, folder);
460 fprintf (stderr, "Out of memory\n");
463 if (create_folder && ! maildir_create_folder (config, maildir))
467 /* Setup our handler for SIGINT. We do not set SA_RESTART so that copying
468 * from standard input may be interrupted. */
469 memset (&action, 0, sizeof (struct sigaction));
470 action.sa_handler = handle_sigint;
471 sigemptyset (&action.sa_mask);
473 sigaction (SIGINT, &action, NULL);
475 if (notmuch_database_open (notmuch_config_get_database_path (config),
476 NOTMUCH_DATABASE_MODE_READ_WRITE, ¬much))
479 /* Write the message to the Maildir new directory. */
480 if (! write_message (config, STDIN_FILENO, maildir, &newpath)) {
481 notmuch_database_destroy (notmuch);
485 /* Add the message to the index.
486 * Even if adding the message to the notmuch database fails,
487 * the message is on disk and we consider the delivery completed. */
488 add_file_to_database (notmuch, newpath, tag_ops,
491 notmuch_database_destroy (notmuch);