s3-clitar: Simplify is_subpath().
[obnox/samba/samba-obnox.git] / source3 / client / clitar.c
1 /*
2    Unix SMB/CIFS implementation.
3    Tar backup command extension
4    Copyright (C) AurĂ©lien Aptel 2013
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 */
19
20 /**
21  * # General overview of the tar extension
22  *
23  * All tar_xxx() functions work on a `struct tar` which store most of
24  * the context of the backup process.
25  *
26  * The current tar context can be accessed via the global variable
27  * `tar_ctx`. It's publicly exported as an opaque handle via
28  * tar_get_ctx().
29  *
30  * A tar context is first configured through tar_parse_args() which
31  * can be called from either the CLI (in client.c) or the interactive
32  * session (via the cmd_tar() callback).
33  *
34  * Once the configuration is done (successfully), the context is ready
35  * for processing and tar_to_process() returns true.
36  *
37  * The next step is to call tar_process() which dispatch the
38  * processing to either tar_create() or tar_extract(), depending on
39  * the context.
40  *
41  * ## Archive creation
42  *
43  * tar_create() creates an archive using the libarchive API then
44  *
45  * - iterates on the requested paths if the context is in inclusion
46  *   mode with tar_create_from_list()
47  *
48  * - or iterates on the whole share (starting from the current dir) if
49  *   in exclusion mode or if no specific path were requested
50  *
51  * The do_list() function from client.c is used to list recursively
52  * the share. In particular it takes a DOS path mask (eg. \mydir\*)
53  * and a callback function which will be called with each file name
54  * and attributes. The tar callback function is get_file_callback().
55  *
56  * The callback function checks whether the file should be skipped
57  * according the the configuration via tar_create_skip_path(). If it's
58  * not skipped it's downloaded and written to the archive in
59  * tar_get_file().
60  *
61  * ## Archive extraction
62  *
63  * tar_extract() opens the archive and iterates on each file in
64  * it. For each file tar_extract_skip_path() checks whether it should
65  * be skipped according to the config. If it's not skipped it's
66  * uploaded on the server in tar_send_file().
67  */
68
69 #include "includes.h"
70 #include "system/filesys.h"
71 #include "client/client_proto.h"
72 #include "client/clitar_proto.h"
73 #include "libsmb/libsmb.h"
74
75 #ifdef HAVE_LIBARCHIVE
76
77 #include <archive.h>
78 #include <archive_entry.h>
79
80 /* prepend module name and line number to debug messages */
81 #define DBG(a, b) (DEBUG(a, ("tar:%-4d ", __LINE__)), DEBUG(a, b))
82
83 /* preprocessor magic to strigify __LINE__ (int) */
84 #define STR1(x) #x
85 #define STR2(x) STR1(x)
86
87 /* helper macro to die in case of NULL pointer */
88 #define PANIC_IF_NULL(x) \
89     _panic_if_null(x, __FILE__ ":" STR2(__LINE__) " (" #x ") == NULL\n")
90
91 /* prototype to silent gcc warning */
92 static inline void* _panic_if_null(void *p, const char *expr);
93 static inline void* _panic_if_null(void *p, const char *expr)
94 {
95     if (!p) {
96         smb_panic(expr);
97     }
98     return p;
99 }
100
101 /**
102  * Number of byte in a block unit.
103  */
104 #define TAR_BLOCK_UNIT 512
105
106 /**
107  * Default tar block size in TAR_BLOCK_UNIT.
108  */
109 #define TAR_DEFAULT_BLOCK_SIZE 20
110
111 /**
112  * Maximum value for the blocksize field
113  */
114 #define TAR_MAX_BLOCK_SIZE 0xffff
115
116 /**
117  * Size of the buffer used when downloading a file
118  */
119 #define TAR_CLI_READ_SIZE 0xff00
120
121 #define TAR_DO_LIST_ATTR (FILE_ATTRIBUTE_DIRECTORY \
122                           | FILE_ATTRIBUTE_SYSTEM  \
123                           | FILE_ATTRIBUTE_HIDDEN)
124
125
126 enum tar_operation {
127     TAR_NO_OPERATION,
128     TAR_CREATE,    /* c flag */
129     TAR_EXTRACT,   /* x flag */
130 };
131
132 enum tar_selection {
133     TAR_NO_SELECTION,
134     TAR_INCLUDE,       /* I and F flag, default */
135     TAR_EXCLUDE,       /* X flag */
136 };
137
138 enum {
139     ATTR_UNSET,
140     ATTR_SET,
141 };
142
143 struct tar {
144     TALLOC_CTX *talloc_ctx;
145
146     /* in state that needs/can be processed? */
147     bool to_process;
148
149     /* flags */
150     struct tar_mode {
151         enum tar_operation operation; /* create, extract */
152         enum tar_selection selection; /* include, exclude */
153         int blocksize;    /* size in TAR_BLOCK_UNIT of a tar file block */
154         bool hidden;      /* backup hidden file? */
155         bool system;      /* backup system file? */
156         bool incremental; /* backup _only_ archived file? */
157         bool reset;       /* unset archive bit? */
158         bool dry;         /* don't write tar file? */
159         bool regex;       /* XXX: never actually using regex... */
160         bool verbose;     /* XXX: ignored */
161     } mode;
162
163     /* nb of bytes received */
164     uint64_t total_size;
165
166     /* path to tar archive name */
167     char *tar_path;
168
169     /* list of path to include or exclude */
170     char **path_list;
171     int path_list_size;
172
173     /* archive handle */
174     struct archive *archive;
175 };
176
177 /**
178  * Global context imported in client.c when needed.
179  *
180  * Default options.
181  */
182 struct tar tar_ctx = {
183     .mode.selection   = TAR_INCLUDE,
184     .mode.blocksize   = TAR_DEFAULT_BLOCK_SIZE,
185     .mode.hidden      = true,
186     .mode.system      = true,
187     .mode.incremental = false,
188     .mode.reset       = false,
189     .mode.dry         = false,
190     .mode.regex       = false,
191     .mode.verbose     = false,
192 };
193
194 /* tar, local function */
195 static int tar_create(struct tar* t);
196 static int tar_create_from_list(struct tar *t);
197 static int tar_extract(struct tar *t);
198 static int tar_read_inclusion_file (struct tar *t, const char* filename);
199 static int tar_send_file(struct tar *t, struct archive_entry *entry);
200 static int tar_set_blocksize(struct tar *t, int size);
201 static int tar_set_newer_than(struct tar *t, const char *filename);
202 static void tar_add_selection_path(struct tar *t, const char *path);
203 static void tar_dump(struct tar *t);
204 static bool tar_extract_skip_path(struct tar *t, struct archive_entry *entry);
205 static TALLOC_CTX *tar_reset_mem_context(struct tar *t);
206 static void tar_free_mem_context(struct tar *t);
207 static bool tar_create_skip_path(struct tar *t,
208                                  const char *fullpath,
209                                  const struct file_info *finfo);
210
211 static bool tar_path_in_list(struct tar *t,
212                              const char *path,
213                              bool reverse);
214
215 static int tar_get_file(struct tar *t,
216                         const char *full_dos_path,
217                         struct file_info *finfo);
218
219 static NTSTATUS get_file_callback(struct cli_state *cli,
220                                   struct file_info *finfo,
221                                   const char *dir);
222
223 /* utilities */
224 static char *fix_unix_path (char *path, bool removeprefix);
225 static char *path_base_name (const char *path);
226 static const char* skip_useless_char_in_path(const char *p);
227 static int make_remote_path(const char *full_path);
228 static int max_token (const char *str);
229 static bool is_subpath(const char *sub, const char *full);
230 static int set_remote_attr(const char *filename, uint16 new_attr, int mode);
231
232 /**
233  * tar_get_ctx - retrieve global tar context handle
234  */
235 struct tar *tar_get_ctx()
236 {
237     return &tar_ctx;
238 }
239
240 /**
241  * cmd_block - interactive command to change tar blocksize
242  *
243  * Read a size from the client command line and update the current
244  * blocksize.
245  */
246 int cmd_block(void)
247 {
248     /* XXX: from client.c */
249     const extern char *cmd_ptr;
250     char *buf;
251     TALLOC_CTX *ctx = PANIC_IF_NULL(talloc_new(NULL));
252     int err = 0;
253     bool ok;
254
255     ok = next_token_talloc(ctx, &cmd_ptr, &buf, NULL);
256     if (!ok) {
257         DBG(0, ("blocksize <n>\n"));
258         err = 1;
259         goto out;
260     }
261
262     ok = tar_set_blocksize(&tar_ctx, atoi(buf));
263     if (ok) {
264         DBG(0, ("invalid blocksize\n"));
265         err = 1;
266         goto out;
267     }
268
269     DBG(2, ("blocksize is now %d\n", tar_ctx.mode.blocksize));
270
271  out:
272     talloc_free(ctx);
273     return err;
274 }
275
276 /**
277  * cmd_tarmode - interactive command to change tar behaviour
278  *
279  * Read one or more modes from the client command line and update the
280  * current tar mode.
281  */
282 int cmd_tarmode(void)
283 {
284     const extern char *cmd_ptr;
285     char *buf;
286     int i;
287     TALLOC_CTX *ctx = PANIC_IF_NULL(talloc_new(NULL));
288
289     struct {
290         const char *cmd;
291         bool *p;
292         bool value;
293     } table[] = {
294         {"full",      &tar_ctx.mode.incremental, false},
295         {"inc",       &tar_ctx.mode.incremental, true },
296         {"reset",     &tar_ctx.mode.reset,       true },
297         {"noreset",   &tar_ctx.mode.reset,       false},
298         {"system",    &tar_ctx.mode.system,      true },
299         {"nosystem",  &tar_ctx.mode.system,      false},
300         {"hidden",    &tar_ctx.mode.hidden,      true },
301         {"nohidden",  &tar_ctx.mode.hidden,      false},
302         {"verbose",   &tar_ctx.mode.verbose,     true },
303         {"noquiet",   &tar_ctx.mode.verbose,     true },
304         {"quiet",     &tar_ctx.mode.verbose,     false},
305         {"noverbose", &tar_ctx.mode.verbose,     false},
306     };
307
308     while (next_token_talloc(ctx, &cmd_ptr, &buf, NULL)) {
309         for (i = 0; i < ARRAY_SIZE(table); i++) {
310             if (strequal(table[i].cmd, buf)) {
311                 *table[i].p = table[i].value;
312                 break;
313             }
314         }
315
316         if (i == ARRAY_SIZE(table))
317             DBG(0, ("tarmode: unrecognised option %s\n", buf));
318     }
319
320     DBG(0, ("tarmode is now %s, %s, %s, %s, %s\n",
321               tar_ctx.mode.incremental ? "incremental" : "full",
322               tar_ctx.mode.system      ? "system"      : "nosystem",
323               tar_ctx.mode.hidden      ? "hidden"      : "nohidden",
324               tar_ctx.mode.reset       ? "reset"       : "noreset",
325               tar_ctx.mode.verbose     ? "verbose"     : "quiet"));
326
327     talloc_free(ctx);
328     return 0;
329 }
330
331 /**
332  * cmd_tar - interactive command to start a tar backup/restoration
333  *
334  * Check presence of argument, parse them and handle the request.
335  */
336 int cmd_tar(void)
337 {
338     TALLOC_CTX *ctx = PANIC_IF_NULL(talloc_new(NULL));
339     const extern char *cmd_ptr;
340     const char *flag;
341     const char **val;
342     char *buf;
343     int maxtok = max_token(cmd_ptr);
344     int i = 0;
345     int err = 0;
346     bool ok;
347     int rc;
348
349     ok = next_token_talloc(ctx, &cmd_ptr, &buf, NULL);
350     if (!ok) {
351         DBG(0, ("tar <c|x>[IXFbganN] [options] <tar file> [path list]\n"));
352         err = 1;
353         goto out;
354     }
355
356     flag = buf;
357     val = PANIC_IF_NULL(talloc_array(ctx, const char*, maxtok));
358
359     while (next_token_talloc(ctx, &cmd_ptr, &buf, NULL)) {
360         val[i++] = buf;
361     }
362
363     rc = tar_parse_args(&tar_ctx, flag, val, i);
364     if (rc != 0) {
365         DBG(0, ("parse_args failed\n"));
366         err = 1;
367         goto out;
368     }
369
370     rc = tar_process(&tar_ctx);
371     if (rc != 0) {
372         DBG(0, ("tar_process failed\n"));
373         err = 1;
374         goto out;
375     }
376
377  out:
378     talloc_free(ctx);
379     return err;
380 }
381
382 /**
383  * cmd_setmode - interactive command to set DOS attributes
384  *
385  * Read a filename and mode from the client command line and update
386  * the file DOS attributes.
387  */
388 int cmd_setmode(void)
389 {
390     const extern char *cmd_ptr;
391     char *buf;
392     char *fname = NULL;
393     uint16 attr[2] = {0};
394     int mode = ATTR_SET;
395     TALLOC_CTX *ctx = PANIC_IF_NULL(talloc_new(NULL));
396     int err = 0;
397     bool ok;
398
399
400     ok = next_token_talloc(ctx, &cmd_ptr, &buf, NULL);
401     if (!ok) {
402         DBG(0, ("setmode <filename> <[+|-]rsha>\n"));
403         err = 1;
404         goto out;
405     }
406
407     fname = PANIC_IF_NULL(talloc_asprintf(ctx,
408                                           "%s%s",
409                                           client_get_cur_dir(),
410                                           buf));
411     if (fname == NULL) {
412         err = 1;
413         goto out;
414     }
415
416     while (next_token_talloc(ctx, &cmd_ptr, &buf, NULL)) {
417         const char *s = buf;
418
419         while (*s) {
420             switch (*s++) {
421             case '+':
422                 mode = ATTR_SET;
423                 break;
424             case '-':
425                 mode = ATTR_UNSET;
426                 break;
427             case 'r':
428                 attr[mode] |= FILE_ATTRIBUTE_READONLY;
429                 break;
430             case 'h':
431                 attr[mode] |= FILE_ATTRIBUTE_HIDDEN;
432                 break;
433             case 's':
434                 attr[mode] |= FILE_ATTRIBUTE_SYSTEM;
435                 break;
436             case 'a':
437                 attr[mode] |= FILE_ATTRIBUTE_ARCHIVE;
438                 break;
439             default:
440                 DBG(0, ("setmode <filename> <perm=[+|-]rsha>\n"));
441                 err = 1;
442                 goto out;
443             }
444         }
445     }
446
447     if (attr[ATTR_SET] == 0 && attr[ATTR_UNSET] == 0) {
448         DBG(0, ("setmode <filename> <[+|-]rsha>\n"));
449         err = 1;
450         goto out;
451     }
452
453     DBG(2, ("perm set %d %d\n", attr[ATTR_SET], attr[ATTR_UNSET]));
454
455     /* ignore return value: server might not store DOS attributes */
456     set_remote_attr(fname, attr[ATTR_SET], ATTR_SET);
457     set_remote_attr(fname, attr[ATTR_UNSET], ATTR_UNSET);
458  out:
459     talloc_free(ctx);
460     return err;
461 }
462
463 /**
464  * tar_parse_args - parse and set tar command line arguments
465  * @flag: string pointing to tar options
466  * @val: number of tar arguments
467  * @valsize: table of arguments after the flags (number of element in val)
468  *
469  * tar arguments work in a weird way. For each flag f that takes a
470  * value v, the user is supposed to type:
471  *
472  * on the CLI:
473  *   -Tf1f2f3 v1 v2 v3 TARFILE PATHS...
474  *
475  * in the interactive session:
476  *   tar f1f2f3 v1 v2 v3 TARFILE PATHS...
477  *
478  * @flag has only flags (eg. "f1f2f3") and @val has the arguments
479  * (values) following them (eg. ["v1", "v2", "v3", "TARFILE", "PATH1",
480  * "PATH2"]).
481  *
482  * There are only 2 flags that take an arg: b and N. The other flags
483  * just change the semantic of PATH or TARFILE.
484  *
485  * PATH can be a list of included/excluded paths, the path to a file
486  * containing a list of included/excluded paths to use (F flag). If no
487  * PATH is provided, the whole share is used (/).
488  */
489 int tar_parse_args(struct tar* t, const char *flag,
490                    const char **val, int valsize)
491 {
492     TALLOC_CTX *ctx;
493     bool do_read_list = false;
494     /* index of next value to use */
495     int ival = 0;
496     int rc;
497
498     if (t == NULL) {
499         DBG(0, ("Invalid tar context\n"));
500         return 1;
501     }
502
503     ctx = tar_reset_mem_context(t);
504     /*
505      * Reset back some options - could be from interactive version
506      * all other modes are left as they are
507      */
508     t->mode.operation = TAR_NO_OPERATION;
509     t->mode.selection = TAR_NO_SELECTION;
510     t->mode.dry = false;
511     t->to_process = false;
512     t->total_size = 0;
513
514     while (flag[0] != '\0') {
515         switch(flag[0]) {
516         /* operation */
517         case 'c':
518             if (t->mode.operation != TAR_NO_OPERATION) {
519                 printf("Tar must be followed by only one of c or x.\n");
520                 return 1;
521             }
522             t->mode.operation = TAR_CREATE;
523             break;
524         case 'x':
525             if (t->mode.operation != TAR_NO_OPERATION) {
526                 printf("Tar must be followed by only one of c or x.\n");
527                 return 1;
528             }
529             t->mode.operation = TAR_EXTRACT;
530             break;
531
532         /* selection  */
533         case 'I':
534             if (t->mode.selection != TAR_NO_SELECTION) {
535                 DBG(0,("Only one of I,X,F must be specified\n"));
536                 return 1;
537             }
538             t->mode.selection = TAR_INCLUDE;
539             break;
540         case 'X':
541             if (t->mode.selection != TAR_NO_SELECTION) {
542                 DBG(0,("Only one of I,X,F must be specified\n"));
543                 return 1;
544             }
545             t->mode.selection = TAR_EXCLUDE;
546             break;
547         case 'F':
548             if (t->mode.selection != TAR_NO_SELECTION) {
549                 DBG(0,("Only one of I,X,F must be specified\n"));
550                 return 1;
551             }
552             t->mode.selection = TAR_INCLUDE;
553             do_read_list = true;
554             break;
555
556         /* blocksize */
557         case 'b':
558             if (ival >= valsize) {
559                 DBG(0, ("Option b must be followed by a blocksize\n"));
560                 return 1;
561             }
562
563             if (tar_set_blocksize(t, atoi(val[ival]))) {
564                 DBG(0, ("Option b must be followed by a valid blocksize\n"));
565                 return 1;
566             }
567
568             ival++;
569             break;
570
571          /* incremental mode */
572         case 'g':
573             t->mode.incremental = true;
574             break;
575
576         /* newer than */
577         case 'N':
578             if (ival >= valsize) {
579                 DBG(0, ("Option N must be followed by valid file name\n"));
580                 return 1;
581             }
582
583             if (tar_set_newer_than(t, val[ival])) {
584                 DBG(0,("Error setting newer-than time\n"));
585                 return 1;
586             }
587
588             ival++;
589             break;
590
591         /* reset mode */
592         case 'a':
593             t->mode.reset = true;
594             break;
595
596         /* verbose */
597         case 'q':
598             t->mode.verbose = true;
599             break;
600
601         /* regex match  */
602         case 'r':
603             t->mode.regex = true;
604             break;
605
606         /* dry run mode */
607         case 'n':
608             if (t->mode.operation != TAR_CREATE) {
609                 DBG(0, ("n is only meaningful when creating a tar-file\n"));
610                 return 1;
611             }
612
613             t->mode.dry = true;
614             DBG(0, ("dry_run set\n"));
615             break;
616
617         default:
618             DBG(0,("Unknown tar option\n"));
619             return 1;
620         }
621
622         flag++;
623     }
624
625     /* no selection given? default selection is include */
626     if (t->mode.selection == TAR_NO_SELECTION) {
627         t->mode.selection = TAR_INCLUDE;
628     }
629
630     if (valsize - ival < 1) {
631         DBG(0, ("No tar file given.\n"));
632         return 1;
633     }
634
635     /* handle TARFILE */
636     t->tar_path = PANIC_IF_NULL(talloc_strdup(ctx, val[ival]));
637     ival++;
638
639     /*
640      * Make sure that dbf points to stderr if we are using stdout for
641      * tar output
642      */
643     if (t->mode.operation == TAR_CREATE && strequal(t->tar_path, "-")) {
644         setup_logging("smbclient", DEBUG_STDERR);
645     }
646
647     /* handle PATHs... */
648
649     /* flag F -> read file list */
650     if (do_read_list) {
651         if (valsize - ival != 1) {
652             DBG(0,("Option F must be followed by exactly one filename.\n"));
653             return 1;
654         }
655
656         rc = tar_read_inclusion_file(t, val[ival]);
657         if (rc != 0) {
658             return 1;
659         }
660         ival++;
661     }
662
663     /* otherwise store all the PATHs on the command line */
664     else {
665         int i;
666         for (i = ival; i < valsize; i++) {
667             tar_add_selection_path(t, val[i]);
668         }
669     }
670
671     t->to_process = true;
672     tar_dump(t);
673     return 0;
674 }
675
676 /**
677  * tar_process - start processing archive
678  *
679  * The talloc context of the fields is freed at the end of the call.
680  */
681 int tar_process(struct tar *t)
682 {
683     int rc = 0;
684
685     if (t == NULL) {
686         DBG(0, ("Invalid tar context\n"));
687         return 1;
688     }
689
690     switch(t->mode.operation) {
691     case TAR_EXTRACT:
692         rc = tar_extract(t);
693         break;
694     case TAR_CREATE:
695         rc = tar_create(t);
696         break;
697     default:
698         DBG(0, ("Invalid tar state\n"));
699         rc = 1;
700     }
701
702     t->to_process = false;
703     tar_free_mem_context(t);
704     DBG(5, ("tar_process done, err = %d\n", rc));
705     return rc;
706 }
707
708 /**
709  * tar_create - create archive and fetch files
710  */
711 static int tar_create(struct tar* t)
712 {
713     TALLOC_CTX *ctx = PANIC_IF_NULL(talloc_new(NULL));
714     int r;
715     int err = 0;
716     NTSTATUS status;
717     const char *mask;
718
719     t->archive = archive_write_new();
720
721     if (!t->mode.dry) {
722         const int bsize = t->mode.blocksize * TAR_BLOCK_UNIT;
723         r = archive_write_set_bytes_per_block(t->archive, bsize);
724         if (r != ARCHIVE_OK) {
725             DBG(0, ("Can't use a block size of %d bytes", bsize));
726             err = 1;
727             goto out;
728         }
729
730         /*
731          * Use PAX restricted format which is not the most
732          * conservative choice but has useful extensions and is widely
733          * supported
734          */
735         r = archive_write_set_format_pax_restricted(t->archive);
736         if (r != ARCHIVE_OK) {
737             DBG(0, ("Can't use pax restricted format: %s\n",
738                     archive_error_string(t->archive)));
739             err = 1;
740             goto out;
741         }
742
743         if (strequal(t->tar_path, "-")) {
744             r = archive_write_open_fd(t->archive, STDOUT_FILENO);
745         } else {
746             r = archive_write_open_filename(t->archive, t->tar_path);
747         }
748
749         if (r != ARCHIVE_OK) {
750             DBG(0, ("Can't open %s: %s\n", t->tar_path,
751                     archive_error_string(t->archive)));
752             err = 1;
753             goto out_close;
754         }
755     }
756
757     /*
758      * In inclusion mode, iterate on the inclusion list
759      */
760     if (t->mode.selection == TAR_INCLUDE && t->path_list_size > 0) {
761         if (tar_create_from_list(t)) {
762             err = 1;
763             goto out_close;
764         }
765     } else {
766         mask = PANIC_IF_NULL(talloc_asprintf(ctx, "%s\\*",
767                                              client_get_cur_dir()));
768         DBG(5, ("tar_process do_list with mask: %s\n", mask));
769         status = do_list(mask, TAR_DO_LIST_ATTR, get_file_callback, false, true);
770         if (!NT_STATUS_IS_OK(status)) {
771             DBG(0, ("do_list fail %s\n", nt_errstr(status)));
772             err = 1;
773             goto out_close;
774         }
775     }
776
777  out_close:
778     DBG(0, ("Total bytes received: %" PRIu64 "\n", t->total_size));
779
780     if (!t->mode.dry) {
781         r = archive_write_close(t->archive);
782         if (r != ARCHIVE_OK) {
783             DBG(0, ("Fatal: %s\n", archive_error_string(t->archive)));
784             err = 1;
785             goto out;
786         }
787     }
788  out:
789     archive_write_free(t->archive);
790     talloc_free(ctx);
791     return err;
792 }
793
794 /**
795  * tar_create_from_list - fetch from path list in include mode
796  */
797 static int tar_create_from_list(struct tar *t)
798 {
799     TALLOC_CTX *ctx = PANIC_IF_NULL(talloc_new(NULL));
800     int err = 0;
801     NTSTATUS status;
802     const char *path, *mask, *base, *start_dir;
803     int i;
804
805     start_dir = talloc_strdup(ctx, client_get_cur_dir());
806
807     for (i = 0; i < t->path_list_size; i++) {
808         path = t->path_list[i];
809         base = path_base_name(path);
810         mask = PANIC_IF_NULL(talloc_asprintf(ctx, "%s\\%s",
811                                              client_get_cur_dir(), path));
812
813         DBG(5, ("incl. path='%s', base='%s', mask='%s'\n",
814                 path, base ? base : "NULL", mask));
815
816         if (base != NULL) {
817             base = talloc_asprintf(ctx, "%s%s\\",
818                                    client_get_cur_dir(), path_base_name(path));
819             DBG(5, ("cd '%s' before do_list\n", base));
820             client_set_cur_dir(base);
821         }
822         status = do_list(mask, TAR_DO_LIST_ATTR, get_file_callback, false, true);
823         if (base != NULL) {
824             client_set_cur_dir(start_dir);
825         }
826         if (!NT_STATUS_IS_OK(status)) {
827             DBG(0, ("do_list failed on %s (%s)\n", path, nt_errstr(status)));
828             err = 1;
829             goto out;
830         }
831     }
832
833  out:
834     talloc_free(ctx);
835     return err;
836 }
837
838 /**
839  * get_file_callback - do_list callback
840  *
841  * Callback for client.c do_list(). Called for each file found on the
842  * share matching do_list mask. Recursively call do_list() with itself
843  * as callback when the current file is a directory.
844  */
845 static NTSTATUS get_file_callback(struct cli_state *cli,
846                                   struct file_info *finfo,
847                                   const char *dir)
848 {
849     TALLOC_CTX *ctx = PANIC_IF_NULL(talloc_new(NULL));
850     NTSTATUS err = NT_STATUS_OK;
851     char *remote_name;
852     const char *initial_dir = client_get_cur_dir();
853     int rc;
854
855     remote_name = PANIC_IF_NULL(talloc_asprintf(ctx, "%s%s",
856                                                 initial_dir, finfo->name));
857
858     if (strequal(finfo->name, "..") || strequal(finfo->name, ".")) {
859         goto out;
860     }
861
862     rc = tar_create_skip_path(&tar_ctx, remote_name, finfo);
863     if (rc != 0) {
864         DBG(5, ("--- %s\n", remote_name));
865         goto out;
866     }
867
868     if (finfo->mode & FILE_ATTRIBUTE_DIRECTORY) {
869         char *old_dir;
870         char *new_dir;
871         char *mask;
872
873         old_dir = PANIC_IF_NULL(talloc_strdup(ctx, initial_dir));
874         new_dir = PANIC_IF_NULL(talloc_asprintf(ctx, "%s%s\\",
875                                                 initial_dir, finfo->name));
876         mask = PANIC_IF_NULL(talloc_asprintf(ctx, "%s*", new_dir));
877
878         rc = tar_get_file(&tar_ctx, remote_name, finfo);
879         if (rc != 0) {
880             err = NT_STATUS_UNSUCCESSFUL;
881             goto out;
882         }
883
884         client_set_cur_dir(new_dir);
885         do_list(mask, TAR_DO_LIST_ATTR, get_file_callback, false, true);
886         client_set_cur_dir(old_dir);
887     } else {
888         rc = tar_get_file(&tar_ctx, remote_name, finfo);
889         if (rc != 0) {
890             err = NT_STATUS_UNSUCCESSFUL;
891             goto out;
892         }
893     }
894
895  out:
896     talloc_free(ctx);
897     return err;
898 }
899
900 /**
901  * tar_get_file - fetch a remote file to the local archive
902  * @full_dos_path: path to the file to fetch
903  * @finfo: attributes of the file to fetch
904  */
905 static int tar_get_file(struct tar *t, const char *full_dos_path,
906                         struct file_info *finfo)
907 {
908     extern struct cli_state *cli;
909     TALLOC_CTX *ctx = PANIC_IF_NULL(talloc_new(NULL));
910     NTSTATUS status;
911     struct archive_entry *entry;
912     char *full_unix_path;
913     char buf[TAR_CLI_READ_SIZE];
914     size_t len;
915     uint64_t off = 0;
916     uint16_t remote_fd = (uint16_t)-1;
917     int err = 0, r;
918     const bool isdir = finfo->mode & FILE_ATTRIBUTE_DIRECTORY;
919
920     DBG(5, ("+++ %s\n", full_dos_path));
921
922     t->total_size += finfo->size;
923
924     if (t->mode.dry) {
925         goto out;
926     }
927
928     if (t->mode.reset) {
929         /* ignore return value: server might not store DOS attributes */
930         set_remote_attr(full_dos_path, FILE_ATTRIBUTE_ARCHIVE, ATTR_UNSET);
931     }
932
933     full_unix_path = PANIC_IF_NULL(talloc_asprintf(ctx, ".%s", full_dos_path));
934     string_replace(full_unix_path, '\\', '/');
935     entry = archive_entry_new();
936     archive_entry_copy_pathname(entry, full_unix_path);
937     archive_entry_set_filetype(entry, isdir ? AE_IFDIR : AE_IFREG);
938     archive_entry_set_atime(entry,
939                             finfo->atime_ts.tv_sec,
940                             finfo->atime_ts.tv_nsec);
941     archive_entry_set_mtime(entry,
942                             finfo->mtime_ts.tv_sec,
943                             finfo->mtime_ts.tv_nsec);
944     archive_entry_set_ctime(entry,
945                             finfo->ctime_ts.tv_sec,
946                             finfo->ctime_ts.tv_nsec);
947     archive_entry_set_perm(entry, isdir ? 0755 : 0644);
948     /*
949      * check if we can safely cast unsigned file size to libarchive
950      * signed size. Very unlikely problem (>9 exabyte file)
951      */
952     if (finfo->size > INT64_MAX) {
953         DBG(0, ("Remote file %s too big\n", full_dos_path));
954         goto out_entry;
955     }
956
957     archive_entry_set_size(entry, (int64_t)finfo->size);
958
959     r = archive_write_header(t->archive, entry);
960     if (r != ARCHIVE_OK) {
961         DBG(0, ("Fatal: %s\n", archive_error_string(t->archive)));
962         err = 1;
963         goto out_entry;
964     }
965
966     if (isdir) {
967         DBG(5, ("get_file skip dir %s\n", full_dos_path));
968         goto out_entry;
969     }
970
971     status = cli_open(cli, full_dos_path, O_RDONLY, DENY_NONE, &remote_fd);
972     if (!NT_STATUS_IS_OK(status)) {
973         DBG(0,("%s opening remote file %s\n",
974                  nt_errstr(status), full_dos_path));
975         goto out_entry;
976     }
977
978     do {
979         status = cli_read(cli, remote_fd, buf, off, sizeof(buf), &len);
980         if (!NT_STATUS_IS_OK(status)) {
981             DBG(0,("Error reading file %s : %s\n",
982                      full_dos_path, nt_errstr(status)));
983             err = 1;
984             goto out_close;
985         }
986
987         off += len;
988
989         r = archive_write_data(t->archive, buf, len);
990         if (r < 0) {
991             DBG(0, ("Fatal: %s\n", archive_error_string(t->archive)));
992             err = 1;
993             goto out_close;
994         }
995
996     } while (off < finfo->size);
997
998  out_close:
999     cli_close(cli, remote_fd);
1000
1001  out_entry:
1002     archive_entry_free(entry);
1003
1004  out:
1005     talloc_free(ctx);
1006     return err;
1007 }
1008
1009 /**
1010  * tar_extract - open archive and send files.
1011  */
1012 static int tar_extract(struct tar *t)
1013 {
1014     int err = 0;
1015     int r;
1016     struct archive_entry *entry;
1017     const size_t bsize = t->mode.blocksize * TAR_BLOCK_UNIT;
1018     int rc;
1019
1020     t->archive = archive_read_new();
1021     archive_read_support_format_all(t->archive);
1022     archive_read_support_filter_all(t->archive);
1023
1024     if (strequal(t->tar_path, "-")) {
1025         r = archive_read_open_fd(t->archive, STDIN_FILENO, bsize);
1026     } else {
1027         r = archive_read_open_filename(t->archive, t->tar_path, bsize);
1028     }
1029
1030     if (r != ARCHIVE_OK) {
1031         DBG(0, ("Can't open %s : %s\n", t->tar_path,
1032                   archive_error_string(t->archive)));
1033         err = 1;
1034         goto out;
1035     }
1036
1037     for (;;) {
1038         r = archive_read_next_header(t->archive, &entry);
1039         if (r == ARCHIVE_EOF) {
1040             break;
1041         }
1042         if (r == ARCHIVE_WARN) {
1043             DBG(0, ("Warning: %s\n", archive_error_string(t->archive)));
1044         }
1045         if (r == ARCHIVE_FATAL) {
1046             DBG(0, ("Fatal: %s\n", archive_error_string(t->archive)));
1047             err = 1;
1048             goto out;
1049         }
1050
1051         rc = tar_extract_skip_path(t, entry);
1052         if (rc != 0) {
1053             DBG(5, ("--- %s\n", archive_entry_pathname(entry)));
1054             continue;
1055         }
1056
1057         DBG(5, ("+++ %s\n", archive_entry_pathname(entry)));
1058
1059         rc = tar_send_file(t, entry);
1060         if (rc != 0) {
1061             err = 1;
1062             goto out;
1063         }
1064     }
1065
1066  out:
1067     r = archive_read_free(t->archive);
1068     if (r != ARCHIVE_OK) {
1069         DBG(0, ("Can't close %s : %s\n", t->tar_path,
1070                   archive_error_string(t->archive)));
1071         err = 1;
1072     }
1073     return err;
1074 }
1075
1076 /**
1077  * tar_send_file - send @entry to the remote server
1078  * @entry: current archive entry
1079  *
1080  * Handle the creation of the parent directories and transfer the
1081  * entry to a new remote file.
1082  */
1083 static int tar_send_file(struct tar *t, struct archive_entry *entry)
1084 {
1085     extern struct cli_state *cli;
1086     TALLOC_CTX *ctx = PANIC_IF_NULL(talloc_new(NULL));
1087     char *dos_path;
1088     char *full_path;
1089     NTSTATUS status;
1090     uint16_t remote_fd = (uint16_t) -1;
1091     int err = 0;
1092     int flags = O_RDWR | O_CREAT | O_TRUNC;
1093     mode_t mode = archive_entry_filetype(entry);
1094     int rc;
1095
1096     dos_path = PANIC_IF_NULL(talloc_strdup(ctx, archive_entry_pathname(entry)));
1097     fix_unix_path(dos_path, true);
1098
1099     full_path = PANIC_IF_NULL(talloc_strdup(ctx, client_get_cur_dir()));
1100     full_path = PANIC_IF_NULL(talloc_strdup_append(full_path, dos_path));
1101
1102     if (mode != AE_IFREG && mode != AE_IFDIR) {
1103         DBG(0, ("Skipping non-dir & non-regular file %s\n", full_path));
1104         goto out;
1105     }
1106
1107     rc = make_remote_path(full_path);
1108     if (rc != 0) {
1109         err = 1;
1110         goto out;
1111     }
1112
1113     if (mode == AE_IFDIR) {
1114         goto out;
1115     }
1116
1117     status = cli_open(cli, full_path, flags, DENY_NONE, &remote_fd);
1118     if (!NT_STATUS_IS_OK(status)) {
1119         DBG(0, ("Error opening remote file %s: %s\n",
1120                   full_path, nt_errstr(status)));
1121         err = 1;
1122         goto out;
1123     }
1124
1125     for (;;) {
1126         const void *buf;
1127         size_t len;
1128         off_t off;
1129         int r;
1130
1131         r = archive_read_data_block(t->archive, &buf, &len, &off);
1132         if (r == ARCHIVE_EOF) {
1133             break;
1134         }
1135         if (r == ARCHIVE_WARN) {
1136             DBG(0, ("Warning: %s\n", archive_error_string(t->archive)));
1137         }
1138         if (r == ARCHIVE_FATAL) {
1139             DBG(0, ("Fatal: %s\n", archive_error_string(t->archive)));
1140             err = 1;
1141             goto close_out;
1142         }
1143
1144         status = cli_writeall(cli, remote_fd, 0, buf, off, len, NULL);
1145         if (!NT_STATUS_IS_OK(status)) {
1146             DBG(0, ("Error writing remote file %s: %s\n",
1147                       full_path, nt_errstr(status)));
1148             err = 1;
1149             goto close_out;
1150         }
1151     }
1152
1153  close_out:
1154     status = cli_close(cli, remote_fd);
1155     if (!NT_STATUS_IS_OK(status)) {
1156         DBG(0, ("Error losing remote file %s: %s\n",
1157                   full_path, nt_errstr(status)));
1158         err = 1;
1159     }
1160
1161  out:
1162     talloc_free(ctx);
1163     return err;
1164 }
1165
1166 /**
1167  * tar_add_selection_path - add a path to the path list
1168  * @path: path to add
1169  */
1170 static void tar_add_selection_path(struct tar *t, const char *path)
1171 {
1172     TALLOC_CTX *ctx = t->talloc_ctx;
1173     if (!t->path_list) {
1174         t->path_list = PANIC_IF_NULL(str_list_make_empty(ctx));
1175         t->path_list_size = 0;
1176     }
1177
1178     /* cast to silent gcc const-qual warning */
1179     t->path_list = PANIC_IF_NULL(str_list_add((void*)t->path_list,
1180                                               path));
1181     t->path_list_size++;
1182     fix_unix_path(t->path_list[t->path_list_size - 1], true);
1183 }
1184
1185 /**
1186  * tar_set_blocksize - set block size in TAR_BLOCK_UNIT
1187  */
1188 static int tar_set_blocksize(struct tar *t, int size)
1189 {
1190     if (size <= 0 || size > TAR_MAX_BLOCK_SIZE) {
1191         return 1;
1192     }
1193
1194     t->mode.blocksize = size;
1195
1196     return 0;
1197 }
1198
1199 /**
1200  * tar_set_newer_than - set date threshold of saved files
1201  * @filename: local path to a file
1202  *
1203  * Only files newer than the modification time of @filename will be
1204  * saved.
1205  *
1206  * Note: this function set the global variable newer_than from
1207  * client.c. Thus the time is not a field of the tar structure. See
1208  * cmd_newer() to change its value from an interactive session.
1209  */
1210 static int tar_set_newer_than(struct tar *t, const char *filename)
1211 {
1212     extern time_t newer_than;
1213     SMB_STRUCT_STAT stbuf;
1214     int rc;
1215
1216     rc = sys_stat(filename, &stbuf, false);
1217     if (rc != 0) {
1218         DBG(0, ("Error setting newer-than time\n"));
1219         return 1;
1220     }
1221
1222     newer_than = convert_timespec_to_time_t(stbuf.st_ex_mtime);
1223     DBG(1, ("Getting files newer than %s\n", time_to_asc(newer_than)));
1224     return 0;
1225 }
1226
1227 /**
1228  * tar_read_inclusion_file - set path list from file
1229  * @filename: path to the list file
1230  *
1231  * Read and add each line of @filename to the path list.
1232  */
1233 static int tar_read_inclusion_file (struct tar *t, const char* filename)
1234 {
1235     char *line;
1236     TALLOC_CTX *ctx = PANIC_IF_NULL(talloc_new(NULL));
1237     int err = 0;
1238     int fd;
1239
1240     fd = open(filename, O_RDONLY);
1241     if (fd < 0) {
1242         DBG(0, ("Can't open inclusion file '%s': %s\n", filename, strerror(errno)));
1243         err = 1;
1244         goto out;
1245     }
1246
1247     for (line = afdgets(fd, ctx, 0);
1248          line != NULL;
1249          line = afdgets(fd, ctx, 0)) {
1250         tar_add_selection_path(t, line);
1251     }
1252
1253     close(fd);
1254
1255  out:
1256     talloc_free(ctx);
1257     return err;
1258 }
1259
1260 /**
1261  * tar_path_in_list - return true if @path is in the path list
1262  * @path: path to find
1263  * @reverse: when true also try to find path list element in @path
1264  *
1265  * Look at each path of the path list and return true if @path is a
1266  * subpath of one of them.
1267  *
1268  * If you want /path to be in the path list (path/a/, path/b/) set
1269  * @reverse to true to try to match the other way around.
1270  */
1271 static bool tar_path_in_list(struct tar *t, const char *path, bool is_reverse)
1272 {
1273     int i;
1274     const char *p;
1275     const char *pattern;
1276
1277     if (path == NULL || path[0] == '\0') {
1278         return false;
1279     }
1280
1281     p = skip_useless_char_in_path(path);
1282
1283     for (i = 0; i < t->path_list_size; i++) {
1284         bool is_in_list;
1285
1286         pattern = skip_useless_char_in_path(t->path_list[i]);
1287         is_in_list = is_subpath(p, pattern);
1288         if (is_reverse) {
1289             is_in_list = is_in_list || is_subpath(pattern, p);
1290         }
1291         if (is_in_list) {
1292             return true;
1293         }
1294     }
1295
1296     return false;
1297 }
1298
1299 /**
1300  * tar_extract_skip_path - return true if @entry should be skipped
1301  * @entry: current tar entry
1302  *
1303  * Skip predicate for tar extraction (archive to server) only.
1304  */
1305 static bool tar_extract_skip_path(struct tar *t,
1306                                   struct archive_entry *entry)
1307 {
1308     const bool skip = true;
1309     const char *fullpath = archive_entry_pathname(entry);
1310     bool in = true;
1311
1312     if (t->path_list_size <= 0) {
1313         return !skip;
1314     }
1315
1316     if (t->mode.regex) {
1317         in = mask_match_list(fullpath, t->path_list, t->path_list_size, true);
1318     } else {
1319         in = tar_path_in_list(t, fullpath, false);
1320     }
1321
1322     if (t->mode.selection == TAR_EXCLUDE) {
1323         in = !in;
1324     }
1325
1326     return in ? !skip : skip;
1327 }
1328
1329 /**
1330  * tar_create_skip_path - return true if @fullpath shoud be skipped
1331  * @fullpath: full remote path of the current file
1332  * @finfo: remote file attributes
1333  *
1334  * Skip predicate for tar creation (server to archive) only.
1335  */
1336 static bool tar_create_skip_path(struct tar *t,
1337                                  const char *fullpath,
1338                                  const struct file_info *finfo)
1339 {
1340     /* syntaxic sugar */
1341     const bool skip = true;
1342     const mode_t mode = finfo->mode;
1343     const bool isdir = mode & FILE_ATTRIBUTE_DIRECTORY;
1344     const bool exclude = t->mode.selection == TAR_EXCLUDE;
1345     bool in = true;
1346
1347     if (!isdir) {
1348
1349         /* 1. if we dont want X and we have X, skip */
1350         if (!t->mode.system && (mode & FILE_ATTRIBUTE_SYSTEM)) {
1351             return skip;
1352         }
1353
1354         if (!t->mode.hidden && (mode & FILE_ATTRIBUTE_HIDDEN)) {
1355             return skip;
1356         }
1357
1358         /* 2. if we only want archive and it's not, skip */
1359
1360         if (t->mode.incremental && !(mode & FILE_ATTRIBUTE_ARCHIVE)) {
1361             return skip;
1362         }
1363     }
1364
1365     /* 3. is it in the selection list? */
1366
1367     /*
1368      * tar_create_from_list() use the include list as a starting
1369      * point, no need to check
1370      */
1371     if (!exclude) {
1372         return !skip;
1373     }
1374
1375     /* we are now in exclude mode */
1376
1377     /* no matter the selection, no list => include everything */
1378     if (t->path_list_size <= 0) {
1379         return !skip;
1380     }
1381
1382     if (t->mode.regex) {
1383         in = mask_match_list(fullpath, t->path_list, t->path_list_size, true);
1384     } else {
1385         in = tar_path_in_list(t, fullpath, isdir && !exclude);
1386     }
1387
1388     return in ? skip : !skip;
1389 }
1390
1391 /**
1392  * tar_to_process - return true if @t is ready to be processed
1393  *
1394  * @t is ready if it properly parsed command line arguments.
1395  */
1396 bool tar_to_process (struct tar *t)
1397 {
1398     if (t == NULL) {
1399         DBG(0, ("Invalid tar context\n"));
1400         return false;
1401     }
1402     return t->to_process;
1403 }
1404
1405 /**
1406  * skip_useless_char_in_path - skip leading slashes/dots
1407  *
1408  * Skip leading slashes, backslashes and dot-slashes.
1409  */
1410 static const char* skip_useless_char_in_path(const char *p)
1411 {
1412     while (p) {
1413         if (*p == '/' || *p == '\\') {
1414             p++;
1415         }
1416         else if (p[0] == '.' && (p[1] == '/' || p[1] == '\\')) {
1417             p += 2;
1418         }
1419         else
1420             return p;
1421     }
1422     return p;
1423 }
1424
1425 /**
1426  * is_subpath - return true if the path @sub is a subpath of @full.
1427  * @sub: path to test
1428  * @full: container path
1429  *
1430  * String comparaison is case-insensitive.
1431  *
1432  * Return true if @sub = @full
1433  */
1434 static bool is_subpath(const char *sub, const char *full)
1435 {
1436         TALLOC_CTX *tmp_ctx = PANIC_IF_NULL(talloc_new(NULL));
1437         int len = 0;
1438         char *f, *s;
1439
1440         f = PANIC_IF_NULL(strlower_talloc(tmp_ctx, full));
1441         string_replace(f, '\\', '/');
1442         s = PANIC_IF_NULL(strlower_talloc(tmp_ctx, sub));
1443         string_replace(s, '\\', '/');
1444
1445         /* find the point where sub and full diverge */
1446         while ((*f != '\0') && (*s != '\0') && (*f == *s)) {
1447                 f++;
1448                 s++;
1449                 len++;
1450         }
1451
1452         if ((*f == '\0') && (*s == '\0')) {
1453                 return true;    /* sub and full match */
1454         }
1455
1456         if ((*f == '\0') && (len > 0) && (*(f - 1) == '/')) {
1457                 /* sub diverges from full at path separator */
1458                 return true;
1459         }
1460
1461         if ((*s == '\0') && (strcmp(f, "/") == 0)) {
1462                 /* full diverges from sub with trailing slash only */
1463                 return true;
1464         }
1465
1466         if ((*s == '/') && (*f == '\0')) {
1467                 /* sub diverges from full with extra path component */
1468                 return true;
1469         }
1470
1471         return false;
1472 }
1473
1474 /**
1475  * set_remote_attr - set DOS attributes of a remote file
1476  * @filename: path to the file name
1477  * @new_attr: attribute bit mask to use
1478  * @mode: one of ATTR_SET or ATTR_UNSET
1479  *
1480  * Update the file attributes with the one provided.
1481  */
1482 static int set_remote_attr(const char *filename, uint16 new_attr, int mode)
1483 {
1484     extern struct cli_state *cli;
1485     uint16 old_attr;
1486     NTSTATUS status;
1487
1488     status = cli_getatr(cli, filename, &old_attr, NULL, NULL);
1489     if (!NT_STATUS_IS_OK(status)) {
1490         DBG(0, ("cli_getatr failed: %s\n", nt_errstr(status)));
1491         return 1;
1492     }
1493
1494     if (mode == ATTR_SET) {
1495         new_attr |= old_attr;
1496     } else {
1497         new_attr = old_attr & ~new_attr;
1498     }
1499
1500     status = cli_setatr(cli, filename, new_attr, 0);
1501     if (!NT_STATUS_IS_OK(status)) {
1502         DBG(1, ("cli_setatr failed: %s\n", nt_errstr(status)));
1503         return 1;
1504     }
1505
1506     return 0;
1507 }
1508
1509
1510 /**
1511  * make_remote_path - recursively make remote dirs
1512  * @full_path: full hierarchy to create
1513  *
1514  * Create @full_path and each parent directories as needed.
1515  */
1516 static int make_remote_path(const char *full_path)
1517 {
1518     extern struct cli_state *cli;
1519     TALLOC_CTX *ctx = PANIC_IF_NULL(talloc_new(NULL));
1520     char *path;
1521     char *subpath;
1522     char *state;
1523     char *last_backslash;
1524     char *p;
1525     int len;
1526     NTSTATUS status;
1527     int err = 0;
1528
1529     subpath = PANIC_IF_NULL(talloc_strdup(ctx, full_path));
1530     path = PANIC_IF_NULL(talloc_strdup(ctx, full_path));
1531     len = talloc_get_size(path) - 1;
1532
1533     last_backslash = strrchr_m(path, '\\');
1534     if (last_backslash == NULL) {
1535         goto out;
1536     }
1537
1538     *last_backslash = 0;
1539
1540     subpath[0] = 0;
1541     p = strtok_r(path, "\\", &state);
1542
1543     while (p != NULL) {
1544         strlcat(subpath, p, len);
1545         status = cli_chkpath(cli, subpath);
1546         if (!NT_STATUS_IS_OK(status)) {
1547             status = cli_mkdir(cli, subpath);
1548             if (!NT_STATUS_IS_OK(status)) {
1549                 DBG(0, ("Can't mkdir %s: %s\n", subpath, nt_errstr(status)));
1550                 err = 1;
1551                 goto out;
1552             }
1553             DBG(3, ("mkdir %s\n", subpath));
1554         }
1555
1556         strlcat(subpath, "\\", len);
1557         p = strtok_r(NULL, "/\\", &state);
1558
1559     }
1560
1561  out:
1562     talloc_free(ctx);
1563     return err;
1564 }
1565
1566 /**
1567  * tar_reset_mem_context - reset talloc context associated with @t
1568  *
1569  * At the start of the program the context is NULL so a new one is
1570  * allocated. On the following runs (interactive session only), simply
1571  * free the children.
1572  */
1573 static TALLOC_CTX *tar_reset_mem_context(struct tar *t)
1574 {
1575     tar_free_mem_context(t);
1576     t->talloc_ctx = PANIC_IF_NULL(talloc_new(NULL));
1577     return t->talloc_ctx;
1578 }
1579
1580 /**
1581  * tar_free_mem_context - free talloc context associated with @t
1582  */
1583 static void tar_free_mem_context(struct tar *t)
1584 {
1585     if (t->talloc_ctx) {
1586         talloc_free(t->talloc_ctx);
1587         t->talloc_ctx = NULL;
1588         t->path_list_size = 0;
1589         t->path_list = NULL;
1590         t->tar_path = NULL;
1591     }
1592 }
1593
1594 #define XSET(v)      [v] = #v
1595 #define XTABLE(v, t) DBG(2, ("DUMP:%-20.20s = %s\n", #v, t[v]))
1596 #define XBOOL(v)     DBG(2, ("DUMP:%-20.20s = %d\n", #v, v ? 1 : 0))
1597 #define XSTR(v)      DBG(2, ("DUMP:%-20.20s = %s\n", #v, v ? v : "NULL"))
1598 #define XINT(v)      DBG(2, ("DUMP:%-20.20s = %d\n", #v, v))
1599 #define XUINT64(v)   DBG(2, ("DUMP:%-20.20s = %" PRIu64  "\n", #v, v))
1600
1601 /**
1602  * tar_dump - dump tar structure on stdout
1603  */
1604 static void tar_dump(struct tar *t)
1605 {
1606     int i;
1607     const char* op[] = {
1608         XSET(TAR_NO_OPERATION),
1609         XSET(TAR_CREATE),
1610         XSET(TAR_EXTRACT),
1611     };
1612
1613     const char* sel[] = {
1614         XSET(TAR_NO_SELECTION),
1615         XSET(TAR_INCLUDE),
1616         XSET(TAR_EXCLUDE),
1617     };
1618
1619     XBOOL(t->to_process);
1620     XTABLE(t->mode.operation, op);
1621     XTABLE(t->mode.selection, sel);
1622     XINT(t->mode.blocksize);
1623     XBOOL(t->mode.hidden);
1624     XBOOL(t->mode.system);
1625     XBOOL(t->mode.incremental);
1626     XBOOL(t->mode.reset);
1627     XBOOL(t->mode.dry);
1628     XBOOL(t->mode.verbose);
1629     XUINT64(t->total_size);
1630     XSTR(t->tar_path);
1631     XINT(t->path_list_size);
1632
1633     for (i = 0; t->path_list && t->path_list[i]; i++) {
1634         DBG(2, ("DUMP: t->path_list[%2d] = %s\n", i, t->path_list[i]));
1635     }
1636
1637     DBG(2, ("DUMP:t->path_list @ %p (%d elem)\n", t->path_list, i));
1638 }
1639 #undef XSET
1640 #undef XTABLE
1641 #undef XBOOL
1642 #undef XSTR
1643 #undef XINT
1644
1645 /**
1646  * max_token - return upper limit for the number of token in @str
1647  *
1648  * The result is not exact, the actual number of token might be less
1649  * than what is returned.
1650  */
1651 static int max_token (const char *str)
1652 {
1653     const char *s;
1654     int nb = 0;
1655
1656     if (str == NULL) {
1657         return 0;
1658     }
1659
1660     s = str;
1661     while (s[0] != '\0') {
1662         if (isspace((int)s[0])) {
1663             nb++;
1664         }
1665         s++;
1666     }
1667
1668     nb++;
1669
1670     return nb;
1671 }
1672
1673 /**
1674  * fix_unix_path - convert @path to a DOS path
1675  * @path: path to convert
1676  * @removeprefix: if true, remove leading ./ or /.
1677  */
1678 static char *fix_unix_path (char *path, bool do_remove_prefix)
1679 {
1680     char *from = path, *to = path;
1681
1682     if (path == NULL || path[0] == '\0') {
1683         return path;
1684     }
1685
1686     /* remove prefix:
1687      * ./path => path
1688      *  /path => path
1689      */
1690     if (do_remove_prefix) {
1691         /* /path */
1692         if (path[0] == '/' || path[0] == '\\') {
1693             from += 1;
1694         }
1695
1696         /* ./path */
1697         if (path[1] != '\0' && path[0] == '.' && (path[1] == '/' || path[1] == '\\')) {
1698             from += 2;
1699         }
1700     }
1701
1702     /* replace / with \ */
1703     while (from[0] != '\0') {
1704         if (from[0] == '/') {
1705             to[0] = '\\';
1706         } else {
1707             to[0] = from[0];
1708         }
1709
1710         from++;
1711         to++;
1712     }
1713     to[0] = '\0';
1714
1715     return path;
1716 }
1717
1718 /**
1719  * path_base_name - return @path basename
1720  *
1721  * If @path doesn't contain any directory separator return NULL.
1722  */
1723 static char *path_base_name (const char *path)
1724 {
1725     TALLOC_CTX *ctx = PANIC_IF_NULL(talloc_tos());
1726     char *base = NULL;
1727     int last = -1;
1728     int i;
1729
1730     for (i = 0; path[i]; i++) {
1731         if (path[i] == '\\' || path[i] == '/') {
1732             last = i;
1733         }
1734     }
1735
1736     if (last >= 0) {
1737         base = PANIC_IF_NULL(talloc_strdup(ctx, path));
1738         base[last] = 0;
1739     }
1740
1741     return base;
1742 }
1743
1744 #else
1745
1746 #define NOT_IMPLEMENTED DEBUG(0, ("tar mode not compiled. build with --with-libarchive\n"))
1747
1748 int cmd_block(void)
1749 {
1750     NOT_IMPLEMENTED;
1751     return 1;
1752 }
1753
1754 int cmd_tarmode(void)
1755 {
1756     NOT_IMPLEMENTED;
1757     return 1;
1758 }
1759
1760 int cmd_setmode(void)
1761 {
1762     NOT_IMPLEMENTED;
1763     return 1;
1764 }
1765
1766 int cmd_tar(void)
1767 {
1768     NOT_IMPLEMENTED;
1769     return 1;
1770 }
1771
1772 int tar_process(struct tar* tar)
1773 {
1774     NOT_IMPLEMENTED;
1775     return 1;
1776 }
1777
1778 int tar_parse_args(struct tar *tar, const char *flag, const char **val, int valsize)
1779 {
1780     NOT_IMPLEMENTED;
1781     return 1;
1782 }
1783
1784 bool tar_to_process(struct tar *tar)
1785 {
1786     NOT_IMPLEMENTED;
1787     return false;
1788 }
1789
1790 struct tar *tar_get_ctx()
1791 {
1792     return NULL;
1793 }
1794
1795 #endif