]> git.notmuchmail.org Git - notmuch/blob - notmuch-restore.c
emacs: Add new option notmuch-search-hide-excluded
[notmuch] / notmuch-restore.c
1 /* notmuch - Not much of an email program, (just index and search)
2  *
3  * Copyright © 2009 Carl Worth
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see https://www.gnu.org/licenses/ .
17  *
18  * Author: Carl Worth <cworth@cworth.org>
19  */
20
21 #include "notmuch-client.h"
22 #include "hex-escape.h"
23 #include "tag-util.h"
24 #include "string-util.h"
25 #include "zlib-extra.h"
26
27 static int
28 process_config_line (notmuch_database_t *notmuch, const char *line)
29 {
30     const char *key_p, *val_p;
31     char *key, *val;
32     size_t key_len, val_len;
33     const char *delim = " \t\n";
34     int ret = EXIT_FAILURE;
35
36     void *local = talloc_new (NULL);
37
38     key_p = strtok_len_c (line, delim, &key_len);
39     val_p = strtok_len_c (key_p + key_len, delim, &val_len);
40
41     key = talloc_strndup (local, key_p, key_len);
42     val = talloc_strndup (local, val_p, val_len);
43     if (hex_decode_inplace (key) != HEX_SUCCESS ||
44         hex_decode_inplace (val) != HEX_SUCCESS ) {
45         fprintf (stderr, "hex decoding failure on line %s\n", line);
46         goto DONE;
47     }
48
49     if (print_status_database ("notmuch restore", notmuch,
50                                notmuch_database_set_config (notmuch, key, val)))
51         goto DONE;
52
53     ret = EXIT_SUCCESS;
54
55   DONE:
56     talloc_free (local);
57     return ret;
58 }
59
60 static int
61 process_properties_line (notmuch_database_t *notmuch, const char *line)
62 {
63     const char *id_p, *tok;
64     size_t id_len = 0, tok_len = 0;
65     char *id;
66
67     notmuch_message_t *message = NULL;
68     const char *delim = " \t\n";
69     int ret = EXIT_FAILURE;
70
71     void *local = talloc_new (NULL);
72
73     id_p = strtok_len_c (line, delim, &id_len);
74     id = talloc_strndup (local, id_p, id_len);
75     if (hex_decode_inplace (id) != HEX_SUCCESS) {
76         fprintf (stderr, "hex decoding failure on line %s\n", line);
77         goto DONE;
78     }
79
80     if (print_status_database ("notmuch restore", notmuch,
81                                notmuch_database_find_message (notmuch, id, &message)))
82         goto DONE;
83
84     if (print_status_database ("notmuch restore", notmuch,
85                                notmuch_message_remove_all_properties (message, NULL)))
86         goto DONE;
87
88     tok = id_p + id_len;
89
90     while ((tok = strtok_len_c (tok + tok_len, delim, &tok_len)) != NULL) {
91         char *key, *value;
92         size_t off = strcspn (tok, "=");
93         if (off > tok_len) {
94             fprintf (stderr, "unparsable token %s\n", tok);
95             goto DONE;
96         }
97
98         key = talloc_strndup (local, tok, off);
99         value = talloc_strndup (local, tok + off + 1, tok_len - off - 1);
100
101         if (hex_decode_inplace (key) != HEX_SUCCESS) {
102             fprintf (stderr, "hex decoding failure on key %s\n", key);
103             goto DONE;
104         }
105
106         if (hex_decode_inplace (value) != HEX_SUCCESS) {
107             fprintf (stderr, "hex decoding failure on value %s\n", value);
108             goto DONE;
109         }
110
111         if (print_status_database ("notmuch restore", notmuch,
112                                    notmuch_message_add_property (message, key, value)))
113             goto DONE;
114
115     }
116
117     ret = EXIT_SUCCESS;
118
119   DONE:
120     talloc_free (local);
121     return ret;
122 }
123
124
125 static regex_t regex;
126
127 /* Non-zero return indicates an error in retrieving the message,
128  * or in applying the tags.  Missing messages are reported, but not
129  * considered errors.
130  */
131 static int
132 tag_message (unused (void *ctx),
133              notmuch_database_t *notmuch,
134              const char *message_id,
135              tag_op_list_t *tag_ops,
136              tag_op_flag_t flags)
137 {
138     notmuch_status_t status;
139     notmuch_message_t *message = NULL;
140     int ret = 0;
141
142     status = notmuch_database_find_message (notmuch, message_id, &message);
143     if (status) {
144         fprintf (stderr, "Error applying tags to message %s: %s\n",
145                  message_id, notmuch_status_to_string (status));
146         return 1;
147     }
148     if (message == NULL) {
149         fprintf (stderr, "Warning: cannot apply tags to missing message: %s\n",
150                  message_id);
151         /* We consider this a non-fatal error. */
152         return 0;
153     }
154
155     /* In order to detect missing messages, this check/optimization is
156      * intentionally done *after* first finding the message. */
157     if ((flags & TAG_FLAG_REMOVE_ALL) || tag_op_list_size (tag_ops))
158         ret = tag_op_list_apply (message, tag_ops, flags);
159
160     notmuch_message_destroy (message);
161
162     return ret;
163 }
164
165 /* Sup dump output is one line per message. We match a sequence of
166  * non-space characters for the message-id, then one or more
167  * spaces, then a list of space-separated tags as a sequence of
168  * characters within literal '(' and ')'. */
169
170 static int
171 parse_sup_line (void *ctx, char *line,
172                 char **query_str, tag_op_list_t *tag_ops)
173 {
174
175     regmatch_t match[3];
176     char *file_tags;
177     int rerr;
178
179     tag_op_list_reset (tag_ops);
180
181     chomp_newline (line);
182
183     /* Silently ignore blank lines */
184     if (line[0] == '\0') {
185         return 1;
186     }
187
188     rerr = xregexec (&regex, line, 3, match, 0);
189     if (rerr == REG_NOMATCH) {
190         fprintf (stderr, "Warning: Ignoring invalid sup format line: %s\n",
191                  line);
192         return 1;
193     }
194
195     *query_str = talloc_strndup_debug (ctx, line + match[1].rm_so,
196                                        match[1].rm_eo - match[1].rm_so);
197
198     file_tags = talloc_strndup_debug (ctx, line + match[2].rm_so,
199                                       match[2].rm_eo - match[2].rm_so);
200
201     char *tok = file_tags;
202     size_t tok_len = 0;
203
204     tag_op_list_reset (tag_ops);
205
206     while ((tok = strtok_len (tok + tok_len, " ", &tok_len)) != NULL) {
207
208         if (*(tok + tok_len) != '\0') {
209             *(tok + tok_len) = '\0';
210             tok_len++;
211         }
212
213         if (tag_op_list_append (tag_ops, tok, false))
214             return -1;
215     }
216
217     return 0;
218
219 }
220
221 int
222 notmuch_restore_command (notmuch_database_t *notmuch, int argc, char *argv[])
223 {
224     bool accumulate = false;
225     tag_op_flag_t flags = 0;
226     tag_op_list_t *tag_ops;
227
228     const char *input_file_name = NULL;
229     const char *name_for_error = NULL;
230     gzFile input = NULL;
231     char *line = NULL;
232     void *line_ctx = NULL;
233     ssize_t line_len;
234
235     int ret = 0;
236     int opt_index;
237     int include = 0;
238     int input_format = DUMP_FORMAT_AUTO;
239     int errnum;
240     notmuch_bool_t synchronize_flags;
241
242     if (print_status_database (
243             "notmuch restore",
244             notmuch,
245             notmuch_config_get_bool (notmuch, NOTMUCH_CONFIG_SYNC_MAILDIR_FLAGS,
246                                      &synchronize_flags)))
247         return EXIT_FAILURE;
248
249     if (synchronize_flags)
250         flags |= TAG_FLAG_MAILDIR_SYNC;
251
252     notmuch_opt_desc_t options[] = {
253         { .opt_keyword = &input_format, .name = "format", .keywords =
254               (notmuch_keyword_t []){ { "auto", DUMP_FORMAT_AUTO },
255                                       { "batch-tag", DUMP_FORMAT_BATCH_TAG },
256                                       { "sup", DUMP_FORMAT_SUP },
257                                       { 0, 0 } } },
258         { .opt_flags = &include, .name = "include", .keywords =
259               (notmuch_keyword_t []){ { "config", DUMP_INCLUDE_CONFIG },
260                                       { "properties", DUMP_INCLUDE_PROPERTIES },
261                                       { "tags", DUMP_INCLUDE_TAGS } } },
262
263         { .opt_string = &input_file_name, .name = "input" },
264         { .opt_bool = &accumulate, .name = "accumulate" },
265         { .opt_inherit = notmuch_shared_options },
266         { }
267     };
268
269     opt_index = parse_arguments (argc, argv, options, 1);
270     if (opt_index < 0) {
271         ret = EXIT_FAILURE;
272         goto DONE;
273     }
274
275     notmuch_process_shared_options (notmuch, argv[0]);
276
277     if (include == 0) {
278         include = DUMP_INCLUDE_CONFIG | DUMP_INCLUDE_PROPERTIES | DUMP_INCLUDE_TAGS;
279     }
280
281     name_for_error = input_file_name ? input_file_name : "stdin";
282
283     if (! accumulate)
284         flags |= TAG_FLAG_REMOVE_ALL;
285
286     errno = 0;
287     if (input_file_name)
288         input = gzopen (input_file_name, "r");
289     else {
290         int infd = dup (STDIN_FILENO);
291         if (infd < 0) {
292             fprintf (stderr, "Error duping stdin: %s\n",
293                      strerror (errno));
294             ret = EXIT_FAILURE;
295             goto DONE;
296         }
297         input = gzdopen (infd, "r");
298         if (! input)
299             close (infd);
300     }
301
302     if (input == NULL) {
303         fprintf (stderr, "Error opening %s for (gzip) reading: %s\n",
304                  name_for_error, strerror (errno));
305         ret = EXIT_FAILURE;
306         goto DONE;
307     }
308
309     if (opt_index < argc) {
310         fprintf (stderr, "Unused positional parameter: %s\n", argv[opt_index]);
311         ret = EXIT_FAILURE;
312         goto DONE;
313     }
314
315     tag_ops = tag_op_list_create (notmuch);
316     if (tag_ops == NULL) {
317         fprintf (stderr, "Out of memory.\n");
318         ret = EXIT_FAILURE;
319         goto DONE;
320     }
321
322     do {
323         util_status_t status;
324
325         status = gz_getline (line_ctx, &line, &line_len, input);
326
327         /* empty input file not considered an error */
328         if (status == UTIL_EOF) {
329             ret = EXIT_SUCCESS;
330             goto DONE;
331         }
332
333         if (status) {
334             fprintf (stderr, "Error reading (gzipped) input: %s\n",
335                      gz_error_string (status, input));
336             ret = EXIT_FAILURE;
337             goto DONE;
338         }
339
340         if ((include & DUMP_INCLUDE_CONFIG) && line_len >= 2 && line[0] == '#' && line[1] == '@') {
341             ret = process_config_line (notmuch, line + 2);
342             if (ret)
343                 goto DONE;
344         }
345         if ((include & DUMP_INCLUDE_PROPERTIES) && line_len >= 2 && line[0] == '#' && line[1] ==
346             '=') {
347             ret = process_properties_line (notmuch, line + 2);
348             if (ret)
349                 goto DONE;
350         }
351
352     } while ((line_len == 0) ||
353              (line[0] == '#') ||
354              /* the cast is safe because we checked about for line_len < 0 */
355              (strspn (line, " \t\n") == (unsigned) line_len));
356
357     if (! ((include & DUMP_INCLUDE_TAGS) || (include & DUMP_INCLUDE_PROPERTIES))) {
358         ret = EXIT_SUCCESS;
359         goto DONE;
360     }
361
362     char *p;
363
364     for (p = line; (input_format == DUMP_FORMAT_AUTO) && *p; p++) {
365         if (*p == '(')
366             input_format = DUMP_FORMAT_SUP;
367     }
368
369     if (input_format == DUMP_FORMAT_AUTO)
370         input_format = DUMP_FORMAT_BATCH_TAG;
371
372     if (input_format == DUMP_FORMAT_SUP)
373         if ( xregcomp (&regex,
374                        "^([^ ]+) \\(([^)]*)\\)$",
375                        REG_EXTENDED) )
376             INTERNAL_ERROR ("compile time constant regex failed.");
377
378     do {
379         char *query_string, *prefix, *term;
380
381         if (line_ctx != NULL)
382             talloc_free (line_ctx);
383
384         line_ctx = talloc_new (notmuch);
385
386         if ((include & DUMP_INCLUDE_PROPERTIES) && line_len >= 2 && line[0] == '#' && line[1] ==
387             '=') {
388             ret = process_properties_line (notmuch, line + 2);
389             if (ret)
390                 goto DONE;
391         }
392
393         if (input_format == DUMP_FORMAT_SUP) {
394             ret = parse_sup_line (line_ctx, line, &query_string, tag_ops);
395         } else {
396             ret = parse_tag_line (line_ctx, line, TAG_FLAG_BE_GENEROUS,
397                                   &query_string, tag_ops);
398
399             if (ret == 0) {
400                 ret = parse_boolean_term (line_ctx, query_string,
401                                           &prefix, &term);
402                 if (ret && errno == EINVAL) {
403                     fprintf (stderr, "Warning: cannot parse query: %s (skipping)\n", query_string);
404                     continue;
405                 } else if (ret) {
406                     /* This is more fatal (e.g., out of memory) */
407                     fprintf (stderr, "Error parsing query: %s\n",
408                              strerror (errno));
409                     ret = 1;
410                     break;
411                 } else if (strcmp ("id", prefix) != 0) {
412                     fprintf (stderr, "Warning: not an id query: %s (skipping)\n", query_string);
413                     continue;
414                 }
415                 query_string = term;
416             }
417         }
418
419         if (ret > 0)
420             continue;
421
422         if (ret < 0)
423             break;
424
425         ret = tag_message (line_ctx, notmuch, query_string,
426                            tag_ops, flags);
427         if (ret)
428             break;
429
430     }  while (! (ret = gz_getline (line_ctx, &line, &line_len, input)));
431
432
433     /* EOF is normal loop termination condition, UTIL_SUCCESS is
434      * impossible here */
435     if (ret == UTIL_EOF) {
436         ret = EXIT_SUCCESS;
437     } else {
438         fprintf (stderr, "Error reading (gzipped) input: %s\n",
439                  gz_error_string (ret, input));
440         ret = EXIT_FAILURE;
441     }
442
443     /* currently this should not be after DONE: since we don't
444      * know if the xregcomp was reached
445      */
446
447     if (input_format == DUMP_FORMAT_SUP)
448         regfree (&regex);
449
450   DONE:
451     if (line_ctx != NULL)
452         talloc_free (line_ctx);
453
454     if (notmuch)
455         notmuch_database_destroy (notmuch);
456
457     if (input) {
458         errnum = gzclose_r (input);
459         if (errnum) {
460             fprintf (stderr, "Error closing %s: %d\n",
461                      name_for_error, errnum);
462             ret = EXIT_FAILURE;
463         }
464     }
465
466     return ret ? EXIT_FAILURE : EXIT_SUCCESS;
467 }