]> git.notmuchmail.org Git - notmuch/blob - notmuch-insert.c
contrib: pick: bind M-p and M-n to prev/next thread
[notmuch] / notmuch-insert.c
1 /* notmuch - Not much of an email program, (just index and search)
2  *
3  * Copyright © 2013 Peter Wang
4  *
5  * Based in part on notmuch-deliver
6  * Copyright © 2010 Ali Polatel
7  *
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.
12  *
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.
17  *
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/ .
20  *
21  * Author: Peter Wang <novalazy@gmail.com>
22  */
23
24 #include "notmuch-client.h"
25 #include "tag-util.h"
26
27 #include <sys/types.h>
28 #include <sys/stat.h>
29 #include <fcntl.h>
30
31 static volatile sig_atomic_t interrupted;
32
33 static void
34 handle_sigint (unused (int sig))
35 {
36     static char msg[] = "Stopping...         \n";
37
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));
43     interrupted = 1;
44 }
45
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.
49  */
50 static void
51 safe_gethostname (char *hostname, size_t len)
52 {
53     char *p;
54
55     if (gethostname (hostname, len) == -1) {
56         strncpy (hostname, "unknown", len);
57     }
58     hostname[len - 1] = '\0';
59
60     for (p = hostname; *p != '\0'; p++) {
61         if (*p == '/' || *p == ':')
62             *p = '_';
63     }
64 }
65
66 /* Call fsync() on a directory path. */
67 static notmuch_bool_t
68 sync_dir (const char *dir)
69 {
70     notmuch_bool_t ret;
71     int fd;
72
73     fd = open (dir, O_RDONLY);
74     if (fd == -1) {
75         fprintf (stderr, "Error: open() dir failed: %s\n", strerror (errno));
76         return FALSE;
77     }
78     ret = (fsync (fd) == 0);
79     if (! ret) {
80         fprintf (stderr, "Error: fsync() dir failed: %s\n", strerror (errno));
81     }
82     close (fd);
83     return ret;
84 }
85
86 /* Check the specified folder name does not contain a directory
87  * component ".." to prevent writes outside of the Maildir hierarchy. */
88 static notmuch_bool_t
89 check_folder_name (const char *folder)
90 {
91     const char *p = folder;
92
93     for (;;) {
94         if ((p[0] == '.') && (p[1] == '.') && (p[2] == '\0' || p[2] == '/'))
95             return FALSE;
96         p = strchr (p, '/');
97         if (!p)
98             return TRUE;
99         p++;
100     }
101 }
102
103 /* Make the given directory, succeeding if it already exists. */
104 static notmuch_bool_t
105 make_directory (char *path, int mode)
106 {
107     notmuch_bool_t ret;
108     char *slash;
109
110     if (mkdir (path, mode) != 0)
111         return (errno == EEXIST);
112
113     /* Sync the parent directory for durability. */
114     ret = TRUE;
115     slash = strrchr (path, '/');
116     if (slash) {
117         *slash = '\0';
118         ret = sync_dir (path);
119         *slash = '/';
120     }
121     return ret;
122 }
123
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)
128 {
129     struct stat st;
130     char *start;
131     char *end;
132     notmuch_bool_t ret;
133
134     /* First check the common case: directory already exists. */
135     if (stat (path, &st) == 0)
136         return S_ISDIR (st.st_mode) ? TRUE : FALSE;
137
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, '/');
142
143         /* If there are no more slashes then all the parent directories
144          * have been made.  Now attempt to make the whole path. */
145         if (end == NULL)
146             return make_directory (path, mode);
147
148         /* Make the path up to the next slash, unless the current
149          * directory component is actually empty. */
150         if (end > start) {
151             *end = '\0';
152             ret = make_directory (path, mode);
153             *end = '/';
154             if (! ret)
155                 return FALSE;
156         }
157     }
158
159     return TRUE;
160 }
161
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)
166 {
167     const int mode = 0700;
168     char *subdir;
169     char *tail;
170
171     /* Create 'cur' directory, including parent directories. */
172     subdir = talloc_asprintf (ctx, "%s/cur", dir);
173     if (! subdir) {
174         fprintf (stderr, "Out of memory.\n");
175         return FALSE;
176     }
177     if (! make_directory_and_parents (subdir, mode))
178         return FALSE;
179
180     tail = subdir + strlen (subdir) - 3;
181
182     /* Create 'new' directory. */
183     strcpy (tail, "new");
184     if (! make_directory (subdir, mode))
185         return FALSE;
186
187     /* Create 'tmp' directory. */
188     strcpy (tail, "tmp");
189     if (! make_directory (subdir, mode))
190         return FALSE;
191
192     talloc_free (subdir);
193     return TRUE;
194 }
195
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. */
201 static int
202 maildir_open_tmp_file (void *ctx, const char *dir,
203                        char **tmppath, char **newpath, char **newdir)
204 {
205     pid_t pid;
206     char hostname[256];
207     struct timeval tv;
208     char *filename;
209     int fd = -1;
210
211     /* We follow the Dovecot file name generation algorithm. */
212     pid = getpid ();
213     safe_gethostname (hostname, sizeof (hostname));
214     do {
215         gettimeofday (&tv, NULL);
216         filename = talloc_asprintf (ctx, "%ld.M%ldP%d.%s",
217                                     tv.tv_sec, tv.tv_usec, pid, hostname);
218         if (! filename) {
219             fprintf (stderr, "Out of memory\n");
220             return -1;
221         }
222
223         *tmppath = talloc_asprintf (ctx, "%s/tmp/%s", dir, filename);
224         if (! *tmppath) {
225             fprintf (stderr, "Out of memory\n");
226             return -1;
227         }
228
229         fd = open (*tmppath, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, 0600);
230     } while (fd == -1 && errno == EEXIST);
231
232     if (fd == -1) {
233         fprintf (stderr, "Error: opening %s: %s\n", *tmppath, strerror (errno));
234         return -1;
235     }
236
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");
241         close (fd);
242         unlink (*tmppath);
243         return -1;
244     }
245
246     talloc_free (filename);
247
248     return fd;
249 }
250
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)
256 {
257     notmuch_bool_t empty = TRUE;
258
259     while (! interrupted) {
260         ssize_t remain;
261         char buf[4096];
262         char *p;
263
264         remain = read (fdin, buf, sizeof (buf));
265         if (remain == 0)
266             break;
267         if (remain < 0) {
268             if (errno == EINTR)
269                 continue;
270             fprintf (stderr, "Error: reading from standard input: %s\n",
271                      strerror (errno));
272             return FALSE;
273         }
274
275         p = buf;
276         do {
277             ssize_t written = write (fdout, p, remain);
278             if (written < 0 && errno == EINTR)
279                 continue;
280             if (written <= 0) {
281                 fprintf (stderr, "Error: writing to temporary file: %s",
282                          strerror (errno));
283                 return FALSE;
284             }
285             p += written;
286             remain -= written;
287             empty = FALSE;
288         } while (remain > 0);
289     }
290
291     return (!interrupted && !empty);
292 }
293
294 /* Add the specified message file to the notmuch database, applying tags.
295  * The file is renamed to encode notmuch tags as maildir flags. */
296 static void
297 add_file_to_database (notmuch_database_t *notmuch, const char *path,
298                       tag_op_list_t *tag_ops)
299 {
300     notmuch_message_t *message;
301     notmuch_status_t status;
302
303     status = notmuch_database_add_message (notmuch, path, &message);
304     switch (status) {
305     case NOTMUCH_STATUS_SUCCESS:
306     case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
307         break;
308     default:
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));
321         return;
322     }
323
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");
329     } else {
330         tag_op_list_apply (message, tag_ops, TAG_FLAG_MAILDIR_SYNC);
331     }
332
333     notmuch_message_destroy (message);
334 }
335
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)
339 {
340     char *tmppath;
341     char *newpath;
342     char *newdir;
343     int fdout;
344     char *cleanup_path;
345
346     fdout = maildir_open_tmp_file (ctx, dir, &tmppath, &newpath, &newdir);
347     if (fdout < 0)
348         return FALSE;
349
350     cleanup_path = tmppath;
351
352     if (! copy_stdin (fdin, fdout))
353         goto FAIL;
354
355     if (fsync (fdout) != 0) {
356         fprintf (stderr, "Error: fsync failed: %s\n", strerror (errno));
357         goto FAIL;
358     }
359
360     close (fdout);
361     fdout = -1;
362
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
367      */
368     if (rename (tmppath, newpath) != 0) {
369         fprintf (stderr, "Error: rename() failed: %s\n", strerror (errno));
370         goto FAIL;
371     }
372
373     cleanup_path = newpath;
374
375     if (! sync_dir (newdir))
376         goto FAIL;
377
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);
381
382     return TRUE;
383
384   FAIL:
385     if (fdout >= 0)
386         close (fdout);
387     unlink (cleanup_path);
388     return FALSE;
389 }
390
391 int
392 notmuch_insert_command (notmuch_config_t *config, int argc, char *argv[])
393 {
394     notmuch_database_t *notmuch;
395     struct sigaction action;
396     const char *db_path;
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     const char *maildir;
404     int opt_index;
405     unsigned int i;
406     notmuch_bool_t ret;
407
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 }
412     };
413
414     opt_index = parse_arguments (argc, argv, options, 1);
415
416     if (opt_index < 0) {
417         /* diagnostics already printed */
418         return 1;
419     }
420
421     db_path = notmuch_config_get_database_path (config);
422     new_tags = notmuch_config_get_new_tags (config, &new_tags_length);
423
424     tag_ops = tag_op_list_create (config);
425     if (tag_ops == NULL) {
426         fprintf (stderr, "Out of memory.\n");
427         return 1;
428     }
429     for (i = 0; i < new_tags_length; i++) {
430         if (tag_op_list_append (tag_ops, new_tags[i], FALSE))
431             return 1;
432     }
433
434     if (parse_tag_command_line (config, argc - opt_index, argv + opt_index,
435                                 &query_string, tag_ops))
436         return 1;
437
438     if (*query_string != '\0') {
439         fprintf (stderr, "Error: unexpected query string: %s\n", query_string);
440         return 1;
441     }
442
443     if (folder == NULL) {
444         maildir = db_path;
445     } else {
446         if (! check_folder_name (folder)) {
447             fprintf (stderr, "Error: bad folder name: %s\n", folder);
448             return 1;
449         }
450         maildir = talloc_asprintf (config, "%s/%s", db_path, folder);
451         if (! maildir) {
452             fprintf (stderr, "Out of memory\n");
453             return 1;
454         }
455         if (create_folder && ! maildir_create_folder (config, maildir)) {
456             fprintf (stderr, "Error: creating maildir %s: %s\n",
457                      maildir, strerror (errno));
458             return 1;
459         }
460     }
461
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);
467     action.sa_flags = 0;
468     sigaction (SIGINT, &action, NULL);
469
470     if (notmuch_database_open (notmuch_config_get_database_path (config),
471                                NOTMUCH_DATABASE_MODE_READ_WRITE, &notmuch))
472         return 1;
473
474     ret = insert_message (config, notmuch, STDIN_FILENO, maildir, tag_ops);
475
476     notmuch_database_destroy (notmuch);
477
478     return (ret) ? 0 : 1;
479 }