]> git.notmuchmail.org Git - notmuch/blob - notmuch-restore.c
test: require test_begin_subtest before test_expect_code
[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 {
64     const char *id_p, *tok;
65     size_t id_len = 0, tok_len = 0;
66     char *id;
67
68     notmuch_message_t *message = NULL;
69     const char *delim = " \t\n";
70     int ret = EXIT_FAILURE;
71
72     void *local = talloc_new (NULL);
73
74     id_p = strtok_len_c (line, delim, &id_len);
75     id = talloc_strndup (local, id_p, id_len);
76     if (hex_decode_inplace (id) != HEX_SUCCESS) {
77         fprintf (stderr, "hex decoding failure on line %s\n", line);
78         goto DONE;
79     }
80
81     if (print_status_database ("notmuch restore", notmuch,
82                                notmuch_database_find_message (notmuch, id, &message)))
83         goto DONE;
84
85     if (print_status_database ("notmuch restore", notmuch,
86                                notmuch_message_remove_all_properties (message, NULL)))
87         goto DONE;
88
89     tok = id_p + id_len;
90
91     while ((tok = strtok_len_c (tok + tok_len, delim, &tok_len)) != NULL) {
92         char *key, *value;
93         size_t off = strcspn (tok, "=");
94         if (off > tok_len) {
95             fprintf (stderr, "unparsable token %s\n", tok);
96             goto DONE;
97         }
98
99         key = talloc_strndup (local, tok, off);
100         value = talloc_strndup (local, tok + off + 1, tok_len - off - 1);
101
102         if (hex_decode_inplace (key) != HEX_SUCCESS) {
103             fprintf (stderr, "hex decoding failure on key %s\n", key);
104             goto DONE;
105         }
106
107         if (hex_decode_inplace (value) != HEX_SUCCESS) {
108             fprintf (stderr, "hex decoding failure on value %s\n", value);
109             goto DONE;
110         }
111
112         if (print_status_database ("notmuch restore", notmuch,
113                                    notmuch_message_add_property (message, key, value)))
114             goto DONE;
115
116     }
117
118     ret = EXIT_SUCCESS;
119
120   DONE:
121     talloc_free (local);
122     return ret;
123 }
124
125
126 static regex_t regex;
127
128 /* Non-zero return indicates an error in retrieving the message,
129  * or in applying the tags.  Missing messages are reported, but not
130  * considered errors.
131  */
132 static int
133 tag_message (unused (void *ctx),
134              notmuch_database_t *notmuch,
135              const char *message_id,
136              tag_op_list_t *tag_ops,
137              tag_op_flag_t flags)
138 {
139     notmuch_status_t status;
140     notmuch_message_t *message = NULL;
141     int ret = 0;
142
143     status = notmuch_database_find_message (notmuch, message_id, &message);
144     if (status) {
145         fprintf (stderr, "Error applying tags to message %s: %s\n",
146                  message_id, notmuch_status_to_string (status));
147         return 1;
148     }
149     if (message == NULL) {
150         fprintf (stderr, "Warning: cannot apply tags to missing message: %s\n",
151                  message_id);
152         /* We consider this a non-fatal error. */
153         return 0;
154     }
155
156     /* In order to detect missing messages, this check/optimization is
157      * intentionally done *after* first finding the message. */
158     if ((flags & TAG_FLAG_REMOVE_ALL) || tag_op_list_size (tag_ops))
159         ret = tag_op_list_apply (message, tag_ops, flags);
160
161     notmuch_message_destroy (message);
162
163     return ret;
164 }
165
166 /* Sup dump output is one line per message. We match a sequence of
167  * non-space characters for the message-id, then one or more
168  * spaces, then a list of space-separated tags as a sequence of
169  * characters within literal '(' and ')'. */
170
171 static int
172 parse_sup_line (void *ctx, char *line,
173                 char **query_str, tag_op_list_t *tag_ops)
174 {
175
176     regmatch_t match[3];
177     char *file_tags;
178     int rerr;
179
180     tag_op_list_reset (tag_ops);
181
182     chomp_newline (line);
183
184     /* Silently ignore blank lines */
185     if (line[0] == '\0') {
186         return 1;
187     }
188
189     rerr = xregexec (&regex, line, 3, match, 0);
190     if (rerr == REG_NOMATCH) {
191         fprintf (stderr, "Warning: Ignoring invalid sup format line: %s\n",
192                  line);
193         return 1;
194     }
195
196     *query_str = talloc_strndup_debug (ctx, line + match[1].rm_so,
197                                        match[1].rm_eo - match[1].rm_so);
198
199     file_tags = talloc_strndup_debug (ctx, line + match[2].rm_so,
200                                       match[2].rm_eo - match[2].rm_so);
201
202     char *tok = file_tags;
203     size_t tok_len = 0;
204
205     tag_op_list_reset (tag_ops);
206
207     while ((tok = strtok_len (tok + tok_len, " ", &tok_len)) != NULL) {
208
209         if (*(tok + tok_len) != '\0') {
210             *(tok + tok_len) = '\0';
211             tok_len++;
212         }
213
214         if (tag_op_list_append (tag_ops, tok, FALSE))
215             return -1;
216     }
217
218     return 0;
219
220 }
221
222 int
223 notmuch_restore_command (notmuch_config_t *config, int argc, char *argv[])
224 {
225     notmuch_database_t *notmuch;
226     notmuch_bool_t accumulate = FALSE;
227     tag_op_flag_t flags = 0;
228     tag_op_list_t *tag_ops;
229
230     char *input_file_name = NULL;
231     const char *name_for_error = NULL;
232     gzFile input = NULL;
233     char *line = NULL;
234     void *line_ctx = NULL;
235     ssize_t line_len;
236
237     int ret = 0;
238     int opt_index;
239     int include = 0;
240     int input_format = DUMP_FORMAT_AUTO;
241
242     if (notmuch_database_open (notmuch_config_get_database_path (config),
243                                NOTMUCH_DATABASE_MODE_READ_WRITE, &notmuch))
244         return EXIT_FAILURE;
245
246     if (notmuch_config_get_maildir_synchronize_flags (config))
247         flags |= TAG_FLAG_MAILDIR_SYNC;
248
249     notmuch_opt_desc_t options[] = {
250         { NOTMUCH_OPT_KEYWORD, &input_format, "format", 'f',
251           (notmuch_keyword_t []){ { "auto", DUMP_FORMAT_AUTO },
252                                   { "batch-tag", DUMP_FORMAT_BATCH_TAG },
253                                   { "sup", DUMP_FORMAT_SUP },
254                                   { 0, 0 } } },
255         { NOTMUCH_OPT_KEYWORD_FLAGS, &include, "include", 'I',
256           (notmuch_keyword_t []){ { "config", DUMP_INCLUDE_CONFIG },
257                                   { "properties", DUMP_INCLUDE_PROPERTIES },
258                                   { "tags", DUMP_INCLUDE_TAGS} } },
259
260         { NOTMUCH_OPT_STRING, &input_file_name, "input", 'i', 0 },
261         { NOTMUCH_OPT_BOOLEAN,  &accumulate, "accumulate", 'a', 0 },
262         { NOTMUCH_OPT_INHERIT, (void *) &notmuch_shared_options, NULL, 0, 0 },
263         { 0, 0, 0, 0, 0 }
264     };
265
266     opt_index = parse_arguments (argc, argv, options, 1);
267     if (opt_index < 0) {
268         ret = EXIT_FAILURE;
269         goto DONE;
270     }
271
272     notmuch_process_shared_options (argv[0]);
273     notmuch_exit_if_unmatched_db_uuid (notmuch);
274
275     if (include == 0) {
276         include = DUMP_INCLUDE_CONFIG | DUMP_INCLUDE_PROPERTIES | DUMP_INCLUDE_TAGS;
277     }
278
279     name_for_error = input_file_name ? input_file_name : "stdin";
280
281     if (! accumulate)
282         flags |= TAG_FLAG_REMOVE_ALL;
283
284     errno = 0;
285     if (input_file_name)
286         input = gzopen (input_file_name, "r");
287     else {
288         int infd = dup (STDIN_FILENO);
289         if (infd < 0) {
290             fprintf (stderr, "Error duping stdin: %s\n",
291                      strerror (errno));
292             ret = EXIT_FAILURE;
293             goto DONE;
294         }
295         input = gzdopen (infd, "r");
296         if (! input)
297             close (infd);
298     }
299
300     if (input == NULL) {
301         fprintf (stderr, "Error opening %s for (gzip) reading: %s\n",
302                  name_for_error, strerror (errno));
303         ret = EXIT_FAILURE;
304         goto DONE;
305     }
306
307     if (opt_index < argc) {
308         fprintf (stderr, "Unused positional parameter: %s\n", argv[opt_index]);
309         ret = EXIT_FAILURE;
310         goto DONE;
311     }
312
313     tag_ops = tag_op_list_create (config);
314     if (tag_ops == NULL) {
315         fprintf (stderr, "Out of memory.\n");
316         ret = EXIT_FAILURE;
317         goto DONE;
318     }
319
320     do {
321         util_status_t status;
322
323         status = gz_getline (line_ctx, &line, &line_len, input);
324
325         /* empty input file not considered an error */
326         if (status == UTIL_EOF) {
327             ret = EXIT_SUCCESS;
328             goto DONE;
329         }
330
331         if (status) {
332             fprintf (stderr, "Error reading (gzipped) input: %s\n",
333                      gz_error_string(status, input));
334             ret = EXIT_FAILURE;
335             goto DONE;
336         }
337
338         if ((include & DUMP_INCLUDE_CONFIG) && line_len >= 2 && line[0] == '#' && line[1] == '@') {
339             ret = process_config_line(notmuch, line+2);
340             if (ret)
341                 goto DONE;
342         }
343         if ((include & DUMP_INCLUDE_PROPERTIES) && line_len >= 2 && line[0] == '#' && line[1] == '=') {
344             ret = process_properties_line (notmuch, line + 2);
345             if (ret)
346                 goto DONE;
347         }
348
349     } while ((line_len == 0) ||
350              (line[0] == '#') ||
351              /* the cast is safe because we checked about for line_len < 0 */
352              (strspn (line, " \t\n") == (unsigned)line_len));
353
354     if (! ((include & DUMP_INCLUDE_TAGS) || (include & DUMP_INCLUDE_PROPERTIES))) {
355         ret = EXIT_SUCCESS;
356         goto DONE;
357     }
358
359     char *p;
360     for (p = line; (input_format == DUMP_FORMAT_AUTO) && *p; p++) {
361         if (*p == '(')
362             input_format = DUMP_FORMAT_SUP;
363     }
364
365     if (input_format == DUMP_FORMAT_AUTO)
366         input_format = DUMP_FORMAT_BATCH_TAG;
367
368     if (input_format == DUMP_FORMAT_SUP)
369         if ( xregcomp (&regex,
370                        "^([^ ]+) \\(([^)]*)\\)$",
371                        REG_EXTENDED) )
372             INTERNAL_ERROR ("compile time constant regex failed.");
373
374     do {
375         char *query_string, *prefix, *term;
376
377         if (line_ctx != NULL)
378             talloc_free (line_ctx);
379
380         line_ctx = talloc_new (config);
381
382         if ((include & DUMP_INCLUDE_PROPERTIES) && line_len >= 2 && line[0] == '#' && line[1] == '=') {
383             ret = process_properties_line (notmuch, line + 2);
384             if (ret)
385                 goto DONE;
386         }
387
388         if (input_format == DUMP_FORMAT_SUP) {
389             ret = parse_sup_line (line_ctx, line, &query_string, tag_ops);
390         } else {
391             ret = parse_tag_line (line_ctx, line, TAG_FLAG_BE_GENEROUS,
392                                   &query_string, tag_ops);
393
394             if (ret == 0) {
395                 ret = parse_boolean_term (line_ctx, query_string,
396                                           &prefix, &term);
397                 if (ret && errno == EINVAL) {
398                     fprintf (stderr, "Warning: cannot parse query: %s (skipping)\n", query_string);
399                     continue;
400                 } else if (ret) {
401                     /* This is more fatal (e.g., out of memory) */
402                     fprintf (stderr, "Error parsing query: %s\n",
403                              strerror (errno));
404                     ret = 1;
405                     break;
406                 } else if (strcmp ("id", prefix) != 0) {
407                     fprintf (stderr, "Warning: not an id query: %s (skipping)\n", query_string);
408                     continue;
409                 }
410                 query_string = term;
411             }
412         }
413
414         if (ret > 0)
415             continue;
416
417         if (ret < 0)
418             break;
419
420         ret = tag_message (line_ctx, notmuch, query_string,
421                            tag_ops, flags);
422         if (ret)
423             break;
424
425     }  while (! (ret = gz_getline (line_ctx, &line, &line_len, input)));
426
427
428     /* EOF is normal loop termination condition, UTIL_SUCCESS is
429      * impossible here */
430     if (ret == UTIL_EOF) {
431         ret = EXIT_SUCCESS;
432     } else {
433         fprintf (stderr, "Error reading (gzipped) input: %s\n",
434                  gz_error_string (ret, input));
435         ret = EXIT_FAILURE;
436     }
437
438     /* currently this should not be after DONE: since we don't 
439      * know if the xregcomp was reached
440      */
441
442     if (input_format == DUMP_FORMAT_SUP)
443         regfree (&regex);
444
445  DONE:
446     if (line_ctx != NULL)
447         talloc_free (line_ctx);
448
449     if (notmuch)
450         notmuch_database_destroy (notmuch);
451
452     if (input && gzclose_r (input)) {
453         fprintf (stderr, "Error closing %s: %s\n",
454                  name_for_error, gzerror (input, NULL));
455         ret = EXIT_FAILURE;
456     }
457
458     return ret ? EXIT_FAILURE : EXIT_SUCCESS;
459 }