]> git.notmuchmail.org Git - notmuch/blob - notmuch-insert.c
lib: fix clang compiler warning
[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, notmuch_bool_t synchronize_flags)
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         if (synchronize_flags) {
327             status = notmuch_message_tags_to_maildir_flags (message);
328             if (status != NOTMUCH_STATUS_SUCCESS)
329                 fprintf (stderr, "Error: failed to sync tags to maildir flags\n");
330         }
331     } else {
332         tag_op_flag_t flags = synchronize_flags ? TAG_FLAG_MAILDIR_SYNC : 0;
333
334         tag_op_list_apply (message, tag_ops, flags);
335     }
336
337     notmuch_message_destroy (message);
338 }
339
340 static notmuch_bool_t
341 insert_message (void *ctx, notmuch_database_t *notmuch, int fdin,
342                 const char *dir, tag_op_list_t *tag_ops,
343                 notmuch_bool_t synchronize_flags)
344 {
345     char *tmppath;
346     char *newpath;
347     char *newdir;
348     int fdout;
349     char *cleanup_path;
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     /* Even if adding the message to the notmuch database fails,
384      * the message is on disk and we consider the delivery completed. */
385     add_file_to_database (notmuch, newpath, tag_ops, synchronize_flags);
386
387     return TRUE;
388
389   FAIL:
390     if (fdout >= 0)
391         close (fdout);
392     unlink (cleanup_path);
393     return FALSE;
394 }
395
396 int
397 notmuch_insert_command (notmuch_config_t *config, int argc, char *argv[])
398 {
399     notmuch_database_t *notmuch;
400     struct sigaction action;
401     const char *db_path;
402     const char **new_tags;
403     size_t new_tags_length;
404     tag_op_list_t *tag_ops;
405     char *query_string = NULL;
406     const char *folder = NULL;
407     notmuch_bool_t create_folder = FALSE;
408     notmuch_bool_t synchronize_flags;
409     const char *maildir;
410     int opt_index;
411     unsigned int i;
412     notmuch_bool_t ret;
413
414     notmuch_opt_desc_t options[] = {
415         { NOTMUCH_OPT_STRING, &folder, "folder", 0, 0 },
416         { NOTMUCH_OPT_BOOLEAN, &create_folder, "create-folder", 0, 0 },
417         { NOTMUCH_OPT_END, 0, 0, 0, 0 }
418     };
419
420     opt_index = parse_arguments (argc, argv, options, 1);
421
422     if (opt_index < 0) {
423         /* diagnostics already printed */
424         return 1;
425     }
426
427     db_path = notmuch_config_get_database_path (config);
428     new_tags = notmuch_config_get_new_tags (config, &new_tags_length);
429     synchronize_flags = notmuch_config_get_maildir_synchronize_flags (config);
430
431     tag_ops = tag_op_list_create (config);
432     if (tag_ops == NULL) {
433         fprintf (stderr, "Out of memory.\n");
434         return 1;
435     }
436     for (i = 0; i < new_tags_length; i++) {
437         if (tag_op_list_append (tag_ops, new_tags[i], FALSE))
438             return 1;
439     }
440
441     if (parse_tag_command_line (config, argc - opt_index, argv + opt_index,
442                                 &query_string, tag_ops))
443         return 1;
444
445     if (*query_string != '\0') {
446         fprintf (stderr, "Error: unexpected query string: %s\n", query_string);
447         return 1;
448     }
449
450     if (folder == NULL) {
451         maildir = db_path;
452     } else {
453         if (! check_folder_name (folder)) {
454             fprintf (stderr, "Error: bad folder name: %s\n", folder);
455             return 1;
456         }
457         maildir = talloc_asprintf (config, "%s/%s", db_path, folder);
458         if (! maildir) {
459             fprintf (stderr, "Out of memory\n");
460             return 1;
461         }
462         if (create_folder && ! maildir_create_folder (config, maildir)) {
463             fprintf (stderr, "Error: creating maildir %s: %s\n",
464                      maildir, strerror (errno));
465             return 1;
466         }
467     }
468
469     /* Setup our handler for SIGINT. We do not set SA_RESTART so that copying
470      * from standard input may be interrupted. */
471     memset (&action, 0, sizeof (struct sigaction));
472     action.sa_handler = handle_sigint;
473     sigemptyset (&action.sa_mask);
474     action.sa_flags = 0;
475     sigaction (SIGINT, &action, NULL);
476
477     if (notmuch_database_open (notmuch_config_get_database_path (config),
478                                NOTMUCH_DATABASE_MODE_READ_WRITE, &notmuch))
479         return 1;
480
481     ret = insert_message (config, notmuch, STDIN_FILENO, maildir, tag_ops,
482                           synchronize_flags);
483
484     notmuch_database_destroy (notmuch);
485
486     return (ret) ? 0 : 1;
487 }