vfs_shadow_copy2: Fix a log message
[samba.git] / source3 / modules / vfs_shadow_copy2.c
1 /*
2  * shadow_copy2: a shadow copy module (second implementation)
3  *
4  * Copyright (C) Andrew Tridgell   2007 (portions taken from shadow_copy2)
5  * Copyright (C) Ed Plese          2009
6  * Copyright (C) Volker Lendecke   2011
7  * Copyright (C) Christian Ambach  2011
8  * Copyright (C) Michael Adam      2013
9  * Copyright (C) Rajesh Joseph     2016
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24  */
25
26 /*
27  * This is a second implemetation of a shadow copy module for exposing
28  * file system snapshots to windows clients as shadow copies.
29  *
30  * See the manual page for documentation.
31  */
32
33 #include "includes.h"
34 #include "smbd/smbd.h"
35 #include "system/filesys.h"
36 #include "include/ntioctl.h"
37 #include "util_tdb.h"
38 #include "lib/util_path.h"
39 #include "libcli/security/security.h"
40 #include "lib/util/tevent_unix.h"
41
42 struct shadow_copy2_config {
43         char *gmt_format;
44         bool use_sscanf;
45         bool use_localtime;
46         char *snapdir;
47         char *delimiter;
48         bool snapdirseverywhere;
49         bool crossmountpoints;
50         bool fixinodes;
51         char *sort_order;
52         bool snapdir_absolute;
53         char *mount_point;
54         char *rel_connectpath; /* share root, relative to a snapshot root */
55         char *snapshot_basepath; /* the absolute version of snapdir */
56 };
57
58 /* Data-structure to hold the list of snap entries */
59 struct shadow_copy2_snapentry {
60         char *snapname;
61         char *time_fmt;
62         struct shadow_copy2_snapentry *next;
63         struct shadow_copy2_snapentry *prev;
64 };
65
66 struct shadow_copy2_snaplist_info {
67         struct shadow_copy2_snapentry *snaplist; /* snapshot list */
68         regex_t *regex; /* Regex to filter snaps */
69         time_t fetch_time; /* snaplist update time */
70 };
71
72
73 /*
74  * shadow_copy2 private structure. This structure will be
75  * used to keep module specific information
76  */
77 struct shadow_copy2_private {
78         struct shadow_copy2_config *config;
79         struct shadow_copy2_snaplist_info *snaps;
80         char *shadow_cwd; /* Absolute $cwd path. */
81         /* Absolute connectpath - can vary depending on $cwd. */
82         char *shadow_connectpath;
83         /* talloc'ed realpath return. */
84         struct smb_filename *shadow_realpath;
85 };
86
87 static int shadow_copy2_get_shadow_copy_data(
88         vfs_handle_struct *handle, files_struct *fsp,
89         struct shadow_copy_data *shadow_copy2_data,
90         bool labels);
91
92 /**
93  *This function will create a new snapshot list entry and
94  * return to the caller. This entry will also be added to
95  * the global snapshot list.
96  *
97  * @param[in]   priv    shadow_copy2 specific data structure
98  * @return      Newly   created snapshot entry or NULL on failure
99  */
100 static struct shadow_copy2_snapentry *shadow_copy2_create_snapentry(
101                                         struct shadow_copy2_private *priv)
102 {
103         struct shadow_copy2_snapentry *tmpentry = NULL;
104
105         tmpentry = talloc_zero(priv->snaps, struct shadow_copy2_snapentry);
106         if (tmpentry == NULL) {
107                 DBG_ERR("talloc_zero() failed\n");
108                 errno = ENOMEM;
109                 return NULL;
110         }
111
112         DLIST_ADD(priv->snaps->snaplist, tmpentry);
113
114         return tmpentry;
115 }
116
117 /**
118  *This function will delete the entire snaplist and reset
119  * priv->snaps->snaplist to NULL.
120  *
121  * @param[in] priv shadow_copye specific data structure
122  */
123 static void shadow_copy2_delete_snaplist(struct shadow_copy2_private *priv)
124 {
125         struct shadow_copy2_snapentry *tmp = NULL;
126
127         while ((tmp = priv->snaps->snaplist) != NULL) {
128                 DLIST_REMOVE(priv->snaps->snaplist, tmp);
129                 talloc_free(tmp);
130         }
131 }
132
133 /**
134  * Given a timestamp this function searches the global snapshot list
135  * and returns the complete snapshot directory name saved in the entry.
136  *
137  * @param[in]   priv            shadow_copy2 specific structure
138  * @param[in]   timestamp       timestamp corresponding to one of the snapshot
139  * @param[out]  snap_str        buffer to copy the actual snapshot name
140  * @param[in]   len             length of snap_str buffer
141  *
142  * @return      Length of actual snapshot name, and -1 on failure
143  */
144 static ssize_t shadow_copy2_saved_snapname(struct shadow_copy2_private *priv,
145                                           struct tm *timestamp,
146                                           char *snap_str, size_t len)
147 {
148         ssize_t snaptime_len = -1;
149         struct shadow_copy2_snapentry *entry = NULL;
150
151         snaptime_len = strftime(snap_str, len, GMT_FORMAT, timestamp);
152         if (snaptime_len == 0) {
153                 DBG_ERR("strftime failed\n");
154                 return -1;
155         }
156
157         snaptime_len = -1;
158
159         for (entry = priv->snaps->snaplist; entry; entry = entry->next) {
160                 if (strcmp(entry->time_fmt, snap_str) == 0) {
161                         snaptime_len = snprintf(snap_str, len, "%s",
162                                                 entry->snapname);
163                         return snaptime_len;
164                 }
165         }
166
167         snap_str[0] = 0;
168         return snaptime_len;
169 }
170
171
172 /**
173  * This function will check if snaplist is updated or not. If snaplist
174  * is empty then it will create a new list. Each time snaplist is updated
175  * the time is recorded. If the snapshot time is greater than the snaplist
176  * update time then chances are we are working on an older list. Then discard
177  * the old list and fetch a new snaplist.
178  *
179  * @param[in]   handle          VFS handle struct
180  * @param[in]   snap_time       time of snapshot
181  *
182  * @return      true if the list is updated else false
183  */
184 static bool shadow_copy2_update_snaplist(struct vfs_handle_struct *handle,
185                 time_t snap_time)
186 {
187         int ret = -1;
188         bool snaplist_updated = false;
189         struct files_struct fsp = {0};
190         struct smb_filename smb_fname = {0};
191         double seconds = 0.0;
192         struct shadow_copy2_private *priv = NULL;
193
194         SMB_VFS_HANDLE_GET_DATA(handle, priv, struct shadow_copy2_private,
195                                 return false);
196
197         seconds = difftime(snap_time, priv->snaps->fetch_time);
198
199         /*
200          * Fetch the snapshot list if either the snaplist is empty or the
201          * required snapshot time is greater than the last fetched snaplist
202          * time.
203          */
204         if (seconds > 0 || (priv->snaps->snaplist == NULL)) {
205                 smb_fname.base_name = discard_const_p(char, ".");
206                 fsp.fsp_name = &smb_fname;
207
208                 ret = shadow_copy2_get_shadow_copy_data(handle, &fsp,
209                                                         NULL, false);
210                 if (ret == 0) {
211                         snaplist_updated = true;
212                 } else {
213                         DBG_ERR("Failed to get shadow copy data\n");
214                 }
215
216         }
217
218         return snaplist_updated;
219 }
220
221 static bool shadow_copy2_find_slashes(TALLOC_CTX *mem_ctx, const char *str,
222                                       size_t **poffsets,
223                                       unsigned *pnum_offsets)
224 {
225         unsigned num_offsets;
226         size_t *offsets;
227         const char *p;
228
229         num_offsets = 0;
230
231         p = str;
232         while ((p = strchr(p, '/')) != NULL) {
233                 num_offsets += 1;
234                 p += 1;
235         }
236
237         offsets = talloc_array(mem_ctx, size_t, num_offsets);
238         if (offsets == NULL) {
239                 return false;
240         }
241
242         p = str;
243         num_offsets = 0;
244         while ((p = strchr(p, '/')) != NULL) {
245                 offsets[num_offsets] = p-str;
246                 num_offsets += 1;
247                 p += 1;
248         }
249
250         *poffsets = offsets;
251         *pnum_offsets = num_offsets;
252         return true;
253 }
254
255 /**
256  * Given a timestamp, build the posix level GMT-tag string
257  * based on the configurable format.
258  */
259 static ssize_t shadow_copy2_posix_gmt_string(struct vfs_handle_struct *handle,
260                                             time_t snapshot,
261                                             char *snaptime_string,
262                                             size_t len)
263 {
264         struct tm snap_tm;
265         ssize_t snaptime_len;
266         struct shadow_copy2_config *config;
267         struct shadow_copy2_private *priv;
268
269         SMB_VFS_HANDLE_GET_DATA(handle, priv, struct shadow_copy2_private,
270                                 return 0);
271
272         config = priv->config;
273
274         if (config->use_sscanf) {
275                 snaptime_len = snprintf(snaptime_string,
276                                         len,
277                                         config->gmt_format,
278                                         (unsigned long)snapshot);
279                 if (snaptime_len <= 0) {
280                         DEBUG(10, ("snprintf failed\n"));
281                         return -1;
282                 }
283         } else {
284                 if (config->use_localtime) {
285                         if (localtime_r(&snapshot, &snap_tm) == 0) {
286                                 DEBUG(10, ("gmtime_r failed\n"));
287                                 return -1;
288                         }
289                 } else {
290                         if (gmtime_r(&snapshot, &snap_tm) == 0) {
291                                 DEBUG(10, ("gmtime_r failed\n"));
292                                 return -1;
293                         }
294                 }
295
296                 if (priv->snaps->regex != NULL) {
297                         snaptime_len = shadow_copy2_saved_snapname(priv,
298                                                 &snap_tm, snaptime_string, len);
299                         if (snaptime_len >= 0)
300                                 return snaptime_len;
301
302                         /*
303                          * If we fail to find the snapshot name, chances are
304                          * that we have not updated our snaplist. Make sure the
305                          * snaplist is updated.
306                          */
307                         if (!shadow_copy2_update_snaplist(handle, snapshot)) {
308                                 DBG_DEBUG("shadow_copy2_update_snaplist "
309                                           "failed\n");
310                                 return -1;
311                         }
312
313                         return shadow_copy2_saved_snapname(priv,
314                                                 &snap_tm, snaptime_string, len);
315                 }
316
317                 snaptime_len = strftime(snaptime_string,
318                                         len,
319                                         config->gmt_format,
320                                         &snap_tm);
321                 if (snaptime_len == 0) {
322                         DEBUG(10, ("strftime failed\n"));
323                         return -1;
324                 }
325         }
326
327         return snaptime_len;
328 }
329
330 /**
331  * Given a timestamp, build the string to insert into a path
332  * as a path component for creating the local path to the
333  * snapshot at the given timestamp of the input path.
334  *
335  * In the case of a parallel snapdir (specified with an
336  * absolute path), this is the initial portion of the
337  * local path of any snapshot file. The complete path is
338  * obtained by appending the portion of the file's path
339  * below the share root's mountpoint.
340  */
341 static char *shadow_copy2_insert_string(TALLOC_CTX *mem_ctx,
342                                         struct vfs_handle_struct *handle,
343                                         time_t snapshot)
344 {
345         fstring snaptime_string;
346         ssize_t snaptime_len = 0;
347         char *result = NULL;
348         struct shadow_copy2_config *config;
349         struct shadow_copy2_private *priv;
350
351         SMB_VFS_HANDLE_GET_DATA(handle, priv, struct shadow_copy2_private,
352                                 return NULL);
353
354         config = priv->config;
355
356         snaptime_len = shadow_copy2_posix_gmt_string(handle,
357                                                      snapshot,
358                                                      snaptime_string,
359                                                      sizeof(snaptime_string));
360         if (snaptime_len <= 0) {
361                 return NULL;
362         }
363
364         if (config->snapdir_absolute) {
365                 result = talloc_asprintf(mem_ctx, "%s/%s",
366                                          config->snapdir, snaptime_string);
367         } else {
368                 result = talloc_asprintf(mem_ctx, "/%s/%s",
369                                          config->snapdir, snaptime_string);
370         }
371         if (result == NULL) {
372                 DEBUG(1, (__location__ " talloc_asprintf failed\n"));
373         }
374
375         return result;
376 }
377
378 /**
379  * Build the posix snapshot path for the connection
380  * at the given timestamp, i.e. the absolute posix path
381  * that contains the snapshot for this file system.
382  *
383  * This only applies to classical case, i.e. not
384  * to the "snapdirseverywhere" mode.
385  */
386 static char *shadow_copy2_snapshot_path(TALLOC_CTX *mem_ctx,
387                                         struct vfs_handle_struct *handle,
388                                         time_t snapshot)
389 {
390         fstring snaptime_string;
391         ssize_t snaptime_len = 0;
392         char *result = NULL;
393         struct shadow_copy2_private *priv;
394
395         SMB_VFS_HANDLE_GET_DATA(handle, priv, struct shadow_copy2_private,
396                                 return NULL);
397
398         snaptime_len = shadow_copy2_posix_gmt_string(handle,
399                                                      snapshot,
400                                                      snaptime_string,
401                                                      sizeof(snaptime_string));
402         if (snaptime_len <= 0) {
403                 return NULL;
404         }
405
406         result = talloc_asprintf(mem_ctx, "%s/%s",
407                                  priv->config->snapshot_basepath, snaptime_string);
408         if (result == NULL) {
409                 DEBUG(1, (__location__ " talloc_asprintf failed\n"));
410         }
411
412         return result;
413 }
414
415 static char *make_path_absolute(TALLOC_CTX *mem_ctx,
416                                 struct shadow_copy2_private *priv,
417                                 const char *name)
418 {
419         char *newpath = NULL;
420         char *abs_path = NULL;
421
422         if (name[0] != '/') {
423                 newpath = talloc_asprintf(mem_ctx,
424                                         "%s/%s",
425                                         priv->shadow_cwd,
426                                         name);
427                 if (newpath == NULL) {
428                         return NULL;
429                 }
430                 name = newpath;
431         }
432         abs_path = canonicalize_absolute_path(mem_ctx, name);
433         TALLOC_FREE(newpath);
434         return abs_path;
435 }
436
437 /* Return a $cwd-relative path. */
438 static bool make_relative_path(const char *cwd, char *abs_path)
439 {
440         size_t cwd_len = strlen(cwd);
441         size_t abs_len = strlen(abs_path);
442
443         if (abs_len < cwd_len) {
444                 return false;
445         }
446         if (memcmp(abs_path, cwd, cwd_len) != 0) {
447                 return false;
448         }
449         /* The cwd_len != 1 case is for $cwd == '/' */
450         if (cwd_len != 1 &&
451             abs_path[cwd_len] != '/' &&
452             abs_path[cwd_len] != '\0')
453         {
454                 return false;
455         }
456         if (abs_path[cwd_len] == '/') {
457                 cwd_len++;
458         }
459         memmove(abs_path, &abs_path[cwd_len], abs_len + 1 - cwd_len);
460         return true;
461 }
462
463 static bool shadow_copy2_snapshot_to_gmt(vfs_handle_struct *handle,
464                                         const char *name,
465                                         char *gmt, size_t gmt_len);
466
467 /*
468  * Check if an incoming filename is already a snapshot converted pathname.
469  *
470  * If so, it returns the pathname truncated at the snapshot point which
471  * will be used as the connectpath.
472  */
473
474 static int check_for_converted_path(TALLOC_CTX *mem_ctx,
475                                 struct vfs_handle_struct *handle,
476                                 struct shadow_copy2_private *priv,
477                                 char *abs_path,
478                                 bool *ppath_already_converted,
479                                 char **pconnectpath)
480 {
481         size_t snapdirlen = 0;
482         char *p = strstr_m(abs_path, priv->config->snapdir);
483         char *q = NULL;
484         char *connect_path = NULL;
485         char snapshot[GMT_NAME_LEN+1];
486
487         *ppath_already_converted = false;
488
489         if (p == NULL) {
490                 /* Must at least contain shadow:snapdir. */
491                 return 0;
492         }
493
494         if (priv->config->snapdir[0] == '/' &&
495                         p != abs_path) {
496                 /* Absolute shadow:snapdir must be at the start. */
497                 return 0;
498         }
499
500         snapdirlen = strlen(priv->config->snapdir);
501         if (p[snapdirlen] != '/') {
502                 /* shadow:snapdir must end as a separate component. */
503                 return 0;
504         }
505
506         if (p > abs_path && p[-1] != '/') {
507                 /* shadow:snapdir must start as a separate component. */
508                 return 0;
509         }
510
511         p += snapdirlen;
512         p++; /* Move past the / */
513
514         /*
515          * Need to return up to the next path
516          * component after the time.
517          * This will be used as the connectpath.
518          */
519         q = strchr(p, '/');
520         if (q == NULL) {
521                 /*
522                  * No next path component.
523                  * Use entire string.
524                  */
525                 connect_path = talloc_strdup(mem_ctx,
526                                         abs_path);
527         } else {
528                 connect_path = talloc_strndup(mem_ctx,
529                                         abs_path,
530                                         q - abs_path);
531         }
532         if (connect_path == NULL) {
533                 return ENOMEM;
534         }
535
536         /*
537          * Point p at the same offset in connect_path as
538          * it is in abs_path.
539          */
540
541         p = &connect_path[p - abs_path];
542
543         /*
544          * Now ensure there is a time string at p.
545          * The SMB-format @GMT-token string is returned
546          * in snapshot.
547          */
548
549         if (!shadow_copy2_snapshot_to_gmt(handle,
550                                 p,
551                                 snapshot,
552                                 sizeof(snapshot))) {
553                 TALLOC_FREE(connect_path);
554                 return 0;
555         }
556
557         if (pconnectpath != NULL) {
558                 *pconnectpath = connect_path;
559         }
560
561         *ppath_already_converted = true;
562
563         DBG_DEBUG("path |%s| is already converted. "
564                 "connect path = |%s|\n",
565                 abs_path,
566                 connect_path);
567
568         return 0;
569 }
570
571 /**
572  * This function does two things.
573  *
574  * 1). Checks if an incoming filename is already a
575  * snapshot converted pathname.
576  *     If so, it returns the pathname truncated
577  *     at the snapshot point which will be used
578  *     as the connectpath, and then does an early return.
579  *
580  * 2). Checks if an incoming filename contains an
581  * SMB-layer @GMT- style timestamp.
582  *     If so, it strips the timestamp, and returns
583  *     both the timestamp and the stripped path
584  *     (making it cwd-relative).
585  */
586
587 static bool _shadow_copy2_strip_snapshot_internal(TALLOC_CTX *mem_ctx,
588                                         struct vfs_handle_struct *handle,
589                                         const struct smb_filename *smb_fname,
590                                         time_t *ptimestamp,
591                                         char **pstripped,
592                                         char **psnappath,
593                                         bool *_already_converted,
594                                         const char *function)
595 {
596         char *stripped = NULL;
597         struct shadow_copy2_private *priv;
598         char *abs_path = NULL;
599         bool ret = true;
600         bool already_converted = false;
601         int err = 0;
602
603         SMB_VFS_HANDLE_GET_DATA(handle, priv, struct shadow_copy2_private,
604                                 return false);
605
606         DBG_DEBUG("[from %s()] Path '%s'\n",
607                   function, smb_fname_str_dbg(smb_fname));
608
609         if (_already_converted != NULL) {
610                 *_already_converted = false;
611         }
612
613         abs_path = make_path_absolute(mem_ctx, priv, smb_fname->base_name);
614         if (abs_path == NULL) {
615                 ret = false;
616                 goto out;
617         }
618
619         DBG_DEBUG("abs path '%s'\n", abs_path);
620
621         err = check_for_converted_path(mem_ctx,
622                                         handle,
623                                         priv,
624                                         abs_path,
625                                         &already_converted,
626                                         psnappath);
627         if (err != 0) {
628                 /* error in conversion. */
629                 ret = false;
630                 goto out;
631         }
632
633         if (already_converted) {
634                 if (_already_converted != NULL) {
635                         *_already_converted = true;
636                 }
637                 goto out;
638         }
639
640         if (smb_fname->twrp == 0) {
641                 goto out;
642         }
643
644         if (ptimestamp != NULL) {
645                 *ptimestamp = nt_time_to_unix(smb_fname->twrp);
646         }
647
648         if (pstripped != NULL) {
649                 stripped = talloc_strdup(mem_ctx, abs_path);
650                 if (stripped == NULL) {
651                         ret = false;
652                         goto out;
653                 }
654
655                 if (smb_fname->base_name[0] != '/') {
656                         ret = make_relative_path(priv->shadow_cwd, stripped);
657                         if (!ret) {
658                                 DBG_DEBUG("Path '%s' "
659                                         "doesn't start with cwd '%s'\n",
660                                         stripped, priv->shadow_cwd);
661                                 ret = false;
662                                 errno = ENOENT;
663                                 goto out;
664                         }
665                 }
666                 *pstripped = stripped;
667         }
668
669         ret = true;
670
671   out:
672         TALLOC_FREE(abs_path);
673         return ret;
674 }
675
676 #define shadow_copy2_strip_snapshot_internal(mem_ctx, handle, orig_name, \
677                 ptimestamp, pstripped, psnappath, _already_converted) \
678         _shadow_copy2_strip_snapshot_internal((mem_ctx), (handle), (orig_name), \
679                 (ptimestamp), (pstripped), (psnappath), (_already_converted), \
680                                               __FUNCTION__)
681
682 static bool _shadow_copy2_strip_snapshot(TALLOC_CTX *mem_ctx,
683                                          struct vfs_handle_struct *handle,
684                                          const struct smb_filename *orig_name,
685                                          time_t *ptimestamp,
686                                          char **pstripped,
687                                          const char *function)
688 {
689         return _shadow_copy2_strip_snapshot_internal(mem_ctx,
690                                         handle,
691                                         orig_name,
692                                         ptimestamp,
693                                         pstripped,
694                                         NULL,
695                                         NULL,
696                                         function);
697 }
698
699 #define shadow_copy2_strip_snapshot(mem_ctx, handle, orig_name, \
700                 ptimestamp, pstripped) \
701         _shadow_copy2_strip_snapshot((mem_ctx), (handle), (orig_name), \
702                 (ptimestamp), (pstripped), __FUNCTION__)
703
704 static bool _shadow_copy2_strip_snapshot_converted(TALLOC_CTX *mem_ctx,
705                                         struct vfs_handle_struct *handle,
706                                         const struct smb_filename *orig_name,
707                                         time_t *ptimestamp,
708                                         char **pstripped,
709                                         bool *is_converted,
710                                         const char *function)
711 {
712         return _shadow_copy2_strip_snapshot_internal(mem_ctx,
713                                         handle,
714                                         orig_name,
715                                         ptimestamp,
716                                         pstripped,
717                                         NULL,
718                                         is_converted,
719                                         function);
720 }
721
722 #define shadow_copy2_strip_snapshot_converted(mem_ctx, handle, orig_name, \
723                 ptimestamp, pstripped, is_converted) \
724         _shadow_copy2_strip_snapshot_converted((mem_ctx), (handle), (orig_name), \
725                 (ptimestamp), (pstripped), (is_converted), __FUNCTION__)
726
727 static char *shadow_copy2_find_mount_point(TALLOC_CTX *mem_ctx,
728                                            vfs_handle_struct *handle)
729 {
730         char *path = talloc_strdup(mem_ctx, handle->conn->connectpath);
731         dev_t dev;
732         struct stat st;
733         char *p;
734
735         if (stat(path, &st) != 0) {
736                 talloc_free(path);
737                 return NULL;
738         }
739
740         dev = st.st_dev;
741
742         while ((p = strrchr(path, '/')) && p > path) {
743                 *p = 0;
744                 if (stat(path, &st) != 0) {
745                         talloc_free(path);
746                         return NULL;
747                 }
748                 if (st.st_dev != dev) {
749                         *p = '/';
750                         break;
751                 }
752         }
753
754         return path;
755 }
756
757 /**
758  * Convert from a name as handed in via the SMB layer
759  * and a timestamp into the local path of the snapshot
760  * of the provided file at the provided time.
761  * Also return the path in the snapshot corresponding
762  * to the file's share root.
763  */
764 static char *shadow_copy2_do_convert(TALLOC_CTX *mem_ctx,
765                                      struct vfs_handle_struct *handle,
766                                      const char *name, time_t timestamp,
767                                      size_t *snaproot_len)
768 {
769         struct smb_filename converted_fname;
770         char *result = NULL;
771         size_t *slashes = NULL;
772         unsigned num_slashes;
773         char *path = NULL;
774         size_t pathlen;
775         char *insert = NULL;
776         char *converted = NULL;
777         size_t insertlen, connectlen = 0;
778         int saved_errno = 0;
779         int i;
780         size_t min_offset;
781         struct shadow_copy2_config *config;
782         struct shadow_copy2_private *priv;
783         size_t in_share_offset = 0;
784
785         SMB_VFS_HANDLE_GET_DATA(handle, priv, struct shadow_copy2_private,
786                                 return NULL);
787
788         config = priv->config;
789
790         DEBUG(10, ("converting '%s'\n", name));
791
792         if (!config->snapdirseverywhere) {
793                 int ret;
794                 char *snapshot_path;
795
796                 snapshot_path = shadow_copy2_snapshot_path(talloc_tos(),
797                                                            handle,
798                                                            timestamp);
799                 if (snapshot_path == NULL) {
800                         goto fail;
801                 }
802
803                 if (config->rel_connectpath == NULL) {
804                         converted = talloc_asprintf(mem_ctx, "%s/%s",
805                                                     snapshot_path, name);
806                 } else {
807                         converted = talloc_asprintf(mem_ctx, "%s/%s/%s",
808                                                     snapshot_path,
809                                                     config->rel_connectpath,
810                                                     name);
811                 }
812                 if (converted == NULL) {
813                         goto fail;
814                 }
815
816                 ZERO_STRUCT(converted_fname);
817                 converted_fname.base_name = converted;
818
819                 ret = SMB_VFS_NEXT_LSTAT(handle, &converted_fname);
820                 DEBUG(10, ("Trying[not snapdirseverywhere] %s: %d (%s)\n",
821                            converted,
822                            ret, ret == 0 ? "ok" : strerror(errno)));
823                 if (ret == 0) {
824                         DEBUG(10, ("Found %s\n", converted));
825                         result = converted;
826                         converted = NULL;
827                         if (snaproot_len != NULL) {
828                                 *snaproot_len = strlen(snapshot_path);
829                                 if (config->rel_connectpath != NULL) {
830                                         *snaproot_len +=
831                                             strlen(config->rel_connectpath) + 1;
832                                 }
833                         }
834                         goto fail;
835                 } else {
836                         errno = ENOENT;
837                         goto fail;
838                 }
839                 /* never reached ... */
840         }
841
842         connectlen = strlen(handle->conn->connectpath);
843         if (name[0] == 0) {
844                 path = talloc_strdup(mem_ctx, handle->conn->connectpath);
845         } else {
846                 path = talloc_asprintf(
847                         mem_ctx, "%s/%s", handle->conn->connectpath, name);
848         }
849         if (path == NULL) {
850                 errno = ENOMEM;
851                 goto fail;
852         }
853         pathlen = talloc_get_size(path)-1;
854
855         if (!shadow_copy2_find_slashes(talloc_tos(), path,
856                                        &slashes, &num_slashes)) {
857                 goto fail;
858         }
859
860         insert = shadow_copy2_insert_string(talloc_tos(), handle, timestamp);
861         if (insert == NULL) {
862                 goto fail;
863         }
864         insertlen = talloc_get_size(insert)-1;
865
866         /*
867          * Note: We deliberatly don't expensively initialize the
868          * array with talloc_zero here: Putting zero into
869          * converted[pathlen+insertlen] below is sufficient, because
870          * in the following for loop, the insert string is inserted
871          * at various slash places. So the memory up to position
872          * pathlen+insertlen will always be initialized when the
873          * converted string is used.
874          */
875         converted = talloc_array(mem_ctx, char, pathlen + insertlen + 1);
876         if (converted == NULL) {
877                 goto fail;
878         }
879
880         if (path[pathlen-1] != '/') {
881                 /*
882                  * Append a fake slash to find the snapshot root
883                  */
884                 size_t *tmp;
885                 tmp = talloc_realloc(talloc_tos(), slashes,
886                                      size_t, num_slashes+1);
887                 if (tmp == NULL) {
888                         goto fail;
889                 }
890                 slashes = tmp;
891                 slashes[num_slashes] = pathlen;
892                 num_slashes += 1;
893         }
894
895         min_offset = 0;
896
897         if (!config->crossmountpoints) {
898                 min_offset = strlen(config->mount_point);
899         }
900
901         memcpy(converted, path, pathlen+1);
902         converted[pathlen+insertlen] = '\0';
903
904         ZERO_STRUCT(converted_fname);
905         converted_fname.base_name = converted;
906
907         for (i = num_slashes-1; i>=0; i--) {
908                 int ret;
909                 size_t offset;
910
911                 offset = slashes[i];
912
913                 if (offset < min_offset) {
914                         errno = ENOENT;
915                         goto fail;
916                 }
917
918                 if (offset >= connectlen) {
919                         in_share_offset = offset;
920                 }
921
922                 memcpy(converted+offset, insert, insertlen);
923
924                 offset += insertlen;
925                 memcpy(converted+offset, path + slashes[i],
926                        pathlen - slashes[i]);
927
928                 ret = SMB_VFS_NEXT_LSTAT(handle, &converted_fname);
929
930                 DEBUG(10, ("Trying[snapdirseverywhere] %s: %d (%s)\n",
931                            converted,
932                            ret, ret == 0 ? "ok" : strerror(errno)));
933                 if (ret == 0) {
934                         /* success */
935                         if (snaproot_len != NULL) {
936                                 *snaproot_len = in_share_offset + insertlen;
937                         }
938                         break;
939                 }
940                 if (errno == ENOTDIR) {
941                         /*
942                          * This is a valid condition: We appended the
943                          * .snapshots/@GMT.. to a file name. Just try
944                          * with the upper levels.
945                          */
946                         continue;
947                 }
948                 if (errno != ENOENT) {
949                         /* Other problem than "not found" */
950                         goto fail;
951                 }
952         }
953
954         if (i >= 0) {
955                 /*
956                  * Found something
957                  */
958                 DEBUG(10, ("Found %s\n", converted));
959                 result = converted;
960                 converted = NULL;
961         } else {
962                 errno = ENOENT;
963         }
964 fail:
965         if (result == NULL) {
966                 saved_errno = errno;
967         }
968         TALLOC_FREE(converted);
969         TALLOC_FREE(insert);
970         TALLOC_FREE(slashes);
971         TALLOC_FREE(path);
972         if (saved_errno != 0) {
973                 errno = saved_errno;
974         }
975         return result;
976 }
977
978 /**
979  * Convert from a name as handed in via the SMB layer
980  * and a timestamp into the local path of the snapshot
981  * of the provided file at the provided time.
982  */
983 static char *shadow_copy2_convert(TALLOC_CTX *mem_ctx,
984                                   struct vfs_handle_struct *handle,
985                                   const char *name, time_t timestamp)
986 {
987         return shadow_copy2_do_convert(mem_ctx, handle, name, timestamp, NULL);
988 }
989
990 /*
991   modify a sbuf return to ensure that inodes in the shadow directory
992   are different from those in the main directory
993  */
994 static void convert_sbuf(vfs_handle_struct *handle, const char *fname,
995                          SMB_STRUCT_STAT *sbuf)
996 {
997         struct shadow_copy2_private *priv;
998
999         SMB_VFS_HANDLE_GET_DATA(handle, priv, struct shadow_copy2_private,
1000                                 return);
1001
1002         if (priv->config->fixinodes) {
1003                 /* some snapshot systems, like GPFS, return the name
1004                    device:inode for the snapshot files as the current
1005                    files. That breaks the 'restore' button in the shadow copy
1006                    GUI, as the client gets a sharing violation.
1007
1008                    This is a crude way of allowing both files to be
1009                    open at once. It has a slight chance of inode
1010                    number collision, but I can't see a better approach
1011                    without significant VFS changes
1012                 */
1013                 TDB_DATA key = { .dptr = discard_const_p(uint8_t, fname),
1014                                  .dsize = strlen(fname) };
1015                 uint32_t shash;
1016
1017                 shash = tdb_jenkins_hash(&key) & 0xFF000000;
1018                 if (shash == 0) {
1019                         shash = 1;
1020                 }
1021                 sbuf->st_ex_ino ^= shash;
1022         }
1023 }
1024
1025 static int shadow_copy2_renameat(vfs_handle_struct *handle,
1026                                 files_struct *srcfsp,
1027                                 const struct smb_filename *smb_fname_src,
1028                                 files_struct *dstfsp,
1029                                 const struct smb_filename *smb_fname_dst)
1030 {
1031         time_t timestamp_src = 0;
1032         time_t timestamp_dst = 0;
1033         char *snappath_src = NULL;
1034         char *snappath_dst = NULL;
1035
1036         if (!shadow_copy2_strip_snapshot_internal(talloc_tos(), handle,
1037                                          smb_fname_src,
1038                                          &timestamp_src, NULL, &snappath_src,
1039                                          NULL)) {
1040                 return -1;
1041         }
1042         if (!shadow_copy2_strip_snapshot_internal(talloc_tos(), handle,
1043                                          smb_fname_dst,
1044                                          &timestamp_dst, NULL, &snappath_dst,
1045                                          NULL)) {
1046                 return -1;
1047         }
1048         if (timestamp_src != 0) {
1049                 errno = EXDEV;
1050                 return -1;
1051         }
1052         if (timestamp_dst != 0) {
1053                 errno = EROFS;
1054                 return -1;
1055         }
1056         /*
1057          * Don't allow rename on already converted paths.
1058          */
1059         if (snappath_src != NULL) {
1060                 errno = EXDEV;
1061                 return -1;
1062         }
1063         if (snappath_dst != NULL) {
1064                 errno = EROFS;
1065                 return -1;
1066         }
1067         return SMB_VFS_NEXT_RENAMEAT(handle,
1068                         srcfsp,
1069                         smb_fname_src,
1070                         dstfsp,
1071                         smb_fname_dst);
1072 }
1073
1074 static int shadow_copy2_symlinkat(vfs_handle_struct *handle,
1075                         const struct smb_filename *link_contents,
1076                         struct files_struct *dirfsp,
1077                         const struct smb_filename *new_smb_fname)
1078 {
1079         time_t timestamp_old = 0;
1080         time_t timestamp_new = 0;
1081         char *snappath_old = NULL;
1082         char *snappath_new = NULL;
1083
1084         if (!shadow_copy2_strip_snapshot_internal(talloc_tos(),
1085                                 handle,
1086                                 link_contents,
1087                                 &timestamp_old,
1088                                 NULL,
1089                                 &snappath_old,
1090                                 NULL)) {
1091                 return -1;
1092         }
1093         if (!shadow_copy2_strip_snapshot_internal(talloc_tos(),
1094                                 handle,
1095                                 new_smb_fname,
1096                                 &timestamp_new,
1097                                 NULL,
1098                                 &snappath_new,
1099                                 NULL)) {
1100                 return -1;
1101         }
1102         if ((timestamp_old != 0) || (timestamp_new != 0)) {
1103                 errno = EROFS;
1104                 return -1;
1105         }
1106         /*
1107          * Don't allow symlinks on already converted paths.
1108          */
1109         if ((snappath_old != NULL) || (snappath_new != NULL)) {
1110                 errno = EROFS;
1111                 return -1;
1112         }
1113         return SMB_VFS_NEXT_SYMLINKAT(handle,
1114                                 link_contents,
1115                                 dirfsp,
1116                                 new_smb_fname);
1117 }
1118
1119 static int shadow_copy2_linkat(vfs_handle_struct *handle,
1120                         files_struct *srcfsp,
1121                         const struct smb_filename *old_smb_fname,
1122                         files_struct *dstfsp,
1123                         const struct smb_filename *new_smb_fname,
1124                         int flags)
1125 {
1126         time_t timestamp_old = 0;
1127         time_t timestamp_new = 0;
1128         char *snappath_old = NULL;
1129         char *snappath_new = NULL;
1130
1131         if (!shadow_copy2_strip_snapshot_internal(talloc_tos(),
1132                                 handle,
1133                                 old_smb_fname,
1134                                 &timestamp_old,
1135                                 NULL,
1136                                 &snappath_old,
1137                                 NULL)) {
1138                 return -1;
1139         }
1140         if (!shadow_copy2_strip_snapshot_internal(talloc_tos(),
1141                                 handle,
1142                                 new_smb_fname,
1143                                 &timestamp_new,
1144                                 NULL,
1145                                 &snappath_new,
1146                                 NULL)) {
1147                 return -1;
1148         }
1149         if ((timestamp_old != 0) || (timestamp_new != 0)) {
1150                 errno = EROFS;
1151                 return -1;
1152         }
1153         /*
1154          * Don't allow links on already converted paths.
1155          */
1156         if ((snappath_old != NULL) || (snappath_new != NULL)) {
1157                 errno = EROFS;
1158                 return -1;
1159         }
1160         return SMB_VFS_NEXT_LINKAT(handle,
1161                         srcfsp,
1162                         old_smb_fname,
1163                         dstfsp,
1164                         new_smb_fname,
1165                         flags);
1166 }
1167
1168 static int shadow_copy2_stat(vfs_handle_struct *handle,
1169                              struct smb_filename *smb_fname)
1170 {
1171         time_t timestamp = 0;
1172         char *stripped = NULL;
1173         char *tmp;
1174         int saved_errno = 0;
1175         int ret;
1176
1177         if (!shadow_copy2_strip_snapshot(talloc_tos(), handle,
1178                                          smb_fname,
1179                                          &timestamp, &stripped)) {
1180                 return -1;
1181         }
1182         if (timestamp == 0) {
1183                 return SMB_VFS_NEXT_STAT(handle, smb_fname);
1184         }
1185
1186         tmp = smb_fname->base_name;
1187         smb_fname->base_name = shadow_copy2_convert(
1188                 talloc_tos(), handle, stripped, timestamp);
1189         TALLOC_FREE(stripped);
1190
1191         if (smb_fname->base_name == NULL) {
1192                 smb_fname->base_name = tmp;
1193                 return -1;
1194         }
1195
1196         ret = SMB_VFS_NEXT_STAT(handle, smb_fname);
1197         if (ret == -1) {
1198                 saved_errno = errno;
1199         }
1200
1201         TALLOC_FREE(smb_fname->base_name);
1202         smb_fname->base_name = tmp;
1203
1204         if (ret == 0) {
1205                 convert_sbuf(handle, smb_fname->base_name, &smb_fname->st);
1206         }
1207         if (saved_errno != 0) {
1208                 errno = saved_errno;
1209         }
1210         return ret;
1211 }
1212
1213 static int shadow_copy2_lstat(vfs_handle_struct *handle,
1214                               struct smb_filename *smb_fname)
1215 {
1216         time_t timestamp = 0;
1217         char *stripped = NULL;
1218         char *tmp;
1219         int saved_errno = 0;
1220         int ret;
1221
1222         if (!shadow_copy2_strip_snapshot(talloc_tos(), handle,
1223                                          smb_fname,
1224                                          &timestamp, &stripped)) {
1225                 return -1;
1226         }
1227         if (timestamp == 0) {
1228                 return SMB_VFS_NEXT_LSTAT(handle, smb_fname);
1229         }
1230
1231         tmp = smb_fname->base_name;
1232         smb_fname->base_name = shadow_copy2_convert(
1233                 talloc_tos(), handle, stripped, timestamp);
1234         TALLOC_FREE(stripped);
1235
1236         if (smb_fname->base_name == NULL) {
1237                 smb_fname->base_name = tmp;
1238                 return -1;
1239         }
1240
1241         ret = SMB_VFS_NEXT_LSTAT(handle, smb_fname);
1242         if (ret == -1) {
1243                 saved_errno = errno;
1244         }
1245
1246         TALLOC_FREE(smb_fname->base_name);
1247         smb_fname->base_name = tmp;
1248
1249         if (ret == 0) {
1250                 convert_sbuf(handle, smb_fname->base_name, &smb_fname->st);
1251         }
1252         if (saved_errno != 0) {
1253                 errno = saved_errno;
1254         }
1255         return ret;
1256 }
1257
1258 static int shadow_copy2_fstat(vfs_handle_struct *handle, files_struct *fsp,
1259                               SMB_STRUCT_STAT *sbuf)
1260 {
1261         time_t timestamp = 0;
1262         struct smb_filename *orig_smb_fname = NULL;
1263         struct smb_filename vss_smb_fname;
1264         struct smb_filename *orig_base_smb_fname = NULL;
1265         struct smb_filename vss_base_smb_fname;
1266         char *stripped = NULL;
1267         int saved_errno = 0;
1268         bool ok;
1269         int ret;
1270
1271         ok = shadow_copy2_strip_snapshot(talloc_tos(), handle,
1272                                          fsp->fsp_name,
1273                                          &timestamp, &stripped);
1274         if (!ok) {
1275                 return -1;
1276         }
1277
1278         if (timestamp == 0) {
1279                 TALLOC_FREE(stripped);
1280                 return SMB_VFS_NEXT_FSTAT(handle, fsp, sbuf);
1281         }
1282
1283         vss_smb_fname = *fsp->fsp_name;
1284         vss_smb_fname.base_name = shadow_copy2_convert(talloc_tos(),
1285                                                        handle,
1286                                                        stripped,
1287                                                        timestamp);
1288         TALLOC_FREE(stripped);
1289         if (vss_smb_fname.base_name == NULL) {
1290                 return -1;
1291         }
1292
1293         orig_smb_fname = fsp->fsp_name;
1294         fsp->fsp_name = &vss_smb_fname;
1295
1296         if (fsp->base_fsp != NULL) {
1297                 vss_base_smb_fname = *fsp->base_fsp->fsp_name;
1298                 vss_base_smb_fname.base_name = vss_smb_fname.base_name;
1299                 orig_base_smb_fname = fsp->base_fsp->fsp_name;
1300                 fsp->base_fsp->fsp_name = &vss_base_smb_fname;
1301         }
1302
1303         ret = SMB_VFS_NEXT_FSTAT(handle, fsp, sbuf);
1304         fsp->fsp_name = orig_smb_fname;
1305         if (fsp->base_fsp != NULL) {
1306                 fsp->base_fsp->fsp_name = orig_base_smb_fname;
1307         }
1308         if (ret == -1) {
1309                 saved_errno = errno;
1310         }
1311
1312         if (ret == 0) {
1313                 convert_sbuf(handle, fsp->fsp_name->base_name, sbuf);
1314         }
1315         if (saved_errno != 0) {
1316                 errno = saved_errno;
1317         }
1318         return ret;
1319 }
1320
1321 static int shadow_copy2_openat(vfs_handle_struct *handle,
1322                                const struct files_struct *dirfsp,
1323                                const struct smb_filename *smb_fname_in,
1324                                struct files_struct *fsp,
1325                                int flags,
1326                                mode_t mode)
1327 {
1328         struct smb_filename *smb_fname = NULL;
1329         time_t timestamp = 0;
1330         char *stripped = NULL;
1331         bool is_converted = false;
1332         int saved_errno = 0;
1333         int ret;
1334         bool ok;
1335
1336         ok = shadow_copy2_strip_snapshot_converted(talloc_tos(),
1337                                                    handle,
1338                                                    smb_fname_in,
1339                                                    &timestamp,
1340                                                    &stripped,
1341                                                    &is_converted);
1342         if (!ok) {
1343                 return -1;
1344         }
1345         if (timestamp == 0) {
1346                 if (is_converted) {
1347                         /*
1348                          * Just pave over the user requested mode and use
1349                          * O_RDONLY. Later attempts by the client to write on
1350                          * the handle will fail in the pwrite() syscall with
1351                          * EINVAL which we carefully map to EROFS. In sum, this
1352                          * matches Windows behaviour.
1353                          */
1354                         flags = O_RDONLY;
1355                 }
1356                 return SMB_VFS_NEXT_OPENAT(handle,
1357                                            dirfsp,
1358                                            smb_fname_in,
1359                                            fsp,
1360                                            flags,
1361                                            mode);
1362         }
1363
1364         smb_fname = cp_smb_filename(talloc_tos(), smb_fname_in);
1365         if (smb_fname == NULL) {
1366                 TALLOC_FREE(stripped);
1367                 errno = ENOMEM;
1368                 return -1;
1369         }
1370
1371         smb_fname->base_name = shadow_copy2_convert(smb_fname,
1372                                                handle,
1373                                                stripped,
1374                                                timestamp);
1375         TALLOC_FREE(stripped);
1376         if (smb_fname->base_name == NULL) {
1377                 TALLOC_FREE(smb_fname);
1378                 errno = ENOMEM;
1379                 return -1;
1380         }
1381
1382         /*
1383          * Just pave over the user requested mode and use O_RDONLY. Later
1384          * attempts by the client to write on the handle will fail in the
1385          * pwrite() syscall with EINVAL which we carefully map to EROFS. In sum,
1386          * this matches Windows behaviour.
1387          */
1388         flags = O_RDONLY;
1389
1390         ret = SMB_VFS_NEXT_OPENAT(handle,
1391                                   dirfsp,
1392                                   smb_fname,
1393                                   fsp,
1394                                   flags,
1395                                   mode);
1396         if (ret == -1) {
1397                 saved_errno = errno;
1398         }
1399
1400         TALLOC_FREE(smb_fname);
1401
1402         if (saved_errno != 0) {
1403                 errno = saved_errno;
1404         }
1405         return ret;
1406 }
1407
1408 static int shadow_copy2_unlinkat(vfs_handle_struct *handle,
1409                         struct files_struct *dirfsp,
1410                         const struct smb_filename *smb_fname,
1411                         int flags)
1412 {
1413         time_t timestamp = 0;
1414
1415         if (!shadow_copy2_strip_snapshot(talloc_tos(), handle,
1416                                          smb_fname,
1417                                          &timestamp, NULL)) {
1418                 return -1;
1419         }
1420         if (timestamp != 0) {
1421                 errno = EROFS;
1422                 return -1;
1423         }
1424         return SMB_VFS_NEXT_UNLINKAT(handle,
1425                         dirfsp,
1426                         smb_fname,
1427                         flags);
1428 }
1429
1430 static int shadow_copy2_chmod(vfs_handle_struct *handle,
1431                         const struct smb_filename *smb_fname,
1432                         mode_t mode)
1433 {
1434         time_t timestamp = 0;
1435
1436         if (!shadow_copy2_strip_snapshot(talloc_tos(),
1437                                 handle,
1438                                 smb_fname,
1439                                 &timestamp,
1440                                 NULL)) {
1441                 return -1;
1442         }
1443         if (timestamp != 0) {
1444                 errno = EROFS;
1445                 return -1;
1446         }
1447         return SMB_VFS_NEXT_CHMOD(handle, smb_fname, mode);
1448 }
1449
1450 static void store_cwd_data(vfs_handle_struct *handle,
1451                                 const char *connectpath)
1452 {
1453         struct shadow_copy2_private *priv = NULL;
1454         struct smb_filename *cwd_fname = NULL;
1455
1456         SMB_VFS_HANDLE_GET_DATA(handle, priv, struct shadow_copy2_private,
1457                                 return);
1458
1459         TALLOC_FREE(priv->shadow_cwd);
1460         cwd_fname = SMB_VFS_NEXT_GETWD(handle, talloc_tos());
1461         if (cwd_fname == NULL) {
1462                 smb_panic("getwd failed\n");
1463         }
1464         DBG_DEBUG("shadow cwd = %s\n", cwd_fname->base_name);
1465         priv->shadow_cwd = talloc_strdup(priv, cwd_fname->base_name);
1466         TALLOC_FREE(cwd_fname);
1467         if (priv->shadow_cwd == NULL) {
1468                 smb_panic("talloc failed\n");
1469         }
1470         TALLOC_FREE(priv->shadow_connectpath);
1471         if (connectpath) {
1472                 DBG_DEBUG("shadow connectpath = %s\n", connectpath);
1473                 priv->shadow_connectpath = talloc_strdup(priv, connectpath);
1474                 if (priv->shadow_connectpath == NULL) {
1475                         smb_panic("talloc failed\n");
1476                 }
1477         }
1478 }
1479
1480 static int shadow_copy2_chdir(vfs_handle_struct *handle,
1481                                const struct smb_filename *smb_fname)
1482 {
1483         time_t timestamp = 0;
1484         char *stripped = NULL;
1485         char *snappath = NULL;
1486         int ret = -1;
1487         int saved_errno = 0;
1488         char *conv = NULL;
1489         size_t rootpath_len = 0;
1490         struct smb_filename *conv_smb_fname = NULL;
1491
1492         if (!shadow_copy2_strip_snapshot_internal(talloc_tos(),
1493                                         handle,
1494                                         smb_fname,
1495                                         &timestamp,
1496                                         &stripped,
1497                                         &snappath,
1498                                         NULL)) {
1499                 return -1;
1500         }
1501         if (stripped != NULL) {
1502                 conv = shadow_copy2_do_convert(talloc_tos(),
1503                                                 handle,
1504                                                 stripped,
1505                                                 timestamp,
1506                                                 &rootpath_len);
1507                 TALLOC_FREE(stripped);
1508                 if (conv == NULL) {
1509                         return -1;
1510                 }
1511                 conv_smb_fname = synthetic_smb_fname(talloc_tos(),
1512                                         conv,
1513                                         NULL,
1514                                         NULL,
1515                                         0,
1516                                         smb_fname->flags);
1517         } else {
1518                 conv_smb_fname = cp_smb_filename(talloc_tos(), smb_fname);
1519         }
1520
1521         if (conv_smb_fname == NULL) {
1522                 TALLOC_FREE(conv);
1523                 errno = ENOMEM;
1524                 return -1;
1525         }
1526
1527         ret = SMB_VFS_NEXT_CHDIR(handle, conv_smb_fname);
1528         if (ret == -1) {
1529                 saved_errno = errno;
1530         }
1531
1532         if (ret == 0) {
1533                 if (conv != NULL && rootpath_len != 0) {
1534                         conv[rootpath_len] = '\0';
1535                 } else if (snappath != 0) {
1536                         TALLOC_FREE(conv);
1537                         conv = snappath;
1538                 }
1539                 store_cwd_data(handle, conv);
1540         }
1541
1542         TALLOC_FREE(stripped);
1543         TALLOC_FREE(conv);
1544         TALLOC_FREE(conv_smb_fname);
1545
1546         if (saved_errno != 0) {
1547                 errno = saved_errno;
1548         }
1549         return ret;
1550 }
1551
1552 static int shadow_copy2_ntimes(vfs_handle_struct *handle,
1553                                const struct smb_filename *smb_fname,
1554                                struct smb_file_time *ft)
1555 {
1556         time_t timestamp = 0;
1557
1558         if (!shadow_copy2_strip_snapshot(talloc_tos(), handle,
1559                                          smb_fname,
1560                                          &timestamp, NULL)) {
1561                 return -1;
1562         }
1563         if (timestamp != 0) {
1564                 errno = EROFS;
1565                 return -1;
1566         }
1567         return SMB_VFS_NEXT_NTIMES(handle, smb_fname, ft);
1568 }
1569
1570 static int shadow_copy2_readlinkat(vfs_handle_struct *handle,
1571                                 files_struct *dirfsp,
1572                                 const struct smb_filename *smb_fname,
1573                                 char *buf,
1574                                 size_t bufsiz)
1575 {
1576         time_t timestamp = 0;
1577         char *stripped = NULL;
1578         int saved_errno = 0;
1579         int ret;
1580         struct smb_filename *conv = NULL;
1581
1582         if (!shadow_copy2_strip_snapshot(talloc_tos(), handle,
1583                                          smb_fname,
1584                                          &timestamp, &stripped)) {
1585                 return -1;
1586         }
1587         if (timestamp == 0) {
1588                 return SMB_VFS_NEXT_READLINKAT(handle,
1589                                 dirfsp,
1590                                 smb_fname,
1591                                 buf,
1592                                 bufsiz);
1593         }
1594         conv = cp_smb_filename(talloc_tos(), smb_fname);
1595         if (conv == NULL) {
1596                 TALLOC_FREE(stripped);
1597                 errno = ENOMEM;
1598                 return -1;
1599         }
1600         conv->base_name = shadow_copy2_convert(
1601                 conv, handle, stripped, timestamp);
1602         TALLOC_FREE(stripped);
1603         if (conv->base_name == NULL) {
1604                 return -1;
1605         }
1606         ret = SMB_VFS_NEXT_READLINKAT(handle,
1607                                 dirfsp,
1608                                 conv,
1609                                 buf,
1610                                 bufsiz);
1611         if (ret == -1) {
1612                 saved_errno = errno;
1613         }
1614         TALLOC_FREE(conv);
1615         if (saved_errno != 0) {
1616                 errno = saved_errno;
1617         }
1618         return ret;
1619 }
1620
1621 static int shadow_copy2_mknodat(vfs_handle_struct *handle,
1622                         files_struct *dirfsp,
1623                         const struct smb_filename *smb_fname,
1624                         mode_t mode,
1625                         SMB_DEV_T dev)
1626 {
1627         time_t timestamp = 0;
1628
1629         if (!shadow_copy2_strip_snapshot(talloc_tos(), handle,
1630                                          smb_fname,
1631                                          &timestamp, NULL)) {
1632                 return -1;
1633         }
1634         if (timestamp != 0) {
1635                 errno = EROFS;
1636                 return -1;
1637         }
1638         return SMB_VFS_NEXT_MKNODAT(handle,
1639                         dirfsp,
1640                         smb_fname,
1641                         mode,
1642                         dev);
1643 }
1644
1645 static struct smb_filename *shadow_copy2_realpath(vfs_handle_struct *handle,
1646                                 TALLOC_CTX *ctx,
1647                                 const struct smb_filename *smb_fname)
1648 {
1649         time_t timestamp = 0;
1650         char *stripped = NULL;
1651         struct smb_filename *result_fname = NULL;
1652         struct smb_filename *conv_fname = NULL;
1653         int saved_errno = 0;
1654
1655         if (!shadow_copy2_strip_snapshot(talloc_tos(), handle,
1656                                 smb_fname,
1657                                 &timestamp, &stripped)) {
1658                 goto done;
1659         }
1660         if (timestamp == 0) {
1661                 return SMB_VFS_NEXT_REALPATH(handle, ctx, smb_fname);
1662         }
1663
1664         conv_fname = cp_smb_filename(talloc_tos(), smb_fname);
1665         if (conv_fname == NULL) {
1666                 goto done;
1667         }
1668         conv_fname->base_name = shadow_copy2_convert(
1669                 conv_fname, handle, stripped, timestamp);
1670         if (conv_fname->base_name == NULL) {
1671                 goto done;
1672         }
1673
1674         result_fname = SMB_VFS_NEXT_REALPATH(handle, ctx, conv_fname);
1675
1676 done:
1677         if (result_fname == NULL) {
1678                 saved_errno = errno;
1679         }
1680         TALLOC_FREE(conv_fname);
1681         TALLOC_FREE(stripped);
1682         if (saved_errno != 0) {
1683                 errno = saved_errno;
1684         }
1685         return result_fname;
1686 }
1687
1688 /**
1689  * Check whether a given directory contains a
1690  * snapshot directory as direct subdirectory.
1691  * If yes, return the path of the snapshot-subdir,
1692  * otherwise return NULL.
1693  */
1694 static char *have_snapdir(struct vfs_handle_struct *handle,
1695                           const char *path)
1696 {
1697         struct smb_filename smb_fname;
1698         int ret;
1699         struct shadow_copy2_private *priv;
1700
1701         SMB_VFS_HANDLE_GET_DATA(handle, priv, struct shadow_copy2_private,
1702                                 return NULL);
1703
1704         ZERO_STRUCT(smb_fname);
1705         smb_fname.base_name = talloc_asprintf(talloc_tos(), "%s/%s",
1706                                               path, priv->config->snapdir);
1707         if (smb_fname.base_name == NULL) {
1708                 return NULL;
1709         }
1710
1711         ret = SMB_VFS_NEXT_STAT(handle, &smb_fname);
1712         if ((ret == 0) && (S_ISDIR(smb_fname.st.st_ex_mode))) {
1713                 return smb_fname.base_name;
1714         }
1715         TALLOC_FREE(smb_fname.base_name);
1716         return NULL;
1717 }
1718
1719 static bool check_access_snapdir(struct vfs_handle_struct *handle,
1720                                 const char *path)
1721 {
1722         struct smb_filename smb_fname;
1723         int ret;
1724         NTSTATUS status;
1725
1726         ZERO_STRUCT(smb_fname);
1727         smb_fname.base_name = talloc_asprintf(talloc_tos(),
1728                                                 "%s",
1729                                                 path);
1730         if (smb_fname.base_name == NULL) {
1731                 return false;
1732         }
1733
1734         ret = SMB_VFS_NEXT_STAT(handle, &smb_fname);
1735         if (ret != 0 || !S_ISDIR(smb_fname.st.st_ex_mode)) {
1736                 TALLOC_FREE(smb_fname.base_name);
1737                 return false;
1738         }
1739
1740         status = smbd_check_access_rights(handle->conn,
1741                                         handle->conn->cwd_fsp,
1742                                         &smb_fname,
1743                                         false,
1744                                         SEC_DIR_LIST);
1745         if (!NT_STATUS_IS_OK(status)) {
1746                 DEBUG(0,("user does not have list permission "
1747                         "on snapdir %s\n",
1748                         smb_fname.base_name));
1749                 TALLOC_FREE(smb_fname.base_name);
1750                 return false;
1751         }
1752         TALLOC_FREE(smb_fname.base_name);
1753         return true;
1754 }
1755
1756 /**
1757  * Find the snapshot directory (if any) for the given
1758  * filename (which is relative to the share).
1759  */
1760 static const char *shadow_copy2_find_snapdir(TALLOC_CTX *mem_ctx,
1761                                              struct vfs_handle_struct *handle,
1762                                              struct smb_filename *smb_fname)
1763 {
1764         char *path, *p;
1765         const char *snapdir;
1766         struct shadow_copy2_config *config;
1767         struct shadow_copy2_private *priv;
1768
1769         SMB_VFS_HANDLE_GET_DATA(handle, priv, struct shadow_copy2_private,
1770                                 return NULL);
1771
1772         config = priv->config;
1773
1774         /*
1775          * If the non-snapdisrseverywhere mode, we should not search!
1776          */
1777         if (!config->snapdirseverywhere) {
1778                 return config->snapshot_basepath;
1779         }
1780
1781         path = talloc_asprintf(mem_ctx, "%s/%s",
1782                                handle->conn->connectpath,
1783                                smb_fname->base_name);
1784         if (path == NULL) {
1785                 return NULL;
1786         }
1787
1788         snapdir = have_snapdir(handle, path);
1789         if (snapdir != NULL) {
1790                 TALLOC_FREE(path);
1791                 return snapdir;
1792         }
1793
1794         while ((p = strrchr(path, '/')) && (p > path)) {
1795
1796                 p[0] = '\0';
1797
1798                 snapdir = have_snapdir(handle, path);
1799                 if (snapdir != NULL) {
1800                         TALLOC_FREE(path);
1801                         return snapdir;
1802                 }
1803         }
1804         TALLOC_FREE(path);
1805         return NULL;
1806 }
1807
1808 static bool shadow_copy2_snapshot_to_gmt(vfs_handle_struct *handle,
1809                                          const char *name,
1810                                          char *gmt, size_t gmt_len)
1811 {
1812         struct tm timestamp;
1813         time_t timestamp_t;
1814         unsigned long int timestamp_long;
1815         const char *fmt;
1816         struct shadow_copy2_config *config;
1817         struct shadow_copy2_private *priv;
1818         char *tmpstr = NULL;
1819         char *tmp = NULL;
1820         bool converted = false;
1821         int ret = -1;
1822
1823         SMB_VFS_HANDLE_GET_DATA(handle, priv, struct shadow_copy2_private,
1824                                 return NULL);
1825
1826         config = priv->config;
1827
1828         fmt = config->gmt_format;
1829
1830         /*
1831          * If regex is provided, then we will have to parse the
1832          * filename which will contain both the prefix and the time format.
1833          * e.g. <prefix><delimiter><time_format>
1834          */
1835         if (priv->snaps->regex != NULL) {
1836                 tmpstr = talloc_strdup(talloc_tos(), name);
1837                 /* point "name" to the time format */
1838                 name = strstr(name, priv->config->delimiter);
1839                 if (name == NULL) {
1840                         goto done;
1841                 }
1842                 /* Extract the prefix */
1843                 tmp = strstr(tmpstr, priv->config->delimiter);
1844                 if (tmp == NULL) {
1845                         goto done;
1846                 }
1847                 *tmp = '\0';
1848
1849                 /* Parse regex */
1850                 ret = regexec(priv->snaps->regex, tmpstr, 0, NULL, 0);
1851                 if (ret) {
1852                         DBG_DEBUG("shadow_copy2_snapshot_to_gmt: "
1853                                   "no regex match for %s\n", tmpstr);
1854                         goto done;
1855                 }
1856         }
1857
1858         ZERO_STRUCT(timestamp);
1859         if (config->use_sscanf) {
1860                 if (sscanf(name, fmt, &timestamp_long) != 1) {
1861                         DEBUG(10, ("shadow_copy2_snapshot_to_gmt: "
1862                                    "no sscanf match %s: %s\n",
1863                                    fmt, name));
1864                         goto done;
1865                 }
1866                 timestamp_t = timestamp_long;
1867                 gmtime_r(&timestamp_t, &timestamp);
1868         } else {
1869                 if (strptime(name, fmt, &timestamp) == NULL) {
1870                         DEBUG(10, ("shadow_copy2_snapshot_to_gmt: "
1871                                    "no match %s: %s\n",
1872                                    fmt, name));
1873                         goto done;
1874                 }
1875                 DEBUG(10, ("shadow_copy2_snapshot_to_gmt: match %s: %s\n",
1876                            fmt, name));
1877                 
1878                 if (config->use_localtime) {
1879                         timestamp.tm_isdst = -1;
1880                         timestamp_t = mktime(&timestamp);
1881                         gmtime_r(&timestamp_t, &timestamp);
1882                 }
1883         }
1884
1885         strftime(gmt, gmt_len, GMT_FORMAT, &timestamp);
1886         converted = true;
1887
1888 done:
1889         TALLOC_FREE(tmpstr);
1890         return converted;
1891 }
1892
1893 static int shadow_copy2_label_cmp_asc(const void *x, const void *y)
1894 {
1895         return strncmp((const char *)x, (const char *)y, sizeof(SHADOW_COPY_LABEL));
1896 }
1897
1898 static int shadow_copy2_label_cmp_desc(const void *x, const void *y)
1899 {
1900         return -strncmp((const char *)x, (const char *)y, sizeof(SHADOW_COPY_LABEL));
1901 }
1902
1903 /*
1904   sort the shadow copy data in ascending or descending order
1905  */
1906 static void shadow_copy2_sort_data(vfs_handle_struct *handle,
1907                                    struct shadow_copy_data *shadow_copy2_data)
1908 {
1909         int (*cmpfunc)(const void *, const void *);
1910         const char *sort;
1911         struct shadow_copy2_private *priv;
1912
1913         SMB_VFS_HANDLE_GET_DATA(handle, priv, struct shadow_copy2_private,
1914                                 return);
1915
1916         sort = priv->config->sort_order;
1917         if (sort == NULL) {
1918                 return;
1919         }
1920
1921         if (strcmp(sort, "asc") == 0) {
1922                 cmpfunc = shadow_copy2_label_cmp_asc;
1923         } else if (strcmp(sort, "desc") == 0) {
1924                 cmpfunc = shadow_copy2_label_cmp_desc;
1925         } else {
1926                 return;
1927         }
1928
1929         if (shadow_copy2_data && shadow_copy2_data->num_volumes > 0 &&
1930             shadow_copy2_data->labels)
1931         {
1932                 TYPESAFE_QSORT(shadow_copy2_data->labels,
1933                                shadow_copy2_data->num_volumes,
1934                                cmpfunc);
1935         }
1936 }
1937
1938 static int shadow_copy2_get_shadow_copy_data(
1939         vfs_handle_struct *handle, files_struct *fsp,
1940         struct shadow_copy_data *shadow_copy2_data,
1941         bool labels)
1942 {
1943         DIR *p = NULL;
1944         const char *snapdir;
1945         struct smb_filename *snapdir_smb_fname = NULL;
1946         struct files_struct *dirfsp = NULL;
1947         struct files_struct *fspcwd = NULL;
1948         struct dirent *d;
1949         TALLOC_CTX *tmp_ctx = talloc_stackframe();
1950         struct shadow_copy2_private *priv = NULL;
1951         struct shadow_copy2_snapentry *tmpentry = NULL;
1952         bool get_snaplist = false;
1953         bool access_granted = false;
1954         int open_flags = O_RDONLY;
1955         int ret = -1;
1956         NTSTATUS status;
1957
1958         snapdir = shadow_copy2_find_snapdir(tmp_ctx, handle, fsp->fsp_name);
1959         if (snapdir == NULL) {
1960                 DEBUG(0,("shadow:snapdir not found for %s in get_shadow_copy_data\n",
1961                          handle->conn->connectpath));
1962                 errno = EINVAL;
1963                 goto done;
1964         }
1965
1966         access_granted = check_access_snapdir(handle, snapdir);
1967         if (!access_granted) {
1968                 DEBUG(0,("access denied on listing snapdir %s\n", snapdir));
1969                 errno = EACCES;
1970                 goto done;
1971         }
1972
1973         snapdir_smb_fname = synthetic_smb_fname(talloc_tos(),
1974                                         snapdir,
1975                                         NULL,
1976                                         NULL,
1977                                         0,
1978                                         fsp->fsp_name->flags);
1979         if (snapdir_smb_fname == NULL) {
1980                 errno = ENOMEM;
1981                 goto done;
1982         }
1983
1984         status = create_internal_dirfsp(handle->conn,
1985                                         snapdir_smb_fname,
1986                                         &dirfsp);
1987         if (!NT_STATUS_IS_OK(status)) {
1988                 DBG_WARNING("create_internal_dir_fsp() failed for '%s'"
1989                             " - %s\n", snapdir, nt_errstr(status));
1990                 errno = ENOSYS;
1991                 goto done;
1992         }
1993
1994         status = vfs_at_fspcwd(talloc_tos(), handle->conn, &fspcwd);
1995         if (!NT_STATUS_IS_OK(status)) {
1996                 errno = ENOMEM;
1997                 goto done;
1998         }
1999
2000 #ifdef O_DIRECTORY
2001         open_flags |= O_DIRECTORY;
2002 #endif
2003
2004         dirfsp->fh->fd = SMB_VFS_NEXT_OPENAT(handle,
2005                                              fspcwd,
2006                                              snapdir_smb_fname,
2007                                              dirfsp,
2008                                              open_flags,
2009                                              0);
2010         if (dirfsp->fh->fd == -1) {
2011                 DBG_WARNING("SMB_VFS_NEXT_OPEN failed for '%s'"
2012                             " - %s\n", snapdir, strerror(errno));
2013                 errno = ENOSYS;
2014                 goto done;
2015         }
2016
2017         p = SMB_VFS_NEXT_FDOPENDIR(handle, dirfsp, NULL, 0);
2018         if (!p) {
2019                 DBG_NOTICE("shadow_copy2: SMB_VFS_NEXT_FDOPENDIR() failed for '%s'"
2020                            " - %s\n", snapdir, strerror(errno));
2021                 errno = ENOSYS;
2022                 goto done;
2023         }
2024
2025         if (shadow_copy2_data != NULL) {
2026                 shadow_copy2_data->num_volumes = 0;
2027                 shadow_copy2_data->labels      = NULL;
2028         }
2029
2030         SMB_VFS_HANDLE_GET_DATA(handle, priv, struct shadow_copy2_private,
2031                                 goto done);
2032
2033         /*
2034          * Normally this function is called twice once with labels = false and
2035          * then with labels = true. When labels is false it will return the
2036          * number of volumes so that the caller can allocate memory for that
2037          * many labels. Therefore to eliminate snaplist both the times it is
2038          * good to check if labels is set or not.
2039          *
2040          * shadow_copy2_data is NULL when we only want to update the list and
2041          * don't want any labels.
2042          */
2043         if ((priv->snaps->regex != NULL) && (labels || shadow_copy2_data == NULL)) {
2044                 get_snaplist = true;
2045                 /* Reset the global snaplist */
2046                 shadow_copy2_delete_snaplist(priv);
2047
2048                 /* Set the current time as snaplist update time */
2049                 time(&(priv->snaps->fetch_time));
2050         }
2051
2052         while ((d = SMB_VFS_NEXT_READDIR(handle, p, NULL))) {
2053                 char snapshot[GMT_NAME_LEN+1];
2054                 SHADOW_COPY_LABEL *tlabels;
2055
2056                 /*
2057                  * ignore names not of the right form in the snapshot
2058                  * directory
2059                  */
2060                 if (!shadow_copy2_snapshot_to_gmt(
2061                             handle, d->d_name,
2062                             snapshot, sizeof(snapshot))) {
2063
2064                         DEBUG(6, ("shadow_copy2_get_shadow_copy_data: "
2065                                   "ignoring %s\n", d->d_name));
2066                         continue;
2067                 }
2068                 DEBUG(6,("shadow_copy2_get_shadow_copy_data: %s -> %s\n",
2069                          d->d_name, snapshot));
2070
2071                 if (get_snaplist) {
2072                         /*
2073                          * Create a snap entry for each successful
2074                          * pattern match.
2075                          */
2076                         tmpentry = shadow_copy2_create_snapentry(priv);
2077                         if (tmpentry == NULL) {
2078                                 DBG_ERR("talloc_zero() failed\n");
2079                                 goto done;
2080                         }
2081                         tmpentry->snapname = talloc_strdup(tmpentry, d->d_name);
2082                         tmpentry->time_fmt = talloc_strdup(tmpentry, snapshot);
2083                 }
2084
2085                 if (shadow_copy2_data == NULL) {
2086                         continue;
2087                 }
2088
2089                 if (!labels) {
2090                         /* the caller doesn't want the labels */
2091                         shadow_copy2_data->num_volumes++;
2092                         continue;
2093                 }
2094
2095                 tlabels = talloc_realloc(shadow_copy2_data,
2096                                          shadow_copy2_data->labels,
2097                                          SHADOW_COPY_LABEL,
2098                                          shadow_copy2_data->num_volumes+1);
2099                 if (tlabels == NULL) {
2100                         DEBUG(0,("shadow_copy2: out of memory\n"));
2101                         goto done;
2102                 }
2103
2104                 strlcpy(tlabels[shadow_copy2_data->num_volumes], snapshot,
2105                         sizeof(*tlabels));
2106
2107                 shadow_copy2_data->num_volumes++;
2108                 shadow_copy2_data->labels = tlabels;
2109         }
2110
2111         shadow_copy2_sort_data(handle, shadow_copy2_data);
2112         ret = 0;
2113
2114 done:
2115         TALLOC_FREE(fspcwd );
2116         if (p != NULL) {
2117                 SMB_VFS_NEXT_CLOSEDIR(handle, p);
2118                 p = NULL;
2119         }
2120         if (dirfsp != NULL) {
2121                 fd_close(dirfsp);
2122                 file_free(NULL, dirfsp);
2123         }
2124         TALLOC_FREE(tmp_ctx);
2125         return ret;
2126 }
2127
2128 static NTSTATUS shadow_copy2_get_nt_acl_at(vfs_handle_struct *handle,
2129                                         struct files_struct *dirfsp,
2130                                         const struct smb_filename *smb_fname,
2131                                         uint32_t security_info,
2132                                         TALLOC_CTX *mem_ctx,
2133                                         struct security_descriptor **ppdesc)
2134 {
2135         time_t timestamp = 0;
2136         char *stripped = NULL;
2137         NTSTATUS status;
2138         char *conv;
2139         struct smb_filename *conv_smb_fname = NULL;
2140
2141         if (!shadow_copy2_strip_snapshot(talloc_tos(),
2142                                         handle,
2143                                         smb_fname,
2144                                         &timestamp,
2145                                         &stripped)) {
2146                 return map_nt_error_from_unix(errno);
2147         }
2148         if (timestamp == 0) {
2149                 return SMB_VFS_NEXT_GET_NT_ACL_AT(handle,
2150                                         dirfsp,
2151                                         smb_fname,
2152                                         security_info,
2153                                         mem_ctx,
2154                                         ppdesc);
2155         }
2156         conv = shadow_copy2_convert(talloc_tos(), handle, stripped, timestamp);
2157         TALLOC_FREE(stripped);
2158         if (conv == NULL) {
2159                 return map_nt_error_from_unix(errno);
2160         }
2161         conv_smb_fname = synthetic_smb_fname(talloc_tos(),
2162                                         conv,
2163                                         NULL,
2164                                         NULL,
2165                                         0,
2166                                         smb_fname->flags);
2167         if (conv_smb_fname == NULL) {
2168                 TALLOC_FREE(conv);
2169                 return NT_STATUS_NO_MEMORY;
2170         }
2171         status = SMB_VFS_NEXT_GET_NT_ACL_AT(handle,
2172                                         dirfsp,
2173                                         conv_smb_fname,
2174                                         security_info,
2175                                         mem_ctx,
2176                                         ppdesc);
2177         TALLOC_FREE(conv);
2178         TALLOC_FREE(conv_smb_fname);
2179         return status;
2180 }
2181
2182 static int shadow_copy2_mkdirat(vfs_handle_struct *handle,
2183                                 struct files_struct *dirfsp,
2184                                 const struct smb_filename *smb_fname,
2185                                 mode_t mode)
2186 {
2187         time_t timestamp = 0;
2188
2189         if (!shadow_copy2_strip_snapshot(talloc_tos(),
2190                                         handle,
2191                                         smb_fname,
2192                                         &timestamp,
2193                                         NULL)) {
2194                 return -1;
2195         }
2196         if (timestamp != 0) {
2197                 errno = EROFS;
2198                 return -1;
2199         }
2200         return SMB_VFS_NEXT_MKDIRAT(handle,
2201                         dirfsp,
2202                         smb_fname,
2203                         mode);
2204 }
2205
2206 static int shadow_copy2_chflags(vfs_handle_struct *handle,
2207                                 const struct smb_filename *smb_fname,
2208                                 unsigned int flags)
2209 {
2210         time_t timestamp = 0;
2211
2212         if (!shadow_copy2_strip_snapshot(talloc_tos(),
2213                                         handle,
2214                                         smb_fname,
2215                                         &timestamp,
2216                                         NULL)) {
2217                 return -1;
2218         }
2219         if (timestamp != 0) {
2220                 errno = EROFS;
2221                 return -1;
2222         }
2223         return SMB_VFS_NEXT_CHFLAGS(handle, smb_fname, flags);
2224 }
2225
2226 static ssize_t shadow_copy2_getxattr(vfs_handle_struct *handle,
2227                                 const struct smb_filename *smb_fname,
2228                                 const char *aname,
2229                                 void *value,
2230                                 size_t size)
2231 {
2232         time_t timestamp = 0;
2233         char *stripped = NULL;
2234         ssize_t ret;
2235         int saved_errno = 0;
2236         char *conv;
2237         struct smb_filename *conv_smb_fname = NULL;
2238
2239         if (!shadow_copy2_strip_snapshot(talloc_tos(),
2240                                 handle,
2241                                 smb_fname,
2242                                 &timestamp,
2243                                 &stripped)) {
2244                 return -1;
2245         }
2246         if (timestamp == 0) {
2247                 return SMB_VFS_NEXT_GETXATTR(handle, smb_fname, aname, value,
2248                                              size);
2249         }
2250         conv = shadow_copy2_convert(talloc_tos(), handle, stripped, timestamp);
2251         TALLOC_FREE(stripped);
2252         if (conv == NULL) {
2253                 return -1;
2254         }
2255
2256         conv_smb_fname = synthetic_smb_fname(talloc_tos(),
2257                                         conv,
2258                                         NULL,
2259                                         NULL,
2260                                         0,
2261                                         smb_fname->flags);
2262         if (conv_smb_fname == NULL) {
2263                 TALLOC_FREE(conv);
2264                 return -1;
2265         }
2266
2267         ret = SMB_VFS_NEXT_GETXATTR(handle, conv_smb_fname, aname, value, size);
2268         if (ret == -1) {
2269                 saved_errno = errno;
2270         }
2271         TALLOC_FREE(conv_smb_fname);
2272         TALLOC_FREE(conv);
2273         if (saved_errno != 0) {
2274                 errno = saved_errno;
2275         }
2276         return ret;
2277 }
2278
2279 static ssize_t shadow_copy2_listxattr(struct vfs_handle_struct *handle,
2280                                       const struct smb_filename *smb_fname,
2281                                       char *list, size_t size)
2282 {
2283         time_t timestamp = 0;
2284         char *stripped = NULL;
2285         ssize_t ret;
2286         int saved_errno = 0;
2287         char *conv;
2288         struct smb_filename *conv_smb_fname = NULL;
2289
2290         if (!shadow_copy2_strip_snapshot(talloc_tos(),
2291                                 handle,
2292                                 smb_fname,
2293                                 &timestamp,
2294                                 &stripped)) {
2295                 return -1;
2296         }
2297         if (timestamp == 0) {
2298                 return SMB_VFS_NEXT_LISTXATTR(handle, smb_fname, list, size);
2299         }
2300         conv = shadow_copy2_convert(talloc_tos(), handle, stripped, timestamp);
2301         TALLOC_FREE(stripped);
2302         if (conv == NULL) {
2303                 return -1;
2304         }
2305         conv_smb_fname = synthetic_smb_fname(talloc_tos(),
2306                                         conv,
2307                                         NULL,
2308                                         NULL,
2309                                         0,
2310                                         smb_fname->flags);
2311         if (conv_smb_fname == NULL) {
2312                 TALLOC_FREE(conv);
2313                 return -1;
2314         }
2315         ret = SMB_VFS_NEXT_LISTXATTR(handle, conv_smb_fname, list, size);
2316         if (ret == -1) {
2317                 saved_errno = errno;
2318         }
2319         TALLOC_FREE(conv_smb_fname);
2320         TALLOC_FREE(conv);
2321         if (saved_errno != 0) {
2322                 errno = saved_errno;
2323         }
2324         return ret;
2325 }
2326
2327 static int shadow_copy2_removexattr(vfs_handle_struct *handle,
2328                                 const struct smb_filename *smb_fname,
2329                                 const char *aname)
2330 {
2331         time_t timestamp = 0;
2332
2333         if (!shadow_copy2_strip_snapshot(talloc_tos(),
2334                                 handle,
2335                                 smb_fname,
2336                                 &timestamp,
2337                                 NULL)) {
2338                 return -1;
2339         }
2340         if (timestamp != 0) {
2341                 errno = EROFS;
2342                 return -1;
2343         }
2344         return SMB_VFS_NEXT_REMOVEXATTR(handle, smb_fname, aname);
2345 }
2346
2347 static int shadow_copy2_setxattr(struct vfs_handle_struct *handle,
2348                                  const struct smb_filename *smb_fname,
2349                                  const char *aname, const void *value,
2350                                  size_t size, int flags)
2351 {
2352         time_t timestamp = 0;
2353
2354         if (!shadow_copy2_strip_snapshot(talloc_tos(),
2355                                 handle,
2356                                 smb_fname,
2357                                 &timestamp,
2358                                 NULL)) {
2359                 return -1;
2360         }
2361         if (timestamp != 0) {
2362                 errno = EROFS;
2363                 return -1;
2364         }
2365         return SMB_VFS_NEXT_SETXATTR(handle, smb_fname,
2366                                 aname, value, size, flags);
2367 }
2368
2369 static NTSTATUS shadow_copy2_create_dfs_pathat(struct vfs_handle_struct *handle,
2370                                 struct files_struct *dirfsp,
2371                                 const struct smb_filename *smb_fname,
2372                                 const struct referral *reflist,
2373                                 size_t referral_count)
2374 {
2375         time_t timestamp = 0;
2376
2377         if (!shadow_copy2_strip_snapshot(talloc_tos(),
2378                                         handle,
2379                                         smb_fname,
2380                                         &timestamp,
2381                                         NULL)) {
2382                 return NT_STATUS_NO_MEMORY;
2383         }
2384         if (timestamp != 0) {
2385                 return NT_STATUS_MEDIA_WRITE_PROTECTED;
2386         }
2387         return SMB_VFS_NEXT_CREATE_DFS_PATHAT(handle,
2388                         dirfsp,
2389                         smb_fname,
2390                         reflist,
2391                         referral_count);
2392 }
2393
2394 static NTSTATUS shadow_copy2_read_dfs_pathat(struct vfs_handle_struct *handle,
2395                                 TALLOC_CTX *mem_ctx,
2396                                 struct files_struct *dirfsp,
2397                                 struct smb_filename *smb_fname,
2398                                 struct referral **ppreflist,
2399                                 size_t *preferral_count)
2400 {
2401         time_t timestamp = 0;
2402         char *stripped = NULL;
2403         struct smb_filename *conv = NULL;
2404         NTSTATUS status;
2405
2406         if (!shadow_copy2_strip_snapshot(mem_ctx,
2407                                         handle,
2408                                         smb_fname,
2409                                         &timestamp,
2410                                         &stripped)) {
2411                 return NT_STATUS_NO_MEMORY;
2412         }
2413         if (timestamp == 0) {
2414                 return SMB_VFS_NEXT_READ_DFS_PATHAT(handle,
2415                                         mem_ctx,
2416                                         dirfsp,
2417                                         smb_fname,
2418                                         ppreflist,
2419                                         preferral_count);
2420         }
2421
2422         conv = cp_smb_filename(mem_ctx, smb_fname);
2423         if (conv == NULL) {
2424                 TALLOC_FREE(stripped);
2425                 return NT_STATUS_NO_MEMORY;
2426         }
2427         conv->base_name = shadow_copy2_convert(conv,
2428                                         handle,
2429                                         stripped,
2430                                         timestamp);
2431         TALLOC_FREE(stripped);
2432         if (conv->base_name == NULL) {
2433                 TALLOC_FREE(conv);
2434                 return NT_STATUS_NO_MEMORY;
2435         }
2436
2437         status = SMB_VFS_NEXT_READ_DFS_PATHAT(handle,
2438                                 mem_ctx,
2439                                 dirfsp,
2440                                 conv,
2441                                 ppreflist,
2442                                 preferral_count);
2443
2444         if (NT_STATUS_IS_OK(status)) {
2445                 /* Return any stat(2) info. */
2446                 smb_fname->st = conv->st;
2447         }
2448
2449         TALLOC_FREE(conv);
2450         return status;
2451 }
2452
2453 static int shadow_copy2_get_real_filename(struct vfs_handle_struct *handle,
2454                                           const struct smb_filename *fname,
2455                                           const char *name,
2456                                           TALLOC_CTX *mem_ctx,
2457                                           char **found_name)
2458 {
2459         struct shadow_copy2_private *priv = NULL;
2460         struct shadow_copy2_config *config = NULL;
2461         time_t timestamp = 0;
2462         char *stripped = NULL;
2463         ssize_t ret;
2464         int saved_errno = 0;
2465         char *conv;
2466         struct smb_filename conv_fname;
2467
2468         SMB_VFS_HANDLE_GET_DATA(handle, priv, struct shadow_copy2_private,
2469                                 return -1);
2470         config = priv->config;
2471
2472         DBG_DEBUG("Path=[%s] name=[%s]\n", smb_fname_str_dbg(fname), name);
2473
2474         if (!shadow_copy2_strip_snapshot(talloc_tos(), handle, fname,
2475                                          &timestamp, &stripped)) {
2476                 DEBUG(10, ("shadow_copy2_strip_snapshot failed\n"));
2477                 return -1;
2478         }
2479         if (timestamp == 0) {
2480                 DEBUG(10, ("timestamp == 0\n"));
2481                 return SMB_VFS_NEXT_GET_REAL_FILENAME(handle, fname, name,
2482                                                       mem_ctx, found_name);
2483         }
2484
2485         /*
2486          * Note that stripped may be an empty string "" if path was ".". As
2487          * shadow_copy2_convert() combines "" with the shadow-copy tree connect
2488          * root fullpath and get_real_filename_full_scan() has an explicit check
2489          * for "" this works.
2490          */
2491         DBG_DEBUG("stripped [%s]\n", stripped);
2492
2493         conv = shadow_copy2_convert(talloc_tos(), handle, stripped, timestamp);
2494         if (conv == NULL) {
2495                 if (!config->snapdirseverywhere) {
2496                         DBG_DEBUG("shadow_copy2_convert [%s] failed\n", stripped);
2497                         return -1;
2498                 }
2499
2500                 /*
2501                  * We're called in the path traversal loop in unix_convert()
2502                  * walking down the directory hierarchy. shadow_copy2_convert()
2503                  * will fail if the snapshot directory is futher down in the
2504                  * hierachy. Set conv to the original stripped path and try to
2505                  * look it up in the filesystem with
2506                  * SMB_VFS_NEXT_GET_REAL_FILENAME() or
2507                  * get_real_filename_full_scan().
2508                  */
2509                 DBG_DEBUG("Use stripped [%s] as conv\n", stripped);
2510                 conv = talloc_strdup(talloc_tos(), stripped);
2511                 if (conv == NULL) {
2512                         TALLOC_FREE(stripped);
2513                         return -1;
2514                 }
2515         }
2516
2517         conv_fname = (struct smb_filename) {
2518                 .base_name = conv,
2519         };
2520
2521         DEBUG(10, ("Calling NEXT_GET_REAL_FILE_NAME for conv=[%s], "
2522                    "name=[%s]\n", conv, name));
2523         ret = SMB_VFS_NEXT_GET_REAL_FILENAME(handle, &conv_fname, name,
2524                                              mem_ctx, found_name);
2525         DEBUG(10, ("NEXT_REAL_FILE_NAME returned %d\n", (int)ret));
2526         if (ret == 0) {
2527                 return 0;
2528         }
2529         if (errno != EOPNOTSUPP) {
2530                 TALLOC_FREE(conv);
2531                 errno = EOPNOTSUPP;
2532                 return -1;
2533         }
2534
2535         ret = get_real_filename_full_scan(handle->conn,
2536                                           conv,
2537                                           name,
2538                                           false,
2539                                           mem_ctx,
2540                                           found_name);
2541         if (ret != 0) {
2542                 saved_errno = errno;
2543                 DBG_DEBUG("Scan [%s] for [%s] failed\n",
2544                           conv, name);
2545                 errno = saved_errno;
2546                 return -1;
2547         }
2548
2549         DBG_DEBUG("Scan [%s] for [%s] returned [%s]\n",
2550                   conv, name, *found_name);
2551
2552         TALLOC_FREE(conv);
2553         return 0;
2554 }
2555
2556 static const char *shadow_copy2_connectpath(struct vfs_handle_struct *handle,
2557                                         const struct smb_filename *smb_fname_in)
2558 {
2559         time_t timestamp = 0;
2560         char *stripped = NULL;
2561         char *tmp = NULL;
2562         const char *fname = smb_fname_in->base_name;
2563         struct smb_filename smb_fname = {0};
2564         struct smb_filename *result_fname = NULL;
2565         char *result = NULL;
2566         char *parent_dir = NULL;
2567         int saved_errno = 0;
2568         size_t rootpath_len = 0;
2569         struct shadow_copy2_private *priv = NULL;
2570
2571         SMB_VFS_HANDLE_GET_DATA(handle, priv, struct shadow_copy2_private,
2572                                 return NULL);
2573
2574         DBG_DEBUG("Calc connect path for [%s]\n", fname);
2575
2576         if (priv->shadow_connectpath != NULL) {
2577                 DBG_DEBUG("cached connect path is [%s]\n",
2578                         priv->shadow_connectpath);
2579                 return priv->shadow_connectpath;
2580         }
2581
2582         if (!shadow_copy2_strip_snapshot(talloc_tos(), handle, smb_fname_in,
2583                                          &timestamp, &stripped)) {
2584                 goto done;
2585         }
2586         if (timestamp == 0) {
2587                 return SMB_VFS_NEXT_CONNECTPATH(handle, smb_fname_in);
2588         }
2589
2590         tmp = shadow_copy2_do_convert(talloc_tos(), handle, stripped, timestamp,
2591                                       &rootpath_len);
2592         if (tmp == NULL) {
2593                 if (errno != ENOENT) {
2594                         goto done;
2595                 }
2596
2597                 /*
2598                  * If the converted path does not exist, and converting
2599                  * the parent yields something that does exist, then
2600                  * this path refers to something that has not been
2601                  * created yet, relative to the parent path.
2602                  * The snapshot finding is relative to the parent.
2603                  * (usually snapshots are read/only but this is not
2604                  * necessarily true).
2605                  * This code also covers getting a wildcard in the
2606                  * last component, because this function is called
2607                  * prior to sanitizing the path, and in SMB1 we may
2608                  * get wildcards in path names.
2609                  */
2610                 if (!parent_dirname(talloc_tos(), stripped, &parent_dir,
2611                                     NULL)) {
2612                         errno = ENOMEM;
2613                         goto done;
2614                 }
2615
2616                 tmp = shadow_copy2_do_convert(talloc_tos(), handle, parent_dir,
2617                                               timestamp, &rootpath_len);
2618                 if (tmp == NULL) {
2619                         goto done;
2620                 }
2621         }
2622
2623         DBG_DEBUG("converted path is [%s] root path is [%.*s]\n", tmp,
2624                   (int)rootpath_len, tmp);
2625
2626         tmp[rootpath_len] = '\0';
2627         smb_fname = (struct smb_filename) { .base_name = tmp };
2628
2629         result_fname = SMB_VFS_NEXT_REALPATH(handle, priv, &smb_fname);
2630         if (result_fname == NULL) {
2631                 goto done;
2632         }
2633
2634         /*
2635          * SMB_VFS_NEXT_REALPATH returns a talloc'ed string.
2636          * Don't leak memory.
2637          */
2638         TALLOC_FREE(priv->shadow_realpath);
2639         priv->shadow_realpath = result_fname;
2640         result = priv->shadow_realpath->base_name;
2641
2642         DBG_DEBUG("connect path is [%s]\n", result);
2643
2644 done:
2645         if (result == NULL) {
2646                 saved_errno = errno;
2647         }
2648         TALLOC_FREE(tmp);
2649         TALLOC_FREE(stripped);
2650         TALLOC_FREE(parent_dir);
2651         if (saved_errno != 0) {
2652                 errno = saved_errno;
2653         }
2654         return result;
2655 }
2656
2657 static uint64_t shadow_copy2_disk_free(vfs_handle_struct *handle,
2658                                 const struct smb_filename *smb_fname,
2659                                 uint64_t *bsize,
2660                                 uint64_t *dfree,
2661                                 uint64_t *dsize)
2662 {
2663         time_t timestamp = 0;
2664         char *stripped = NULL;
2665         int saved_errno = 0;
2666         char *conv = NULL;
2667         struct smb_filename *conv_smb_fname = NULL;
2668         uint64_t ret = (uint64_t)-1;
2669
2670         if (!shadow_copy2_strip_snapshot(talloc_tos(),
2671                                 handle,
2672                                 smb_fname,
2673                                 &timestamp,
2674                                 &stripped)) {
2675                 return (uint64_t)-1;
2676         }
2677         if (timestamp == 0) {
2678                 return SMB_VFS_NEXT_DISK_FREE(handle, smb_fname,
2679                                               bsize, dfree, dsize);
2680         }
2681         conv = shadow_copy2_convert(talloc_tos(), handle, stripped, timestamp);
2682         TALLOC_FREE(stripped);
2683         if (conv == NULL) {
2684                 return (uint64_t)-1;
2685         }
2686         conv_smb_fname = synthetic_smb_fname(talloc_tos(),
2687                                         conv,
2688                                         NULL,
2689                                         NULL,
2690                                         0,
2691                                         smb_fname->flags);
2692         if (conv_smb_fname == NULL) {
2693                 TALLOC_FREE(conv);
2694                 return (uint64_t)-1;
2695         }
2696         ret = SMB_VFS_NEXT_DISK_FREE(handle, conv_smb_fname,
2697                                 bsize, dfree, dsize);
2698         if (ret == (uint64_t)-1) {
2699                 saved_errno = errno;
2700         }
2701         TALLOC_FREE(conv);
2702         TALLOC_FREE(conv_smb_fname);
2703         if (saved_errno != 0) {
2704                 errno = saved_errno;
2705         }
2706         return ret;
2707 }
2708
2709 static int shadow_copy2_get_quota(vfs_handle_struct *handle,
2710                                 const struct smb_filename *smb_fname,
2711                                 enum SMB_QUOTA_TYPE qtype,
2712                                 unid_t id,
2713                                 SMB_DISK_QUOTA *dq)
2714 {
2715         time_t timestamp = 0;
2716         char *stripped = NULL;
2717         int ret;
2718         int saved_errno = 0;
2719         char *conv;
2720         struct smb_filename *conv_smb_fname = NULL;
2721
2722         if (!shadow_copy2_strip_snapshot(talloc_tos(),
2723                                 handle,
2724                                 smb_fname,
2725                                 &timestamp,
2726                                 &stripped)) {
2727                 return -1;
2728         }
2729         if (timestamp == 0) {
2730                 return SMB_VFS_NEXT_GET_QUOTA(handle, smb_fname, qtype, id, dq);
2731         }
2732
2733         conv = shadow_copy2_convert(talloc_tos(), handle, stripped, timestamp);
2734         TALLOC_FREE(stripped);
2735         if (conv == NULL) {
2736                 return -1;
2737         }
2738         conv_smb_fname = synthetic_smb_fname(talloc_tos(),
2739                                         conv,
2740                                         NULL,
2741                                         NULL,
2742                                         0,
2743                                         smb_fname->flags);
2744         if (conv_smb_fname == NULL) {
2745                 TALLOC_FREE(conv);
2746                 return -1;
2747         }
2748         ret = SMB_VFS_NEXT_GET_QUOTA(handle, conv_smb_fname, qtype, id, dq);
2749
2750         if (ret == -1) {
2751                 saved_errno = errno;
2752         }
2753         TALLOC_FREE(conv);
2754         TALLOC_FREE(conv_smb_fname);
2755         if (saved_errno != 0) {
2756                 errno = saved_errno;
2757         }
2758
2759         return ret;
2760 }
2761
2762 static ssize_t shadow_copy2_pwrite(vfs_handle_struct *handle,
2763                                    files_struct *fsp,
2764                                    const void *data,
2765                                    size_t n,
2766                                    off_t offset)
2767 {
2768         ssize_t nwritten;
2769
2770         nwritten = SMB_VFS_NEXT_PWRITE(handle, fsp, data, n, offset);
2771         if (nwritten == -1) {
2772                 if (errno == EBADF && fsp->fsp_flags.can_write) {
2773                         errno = EROFS;
2774                 }
2775         }
2776
2777         return nwritten;
2778 }
2779
2780 struct shadow_copy2_pwrite_state {
2781         vfs_handle_struct *handle;
2782         files_struct *fsp;
2783         ssize_t ret;
2784         struct vfs_aio_state vfs_aio_state;
2785 };
2786
2787 static void shadow_copy2_pwrite_done(struct tevent_req *subreq);
2788
2789 static struct tevent_req *shadow_copy2_pwrite_send(
2790         struct vfs_handle_struct *handle, TALLOC_CTX *mem_ctx,
2791         struct tevent_context *ev, struct files_struct *fsp,
2792         const void *data, size_t n, off_t offset)
2793 {
2794         struct tevent_req *req = NULL, *subreq = NULL;
2795         struct shadow_copy2_pwrite_state *state = NULL;
2796
2797         req = tevent_req_create(mem_ctx, &state,
2798                                 struct shadow_copy2_pwrite_state);
2799         if (req == NULL) {
2800                 return NULL;
2801         }
2802         state->handle = handle;
2803         state->fsp = fsp;
2804
2805         subreq = SMB_VFS_NEXT_PWRITE_SEND(state,
2806                                           ev,
2807                                           handle,
2808                                           fsp,
2809                                           data,
2810                                           n,
2811                                           offset);
2812         if (tevent_req_nomem(subreq, req)) {
2813                 return tevent_req_post(req, ev);
2814         }
2815         tevent_req_set_callback(subreq, shadow_copy2_pwrite_done, req);
2816
2817         return req;
2818 }
2819
2820 static void shadow_copy2_pwrite_done(struct tevent_req *subreq)
2821 {
2822         struct tevent_req *req = tevent_req_callback_data(
2823                 subreq, struct tevent_req);
2824         struct shadow_copy2_pwrite_state *state = tevent_req_data(
2825                 req, struct shadow_copy2_pwrite_state);
2826
2827         state->ret = SMB_VFS_PWRITE_RECV(subreq, &state->vfs_aio_state);
2828         TALLOC_FREE(subreq);
2829         if (state->ret == -1) {
2830                 tevent_req_error(req, state->vfs_aio_state.error);
2831                 return;
2832         }
2833
2834         tevent_req_done(req);
2835 }
2836
2837 static ssize_t shadow_copy2_pwrite_recv(struct tevent_req *req,
2838                                           struct vfs_aio_state *vfs_aio_state)
2839 {
2840         struct shadow_copy2_pwrite_state *state = tevent_req_data(
2841                 req, struct shadow_copy2_pwrite_state);
2842
2843         if (tevent_req_is_unix_error(req, &vfs_aio_state->error)) {
2844                 if ((vfs_aio_state->error == EBADF) &&
2845                     state->fsp->fsp_flags.can_write)
2846                 {
2847                         vfs_aio_state->error = EROFS;
2848                         errno = EROFS;
2849                 }
2850                 return -1;
2851         }
2852
2853         *vfs_aio_state = state->vfs_aio_state;
2854         return state->ret;
2855 }
2856
2857 static int shadow_copy2_connect(struct vfs_handle_struct *handle,
2858                                 const char *service, const char *user)
2859 {
2860         struct shadow_copy2_config *config;
2861         struct shadow_copy2_private *priv;
2862         int ret;
2863         const char *snapdir;
2864         const char *snapprefix = NULL;
2865         const char *delimiter;
2866         const char *gmt_format;
2867         const char *sort_order;
2868         const char *basedir = NULL;
2869         const char *snapsharepath = NULL;
2870         const char *mount_point;
2871
2872         DEBUG(10, (__location__ ": cnum[%u], connectpath[%s]\n",
2873                    (unsigned)handle->conn->cnum,
2874                    handle->conn->connectpath));
2875
2876         ret = SMB_VFS_NEXT_CONNECT(handle, service, user);
2877         if (ret < 0) {
2878                 return ret;
2879         }
2880
2881         priv = talloc_zero(handle->conn, struct shadow_copy2_private);
2882         if (priv == NULL) {
2883                 DBG_ERR("talloc_zero() failed\n");
2884                 errno = ENOMEM;
2885                 return -1;
2886         }
2887
2888         priv->snaps = talloc_zero(priv, struct shadow_copy2_snaplist_info);
2889         if (priv->snaps == NULL) {
2890                 DBG_ERR("talloc_zero() failed\n");
2891                 errno = ENOMEM;
2892                 return -1;
2893         }
2894
2895         config = talloc_zero(priv, struct shadow_copy2_config);
2896         if (config == NULL) {
2897                 DEBUG(0, ("talloc_zero() failed\n"));
2898                 errno = ENOMEM;
2899                 return -1;
2900         }
2901
2902         priv->config = config;
2903
2904         gmt_format = lp_parm_const_string(SNUM(handle->conn),
2905                                           "shadow", "format",
2906                                           GMT_FORMAT);
2907         config->gmt_format = talloc_strdup(config, gmt_format);
2908         if (config->gmt_format == NULL) {
2909                 DEBUG(0, ("talloc_strdup() failed\n"));
2910                 errno = ENOMEM;
2911                 return -1;
2912         }
2913
2914         /* config->gmt_format must not contain a path separator. */
2915         if (strchr(config->gmt_format, '/') != NULL) {
2916                 DEBUG(0, ("shadow:format %s must not contain a /"
2917                         "character. Unable to initialize module.\n",
2918                         config->gmt_format));
2919                 errno = EINVAL;
2920                 return -1;
2921         }
2922
2923         config->use_sscanf = lp_parm_bool(SNUM(handle->conn),
2924                                           "shadow", "sscanf", false);
2925
2926         config->use_localtime = lp_parm_bool(SNUM(handle->conn),
2927                                              "shadow", "localtime",
2928                                              false);
2929
2930         snapdir = lp_parm_const_string(SNUM(handle->conn),
2931                                        "shadow", "snapdir",
2932                                        ".snapshots");
2933         config->snapdir = talloc_strdup(config, snapdir);
2934         if (config->snapdir == NULL) {
2935                 DEBUG(0, ("talloc_strdup() failed\n"));
2936                 errno = ENOMEM;
2937                 return -1;
2938         }
2939
2940         snapprefix = lp_parm_const_string(SNUM(handle->conn),
2941                                        "shadow", "snapprefix",
2942                                        NULL);
2943         if (snapprefix != NULL) {
2944                 priv->snaps->regex = talloc_zero(priv->snaps, regex_t);
2945                 if (priv->snaps->regex == NULL) {
2946                         DBG_ERR("talloc_zero() failed\n");
2947                         errno = ENOMEM;
2948                         return -1;
2949                 }
2950
2951                 /* pre-compute regex rule for matching pattern later */
2952                 ret = regcomp(priv->snaps->regex, snapprefix, 0);
2953                 if (ret) {
2954                         DBG_ERR("Failed to create regex object\n");
2955                         return -1;
2956                 }
2957         }
2958
2959         delimiter = lp_parm_const_string(SNUM(handle->conn),
2960                                        "shadow", "delimiter",
2961                                        "_GMT");
2962         if (delimiter != NULL) {
2963                 priv->config->delimiter = talloc_strdup(priv->config, delimiter);
2964                 if (priv->config->delimiter == NULL) {
2965                         DBG_ERR("talloc_strdup() failed\n");
2966                         errno = ENOMEM;
2967                         return -1;
2968                 }
2969         }
2970
2971         config->snapdirseverywhere = lp_parm_bool(SNUM(handle->conn),
2972                                                   "shadow",
2973                                                   "snapdirseverywhere",
2974                                                   false);
2975
2976         config->crossmountpoints = lp_parm_bool(SNUM(handle->conn),
2977                                                 "shadow", "crossmountpoints",
2978                                                 false);
2979
2980         if (config->crossmountpoints && !config->snapdirseverywhere) {
2981                 DBG_WARNING("Warning: 'crossmountpoints' depends on "
2982                             "'snapdirseverywhere'. Disabling crossmountpoints.\n");
2983         }
2984
2985         config->fixinodes = lp_parm_bool(SNUM(handle->conn),
2986                                          "shadow", "fixinodes",
2987                                          false);
2988
2989         sort_order = lp_parm_const_string(SNUM(handle->conn),
2990                                           "shadow", "sort", "desc");
2991         config->sort_order = talloc_strdup(config, sort_order);
2992         if (config->sort_order == NULL) {
2993                 DEBUG(0, ("talloc_strdup() failed\n"));
2994                 errno = ENOMEM;
2995                 return -1;
2996         }
2997
2998         mount_point = lp_parm_const_string(SNUM(handle->conn),
2999                                            "shadow", "mountpoint", NULL);
3000         if (mount_point != NULL) {
3001                 if (mount_point[0] != '/') {
3002                         DEBUG(1, (__location__ " Warning: 'mountpoint' is "
3003                                   "relative ('%s'), but it has to be an "
3004                                   "absolute path. Ignoring provided value.\n",
3005                                   mount_point));
3006                         mount_point = NULL;
3007                 } else {
3008                         char *p;
3009                         p = strstr(handle->conn->connectpath, mount_point);
3010                         if (p != handle->conn->connectpath) {
3011                                 DBG_WARNING("Warning: the share root (%s) is "
3012                                             "not a subdirectory of the "
3013                                             "specified mountpoint (%s). "
3014                                             "Ignoring provided value.\n",
3015                                             handle->conn->connectpath,
3016                                             mount_point);
3017                                 mount_point = NULL;
3018                         }
3019                 }
3020         }
3021
3022         if (mount_point != NULL) {
3023                 config->mount_point = talloc_strdup(config, mount_point);
3024                 if (config->mount_point == NULL) {
3025                         DEBUG(0, (__location__ " talloc_strdup() failed\n"));
3026                         return -1;
3027                 }
3028         } else {
3029                 config->mount_point = shadow_copy2_find_mount_point(config,
3030                                                                     handle);
3031                 if (config->mount_point == NULL) {
3032                         DBG_WARNING("shadow_copy2_find_mount_point "
3033                                     "of the share root '%s' failed: %s\n",
3034                                     handle->conn->connectpath, strerror(errno));
3035                         return -1;
3036                 }
3037         }
3038
3039         basedir = lp_parm_const_string(SNUM(handle->conn),
3040                                        "shadow", "basedir", NULL);
3041
3042         if (basedir != NULL) {
3043                 if (basedir[0] != '/') {
3044                         DEBUG(1, (__location__ " Warning: 'basedir' is "
3045                                   "relative ('%s'), but it has to be an "
3046                                   "absolute path. Disabling basedir.\n",
3047                                   basedir));
3048                         basedir = NULL;
3049                 } else {
3050                         char *p;
3051                         p = strstr(basedir, config->mount_point);
3052                         if (p != basedir) {
3053                                 DEBUG(1, ("Warning: basedir (%s) is not a "
3054                                           "subdirectory of the share root's "
3055                                           "mount point (%s). "
3056                                           "Disabling basedir\n",
3057                                           basedir, config->mount_point));
3058                                 basedir = NULL;
3059                         }
3060                 }
3061         }
3062
3063         if (config->snapdirseverywhere && basedir != NULL) {
3064                 DEBUG(1, (__location__ " Warning: 'basedir' is incompatible "
3065                           "with 'snapdirseverywhere'. Disabling basedir.\n"));
3066                 basedir = NULL;
3067         }
3068
3069         snapsharepath = lp_parm_const_string(SNUM(handle->conn), "shadow",
3070                                              "snapsharepath", NULL);
3071         if (snapsharepath != NULL) {
3072                 if (snapsharepath[0] == '/') {
3073                         DBG_WARNING("Warning: 'snapsharepath' is "
3074                                     "absolute ('%s'), but it has to be a "
3075                                     "relative path. Disabling snapsharepath.\n",
3076                                     snapsharepath);
3077                         snapsharepath = NULL;
3078                 }
3079                 if (config->snapdirseverywhere && snapsharepath != NULL) {
3080                         DBG_WARNING("Warning: 'snapsharepath' is incompatible "
3081                                     "with 'snapdirseverywhere'. Disabling "
3082                                     "snapsharepath.\n");
3083                         snapsharepath = NULL;
3084                 }
3085         }
3086
3087         if (basedir != NULL && snapsharepath != NULL) {
3088                 DBG_WARNING("Warning: 'snapsharepath' is incompatible with "
3089                             "'basedir'. Disabling snapsharepath\n");
3090                 snapsharepath = NULL;
3091         }
3092
3093         if (snapsharepath != NULL) {
3094                 config->rel_connectpath = talloc_strdup(config, snapsharepath);
3095                 if (config->rel_connectpath == NULL) {
3096                         DBG_ERR("talloc_strdup() failed\n");
3097                         errno = ENOMEM;
3098                         return -1;
3099                 }
3100         }
3101
3102         if (basedir == NULL) {
3103                 basedir = config->mount_point;
3104         }
3105
3106         if (config->rel_connectpath == NULL &&
3107             strlen(basedir) < strlen(handle->conn->connectpath)) {
3108                 config->rel_connectpath = talloc_strdup(config,
3109                         handle->conn->connectpath + strlen(basedir));
3110                 if (config->rel_connectpath == NULL) {
3111                         DEBUG(0, ("talloc_strdup() failed\n"));
3112                         errno = ENOMEM;
3113                         return -1;
3114                 }
3115         }
3116
3117         if (config->snapdir[0] == '/') {
3118                 config->snapdir_absolute = true;
3119
3120                 if (config->snapdirseverywhere == true) {
3121                         DEBUG(1, (__location__ " Warning: An absolute snapdir "
3122                                   "is incompatible with 'snapdirseverywhere', "
3123                                   "setting 'snapdirseverywhere' to false.\n"));
3124                         config->snapdirseverywhere = false;
3125                 }
3126
3127                 if (config->crossmountpoints == true) {
3128                         DEBUG(1, (__location__ " Warning: 'crossmountpoints' "
3129                                   "is not supported with an absolute snapdir. "
3130                                   "Disabling it.\n"));
3131                         config->crossmountpoints = false;
3132                 }
3133
3134                 config->snapshot_basepath = config->snapdir;
3135         } else {
3136                 config->snapshot_basepath = talloc_asprintf(config, "%s/%s",
3137                                 config->mount_point, config->snapdir);
3138                 if (config->snapshot_basepath == NULL) {
3139                         DEBUG(0, ("talloc_asprintf() failed\n"));
3140                         errno = ENOMEM;
3141                         return -1;
3142                 }
3143         }
3144
3145         trim_string(config->mount_point, NULL, "/");
3146         trim_string(config->rel_connectpath, "/", "/");
3147         trim_string(config->snapdir, NULL, "/");
3148         trim_string(config->snapshot_basepath, NULL, "/");
3149
3150         DEBUG(10, ("shadow_copy2_connect: configuration:\n"
3151                    "  share root: '%s'\n"
3152                    "  mountpoint: '%s'\n"
3153                    "  rel share root: '%s'\n"
3154                    "  snapdir: '%s'\n"
3155                    "  snapprefix: '%s'\n"
3156                    "  delimiter: '%s'\n"
3157                    "  snapshot base path: '%s'\n"
3158                    "  format: '%s'\n"
3159                    "  use sscanf: %s\n"
3160                    "  snapdirs everywhere: %s\n"
3161                    "  cross mountpoints: %s\n"
3162                    "  fix inodes: %s\n"
3163                    "  sort order: %s\n"
3164                    "",
3165                    handle->conn->connectpath,
3166                    config->mount_point,
3167                    config->rel_connectpath,
3168                    config->snapdir,
3169                    snapprefix,
3170                    config->delimiter,
3171                    config->snapshot_basepath,
3172                    config->gmt_format,
3173                    config->use_sscanf ? "yes" : "no",
3174                    config->snapdirseverywhere ? "yes" : "no",
3175                    config->crossmountpoints ? "yes" : "no",
3176                    config->fixinodes ? "yes" : "no",
3177                    config->sort_order
3178                    ));
3179
3180
3181         SMB_VFS_HANDLE_SET_DATA(handle, priv,
3182                                 NULL, struct shadow_copy2_private,
3183                                 return -1);
3184
3185         return 0;
3186 }
3187
3188 static struct vfs_fn_pointers vfs_shadow_copy2_fns = {
3189         .connect_fn = shadow_copy2_connect,
3190         .disk_free_fn = shadow_copy2_disk_free,
3191         .get_quota_fn = shadow_copy2_get_quota,
3192         .create_dfs_pathat_fn = shadow_copy2_create_dfs_pathat,
3193         .read_dfs_pathat_fn = shadow_copy2_read_dfs_pathat,
3194         .renameat_fn = shadow_copy2_renameat,
3195         .linkat_fn = shadow_copy2_linkat,
3196         .symlinkat_fn = shadow_copy2_symlinkat,
3197         .stat_fn = shadow_copy2_stat,
3198         .lstat_fn = shadow_copy2_lstat,
3199         .fstat_fn = shadow_copy2_fstat,
3200         .openat_fn = shadow_copy2_openat,
3201         .unlinkat_fn = shadow_copy2_unlinkat,
3202         .chmod_fn = shadow_copy2_chmod,
3203         .chdir_fn = shadow_copy2_chdir,
3204         .ntimes_fn = shadow_copy2_ntimes,
3205         .readlinkat_fn = shadow_copy2_readlinkat,
3206         .mknodat_fn = shadow_copy2_mknodat,
3207         .realpath_fn = shadow_copy2_realpath,
3208         .get_nt_acl_at_fn = shadow_copy2_get_nt_acl_at,
3209         .get_shadow_copy_data_fn = shadow_copy2_get_shadow_copy_data,
3210         .mkdirat_fn = shadow_copy2_mkdirat,
3211         .getxattr_fn = shadow_copy2_getxattr,
3212         .getxattrat_send_fn = vfs_not_implemented_getxattrat_send,
3213         .getxattrat_recv_fn = vfs_not_implemented_getxattrat_recv,
3214         .listxattr_fn = shadow_copy2_listxattr,
3215         .removexattr_fn = shadow_copy2_removexattr,
3216         .setxattr_fn = shadow_copy2_setxattr,
3217         .chflags_fn = shadow_copy2_chflags,
3218         .get_real_filename_fn = shadow_copy2_get_real_filename,
3219         .pwrite_fn = shadow_copy2_pwrite,
3220         .pwrite_send_fn = shadow_copy2_pwrite_send,
3221         .pwrite_recv_fn = shadow_copy2_pwrite_recv,
3222         .connectpath_fn = shadow_copy2_connectpath,
3223 };
3224
3225 static_decl_vfs;
3226 NTSTATUS vfs_shadow_copy2_init(TALLOC_CTX *ctx)
3227 {
3228         return smb_register_vfs(SMB_VFS_INTERFACE_VERSION,
3229                                 "shadow_copy2", &vfs_shadow_copy2_fns);
3230 }