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