]> git.notmuchmail.org Git - notmuch/blob - notmuch-insert.c
cli/insert: rename check_folder_name to is_valid_folder_name
[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 /*
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.
90  */
91 static notmuch_bool_t
92 is_valid_folder_name (const char *folder)
93 {
94     const char *p = folder;
95
96     for (;;) {
97         if ((p[0] == '.') && (p[1] == '.') && (p[2] == '\0' || p[2] == '/'))
98             return FALSE;
99         p = strchr (p, '/');
100         if (!p)
101             return TRUE;
102         p++;
103     }
104 }
105
106 /* Make the given directory, succeeding if it already exists. */
107 static notmuch_bool_t
108 make_directory (char *path, int mode)
109 {
110     notmuch_bool_t ret;
111     char *slash;
112
113     if (mkdir (path, mode) != 0)
114         return (errno == EEXIST);
115
116     /* Sync the parent directory for durability. */
117     ret = TRUE;
118     slash = strrchr (path, '/');
119     if (slash) {
120         *slash = '\0';
121         ret = sync_dir (path);
122         *slash = '/';
123     }
124     return ret;
125 }
126
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)
131 {
132     struct stat st;
133     char *start;
134     char *end;
135     notmuch_bool_t ret;
136
137     /* First check the common case: directory already exists. */
138     if (stat (path, &st) == 0)
139         return S_ISDIR (st.st_mode) ? TRUE : FALSE;
140
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, '/');
145
146         /* If there are no more slashes then all the parent directories
147          * have been made.  Now attempt to make the whole path. */
148         if (end == NULL)
149             return make_directory (path, mode);
150
151         /* Make the path up to the next slash, unless the current
152          * directory component is actually empty. */
153         if (end > start) {
154             *end = '\0';
155             ret = make_directory (path, mode);
156             *end = '/';
157             if (! ret)
158                 return FALSE;
159         }
160     }
161
162     return TRUE;
163 }
164
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)
169 {
170     const int mode = 0700;
171     char *subdir;
172     char *tail;
173
174     /* Create 'cur' directory, including parent directories. */
175     subdir = talloc_asprintf (ctx, "%s/cur", dir);
176     if (! subdir) {
177         fprintf (stderr, "Out of memory.\n");
178         return FALSE;
179     }
180     if (! make_directory_and_parents (subdir, mode))
181         return FALSE;
182
183     tail = subdir + strlen (subdir) - 3;
184
185     /* Create 'new' directory. */
186     strcpy (tail, "new");
187     if (! make_directory (subdir, mode))
188         return FALSE;
189
190     /* Create 'tmp' directory. */
191     strcpy (tail, "tmp");
192     if (! make_directory (subdir, mode))
193         return FALSE;
194
195     talloc_free (subdir);
196     return TRUE;
197 }
198
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. */
204 static int
205 maildir_open_tmp_file (void *ctx, const char *dir,
206                        char **tmppath, char **newpath, char **newdir)
207 {
208     pid_t pid;
209     char hostname[256];
210     struct timeval tv;
211     char *filename;
212     int fd = -1;
213
214     /* We follow the Dovecot file name generation algorithm. */
215     pid = getpid ();
216     safe_gethostname (hostname, sizeof (hostname));
217     do {
218         gettimeofday (&tv, NULL);
219         filename = talloc_asprintf (ctx, "%ld.M%ldP%d.%s",
220                                     tv.tv_sec, tv.tv_usec, pid, hostname);
221         if (! filename) {
222             fprintf (stderr, "Out of memory\n");
223             return -1;
224         }
225
226         *tmppath = talloc_asprintf (ctx, "%s/tmp/%s", dir, filename);
227         if (! *tmppath) {
228             fprintf (stderr, "Out of memory\n");
229             return -1;
230         }
231
232         fd = open (*tmppath, O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, 0600);
233     } while (fd == -1 && errno == EEXIST);
234
235     if (fd == -1) {
236         fprintf (stderr, "Error: opening %s: %s\n", *tmppath, strerror (errno));
237         return -1;
238     }
239
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");
244         close (fd);
245         unlink (*tmppath);
246         return -1;
247     }
248
249     talloc_free (filename);
250
251     return fd;
252 }
253
254 /* Copy the contents of standard input (fdin) into fdout.
255  * Returns TRUE if a non-empty file was written successfully.
256  * Otherwise, return FALSE. */
257 static notmuch_bool_t
258 copy_stdin (int fdin, int fdout)
259 {
260     notmuch_bool_t empty = TRUE;
261
262     while (! interrupted) {
263         ssize_t remain;
264         char buf[4096];
265         char *p;
266
267         remain = read (fdin, buf, sizeof (buf));
268         if (remain == 0)
269             break;
270         if (remain < 0) {
271             if (errno == EINTR)
272                 continue;
273             fprintf (stderr, "Error: reading from standard input: %s\n",
274                      strerror (errno));
275             return FALSE;
276         }
277
278         p = buf;
279         do {
280             ssize_t written = write (fdout, p, remain);
281             if (written < 0 && errno == EINTR)
282                 continue;
283             if (written <= 0) {
284                 fprintf (stderr, "Error: writing to temporary file: %s",
285                          strerror (errno));
286                 return FALSE;
287             }
288             p += written;
289             remain -= written;
290             empty = FALSE;
291         } while (remain > 0);
292     }
293
294     return (!interrupted && !empty);
295 }
296
297 /* Add the specified message file to the notmuch database, applying tags.
298  * The file is renamed to encode notmuch tags as maildir flags. */
299 static void
300 add_file_to_database (notmuch_database_t *notmuch, const char *path,
301                       tag_op_list_t *tag_ops, notmuch_bool_t synchronize_flags)
302 {
303     notmuch_message_t *message;
304     notmuch_status_t status;
305
306     status = notmuch_database_add_message (notmuch, path, &message);
307     switch (status) {
308     case NOTMUCH_STATUS_SUCCESS:
309     case NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID:
310         break;
311     default:
312     case NOTMUCH_STATUS_FILE_NOT_EMAIL:
313     case NOTMUCH_STATUS_READ_ONLY_DATABASE:
314     case NOTMUCH_STATUS_XAPIAN_EXCEPTION:
315     case NOTMUCH_STATUS_OUT_OF_MEMORY:
316     case NOTMUCH_STATUS_FILE_ERROR:
317     case NOTMUCH_STATUS_NULL_POINTER:
318     case NOTMUCH_STATUS_TAG_TOO_LONG:
319     case NOTMUCH_STATUS_UNBALANCED_FREEZE_THAW:
320     case NOTMUCH_STATUS_UNBALANCED_ATOMIC:
321     case NOTMUCH_STATUS_LAST_STATUS:
322         fprintf (stderr, "Error: failed to add `%s' to notmuch database: %s\n",
323                  path, notmuch_status_to_string (status));
324         return;
325     }
326
327     if (status == NOTMUCH_STATUS_DUPLICATE_MESSAGE_ID) {
328         /* Don't change tags of an existing message. */
329         if (synchronize_flags) {
330             status = notmuch_message_tags_to_maildir_flags (message);
331             if (status != NOTMUCH_STATUS_SUCCESS)
332                 fprintf (stderr, "Error: failed to sync tags to maildir flags\n");
333         }
334     } else {
335         tag_op_flag_t flags = synchronize_flags ? TAG_FLAG_MAILDIR_SYNC : 0;
336
337         tag_op_list_apply (message, tag_ops, flags);
338     }
339
340     notmuch_message_destroy (message);
341 }
342
343 static notmuch_bool_t
344 write_message (void *ctx, int fdin, const char *dir, char **newpath)
345 {
346     char *tmppath;
347     char *newdir;
348     char *cleanup_path;
349     int fdout;
350
351     fdout = maildir_open_tmp_file (ctx, dir, &tmppath, newpath, &newdir);
352     if (fdout < 0)
353         return FALSE;
354
355     cleanup_path = tmppath;
356
357     if (! copy_stdin (fdin, fdout))
358         goto FAIL;
359
360     if (fsync (fdout) != 0) {
361         fprintf (stderr, "Error: fsync failed: %s\n", strerror (errno));
362         goto FAIL;
363     }
364
365     close (fdout);
366     fdout = -1;
367
368     /* Atomically move the new message file from the Maildir 'tmp' directory
369      * to the 'new' directory.  We follow the Dovecot recommendation to
370      * simply use rename() instead of link() and unlink().
371      * See also: http://wiki.dovecot.org/MailboxFormat/Maildir#Mail_delivery
372      */
373     if (rename (tmppath, *newpath) != 0) {
374         fprintf (stderr, "Error: rename() failed: %s\n", strerror (errno));
375         goto FAIL;
376     }
377
378     cleanup_path = *newpath;
379
380     if (! sync_dir (newdir))
381         goto FAIL;
382
383     return TRUE;
384
385   FAIL:
386     if (fdout >= 0)
387         close (fdout);
388     unlink (cleanup_path);
389     return FALSE;
390 }
391
392 int
393 notmuch_insert_command (notmuch_config_t *config, int argc, char *argv[])
394 {
395     notmuch_database_t *notmuch;
396     struct sigaction action;
397     const char *db_path;
398     const char **new_tags;
399     size_t new_tags_length;
400     tag_op_list_t *tag_ops;
401     char *query_string = NULL;
402     const char *folder = NULL;
403     notmuch_bool_t create_folder = FALSE;
404     notmuch_bool_t synchronize_flags;
405     const char *maildir;
406     char *newpath;
407     int opt_index;
408     unsigned int i;
409
410     notmuch_opt_desc_t options[] = {
411         { NOTMUCH_OPT_STRING, &folder, "folder", 0, 0 },
412         { NOTMUCH_OPT_BOOLEAN, &create_folder, "create-folder", 0, 0 },
413         { NOTMUCH_OPT_END, 0, 0, 0, 0 }
414     };
415
416     opt_index = parse_arguments (argc, argv, options, 1);
417     if (opt_index < 0)
418         return EXIT_FAILURE;
419
420     db_path = notmuch_config_get_database_path (config);
421     new_tags = notmuch_config_get_new_tags (config, &new_tags_length);
422     synchronize_flags = notmuch_config_get_maildir_synchronize_flags (config);
423
424     tag_ops = tag_op_list_create (config);
425     if (tag_ops == NULL) {
426         fprintf (stderr, "Out of memory.\n");
427         return EXIT_FAILURE;
428     }
429     for (i = 0; i < new_tags_length; i++) {
430         const char *error_msg;
431
432         error_msg = illegal_tag (new_tags[i], FALSE);
433         if (error_msg) {
434             fprintf (stderr, "Error: tag '%s' in new.tags: %s\n",
435                      new_tags[i],  error_msg);
436             return EXIT_FAILURE;
437         }
438
439         if (tag_op_list_append (tag_ops, new_tags[i], FALSE))
440             return EXIT_FAILURE;
441     }
442
443     if (parse_tag_command_line (config, argc - opt_index, argv + opt_index,
444                                 &query_string, tag_ops))
445         return EXIT_FAILURE;
446
447     if (*query_string != '\0') {
448         fprintf (stderr, "Error: unexpected query string: %s\n", query_string);
449         return EXIT_FAILURE;
450     }
451
452     if (folder == NULL) {
453         maildir = db_path;
454     } else {
455         if (! is_valid_folder_name (folder)) {
456             fprintf (stderr, "Error: invalid folder name: '%s'\n", folder);
457             return EXIT_FAILURE;
458         }
459         maildir = talloc_asprintf (config, "%s/%s", db_path, folder);
460         if (! maildir) {
461             fprintf (stderr, "Out of memory\n");
462             return EXIT_FAILURE;
463         }
464         if (create_folder && ! maildir_create_folder (config, maildir)) {
465             fprintf (stderr, "Error: creating maildir %s: %s\n",
466                      maildir, strerror (errno));
467             return EXIT_FAILURE;
468         }
469     }
470
471     /* Setup our handler for SIGINT. We do not set SA_RESTART so that copying
472      * from standard input may be interrupted. */
473     memset (&action, 0, sizeof (struct sigaction));
474     action.sa_handler = handle_sigint;
475     sigemptyset (&action.sa_mask);
476     action.sa_flags = 0;
477     sigaction (SIGINT, &action, NULL);
478
479     if (notmuch_database_open (notmuch_config_get_database_path (config),
480                                NOTMUCH_DATABASE_MODE_READ_WRITE, &notmuch))
481         return EXIT_FAILURE;
482
483     /* Write the message to the Maildir new directory. */
484     if (! write_message (config, STDIN_FILENO, maildir, &newpath)) {
485         notmuch_database_destroy (notmuch);
486         return EXIT_FAILURE;
487     }
488
489     /* Add the message to the index.
490      * Even if adding the message to the notmuch database fails,
491      * the message is on disk and we consider the delivery completed. */
492     add_file_to_database (notmuch, newpath, tag_ops,
493                                     synchronize_flags);
494
495     notmuch_database_destroy (notmuch);
496     return EXIT_SUCCESS;
497 }