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));
86 /* Check the specified folder name does not contain a directory
87 * component ".." to prevent writes outside of the Maildir hierarchy. */
89 check_folder_name (const char *folder)
91 const char *p = folder;
94 if ((p[0] == '.') && (p[1] == '.') && (p[2] == '\0' || p[2] == '/'))
103 /* Make the given directory, succeeding if it already exists. */
104 static notmuch_bool_t
105 make_directory (char *path, int mode)
110 if (mkdir (path, mode) != 0)
111 return (errno == EEXIST);
113 /* Sync the parent directory for durability. */
115 slash = strrchr (path, '/');
118 ret = sync_dir (path);
124 /* Make the given directory including its parent directories as necessary.
125 * Return TRUE on success, FALSE on error. */
126 static notmuch_bool_t
127 make_directory_and_parents (char *path, int mode)
134 /* First check the common case: directory already exists. */
135 if (stat (path, &st) == 0)
136 return S_ISDIR (st.st_mode) ? TRUE : FALSE;
138 for (start = path; *start != '\0'; start = end + 1) {
139 /* start points to the first unprocessed character.
140 * Find the next slash from start onwards. */
141 end = strchr (start, '/');
143 /* If there are no more slashes then all the parent directories
144 * have been made. Now attempt to make the whole path. */
146 return make_directory (path, mode);
148 /* Make the path up to the next slash, unless the current
149 * directory component is actually empty. */
152 ret = make_directory (path, mode);
162 /* Create the given maildir folder, i.e. dir and its subdirectories
163 * 'cur', 'new', 'tmp'. */
164 static notmuch_bool_t
165 maildir_create_folder (void *ctx, const char *dir)
167 const int mode = 0700;
171 /* Create 'cur' directory, including parent directories. */
172 subdir = talloc_asprintf (ctx, "%s/cur", dir);
174 fprintf (stderr, "Out of memory.\n");
177 if (! make_directory_and_parents (subdir, mode))
180 tail = subdir + strlen (subdir) - 3;
182 /* Create 'new' directory. */
183 strcpy (tail, "new");
184 if (! make_directory (subdir, mode))
187 /* Create 'tmp' directory. */
188 strcpy (tail, "tmp");
189 if (! make_directory (subdir, mode))
192 talloc_free (subdir);
196 /* Open a unique file in the 'tmp' sub-directory of dir.
197 * Returns the file descriptor on success, or -1 on failure.
198 * On success, file paths for the message in the 'tmp' and 'new'
199 * directories are returned via tmppath and newpath,
200 * and the path of the 'new' directory itself in newdir. */
202 maildir_open_tmp_file (void *ctx, const char *dir,
203 char **tmppath, char **newpath, char **newdir)
211 /* We follow the Dovecot file name generation algorithm. */
213 safe_gethostname (hostname, sizeof (hostname));
215 gettimeofday (&tv, NULL);
216 filename = talloc_asprintf (ctx, "%ld.M%ldP%d.%s",
217 tv.tv_sec, tv.tv_usec, pid, hostname);
219 fprintf (stderr, "Out of memory\n");
223 *tmppath = talloc_asprintf (ctx, "%s/tmp/%s", dir, filename);
225 fprintf (stderr, "Out of memory\n");
229 fd = open (*tmppath, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, 0600);
230 } while (fd == -1 && errno == EEXIST);
233 fprintf (stderr, "Error: opening %s: %s\n", *tmppath, strerror (errno));
237 *newdir = talloc_asprintf (ctx, "%s/new", dir);
238 *newpath = talloc_asprintf (ctx, "%s/new/%s", dir, filename);
239 if (! *newdir || ! *newpath) {
240 fprintf (stderr, "Out of memory\n");
246 talloc_free (filename);
251 /* Copy the contents of standard input (fdin) into fdout.
252 * Returns TRUE if a non-empty file was written successfully.
253 * Otherwise, return FALSE. */
254 static notmuch_bool_t
255 copy_stdin (int fdin, int fdout)
257 notmuch_bool_t empty = TRUE;
259 while (! interrupted) {
264 remain = read (fdin, buf, sizeof (buf));
270 fprintf (stderr, "Error: reading from standard input: %s\n",
277 ssize_t written = write (fdout, p, remain);
278 if (written < 0 && errno == EINTR)
281 fprintf (stderr, "Error: writing to temporary file: %s",
288 } while (remain > 0);
291 return (!interrupted && !empty);
294 /* Add the specified message file to the notmuch database, applying tags.
295 * The file is renamed to encode notmuch tags as maildir flags. */
297 add_file_to_database (notmuch_database_t *notmuch, const char *path,
298 tag_op_list_t *tag_ops)
300 notmuch_message_t *message;
301 notmuch_status_t status;
303 status = notmuch_database_add_message (notmuch, path, &message);
305 case NOTMUCH_STATUS_SUCCESS:
306 case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
309 case NOTMUCH_STATUS_FILE_NOT_EMAIL:
310 case NOTMUCH_STATUS_READ_ONLY_DATABASE:
311 case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
312 case NOTMUCH_STATUS_OUT_OF_MEMORY:
313 case NOTMUCH_STATUS_FILE_ERROR:
314 case NOTMUCH_STATUS_NULL_POINTER:
315 case NOTMUCH_STATUS_TAG_TOO_LONG:
316 case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
317 case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
318 case NOTMUCH_STATUS_LAST_STATUS:
319 fprintf (stderr, "Error: failed to add `%s' to notmuch database: %s\n",
320 path, notmuch_status_to_string (status));
324 if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) {
325 /* Don't change tags of an existing message. */
326 status = notmuch_message_tags_to_maildir_flags (message);
327 if (status != NOTMUCH_STATUS_SUCCESS)
328 fprintf (stderr, "Error: failed to sync tags to maildir flags\n");
330 tag_op_list_apply (message, tag_ops, TAG_FLAG_MAILDIR_SYNC);
333 notmuch_message_destroy (message);
336 static notmuch_bool_t
337 insert_message (void *ctx, notmuch_database_t *notmuch, int fdin,
338 const char *dir, tag_op_list_t *tag_ops)
346 fdout = maildir_open_tmp_file (ctx, dir, &tmppath, &newpath, &newdir);
350 cleanup_path = tmppath;
352 if (! copy_stdin (fdin, fdout))
355 if (fsync (fdout) != 0) {
356 fprintf (stderr, "Error: fsync failed: %s\n", strerror (errno));
363 /* Atomically move the new message file from the Maildir 'tmp' directory
364 * to the 'new' directory. We follow the Dovecot recommendation to
365 * simply use rename() instead of link() and unlink().
366 * See also: http://wiki.dovecot.org/MailboxFormat/Maildir#Mail_delivery
368 if (rename (tmppath, newpath) != 0) {
369 fprintf (stderr, "Error: rename() failed: %s\n", strerror (errno));
373 cleanup_path = newpath;
375 if (! sync_dir (newdir))
378 /* Even if adding the message to the notmuch database fails,
379 * the message is on disk and we consider the delivery completed. */
380 add_file_to_database (notmuch, newpath, tag_ops);
387 unlink (cleanup_path);
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;
408 notmuch_opt_desc_t options[] = {
409 { NOTMUCH_OPT_STRING, &folder, "folder", 0, 0 },
410 { NOTMUCH_OPT_BOOLEAN, &create_folder, "create-folder", 0, 0 },
411 { NOTMUCH_OPT_END, 0, 0, 0, 0 }
414 opt_index = parse_arguments (argc, argv, options, 1);
417 /* diagnostics already printed */
421 db_path = notmuch_config_get_database_path (config);
422 new_tags = notmuch_config_get_new_tags (config, &new_tags_length);
424 tag_ops = tag_op_list_create (config);
425 if (tag_ops == NULL) {
426 fprintf (stderr, "Out of memory.\n");
429 for (i = 0; i < new_tags_length; i++) {
430 if (tag_op_list_append (tag_ops, new_tags[i], FALSE))
434 if (parse_tag_command_line (config, argc - opt_index, argv + opt_index,
435 &query_string, tag_ops))
438 if (*query_string != '\0') {
439 fprintf (stderr, "Error: unexpected query string: %s\n", query_string);
443 if (folder == NULL) {
446 if (! check_folder_name (folder)) {
447 fprintf (stderr, "Error: bad folder name: %s\n", folder);
450 maildir = talloc_asprintf (config, "%s/%s", db_path, folder);
452 fprintf (stderr, "Out of memory\n");
455 if (create_folder && ! maildir_create_folder (config, maildir)) {
456 fprintf (stderr, "Error: creating maildir %s: %s\n",
457 maildir, strerror (errno));
462 /* Setup our handler for SIGINT. We do not set SA_RESTART so that copying
463 * from standard input may be interrupted. */
464 memset (&action, 0, sizeof (struct sigaction));
465 action.sa_handler = handle_sigint;
466 sigemptyset (&action.sa_mask);
468 sigaction (SIGINT, &action, NULL);
470 if (notmuch_database_open (notmuch_config_get_database_path (config),
471 NOTMUCH_DATABASE_MODE_READ_WRITE, ¬much))
474 ret = insert_message (config, notmuch, STDIN_FILENO, maildir, tag_ops);
476 notmuch_database_destroy (notmuch);
478 return (ret) ? 0 : 1;