s3: VFS: vfs_shadow_copy2. Implement mkdirat().
[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 char *orig_name,
590                                         time_t *ptimestamp,
591                                         char **pstripped,
592                                         char **psnappath,
593                                         bool *_already_converted)
594 {
595         struct tm tm;
596         time_t timestamp = 0;
597         const char *p;
598         char *q;
599         char *stripped = NULL;
600         size_t rest_len, dst_len;
601         struct shadow_copy2_private *priv;
602         ptrdiff_t len_before_gmt;
603         const char *name = orig_name;
604         char *abs_path = NULL;
605         bool ret = true;
606         bool already_converted = false;
607         int err = 0;
608
609         SMB_VFS_HANDLE_GET_DATA(handle, priv, struct shadow_copy2_private,
610                                 return false);
611
612         DEBUG(10, (__location__ ": enter path '%s'\n", name));
613
614         if (_already_converted != NULL) {
615                 *_already_converted = false;
616         }
617
618         abs_path = make_path_absolute(mem_ctx, priv, name);
619         if (abs_path == NULL) {
620                 ret = false;
621                 goto out;
622         }
623         name = abs_path;
624
625         DEBUG(10, (__location__ ": abs path '%s'\n", name));
626
627         err = check_for_converted_path(mem_ctx,
628                                         handle,
629                                         priv,
630                                         abs_path,
631                                         &already_converted,
632                                         psnappath);
633         if (err != 0) {
634                 /* error in conversion. */
635                 ret = false;
636                 goto out;
637         }
638
639         if (already_converted) {
640                 if (_already_converted != NULL) {
641                         *_already_converted = true;
642                 }
643                 goto out;
644         }
645
646         /*
647          * From here we're only looking to strip an
648          * SMB-layer @GMT- token.
649          */
650
651         p = strstr_m(name, "@GMT-");
652         if (p == NULL) {
653                 DEBUG(11, ("@GMT not found\n"));
654                 goto out;
655         }
656         if ((p > name) && (p[-1] != '/')) {
657                 /* the GMT-token does not start a path-component */
658                 DEBUG(10, ("not at start, p=%p, name=%p, p[-1]=%d\n",
659                            p, name, (int)p[-1]));
660                 goto out;
661         }
662
663         len_before_gmt = p - name;
664
665         q = strptime(p, GMT_FORMAT, &tm);
666         if (q == NULL) {
667                 DEBUG(10, ("strptime failed\n"));
668                 goto out;
669         }
670         tm.tm_isdst = -1;
671         timestamp = timegm(&tm);
672         if (timestamp == (time_t)-1) {
673                 DEBUG(10, ("timestamp==-1\n"));
674                 goto out;
675         }
676         if (q[0] == '\0') {
677                 /*
678                  * The name consists of only the GMT token or the GMT
679                  * token is at the end of the path. XP seems to send
680                  * @GMT- at the end under certain circumstances even
681                  * with a path prefix.
682                  */
683                 if (pstripped != NULL) {
684                         if (len_before_gmt > 1) {
685                                 /*
686                                  * There is a path (and not only a slash)
687                                  * before the @GMT-. Remove the trailing
688                                  * slash character.
689                                  */
690                                 len_before_gmt -= 1;
691                         }
692                         stripped = talloc_strndup(mem_ctx, name,
693                                         len_before_gmt);
694                         if (stripped == NULL) {
695                                 ret = false;
696                                 goto out;
697                         }
698                         if (orig_name[0] != '/') {
699                                 if (make_relative_path(priv->shadow_cwd,
700                                                 stripped) == false) {
701                                         DEBUG(10, (__location__ ": path '%s' "
702                                                 "doesn't start with cwd '%s'\n",
703                                                 stripped, priv->shadow_cwd));
704                                                 ret = false;
705                                         errno = ENOENT;
706                                         goto out;
707                                 }
708                         }
709                         *pstripped = stripped;
710                 }
711                 *ptimestamp = timestamp;
712                 goto out;
713         }
714         if (q[0] != '/') {
715                 /*
716                  * It is not a complete path component, i.e. the path
717                  * component continues after the gmt-token.
718                  */
719                 DEBUG(10, ("q[0] = %d\n", (int)q[0]));
720                 goto out;
721         }
722         q += 1;
723
724         rest_len = strlen(q);
725         dst_len = len_before_gmt + rest_len;
726
727         if (pstripped != NULL) {
728                 stripped = talloc_array(mem_ctx, char, dst_len+1);
729                 if (stripped == NULL) {
730                         ret = false;
731                         goto out;
732                 }
733                 if (p > name) {
734                         memcpy(stripped, name, len_before_gmt);
735                 }
736                 if (rest_len > 0) {
737                         memcpy(stripped + len_before_gmt, q, rest_len);
738                 }
739                 stripped[dst_len] = '\0';
740                 if (orig_name[0] != '/') {
741                         if (make_relative_path(priv->shadow_cwd,
742                                         stripped) == false) {
743                                 DEBUG(10, (__location__ ": path '%s' "
744                                         "doesn't start with cwd '%s'\n",
745                                         stripped, priv->shadow_cwd));
746                                 ret = false;
747                                 errno = ENOENT;
748                                 goto out;
749                         }
750                 }
751                 *pstripped = stripped;
752         }
753         *ptimestamp = timestamp;
754         ret = true;
755
756   out:
757         TALLOC_FREE(abs_path);
758         return ret;
759 }
760
761 static bool shadow_copy2_strip_snapshot(TALLOC_CTX *mem_ctx,
762                                         struct vfs_handle_struct *handle,
763                                         const char *orig_name,
764                                         time_t *ptimestamp,
765                                         char **pstripped)
766 {
767         return shadow_copy2_strip_snapshot_internal(mem_ctx,
768                                         handle,
769                                         orig_name,
770                                         ptimestamp,
771                                         pstripped,
772                                         NULL,
773                                         NULL);
774 }
775
776 static bool shadow_copy2_strip_snapshot_converted(TALLOC_CTX *mem_ctx,
777                                         struct vfs_handle_struct *handle,
778                                         const char *orig_name,
779                                         time_t *ptimestamp,
780                                         char **pstripped,
781                                         bool *is_converted)
782 {
783         return shadow_copy2_strip_snapshot_internal(mem_ctx,
784                                         handle,
785                                         orig_name,
786                                         ptimestamp,
787                                         pstripped,
788                                         NULL,
789                                         is_converted);
790 }
791
792 static char *shadow_copy2_find_mount_point(TALLOC_CTX *mem_ctx,
793                                            vfs_handle_struct *handle)
794 {
795         char *path = talloc_strdup(mem_ctx, handle->conn->connectpath);
796         dev_t dev;
797         struct stat st;
798         char *p;
799
800         if (stat(path, &st) != 0) {
801                 talloc_free(path);
802                 return NULL;
803         }
804
805         dev = st.st_dev;
806
807         while ((p = strrchr(path, '/')) && p > path) {
808                 *p = 0;
809                 if (stat(path, &st) != 0) {
810                         talloc_free(path);
811                         return NULL;
812                 }
813                 if (st.st_dev != dev) {
814                         *p = '/';
815                         break;
816                 }
817         }
818
819         return path;
820 }
821
822 /**
823  * Convert from a name as handed in via the SMB layer
824  * and a timestamp into the local path of the snapshot
825  * of the provided file at the provided time.
826  * Also return the path in the snapshot corresponding
827  * to the file's share root.
828  */
829 static char *shadow_copy2_do_convert(TALLOC_CTX *mem_ctx,
830                                      struct vfs_handle_struct *handle,
831                                      const char *name, time_t timestamp,
832                                      size_t *snaproot_len)
833 {
834         struct smb_filename converted_fname;
835         char *result = NULL;
836         size_t *slashes = NULL;
837         unsigned num_slashes;
838         char *path = NULL;
839         size_t pathlen;
840         char *insert = NULL;
841         char *converted = NULL;
842         size_t insertlen, connectlen = 0;
843         int saved_errno = 0;
844         int i;
845         size_t min_offset;
846         struct shadow_copy2_config *config;
847         struct shadow_copy2_private *priv;
848         size_t in_share_offset = 0;
849
850         SMB_VFS_HANDLE_GET_DATA(handle, priv, struct shadow_copy2_private,
851                                 return NULL);
852
853         config = priv->config;
854
855         DEBUG(10, ("converting '%s'\n", name));
856
857         if (!config->snapdirseverywhere) {
858                 int ret;
859                 char *snapshot_path;
860
861                 snapshot_path = shadow_copy2_snapshot_path(talloc_tos(),
862                                                            handle,
863                                                            timestamp);
864                 if (snapshot_path == NULL) {
865                         goto fail;
866                 }
867
868                 if (config->rel_connectpath == NULL) {
869                         converted = talloc_asprintf(mem_ctx, "%s/%s",
870                                                     snapshot_path, name);
871                 } else {
872                         converted = talloc_asprintf(mem_ctx, "%s/%s/%s",
873                                                     snapshot_path,
874                                                     config->rel_connectpath,
875                                                     name);
876                 }
877                 if (converted == NULL) {
878                         goto fail;
879                 }
880
881                 ZERO_STRUCT(converted_fname);
882                 converted_fname.base_name = converted;
883
884                 ret = SMB_VFS_NEXT_LSTAT(handle, &converted_fname);
885                 DEBUG(10, ("Trying[not snapdirseverywhere] %s: %d (%s)\n",
886                            converted,
887                            ret, ret == 0 ? "ok" : strerror(errno)));
888                 if (ret == 0) {
889                         DEBUG(10, ("Found %s\n", converted));
890                         result = converted;
891                         converted = NULL;
892                         if (snaproot_len != NULL) {
893                                 *snaproot_len = strlen(snapshot_path);
894                                 if (config->rel_connectpath != NULL) {
895                                         *snaproot_len +=
896                                             strlen(config->rel_connectpath) + 1;
897                                 }
898                         }
899                         goto fail;
900                 } else {
901                         errno = ENOENT;
902                         goto fail;
903                 }
904                 /* never reached ... */
905         }
906
907         connectlen = strlen(handle->conn->connectpath);
908         if (name[0] == 0) {
909                 path = talloc_strdup(mem_ctx, handle->conn->connectpath);
910         } else {
911                 path = talloc_asprintf(
912                         mem_ctx, "%s/%s", handle->conn->connectpath, name);
913         }
914         if (path == NULL) {
915                 errno = ENOMEM;
916                 goto fail;
917         }
918         pathlen = talloc_get_size(path)-1;
919
920         if (!shadow_copy2_find_slashes(talloc_tos(), path,
921                                        &slashes, &num_slashes)) {
922                 goto fail;
923         }
924
925         insert = shadow_copy2_insert_string(talloc_tos(), handle, timestamp);
926         if (insert == NULL) {
927                 goto fail;
928         }
929         insertlen = talloc_get_size(insert)-1;
930
931         /*
932          * Note: We deliberatly don't expensively initialize the
933          * array with talloc_zero here: Putting zero into
934          * converted[pathlen+insertlen] below is sufficient, because
935          * in the following for loop, the insert string is inserted
936          * at various slash places. So the memory up to position
937          * pathlen+insertlen will always be initialized when the
938          * converted string is used.
939          */
940         converted = talloc_array(mem_ctx, char, pathlen + insertlen + 1);
941         if (converted == NULL) {
942                 goto fail;
943         }
944
945         if (path[pathlen-1] != '/') {
946                 /*
947                  * Append a fake slash to find the snapshot root
948                  */
949                 size_t *tmp;
950                 tmp = talloc_realloc(talloc_tos(), slashes,
951                                      size_t, num_slashes+1);
952                 if (tmp == NULL) {
953                         goto fail;
954                 }
955                 slashes = tmp;
956                 slashes[num_slashes] = pathlen;
957                 num_slashes += 1;
958         }
959
960         min_offset = 0;
961
962         if (!config->crossmountpoints) {
963                 min_offset = strlen(config->mount_point);
964         }
965
966         memcpy(converted, path, pathlen+1);
967         converted[pathlen+insertlen] = '\0';
968
969         ZERO_STRUCT(converted_fname);
970         converted_fname.base_name = converted;
971
972         for (i = num_slashes-1; i>=0; i--) {
973                 int ret;
974                 size_t offset;
975
976                 offset = slashes[i];
977
978                 if (offset < min_offset) {
979                         errno = ENOENT;
980                         goto fail;
981                 }
982
983                 if (offset >= connectlen) {
984                         in_share_offset = offset;
985                 }
986
987                 memcpy(converted+offset, insert, insertlen);
988
989                 offset += insertlen;
990                 memcpy(converted+offset, path + slashes[i],
991                        pathlen - slashes[i]);
992
993                 ret = SMB_VFS_NEXT_LSTAT(handle, &converted_fname);
994
995                 DEBUG(10, ("Trying[snapdirseverywhere] %s: %d (%s)\n",
996                            converted,
997                            ret, ret == 0 ? "ok" : strerror(errno)));
998                 if (ret == 0) {
999                         /* success */
1000                         if (snaproot_len != NULL) {
1001                                 *snaproot_len = in_share_offset + insertlen;
1002                         }
1003                         break;
1004                 }
1005                 if (errno == ENOTDIR) {
1006                         /*
1007                          * This is a valid condition: We appended the
1008                          * .snaphots/@GMT.. to a file name. Just try
1009                          * with the upper levels.
1010                          */
1011                         continue;
1012                 }
1013                 if (errno != ENOENT) {
1014                         /* Other problem than "not found" */
1015                         goto fail;
1016                 }
1017         }
1018
1019         if (i >= 0) {
1020                 /*
1021                  * Found something
1022                  */
1023                 DEBUG(10, ("Found %s\n", converted));
1024                 result = converted;
1025                 converted = NULL;
1026         } else {
1027                 errno = ENOENT;
1028         }
1029 fail:
1030         if (result == NULL) {
1031                 saved_errno = errno;
1032         }
1033         TALLOC_FREE(converted);
1034         TALLOC_FREE(insert);
1035         TALLOC_FREE(slashes);
1036         TALLOC_FREE(path);
1037         if (saved_errno != 0) {
1038                 errno = saved_errno;
1039         }
1040         return result;
1041 }
1042
1043 /**
1044  * Convert from a name as handed in via the SMB layer
1045  * and a timestamp into the local path of the snapshot
1046  * of the provided file at the provided time.
1047  */
1048 static char *shadow_copy2_convert(TALLOC_CTX *mem_ctx,
1049                                   struct vfs_handle_struct *handle,
1050                                   const char *name, time_t timestamp)
1051 {
1052         return shadow_copy2_do_convert(mem_ctx, handle, name, timestamp, NULL);
1053 }
1054
1055 /*
1056   modify a sbuf return to ensure that inodes in the shadow directory
1057   are different from those in the main directory
1058  */
1059 static void convert_sbuf(vfs_handle_struct *handle, const char *fname,
1060                          SMB_STRUCT_STAT *sbuf)
1061 {
1062         struct shadow_copy2_private *priv;
1063
1064         SMB_VFS_HANDLE_GET_DATA(handle, priv, struct shadow_copy2_private,
1065                                 return);
1066
1067         if (priv->config->fixinodes) {
1068                 /* some snapshot systems, like GPFS, return the name
1069                    device:inode for the snapshot files as the current
1070                    files. That breaks the 'restore' button in the shadow copy
1071                    GUI, as the client gets a sharing violation.
1072
1073                    This is a crude way of allowing both files to be
1074                    open at once. It has a slight chance of inode
1075                    number collision, but I can't see a better approach
1076                    without significant VFS changes
1077                 */
1078                 TDB_DATA key = { .dptr = discard_const_p(uint8_t, fname),
1079                                  .dsize = strlen(fname) };
1080                 uint32_t shash;
1081
1082                 shash = tdb_jenkins_hash(&key) & 0xFF000000;
1083                 if (shash == 0) {
1084                         shash = 1;
1085                 }
1086                 sbuf->st_ex_ino ^= shash;
1087         }
1088 }
1089
1090 static DIR *shadow_copy2_opendir(vfs_handle_struct *handle,
1091                         const struct smb_filename *smb_fname,
1092                         const char *mask,
1093                         uint32_t attr)
1094 {
1095         time_t timestamp = 0;
1096         char *stripped = NULL;
1097         DIR *ret;
1098         int saved_errno = 0;
1099         char *conv;
1100         struct smb_filename *conv_smb_fname = NULL;
1101
1102         if (!shadow_copy2_strip_snapshot(talloc_tos(),
1103                                 handle,
1104                                 smb_fname->base_name,
1105                                 &timestamp,
1106                                 &stripped)) {
1107                 return NULL;
1108         }
1109         if (timestamp == 0) {
1110                 return SMB_VFS_NEXT_OPENDIR(handle, smb_fname, mask, attr);
1111         }
1112         conv = shadow_copy2_convert(talloc_tos(), handle, stripped, timestamp);
1113         TALLOC_FREE(stripped);
1114         if (conv == NULL) {
1115                 return NULL;
1116         }
1117         conv_smb_fname = synthetic_smb_fname(talloc_tos(),
1118                                         conv,
1119                                         NULL,
1120                                         NULL,
1121                                         smb_fname->flags);
1122         if (conv_smb_fname == NULL) {
1123                 TALLOC_FREE(conv);
1124                 return NULL;
1125         }
1126         ret = SMB_VFS_NEXT_OPENDIR(handle, conv_smb_fname, mask, attr);
1127         if (ret == NULL) {
1128                 saved_errno = errno;
1129         }
1130         TALLOC_FREE(conv);
1131         TALLOC_FREE(conv_smb_fname);
1132         if (saved_errno != 0) {
1133                 errno = saved_errno;
1134         }
1135         return ret;
1136 }
1137
1138 static int shadow_copy2_renameat(vfs_handle_struct *handle,
1139                                 files_struct *srcfsp,
1140                                 const struct smb_filename *smb_fname_src,
1141                                 files_struct *dstfsp,
1142                                 const struct smb_filename *smb_fname_dst)
1143 {
1144         time_t timestamp_src = 0;
1145         time_t timestamp_dst = 0;
1146         char *snappath_src = NULL;
1147         char *snappath_dst = NULL;
1148
1149         if (!shadow_copy2_strip_snapshot_internal(talloc_tos(), handle,
1150                                          smb_fname_src->base_name,
1151                                          &timestamp_src, NULL, &snappath_src,
1152                                          NULL)) {
1153                 return -1;
1154         }
1155         if (!shadow_copy2_strip_snapshot_internal(talloc_tos(), handle,
1156                                          smb_fname_dst->base_name,
1157                                          &timestamp_dst, NULL, &snappath_dst,
1158                                          NULL)) {
1159                 return -1;
1160         }
1161         if (timestamp_src != 0) {
1162                 errno = EXDEV;
1163                 return -1;
1164         }
1165         if (timestamp_dst != 0) {
1166                 errno = EROFS;
1167                 return -1;
1168         }
1169         /*
1170          * Don't allow rename on already converted paths.
1171          */
1172         if (snappath_src != NULL) {
1173                 errno = EXDEV;
1174                 return -1;
1175         }
1176         if (snappath_dst != NULL) {
1177                 errno = EROFS;
1178                 return -1;
1179         }
1180         return SMB_VFS_NEXT_RENAMEAT(handle,
1181                         srcfsp,
1182                         smb_fname_src,
1183                         dstfsp,
1184                         smb_fname_dst);
1185 }
1186
1187 static int shadow_copy2_symlinkat(vfs_handle_struct *handle,
1188                         const char *link_contents,
1189                         struct files_struct *dirfsp,
1190                         const struct smb_filename *new_smb_fname)
1191 {
1192         time_t timestamp_old = 0;
1193         time_t timestamp_new = 0;
1194         char *snappath_old = NULL;
1195         char *snappath_new = NULL;
1196
1197         if (!shadow_copy2_strip_snapshot_internal(talloc_tos(),
1198                                 handle,
1199                                 link_contents,
1200                                 &timestamp_old,
1201                                 NULL,
1202                                 &snappath_old,
1203                                 NULL)) {
1204                 return -1;
1205         }
1206         if (!shadow_copy2_strip_snapshot_internal(talloc_tos(),
1207                                 handle,
1208                                 new_smb_fname->base_name,
1209                                 &timestamp_new,
1210                                 NULL,
1211                                 &snappath_new,
1212                                 NULL)) {
1213                 return -1;
1214         }
1215         if ((timestamp_old != 0) || (timestamp_new != 0)) {
1216                 errno = EROFS;
1217                 return -1;
1218         }
1219         /*
1220          * Don't allow symlinks on already converted paths.
1221          */
1222         if ((snappath_old != NULL) || (snappath_new != NULL)) {
1223                 errno = EROFS;
1224                 return -1;
1225         }
1226         return SMB_VFS_NEXT_SYMLINKAT(handle,
1227                                 link_contents,
1228                                 dirfsp,
1229                                 new_smb_fname);
1230 }
1231
1232 static int shadow_copy2_linkat(vfs_handle_struct *handle,
1233                         files_struct *srcfsp,
1234                         const struct smb_filename *old_smb_fname,
1235                         files_struct *dstfsp,
1236                         const struct smb_filename *new_smb_fname,
1237                         int flags)
1238 {
1239         time_t timestamp_old = 0;
1240         time_t timestamp_new = 0;
1241         char *snappath_old = NULL;
1242         char *snappath_new = NULL;
1243
1244         if (!shadow_copy2_strip_snapshot_internal(talloc_tos(),
1245                                 handle,
1246                                 old_smb_fname->base_name,
1247                                 &timestamp_old,
1248                                 NULL,
1249                                 &snappath_old,
1250                                 NULL)) {
1251                 return -1;
1252         }
1253         if (!shadow_copy2_strip_snapshot_internal(talloc_tos(),
1254                                 handle,
1255                                 new_smb_fname->base_name,
1256                                 &timestamp_new,
1257                                 NULL,
1258                                 &snappath_new,
1259                                 NULL)) {
1260                 return -1;
1261         }
1262         if ((timestamp_old != 0) || (timestamp_new != 0)) {
1263                 errno = EROFS;
1264                 return -1;
1265         }
1266         /*
1267          * Don't allow links on already converted paths.
1268          */
1269         if ((snappath_old != NULL) || (snappath_new != NULL)) {
1270                 errno = EROFS;
1271                 return -1;
1272         }
1273         return SMB_VFS_NEXT_LINKAT(handle,
1274                         srcfsp,
1275                         old_smb_fname,
1276                         dstfsp,
1277                         new_smb_fname,
1278                         flags);
1279 }
1280
1281 static int shadow_copy2_stat(vfs_handle_struct *handle,
1282                              struct smb_filename *smb_fname)
1283 {
1284         time_t timestamp = 0;
1285         char *stripped = NULL;
1286         char *tmp;
1287         int saved_errno = 0;
1288         int ret;
1289
1290         if (!shadow_copy2_strip_snapshot(talloc_tos(), handle,
1291                                          smb_fname->base_name,
1292                                          &timestamp, &stripped)) {
1293                 return -1;
1294         }
1295         if (timestamp == 0) {
1296                 return SMB_VFS_NEXT_STAT(handle, smb_fname);
1297         }
1298
1299         tmp = smb_fname->base_name;
1300         smb_fname->base_name = shadow_copy2_convert(
1301                 talloc_tos(), handle, stripped, timestamp);
1302         TALLOC_FREE(stripped);
1303
1304         if (smb_fname->base_name == NULL) {
1305                 smb_fname->base_name = tmp;
1306                 return -1;
1307         }
1308
1309         ret = SMB_VFS_NEXT_STAT(handle, smb_fname);
1310         if (ret == -1) {
1311                 saved_errno = errno;
1312         }
1313
1314         TALLOC_FREE(smb_fname->base_name);
1315         smb_fname->base_name = tmp;
1316
1317         if (ret == 0) {
1318                 convert_sbuf(handle, smb_fname->base_name, &smb_fname->st);
1319         }
1320         if (saved_errno != 0) {
1321                 errno = saved_errno;
1322         }
1323         return ret;
1324 }
1325
1326 static int shadow_copy2_lstat(vfs_handle_struct *handle,
1327                               struct smb_filename *smb_fname)
1328 {
1329         time_t timestamp = 0;
1330         char *stripped = NULL;
1331         char *tmp;
1332         int saved_errno = 0;
1333         int ret;
1334
1335         if (!shadow_copy2_strip_snapshot(talloc_tos(), handle,
1336                                          smb_fname->base_name,
1337                                          &timestamp, &stripped)) {
1338                 return -1;
1339         }
1340         if (timestamp == 0) {
1341                 return SMB_VFS_NEXT_LSTAT(handle, smb_fname);
1342         }
1343
1344         tmp = smb_fname->base_name;
1345         smb_fname->base_name = shadow_copy2_convert(
1346                 talloc_tos(), handle, stripped, timestamp);
1347         TALLOC_FREE(stripped);
1348
1349         if (smb_fname->base_name == NULL) {
1350                 smb_fname->base_name = tmp;
1351                 return -1;
1352         }
1353
1354         ret = SMB_VFS_NEXT_LSTAT(handle, smb_fname);
1355         if (ret == -1) {
1356                 saved_errno = errno;
1357         }
1358
1359         TALLOC_FREE(smb_fname->base_name);
1360         smb_fname->base_name = tmp;
1361
1362         if (ret == 0) {
1363                 convert_sbuf(handle, smb_fname->base_name, &smb_fname->st);
1364         }
1365         if (saved_errno != 0) {
1366                 errno = saved_errno;
1367         }
1368         return ret;
1369 }
1370
1371 static int shadow_copy2_fstat(vfs_handle_struct *handle, files_struct *fsp,
1372                               SMB_STRUCT_STAT *sbuf)
1373 {
1374         time_t timestamp = 0;
1375         struct smb_filename *orig_smb_fname = NULL;
1376         struct smb_filename vss_smb_fname;
1377         struct smb_filename *orig_base_smb_fname = NULL;
1378         struct smb_filename vss_base_smb_fname;
1379         char *stripped = NULL;
1380         int saved_errno = 0;
1381         bool ok;
1382         int ret;
1383
1384         ok = shadow_copy2_strip_snapshot(talloc_tos(), handle,
1385                                          fsp->fsp_name->base_name,
1386                                          &timestamp, &stripped);
1387         if (!ok) {
1388                 return -1;
1389         }
1390
1391         if (timestamp == 0) {
1392                 TALLOC_FREE(stripped);
1393                 return SMB_VFS_NEXT_FSTAT(handle, fsp, sbuf);
1394         }
1395
1396         vss_smb_fname = *fsp->fsp_name;
1397         vss_smb_fname.base_name = shadow_copy2_convert(talloc_tos(),
1398                                                        handle,
1399                                                        stripped,
1400                                                        timestamp);
1401         TALLOC_FREE(stripped);
1402         if (vss_smb_fname.base_name == NULL) {
1403                 return -1;
1404         }
1405
1406         orig_smb_fname = fsp->fsp_name;
1407         fsp->fsp_name = &vss_smb_fname;
1408
1409         if (fsp->base_fsp != NULL) {
1410                 vss_base_smb_fname = *fsp->base_fsp->fsp_name;
1411                 vss_base_smb_fname.base_name = vss_smb_fname.base_name;
1412                 orig_base_smb_fname = fsp->base_fsp->fsp_name;
1413                 fsp->base_fsp->fsp_name = &vss_base_smb_fname;
1414         }
1415
1416         ret = SMB_VFS_NEXT_FSTAT(handle, fsp, sbuf);
1417         fsp->fsp_name = orig_smb_fname;
1418         if (fsp->base_fsp != NULL) {
1419                 fsp->base_fsp->fsp_name = orig_base_smb_fname;
1420         }
1421         if (ret == -1) {
1422                 saved_errno = errno;
1423         }
1424
1425         if (ret == 0) {
1426                 convert_sbuf(handle, fsp->fsp_name->base_name, sbuf);
1427         }
1428         if (saved_errno != 0) {
1429                 errno = saved_errno;
1430         }
1431         return ret;
1432 }
1433
1434 static int shadow_copy2_open(vfs_handle_struct *handle,
1435                              struct smb_filename *smb_fname, files_struct *fsp,
1436                              int flags, mode_t mode)
1437 {
1438         time_t timestamp = 0;
1439         char *stripped = NULL;
1440         char *tmp;
1441         bool is_converted = false;
1442         int saved_errno = 0;
1443         int ret;
1444
1445         if (!shadow_copy2_strip_snapshot_converted(talloc_tos(), handle,
1446                                          smb_fname->base_name,
1447                                          &timestamp, &stripped,
1448                                          &is_converted)) {
1449                 return -1;
1450         }
1451         if (timestamp == 0) {
1452                 if (is_converted) {
1453                         /*
1454                          * Just pave over the user requested mode and use
1455                          * O_RDONLY. Later attempts by the client to write on
1456                          * the handle will fail in the pwrite() syscall with
1457                          * EINVAL which we carefully map to EROFS. In sum, this
1458                          * matches Windows behaviour.
1459                          */
1460                         flags = O_RDONLY;
1461                 }
1462                 return SMB_VFS_NEXT_OPEN(handle, smb_fname, fsp, flags, mode);
1463         }
1464
1465         tmp = smb_fname->base_name;
1466         smb_fname->base_name = shadow_copy2_convert(
1467                 talloc_tos(), handle, stripped, timestamp);
1468         TALLOC_FREE(stripped);
1469
1470         if (smb_fname->base_name == NULL) {
1471                 smb_fname->base_name = tmp;
1472                 return -1;
1473         }
1474
1475         /*
1476          * Just pave over the user requested mode and use O_RDONLY. Later
1477          * attempts by the client to write on the handle will fail in the
1478          * pwrite() syscall with EINVAL which we carefully map to EROFS. In sum,
1479          * this matches Windows behaviour.
1480          */
1481         flags = O_RDONLY;
1482
1483         ret = SMB_VFS_NEXT_OPEN(handle, smb_fname, fsp, flags, mode);
1484         if (ret == -1) {
1485                 saved_errno = errno;
1486         }
1487
1488         TALLOC_FREE(smb_fname->base_name);
1489         smb_fname->base_name = tmp;
1490
1491         if (saved_errno != 0) {
1492                 errno = saved_errno;
1493         }
1494         return ret;
1495 }
1496
1497 static int shadow_copy2_unlink(vfs_handle_struct *handle,
1498                                const struct smb_filename *smb_fname)
1499 {
1500         time_t timestamp = 0;
1501
1502         if (!shadow_copy2_strip_snapshot(talloc_tos(), handle,
1503                                          smb_fname->base_name,
1504                                          &timestamp, NULL)) {
1505                 return -1;
1506         }
1507         if (timestamp != 0) {
1508                 errno = EROFS;
1509                 return -1;
1510         }
1511         return SMB_VFS_NEXT_UNLINK(handle, smb_fname);
1512 }
1513
1514 static int shadow_copy2_chmod(vfs_handle_struct *handle,
1515                         const struct smb_filename *smb_fname,
1516                         mode_t mode)
1517 {
1518         time_t timestamp = 0;
1519
1520         if (!shadow_copy2_strip_snapshot(talloc_tos(),
1521                                 handle,
1522                                 smb_fname->base_name,
1523                                 &timestamp,
1524                                 NULL)) {
1525                 return -1;
1526         }
1527         if (timestamp != 0) {
1528                 errno = EROFS;
1529                 return -1;
1530         }
1531         return SMB_VFS_NEXT_CHMOD(handle, smb_fname, mode);
1532 }
1533
1534 static int shadow_copy2_chown(vfs_handle_struct *handle,
1535                         const struct smb_filename *smb_fname,
1536                         uid_t uid,
1537                         gid_t gid)
1538 {
1539         time_t timestamp = 0;
1540
1541         if (!shadow_copy2_strip_snapshot(talloc_tos(),
1542                                 handle,
1543                                 smb_fname->base_name,
1544                                 &timestamp,
1545                                 NULL)) {
1546                 return -1;
1547         }
1548         if (timestamp != 0) {
1549                 errno = EROFS;
1550                 return -1;
1551         }
1552         return SMB_VFS_NEXT_CHOWN(handle, smb_fname, uid, gid);
1553 }
1554
1555 static void store_cwd_data(vfs_handle_struct *handle,
1556                                 const char *connectpath)
1557 {
1558         struct shadow_copy2_private *priv = NULL;
1559         struct smb_filename *cwd_fname = NULL;
1560
1561         SMB_VFS_HANDLE_GET_DATA(handle, priv, struct shadow_copy2_private,
1562                                 return);
1563
1564         TALLOC_FREE(priv->shadow_cwd);
1565         cwd_fname = SMB_VFS_NEXT_GETWD(handle, talloc_tos());
1566         if (cwd_fname == NULL) {
1567                 smb_panic("getwd failed\n");
1568         }
1569         DBG_DEBUG("shadow cwd = %s\n", cwd_fname->base_name);
1570         priv->shadow_cwd = talloc_strdup(priv, cwd_fname->base_name);
1571         TALLOC_FREE(cwd_fname);
1572         if (priv->shadow_cwd == NULL) {
1573                 smb_panic("talloc failed\n");
1574         }
1575         TALLOC_FREE(priv->shadow_connectpath);
1576         if (connectpath) {
1577                 DBG_DEBUG("shadow conectpath = %s\n", connectpath);
1578                 priv->shadow_connectpath = talloc_strdup(priv, connectpath);
1579                 if (priv->shadow_connectpath == NULL) {
1580                         smb_panic("talloc failed\n");
1581                 }
1582         }
1583 }
1584
1585 static int shadow_copy2_chdir(vfs_handle_struct *handle,
1586                                const struct smb_filename *smb_fname)
1587 {
1588         time_t timestamp = 0;
1589         char *stripped = NULL;
1590         char *snappath = NULL;
1591         int ret = -1;
1592         int saved_errno = 0;
1593         char *conv = NULL;
1594         size_t rootpath_len = 0;
1595         struct smb_filename *conv_smb_fname = NULL;
1596
1597         if (!shadow_copy2_strip_snapshot_internal(talloc_tos(),
1598                                         handle,
1599                                         smb_fname->base_name,
1600                                         &timestamp,
1601                                         &stripped,
1602                                         &snappath,
1603                                         NULL)) {
1604                 return -1;
1605         }
1606         if (stripped != NULL) {
1607                 conv = shadow_copy2_do_convert(talloc_tos(),
1608                                                 handle,
1609                                                 stripped,
1610                                                 timestamp,
1611                                                 &rootpath_len);
1612                 TALLOC_FREE(stripped);
1613                 if (conv == NULL) {
1614                         return -1;
1615                 }
1616                 conv_smb_fname = synthetic_smb_fname(talloc_tos(),
1617                                         conv,
1618                                         NULL,
1619                                         NULL,
1620                                         smb_fname->flags);
1621         } else {
1622                 conv_smb_fname = cp_smb_filename(talloc_tos(), smb_fname);
1623         }
1624
1625         if (conv_smb_fname == NULL) {
1626                 TALLOC_FREE(conv);
1627                 errno = ENOMEM;
1628                 return -1;
1629         }
1630
1631         ret = SMB_VFS_NEXT_CHDIR(handle, conv_smb_fname);
1632         if (ret == -1) {
1633                 saved_errno = errno;
1634         }
1635
1636         if (ret == 0) {
1637                 if (conv != NULL && rootpath_len != 0) {
1638                         conv[rootpath_len] = '\0';
1639                 } else if (snappath != 0) {
1640                         TALLOC_FREE(conv);
1641                         conv = snappath;
1642                 }
1643                 store_cwd_data(handle, conv);
1644         }
1645
1646         TALLOC_FREE(stripped);
1647         TALLOC_FREE(conv);
1648         TALLOC_FREE(conv_smb_fname);
1649
1650         if (saved_errno != 0) {
1651                 errno = saved_errno;
1652         }
1653         return ret;
1654 }
1655
1656 static int shadow_copy2_ntimes(vfs_handle_struct *handle,
1657                                const struct smb_filename *smb_fname,
1658                                struct smb_file_time *ft)
1659 {
1660         time_t timestamp = 0;
1661
1662         if (!shadow_copy2_strip_snapshot(talloc_tos(), handle,
1663                                          smb_fname->base_name,
1664                                          &timestamp, NULL)) {
1665                 return -1;
1666         }
1667         if (timestamp != 0) {
1668                 errno = EROFS;
1669                 return -1;
1670         }
1671         return SMB_VFS_NEXT_NTIMES(handle, smb_fname, ft);
1672 }
1673
1674 static int shadow_copy2_readlinkat(vfs_handle_struct *handle,
1675                                 files_struct *dirfsp,
1676                                 const struct smb_filename *smb_fname,
1677                                 char *buf,
1678                                 size_t bufsiz)
1679 {
1680         time_t timestamp = 0;
1681         char *stripped = NULL;
1682         int saved_errno = 0;
1683         int ret;
1684         struct smb_filename *conv = NULL;
1685
1686         if (!shadow_copy2_strip_snapshot(talloc_tos(), handle,
1687                                          smb_fname->base_name,
1688                                          &timestamp, &stripped)) {
1689                 return -1;
1690         }
1691         if (timestamp == 0) {
1692                 return SMB_VFS_NEXT_READLINKAT(handle,
1693                                 dirfsp,
1694                                 smb_fname,
1695                                 buf,
1696                                 bufsiz);
1697         }
1698         conv = cp_smb_filename(talloc_tos(), smb_fname);
1699         if (conv == NULL) {
1700                 TALLOC_FREE(stripped);
1701                 errno = ENOMEM;
1702                 return -1;
1703         }
1704         conv->base_name = shadow_copy2_convert(
1705                 conv, handle, stripped, timestamp);
1706         TALLOC_FREE(stripped);
1707         if (conv->base_name == NULL) {
1708                 return -1;
1709         }
1710         ret = SMB_VFS_NEXT_READLINKAT(handle,
1711                                 dirfsp,
1712                                 conv,
1713                                 buf,
1714                                 bufsiz);
1715         if (ret == -1) {
1716                 saved_errno = errno;
1717         }
1718         TALLOC_FREE(conv);
1719         if (saved_errno != 0) {
1720                 errno = saved_errno;
1721         }
1722         return ret;
1723 }
1724
1725 static int shadow_copy2_mknodat(vfs_handle_struct *handle,
1726                         files_struct *dirfsp,
1727                         const struct smb_filename *smb_fname,
1728                         mode_t mode,
1729                         SMB_DEV_T dev)
1730 {
1731         time_t timestamp = 0;
1732
1733         if (!shadow_copy2_strip_snapshot(talloc_tos(), handle,
1734                                          smb_fname->base_name,
1735                                          &timestamp, NULL)) {
1736                 return -1;
1737         }
1738         if (timestamp != 0) {
1739                 errno = EROFS;
1740                 return -1;
1741         }
1742         return SMB_VFS_NEXT_MKNODAT(handle,
1743                         dirfsp,
1744                         smb_fname,
1745                         mode,
1746                         dev);
1747 }
1748
1749 static struct smb_filename *shadow_copy2_realpath(vfs_handle_struct *handle,
1750                                 TALLOC_CTX *ctx,
1751                                 const struct smb_filename *smb_fname)
1752 {
1753         time_t timestamp = 0;
1754         char *stripped = NULL;
1755         struct smb_filename *result_fname = NULL;
1756         struct smb_filename *conv_fname = NULL;
1757         int saved_errno = 0;
1758
1759         if (!shadow_copy2_strip_snapshot(talloc_tos(), handle,
1760                                 smb_fname->base_name,
1761                                 &timestamp, &stripped)) {
1762                 goto done;
1763         }
1764         if (timestamp == 0) {
1765                 return SMB_VFS_NEXT_REALPATH(handle, ctx, smb_fname);
1766         }
1767
1768         conv_fname = cp_smb_filename(talloc_tos(), smb_fname);
1769         if (conv_fname == NULL) {
1770                 goto done;
1771         }
1772         conv_fname->base_name = shadow_copy2_convert(
1773                 conv_fname, handle, stripped, timestamp);
1774         if (conv_fname->base_name == NULL) {
1775                 goto done;
1776         }
1777
1778         result_fname = SMB_VFS_NEXT_REALPATH(handle, ctx, conv_fname);
1779
1780 done:
1781         if (result_fname == NULL) {
1782                 saved_errno = errno;
1783         }
1784         TALLOC_FREE(conv_fname);
1785         TALLOC_FREE(stripped);
1786         if (saved_errno != 0) {
1787                 errno = saved_errno;
1788         }
1789         return result_fname;
1790 }
1791
1792 /**
1793  * Check whether a given directory contains a
1794  * snapshot directory as direct subdirectory.
1795  * If yes, return the path of the snapshot-subdir,
1796  * otherwise return NULL.
1797  */
1798 static char *have_snapdir(struct vfs_handle_struct *handle,
1799                           const char *path)
1800 {
1801         struct smb_filename smb_fname;
1802         int ret;
1803         struct shadow_copy2_private *priv;
1804
1805         SMB_VFS_HANDLE_GET_DATA(handle, priv, struct shadow_copy2_private,
1806                                 return NULL);
1807
1808         ZERO_STRUCT(smb_fname);
1809         smb_fname.base_name = talloc_asprintf(talloc_tos(), "%s/%s",
1810                                               path, priv->config->snapdir);
1811         if (smb_fname.base_name == NULL) {
1812                 return NULL;
1813         }
1814
1815         ret = SMB_VFS_NEXT_STAT(handle, &smb_fname);
1816         if ((ret == 0) && (S_ISDIR(smb_fname.st.st_ex_mode))) {
1817                 return smb_fname.base_name;
1818         }
1819         TALLOC_FREE(smb_fname.base_name);
1820         return NULL;
1821 }
1822
1823 static bool check_access_snapdir(struct vfs_handle_struct *handle,
1824                                 const char *path)
1825 {
1826         struct smb_filename smb_fname;
1827         int ret;
1828         NTSTATUS status;
1829
1830         ZERO_STRUCT(smb_fname);
1831         smb_fname.base_name = talloc_asprintf(talloc_tos(),
1832                                                 "%s",
1833                                                 path);
1834         if (smb_fname.base_name == NULL) {
1835                 return false;
1836         }
1837
1838         ret = SMB_VFS_NEXT_STAT(handle, &smb_fname);
1839         if (ret != 0 || !S_ISDIR(smb_fname.st.st_ex_mode)) {
1840                 TALLOC_FREE(smb_fname.base_name);
1841                 return false;
1842         }
1843
1844         status = smbd_check_access_rights(handle->conn,
1845                                         &smb_fname,
1846                                         false,
1847                                         SEC_DIR_LIST);
1848         if (!NT_STATUS_IS_OK(status)) {
1849                 DEBUG(0,("user does not have list permission "
1850                         "on snapdir %s\n",
1851                         smb_fname.base_name));
1852                 TALLOC_FREE(smb_fname.base_name);
1853                 return false;
1854         }
1855         TALLOC_FREE(smb_fname.base_name);
1856         return true;
1857 }
1858
1859 /**
1860  * Find the snapshot directory (if any) for the given
1861  * filename (which is relative to the share).
1862  */
1863 static const char *shadow_copy2_find_snapdir(TALLOC_CTX *mem_ctx,
1864                                              struct vfs_handle_struct *handle,
1865                                              struct smb_filename *smb_fname)
1866 {
1867         char *path, *p;
1868         const char *snapdir;
1869         struct shadow_copy2_config *config;
1870         struct shadow_copy2_private *priv;
1871
1872         SMB_VFS_HANDLE_GET_DATA(handle, priv, struct shadow_copy2_private,
1873                                 return NULL);
1874
1875         config = priv->config;
1876
1877         /*
1878          * If the non-snapdisrseverywhere mode, we should not search!
1879          */
1880         if (!config->snapdirseverywhere) {
1881                 return config->snapshot_basepath;
1882         }
1883
1884         path = talloc_asprintf(mem_ctx, "%s/%s",
1885                                handle->conn->connectpath,
1886                                smb_fname->base_name);
1887         if (path == NULL) {
1888                 return NULL;
1889         }
1890
1891         snapdir = have_snapdir(handle, path);
1892         if (snapdir != NULL) {
1893                 TALLOC_FREE(path);
1894                 return snapdir;
1895         }
1896
1897         while ((p = strrchr(path, '/')) && (p > path)) {
1898
1899                 p[0] = '\0';
1900
1901                 snapdir = have_snapdir(handle, path);
1902                 if (snapdir != NULL) {
1903                         TALLOC_FREE(path);
1904                         return snapdir;
1905                 }
1906         }
1907         TALLOC_FREE(path);
1908         return NULL;
1909 }
1910
1911 static bool shadow_copy2_snapshot_to_gmt(vfs_handle_struct *handle,
1912                                          const char *name,
1913                                          char *gmt, size_t gmt_len)
1914 {
1915         struct tm timestamp;
1916         time_t timestamp_t;
1917         unsigned long int timestamp_long;
1918         const char *fmt;
1919         struct shadow_copy2_config *config;
1920         struct shadow_copy2_private *priv;
1921         char *tmpstr = NULL;
1922         char *tmp = NULL;
1923         bool converted = false;
1924         int ret = -1;
1925
1926         SMB_VFS_HANDLE_GET_DATA(handle, priv, struct shadow_copy2_private,
1927                                 return NULL);
1928
1929         config = priv->config;
1930
1931         fmt = config->gmt_format;
1932
1933         /*
1934          * If regex is provided, then we will have to parse the
1935          * filename which will contain both the prefix and the time format.
1936          * e.g. <prefix><delimiter><time_format>
1937          */
1938         if (priv->snaps->regex != NULL) {
1939                 tmpstr = talloc_strdup(talloc_tos(), name);
1940                 /* point "name" to the time format */
1941                 name = strstr(name, priv->config->delimiter);
1942                 if (name == NULL) {
1943                         goto done;
1944                 }
1945                 /* Extract the prefix */
1946                 tmp = strstr(tmpstr, priv->config->delimiter);
1947                 if (tmp == NULL) {
1948                         goto done;
1949                 }
1950                 *tmp = '\0';
1951
1952                 /* Parse regex */
1953                 ret = regexec(priv->snaps->regex, tmpstr, 0, NULL, 0);
1954                 if (ret) {
1955                         DBG_DEBUG("shadow_copy2_snapshot_to_gmt: "
1956                                   "no regex match for %s\n", tmpstr);
1957                         goto done;
1958                 }
1959         }
1960
1961         ZERO_STRUCT(timestamp);
1962         if (config->use_sscanf) {
1963                 if (sscanf(name, fmt, &timestamp_long) != 1) {
1964                         DEBUG(10, ("shadow_copy2_snapshot_to_gmt: "
1965                                    "no sscanf match %s: %s\n",
1966                                    fmt, name));
1967                         goto done;
1968                 }
1969                 timestamp_t = timestamp_long;
1970                 gmtime_r(&timestamp_t, &timestamp);
1971         } else {
1972                 if (strptime(name, fmt, &timestamp) == NULL) {
1973                         DEBUG(10, ("shadow_copy2_snapshot_to_gmt: "
1974                                    "no match %s: %s\n",
1975                                    fmt, name));
1976                         goto done;
1977                 }
1978                 DEBUG(10, ("shadow_copy2_snapshot_to_gmt: match %s: %s\n",
1979                            fmt, name));
1980                 
1981                 if (config->use_localtime) {
1982                         timestamp.tm_isdst = -1;
1983                         timestamp_t = mktime(&timestamp);
1984                         gmtime_r(&timestamp_t, &timestamp);
1985                 }
1986         }
1987
1988         strftime(gmt, gmt_len, GMT_FORMAT, &timestamp);
1989         converted = true;
1990
1991 done:
1992         TALLOC_FREE(tmpstr);
1993         return converted;
1994 }
1995
1996 static int shadow_copy2_label_cmp_asc(const void *x, const void *y)
1997 {
1998         return strncmp((const char *)x, (const char *)y, sizeof(SHADOW_COPY_LABEL));
1999 }
2000
2001 static int shadow_copy2_label_cmp_desc(const void *x, const void *y)
2002 {
2003         return -strncmp((const char *)x, (const char *)y, sizeof(SHADOW_COPY_LABEL));
2004 }
2005
2006 /*
2007   sort the shadow copy data in ascending or descending order
2008  */
2009 static void shadow_copy2_sort_data(vfs_handle_struct *handle,
2010                                    struct shadow_copy_data *shadow_copy2_data)
2011 {
2012         int (*cmpfunc)(const void *, const void *);
2013         const char *sort;
2014         struct shadow_copy2_private *priv;
2015
2016         SMB_VFS_HANDLE_GET_DATA(handle, priv, struct shadow_copy2_private,
2017                                 return);
2018
2019         sort = priv->config->sort_order;
2020         if (sort == NULL) {
2021                 return;
2022         }
2023
2024         if (strcmp(sort, "asc") == 0) {
2025                 cmpfunc = shadow_copy2_label_cmp_asc;
2026         } else if (strcmp(sort, "desc") == 0) {
2027                 cmpfunc = shadow_copy2_label_cmp_desc;
2028         } else {
2029                 return;
2030         }
2031
2032         if (shadow_copy2_data && shadow_copy2_data->num_volumes > 0 &&
2033             shadow_copy2_data->labels)
2034         {
2035                 TYPESAFE_QSORT(shadow_copy2_data->labels,
2036                                shadow_copy2_data->num_volumes,
2037                                cmpfunc);
2038         }
2039 }
2040
2041 static int shadow_copy2_get_shadow_copy_data(
2042         vfs_handle_struct *handle, files_struct *fsp,
2043         struct shadow_copy_data *shadow_copy2_data,
2044         bool labels)
2045 {
2046         DIR *p;
2047         const char *snapdir;
2048         struct smb_filename *snapdir_smb_fname = NULL;
2049         struct dirent *d;
2050         TALLOC_CTX *tmp_ctx = talloc_stackframe();
2051         struct shadow_copy2_private *priv = NULL;
2052         struct shadow_copy2_snapentry *tmpentry = NULL;
2053         bool get_snaplist = false;
2054         bool access_granted = false;
2055         int ret = -1;
2056
2057         snapdir = shadow_copy2_find_snapdir(tmp_ctx, handle, fsp->fsp_name);
2058         if (snapdir == NULL) {
2059                 DEBUG(0,("shadow:snapdir not found for %s in get_shadow_copy_data\n",
2060                          handle->conn->connectpath));
2061                 errno = EINVAL;
2062                 goto done;
2063         }
2064
2065         access_granted = check_access_snapdir(handle, snapdir);
2066         if (!access_granted) {
2067                 DEBUG(0,("access denied on listing snapdir %s\n", snapdir));
2068                 errno = EACCES;
2069                 goto done;
2070         }
2071
2072         snapdir_smb_fname = synthetic_smb_fname(talloc_tos(),
2073                                         snapdir,
2074                                         NULL,
2075                                         NULL,
2076                                         fsp->fsp_name->flags);
2077         if (snapdir_smb_fname == NULL) {
2078                 errno = ENOMEM;
2079                 goto done;
2080         }
2081
2082         p = SMB_VFS_NEXT_OPENDIR(handle, snapdir_smb_fname, NULL, 0);
2083
2084         if (!p) {
2085                 DEBUG(2,("shadow_copy2: SMB_VFS_NEXT_OPENDIR() failed for '%s'"
2086                          " - %s\n", snapdir, strerror(errno)));
2087                 errno = ENOSYS;
2088                 goto done;
2089         }
2090
2091         if (shadow_copy2_data != NULL) {
2092                 shadow_copy2_data->num_volumes = 0;
2093                 shadow_copy2_data->labels      = NULL;
2094         }
2095
2096         SMB_VFS_HANDLE_GET_DATA(handle, priv, struct shadow_copy2_private,
2097                                 goto done);
2098
2099         /*
2100          * Normally this function is called twice once with labels = false and
2101          * then with labels = true. When labels is false it will return the
2102          * number of volumes so that the caller can allocate memory for that
2103          * many labels. Therefore to eliminate snaplist both the times it is
2104          * good to check if labels is set or not.
2105          *
2106          * shadow_copy2_data is NULL when we only want to update the list and
2107          * don't want any labels.
2108          */
2109         if ((priv->snaps->regex != NULL) && (labels || shadow_copy2_data == NULL)) {
2110                 get_snaplist = true;
2111                 /* Reset the global snaplist */
2112                 shadow_copy2_delete_snaplist(priv);
2113
2114                 /* Set the current time as snaplist update time */
2115                 time(&(priv->snaps->fetch_time));
2116         }
2117
2118         while ((d = SMB_VFS_NEXT_READDIR(handle, p, NULL))) {
2119                 char snapshot[GMT_NAME_LEN+1];
2120                 SHADOW_COPY_LABEL *tlabels;
2121
2122                 /*
2123                  * ignore names not of the right form in the snapshot
2124                  * directory
2125                  */
2126                 if (!shadow_copy2_snapshot_to_gmt(
2127                             handle, d->d_name,
2128                             snapshot, sizeof(snapshot))) {
2129
2130                         DEBUG(6, ("shadow_copy2_get_shadow_copy_data: "
2131                                   "ignoring %s\n", d->d_name));
2132                         continue;
2133                 }
2134                 DEBUG(6,("shadow_copy2_get_shadow_copy_data: %s -> %s\n",
2135                          d->d_name, snapshot));
2136
2137                 if (get_snaplist) {
2138                         /*
2139                          * Create a snap entry for each successful
2140                          * pattern match.
2141                          */
2142                         tmpentry = shadow_copy2_create_snapentry(priv);
2143                         if (tmpentry == NULL) {
2144                                 DBG_ERR("talloc_zero() failed\n");
2145                                 goto done;
2146                         }
2147                         tmpentry->snapname = talloc_strdup(tmpentry, d->d_name);
2148                         tmpentry->time_fmt = talloc_strdup(tmpentry, snapshot);
2149                 }
2150
2151                 if (shadow_copy2_data == NULL) {
2152                         continue;
2153                 }
2154
2155                 if (!labels) {
2156                         /* the caller doesn't want the labels */
2157                         shadow_copy2_data->num_volumes++;
2158                         continue;
2159                 }
2160
2161                 tlabels = talloc_realloc(shadow_copy2_data,
2162                                          shadow_copy2_data->labels,
2163                                          SHADOW_COPY_LABEL,
2164                                          shadow_copy2_data->num_volumes+1);
2165                 if (tlabels == NULL) {
2166                         DEBUG(0,("shadow_copy2: out of memory\n"));
2167                         SMB_VFS_NEXT_CLOSEDIR(handle, p);
2168                         goto done;
2169                 }
2170
2171                 strlcpy(tlabels[shadow_copy2_data->num_volumes], snapshot,
2172                         sizeof(*tlabels));
2173
2174                 shadow_copy2_data->num_volumes++;
2175                 shadow_copy2_data->labels = tlabels;
2176         }
2177
2178         SMB_VFS_NEXT_CLOSEDIR(handle,p);
2179
2180         shadow_copy2_sort_data(handle, shadow_copy2_data);
2181         ret = 0;
2182
2183 done:
2184         TALLOC_FREE(tmp_ctx);
2185         return ret;
2186 }
2187
2188 static NTSTATUS shadow_copy2_fget_nt_acl(vfs_handle_struct *handle,
2189                                         struct files_struct *fsp,
2190                                         uint32_t security_info,
2191                                          TALLOC_CTX *mem_ctx,
2192                                         struct security_descriptor **ppdesc)
2193 {
2194         time_t timestamp = 0;
2195         char *stripped = NULL;
2196         NTSTATUS status;
2197         char *conv;
2198         struct smb_filename *smb_fname = NULL;
2199
2200         if (!shadow_copy2_strip_snapshot(talloc_tos(), handle,
2201                                          fsp->fsp_name->base_name,
2202                                          &timestamp, &stripped)) {
2203                 return map_nt_error_from_unix(errno);
2204         }
2205         if (timestamp == 0) {
2206                 return SMB_VFS_NEXT_FGET_NT_ACL(handle, fsp, security_info,
2207                                                 mem_ctx,
2208                                                 ppdesc);
2209         }
2210         conv = shadow_copy2_convert(talloc_tos(), handle, stripped, timestamp);
2211         TALLOC_FREE(stripped);
2212         if (conv == NULL) {
2213                 return map_nt_error_from_unix(errno);
2214         }
2215         smb_fname = synthetic_smb_fname(talloc_tos(),
2216                                         conv,
2217                                         NULL,
2218                                         NULL,
2219                                         fsp->fsp_name->flags);
2220         if (smb_fname == NULL) {
2221                 TALLOC_FREE(conv);
2222                 return NT_STATUS_NO_MEMORY;
2223         }
2224
2225         status = SMB_VFS_NEXT_GET_NT_ACL(handle, smb_fname, security_info,
2226                                          mem_ctx, ppdesc);
2227         TALLOC_FREE(conv);
2228         TALLOC_FREE(smb_fname);
2229         return status;
2230 }
2231
2232 static NTSTATUS shadow_copy2_get_nt_acl(vfs_handle_struct *handle,
2233                                         const struct smb_filename *smb_fname,
2234                                         uint32_t security_info,
2235                                         TALLOC_CTX *mem_ctx,
2236                                         struct security_descriptor **ppdesc)
2237 {
2238         time_t timestamp = 0;
2239         char *stripped = NULL;
2240         NTSTATUS status;
2241         char *conv;
2242         struct smb_filename *conv_smb_fname = NULL;
2243
2244         if (!shadow_copy2_strip_snapshot(talloc_tos(),
2245                                         handle,
2246                                         smb_fname->base_name,
2247                                         &timestamp,
2248                                         &stripped)) {
2249                 return map_nt_error_from_unix(errno);
2250         }
2251         if (timestamp == 0) {
2252                 return SMB_VFS_NEXT_GET_NT_ACL(handle, smb_fname, security_info,
2253                                                mem_ctx, ppdesc);
2254         }
2255         conv = shadow_copy2_convert(talloc_tos(), handle, stripped, timestamp);
2256         TALLOC_FREE(stripped);
2257         if (conv == NULL) {
2258                 return map_nt_error_from_unix(errno);
2259         }
2260         conv_smb_fname = synthetic_smb_fname(talloc_tos(),
2261                                         conv,
2262                                         NULL,
2263                                         NULL,
2264                                         smb_fname->flags);
2265         if (conv_smb_fname == NULL) {
2266                 TALLOC_FREE(conv);
2267                 return NT_STATUS_NO_MEMORY;
2268         }
2269         status = SMB_VFS_NEXT_GET_NT_ACL(handle, conv_smb_fname, security_info,
2270                                          mem_ctx, ppdesc);
2271         TALLOC_FREE(conv);
2272         TALLOC_FREE(conv_smb_fname);
2273         return status;
2274 }
2275
2276 static int shadow_copy2_mkdir(vfs_handle_struct *handle,
2277                                 const struct smb_filename *smb_fname,
2278                                 mode_t mode)
2279 {
2280         time_t timestamp = 0;
2281
2282         if (!shadow_copy2_strip_snapshot(talloc_tos(),
2283                                         handle,
2284                                         smb_fname->base_name,
2285                                         &timestamp,
2286                                         NULL)) {
2287                 return -1;
2288         }
2289         if (timestamp != 0) {
2290                 errno = EROFS;
2291                 return -1;
2292         }
2293         return SMB_VFS_NEXT_MKDIR(handle, smb_fname, mode);
2294 }
2295
2296 static int shadow_copy2_mkdirat(vfs_handle_struct *handle,
2297                                 struct files_struct *dirfsp,
2298                                 const struct smb_filename *smb_fname,
2299                                 mode_t mode)
2300 {
2301         time_t timestamp = 0;
2302
2303         if (!shadow_copy2_strip_snapshot(talloc_tos(),
2304                                         handle,
2305                                         smb_fname->base_name,
2306                                         &timestamp,
2307                                         NULL)) {
2308                 return -1;
2309         }
2310         if (timestamp != 0) {
2311                 errno = EROFS;
2312                 return -1;
2313         }
2314         return SMB_VFS_NEXT_MKDIRAT(handle,
2315                         dirfsp,
2316                         smb_fname,
2317                         mode);
2318 }
2319
2320 static int shadow_copy2_rmdir(vfs_handle_struct *handle,
2321                                 const struct smb_filename *smb_fname)
2322 {
2323         time_t timestamp = 0;
2324
2325         if (!shadow_copy2_strip_snapshot(talloc_tos(),
2326                                         handle,
2327                                         smb_fname->base_name,
2328                                         &timestamp,
2329                                         NULL)) {
2330                 return -1;
2331         }
2332         if (timestamp != 0) {
2333                 errno = EROFS;
2334                 return -1;
2335         }
2336         return SMB_VFS_NEXT_RMDIR(handle, smb_fname);
2337 }
2338
2339 static int shadow_copy2_chflags(vfs_handle_struct *handle,
2340                                 const struct smb_filename *smb_fname,
2341                                 unsigned int flags)
2342 {
2343         time_t timestamp = 0;
2344
2345         if (!shadow_copy2_strip_snapshot(talloc_tos(),
2346                                         handle,
2347                                         smb_fname->base_name,
2348                                         &timestamp,
2349                                         NULL)) {
2350                 return -1;
2351         }
2352         if (timestamp != 0) {
2353                 errno = EROFS;
2354                 return -1;
2355         }
2356         return SMB_VFS_NEXT_CHFLAGS(handle, smb_fname, flags);
2357 }
2358
2359 static ssize_t shadow_copy2_getxattr(vfs_handle_struct *handle,
2360                                 const struct smb_filename *smb_fname,
2361                                 const char *aname,
2362                                 void *value,
2363                                 size_t size)
2364 {
2365         time_t timestamp = 0;
2366         char *stripped = NULL;
2367         ssize_t ret;
2368         int saved_errno = 0;
2369         char *conv;
2370         struct smb_filename *conv_smb_fname = NULL;
2371
2372         if (!shadow_copy2_strip_snapshot(talloc_tos(),
2373                                 handle,
2374                                 smb_fname->base_name,
2375                                 &timestamp,
2376                                 &stripped)) {
2377                 return -1;
2378         }
2379         if (timestamp == 0) {
2380                 return SMB_VFS_NEXT_GETXATTR(handle, smb_fname, aname, value,
2381                                              size);
2382         }
2383         conv = shadow_copy2_convert(talloc_tos(), handle, stripped, timestamp);
2384         TALLOC_FREE(stripped);
2385         if (conv == NULL) {
2386                 return -1;
2387         }
2388
2389         conv_smb_fname = synthetic_smb_fname(talloc_tos(),
2390                                         conv,
2391                                         NULL,
2392                                         NULL,
2393                                         smb_fname->flags);
2394         if (conv_smb_fname == NULL) {
2395                 TALLOC_FREE(conv);
2396                 return -1;
2397         }
2398
2399         ret = SMB_VFS_NEXT_GETXATTR(handle, conv_smb_fname, aname, value, size);
2400         if (ret == -1) {
2401                 saved_errno = errno;
2402         }
2403         TALLOC_FREE(conv_smb_fname);
2404         TALLOC_FREE(conv);
2405         if (saved_errno != 0) {
2406                 errno = saved_errno;
2407         }
2408         return ret;
2409 }
2410
2411 static ssize_t shadow_copy2_listxattr(struct vfs_handle_struct *handle,
2412                                       const struct smb_filename *smb_fname,
2413                                       char *list, size_t size)
2414 {
2415         time_t timestamp = 0;
2416         char *stripped = NULL;
2417         ssize_t ret;
2418         int saved_errno = 0;
2419         char *conv;
2420         struct smb_filename *conv_smb_fname = NULL;
2421
2422         if (!shadow_copy2_strip_snapshot(talloc_tos(),
2423                                 handle,
2424                                 smb_fname->base_name,
2425                                 &timestamp,
2426                                 &stripped)) {
2427                 return -1;
2428         }
2429         if (timestamp == 0) {
2430                 return SMB_VFS_NEXT_LISTXATTR(handle, smb_fname, list, size);
2431         }
2432         conv = shadow_copy2_convert(talloc_tos(), handle, stripped, timestamp);
2433         TALLOC_FREE(stripped);
2434         if (conv == NULL) {
2435                 return -1;
2436         }
2437         conv_smb_fname = synthetic_smb_fname(talloc_tos(),
2438                                         conv,
2439                                         NULL,
2440                                         NULL,
2441                                         smb_fname->flags);
2442         if (conv_smb_fname == NULL) {
2443                 TALLOC_FREE(conv);
2444                 return -1;
2445         }
2446         ret = SMB_VFS_NEXT_LISTXATTR(handle, conv_smb_fname, list, size);
2447         if (ret == -1) {
2448                 saved_errno = errno;
2449         }
2450         TALLOC_FREE(conv_smb_fname);
2451         TALLOC_FREE(conv);
2452         if (saved_errno != 0) {
2453                 errno = saved_errno;
2454         }
2455         return ret;
2456 }
2457
2458 static int shadow_copy2_removexattr(vfs_handle_struct *handle,
2459                                 const struct smb_filename *smb_fname,
2460                                 const char *aname)
2461 {
2462         time_t timestamp = 0;
2463
2464         if (!shadow_copy2_strip_snapshot(talloc_tos(),
2465                                 handle,
2466                                 smb_fname->base_name,
2467                                 &timestamp,
2468                                 NULL)) {
2469                 return -1;
2470         }
2471         if (timestamp != 0) {
2472                 errno = EROFS;
2473                 return -1;
2474         }
2475         return SMB_VFS_NEXT_REMOVEXATTR(handle, smb_fname, aname);
2476 }
2477
2478 static int shadow_copy2_setxattr(struct vfs_handle_struct *handle,
2479                                  const struct smb_filename *smb_fname,
2480                                  const char *aname, const void *value,
2481                                  size_t size, int flags)
2482 {
2483         time_t timestamp = 0;
2484
2485         if (!shadow_copy2_strip_snapshot(talloc_tos(),
2486                                 handle,
2487                                 smb_fname->base_name,
2488                                 &timestamp,
2489                                 NULL)) {
2490                 return -1;
2491         }
2492         if (timestamp != 0) {
2493                 errno = EROFS;
2494                 return -1;
2495         }
2496         return SMB_VFS_NEXT_SETXATTR(handle, smb_fname,
2497                                 aname, value, size, flags);
2498 }
2499
2500 static int shadow_copy2_get_real_filename(struct vfs_handle_struct *handle,
2501                                           const char *path,
2502                                           const char *name,
2503                                           TALLOC_CTX *mem_ctx,
2504                                           char **found_name)
2505 {
2506         time_t timestamp = 0;
2507         char *stripped = NULL;
2508         ssize_t ret;
2509         int saved_errno = 0;
2510         char *conv;
2511
2512         DEBUG(10, ("shadow_copy2_get_real_filename called for path=[%s], "
2513                    "name=[%s]\n", path, name));
2514
2515         if (!shadow_copy2_strip_snapshot(talloc_tos(), handle, path,
2516                                          &timestamp, &stripped)) {
2517                 DEBUG(10, ("shadow_copy2_strip_snapshot failed\n"));
2518                 return -1;
2519         }
2520         if (timestamp == 0) {
2521                 DEBUG(10, ("timestamp == 0\n"));
2522                 return SMB_VFS_NEXT_GET_REAL_FILENAME(handle, path, name,
2523                                                       mem_ctx, found_name);
2524         }
2525         conv = shadow_copy2_convert(talloc_tos(), handle, stripped, timestamp);
2526         TALLOC_FREE(stripped);
2527         if (conv == NULL) {
2528                 DEBUG(10, ("shadow_copy2_convert failed\n"));
2529                 return -1;
2530         }
2531         DEBUG(10, ("Calling NEXT_GET_REAL_FILE_NAME for conv=[%s], "
2532                    "name=[%s]\n", conv, name));
2533         ret = SMB_VFS_NEXT_GET_REAL_FILENAME(handle, conv, name,
2534                                              mem_ctx, found_name);
2535         DEBUG(10, ("NEXT_REAL_FILE_NAME returned %d\n", (int)ret));
2536         if (ret == -1) {
2537                 saved_errno = errno;
2538         }
2539         TALLOC_FREE(conv);
2540         if (saved_errno != 0) {
2541                 errno = saved_errno;
2542         }
2543         return ret;
2544 }
2545
2546 static const char *shadow_copy2_connectpath(struct vfs_handle_struct *handle,
2547                                         const struct smb_filename *smb_fname_in)
2548 {
2549         time_t timestamp = 0;
2550         char *stripped = NULL;
2551         char *tmp = NULL;
2552         const char *fname = smb_fname_in->base_name;
2553         struct smb_filename smb_fname = {0};
2554         struct smb_filename *result_fname = NULL;
2555         char *result = NULL;
2556         char *parent_dir = NULL;
2557         int saved_errno = 0;
2558         size_t rootpath_len = 0;
2559         struct shadow_copy2_private *priv = NULL;
2560
2561         SMB_VFS_HANDLE_GET_DATA(handle, priv, struct shadow_copy2_private,
2562                                 return NULL);
2563
2564         DBG_DEBUG("Calc connect path for [%s]\n", fname);
2565
2566         if (priv->shadow_connectpath != NULL) {
2567                 DBG_DEBUG("cached connect path is [%s]\n",
2568                         priv->shadow_connectpath);
2569                 return priv->shadow_connectpath;
2570         }
2571
2572         if (!shadow_copy2_strip_snapshot(talloc_tos(), handle, fname,
2573                                          &timestamp, &stripped)) {
2574                 goto done;
2575         }
2576         if (timestamp == 0) {
2577                 return SMB_VFS_NEXT_CONNECTPATH(handle, smb_fname_in);
2578         }
2579
2580         tmp = shadow_copy2_do_convert(talloc_tos(), handle, stripped, timestamp,
2581                                       &rootpath_len);
2582         if (tmp == NULL) {
2583                 if (errno != ENOENT) {
2584                         goto done;
2585                 }
2586
2587                 /*
2588                  * If the converted path does not exist, and converting
2589                  * the parent yields something that does exist, then
2590                  * this path refers to something that has not been
2591                  * created yet, relative to the parent path.
2592                  * The snapshot finding is relative to the parent.
2593                  * (usually snapshots are read/only but this is not
2594                  * necessarily true).
2595                  * This code also covers getting a wildcard in the
2596                  * last component, because this function is called
2597                  * prior to sanitizing the path, and in SMB1 we may
2598                  * get wildcards in path names.
2599                  */
2600                 if (!parent_dirname(talloc_tos(), stripped, &parent_dir,
2601                                     NULL)) {
2602                         errno = ENOMEM;
2603                         goto done;
2604                 }
2605
2606                 tmp = shadow_copy2_do_convert(talloc_tos(), handle, parent_dir,
2607                                               timestamp, &rootpath_len);
2608                 if (tmp == NULL) {
2609                         goto done;
2610                 }
2611         }
2612
2613         DBG_DEBUG("converted path is [%s] root path is [%.*s]\n", tmp,
2614                   (int)rootpath_len, tmp);
2615
2616         tmp[rootpath_len] = '\0';
2617         smb_fname = (struct smb_filename) { .base_name = tmp };
2618
2619         result_fname = SMB_VFS_NEXT_REALPATH(handle, priv, &smb_fname);
2620         if (result_fname == NULL) {
2621                 goto done;
2622         }
2623
2624         /*
2625          * SMB_VFS_NEXT_REALPATH returns a talloc'ed string.
2626          * Don't leak memory.
2627          */
2628         TALLOC_FREE(priv->shadow_realpath);
2629         priv->shadow_realpath = result_fname;
2630         result = priv->shadow_realpath->base_name;
2631
2632         DBG_DEBUG("connect path is [%s]\n", result);
2633
2634 done:
2635         if (result == NULL) {
2636                 saved_errno = errno;
2637         }
2638         TALLOC_FREE(tmp);
2639         TALLOC_FREE(stripped);
2640         TALLOC_FREE(parent_dir);
2641         if (saved_errno != 0) {
2642                 errno = saved_errno;
2643         }
2644         return result;
2645 }
2646
2647 static uint64_t shadow_copy2_disk_free(vfs_handle_struct *handle,
2648                                 const struct smb_filename *smb_fname,
2649                                 uint64_t *bsize,
2650                                 uint64_t *dfree,
2651                                 uint64_t *dsize)
2652 {
2653         time_t timestamp = 0;
2654         char *stripped = NULL;
2655         int saved_errno = 0;
2656         char *conv = NULL;
2657         struct smb_filename *conv_smb_fname = NULL;
2658         uint64_t ret = (uint64_t)-1;
2659
2660         if (!shadow_copy2_strip_snapshot(talloc_tos(),
2661                                 handle,
2662                                 smb_fname->base_name,
2663                                 &timestamp,
2664                                 &stripped)) {
2665                 return (uint64_t)-1;
2666         }
2667         if (timestamp == 0) {
2668                 return SMB_VFS_NEXT_DISK_FREE(handle, smb_fname,
2669                                               bsize, dfree, dsize);
2670         }
2671         conv = shadow_copy2_convert(talloc_tos(), handle, stripped, timestamp);
2672         TALLOC_FREE(stripped);
2673         if (conv == NULL) {
2674                 return (uint64_t)-1;
2675         }
2676         conv_smb_fname = synthetic_smb_fname(talloc_tos(),
2677                                         conv,
2678                                         NULL,
2679                                         NULL,
2680                                         smb_fname->flags);
2681         if (conv_smb_fname == NULL) {
2682                 TALLOC_FREE(conv);
2683                 return (uint64_t)-1;
2684         }
2685         ret = SMB_VFS_NEXT_DISK_FREE(handle, conv_smb_fname,
2686                                 bsize, dfree, dsize);
2687         if (ret == (uint64_t)-1) {
2688                 saved_errno = errno;
2689         }
2690         TALLOC_FREE(conv);
2691         TALLOC_FREE(conv_smb_fname);
2692         if (saved_errno != 0) {
2693                 errno = saved_errno;
2694         }
2695         return ret;
2696 }
2697
2698 static int shadow_copy2_get_quota(vfs_handle_struct *handle,
2699                                 const struct smb_filename *smb_fname,
2700                                 enum SMB_QUOTA_TYPE qtype,
2701                                 unid_t id,
2702                                 SMB_DISK_QUOTA *dq)
2703 {
2704         time_t timestamp = 0;
2705         char *stripped = NULL;
2706         int ret;
2707         int saved_errno = 0;
2708         char *conv;
2709         struct smb_filename *conv_smb_fname = NULL;
2710
2711         if (!shadow_copy2_strip_snapshot(talloc_tos(),
2712                                 handle,
2713                                 smb_fname->base_name,
2714                                 &timestamp,
2715                                 &stripped)) {
2716                 return -1;
2717         }
2718         if (timestamp == 0) {
2719                 return SMB_VFS_NEXT_GET_QUOTA(handle, smb_fname, qtype, id, dq);
2720         }
2721
2722         conv = shadow_copy2_convert(talloc_tos(), handle, stripped, timestamp);
2723         TALLOC_FREE(stripped);
2724         if (conv == NULL) {
2725                 return -1;
2726         }
2727         conv_smb_fname = synthetic_smb_fname(talloc_tos(),
2728                                         conv,
2729                                         NULL,
2730                                         NULL,
2731                                         smb_fname->flags);
2732         if (conv_smb_fname == NULL) {
2733                 TALLOC_FREE(conv);
2734                 return -1;
2735         }
2736         ret = SMB_VFS_NEXT_GET_QUOTA(handle, conv_smb_fname, qtype, id, dq);
2737
2738         if (ret == -1) {
2739                 saved_errno = errno;
2740         }
2741         TALLOC_FREE(conv);
2742         TALLOC_FREE(conv_smb_fname);
2743         if (saved_errno != 0) {
2744                 errno = saved_errno;
2745         }
2746
2747         return ret;
2748 }
2749
2750 static ssize_t shadow_copy2_pwrite(vfs_handle_struct *handle,
2751                                    files_struct *fsp,
2752                                    const void *data,
2753                                    size_t n,
2754                                    off_t offset)
2755 {
2756         ssize_t nwritten;
2757
2758         nwritten = SMB_VFS_NEXT_PWRITE(handle, fsp, data, n, offset);
2759         if (nwritten == -1) {
2760                 if (errno == EBADF && fsp->can_write) {
2761                         errno = EROFS;
2762                 }
2763         }
2764
2765         return nwritten;
2766 }
2767
2768 struct shadow_copy2_pwrite_state {
2769         vfs_handle_struct *handle;
2770         files_struct *fsp;
2771         ssize_t ret;
2772         struct vfs_aio_state vfs_aio_state;
2773 };
2774
2775 static void shadow_copy2_pwrite_done(struct tevent_req *subreq);
2776
2777 static struct tevent_req *shadow_copy2_pwrite_send(
2778         struct vfs_handle_struct *handle, TALLOC_CTX *mem_ctx,
2779         struct tevent_context *ev, struct files_struct *fsp,
2780         const void *data, size_t n, off_t offset)
2781 {
2782         struct tevent_req *req = NULL, *subreq = NULL;
2783         struct shadow_copy2_pwrite_state *state = NULL;
2784
2785         req = tevent_req_create(mem_ctx, &state,
2786                                 struct shadow_copy2_pwrite_state);
2787         if (req == NULL) {
2788                 return NULL;
2789         }
2790         state->handle = handle;
2791         state->fsp = fsp;
2792
2793         subreq = SMB_VFS_NEXT_PWRITE_SEND(state,
2794                                           ev,
2795                                           handle,
2796                                           fsp,
2797                                           data,
2798                                           n,
2799                                           offset);
2800         if (tevent_req_nomem(subreq, req)) {
2801                 return tevent_req_post(req, ev);
2802         }
2803         tevent_req_set_callback(subreq, shadow_copy2_pwrite_done, req);
2804
2805         return req;
2806 }
2807
2808 static void shadow_copy2_pwrite_done(struct tevent_req *subreq)
2809 {
2810         struct tevent_req *req = tevent_req_callback_data(
2811                 subreq, struct tevent_req);
2812         struct shadow_copy2_pwrite_state *state = tevent_req_data(
2813                 req, struct shadow_copy2_pwrite_state);
2814
2815         state->ret = SMB_VFS_PWRITE_RECV(subreq, &state->vfs_aio_state);
2816         TALLOC_FREE(subreq);
2817         if (state->ret == -1) {
2818                 tevent_req_error(req, state->vfs_aio_state.error);
2819                 return;
2820         }
2821
2822         tevent_req_done(req);
2823 }
2824
2825 static ssize_t shadow_copy2_pwrite_recv(struct tevent_req *req,
2826                                           struct vfs_aio_state *vfs_aio_state)
2827 {
2828         struct shadow_copy2_pwrite_state *state = tevent_req_data(
2829                 req, struct shadow_copy2_pwrite_state);
2830
2831         if (tevent_req_is_unix_error(req, &vfs_aio_state->error)) {
2832                 if ((vfs_aio_state->error == EBADF) &&
2833                     state->fsp->can_write)
2834                 {
2835                         vfs_aio_state->error = EROFS;
2836                         errno = EROFS;
2837                 }
2838                 return -1;
2839         }
2840
2841         *vfs_aio_state = state->vfs_aio_state;
2842         return state->ret;
2843 }
2844
2845 static int shadow_copy2_connect(struct vfs_handle_struct *handle,
2846                                 const char *service, const char *user)
2847 {
2848         struct shadow_copy2_config *config;
2849         struct shadow_copy2_private *priv;
2850         int ret;
2851         const char *snapdir;
2852         const char *snapprefix = NULL;
2853         const char *delimiter;
2854         const char *gmt_format;
2855         const char *sort_order;
2856         const char *basedir = NULL;
2857         const char *snapsharepath = NULL;
2858         const char *mount_point;
2859
2860         DEBUG(10, (__location__ ": cnum[%u], connectpath[%s]\n",
2861                    (unsigned)handle->conn->cnum,
2862                    handle->conn->connectpath));
2863
2864         ret = SMB_VFS_NEXT_CONNECT(handle, service, user);
2865         if (ret < 0) {
2866                 return ret;
2867         }
2868
2869         priv = talloc_zero(handle->conn, struct shadow_copy2_private);
2870         if (priv == NULL) {
2871                 DBG_ERR("talloc_zero() failed\n");
2872                 errno = ENOMEM;
2873                 return -1;
2874         }
2875
2876         priv->snaps = talloc_zero(priv, struct shadow_copy2_snaplist_info);
2877         if (priv->snaps == NULL) {
2878                 DBG_ERR("talloc_zero() failed\n");
2879                 errno = ENOMEM;
2880                 return -1;
2881         }
2882
2883         config = talloc_zero(priv, struct shadow_copy2_config);
2884         if (config == NULL) {
2885                 DEBUG(0, ("talloc_zero() failed\n"));
2886                 errno = ENOMEM;
2887                 return -1;
2888         }
2889
2890         priv->config = config;
2891
2892         gmt_format = lp_parm_const_string(SNUM(handle->conn),
2893                                           "shadow", "format",
2894                                           GMT_FORMAT);
2895         config->gmt_format = talloc_strdup(config, gmt_format);
2896         if (config->gmt_format == NULL) {
2897                 DEBUG(0, ("talloc_strdup() failed\n"));
2898                 errno = ENOMEM;
2899                 return -1;
2900         }
2901
2902         /* config->gmt_format must not contain a path separator. */
2903         if (strchr(config->gmt_format, '/') != NULL) {
2904                 DEBUG(0, ("shadow:format %s must not contain a /"
2905                         "character. Unable to initialize module.\n",
2906                         config->gmt_format));
2907                 errno = EINVAL;
2908                 return -1;
2909         }
2910
2911         config->use_sscanf = lp_parm_bool(SNUM(handle->conn),
2912                                           "shadow", "sscanf", false);
2913
2914         config->use_localtime = lp_parm_bool(SNUM(handle->conn),
2915                                              "shadow", "localtime",
2916                                              false);
2917
2918         snapdir = lp_parm_const_string(SNUM(handle->conn),
2919                                        "shadow", "snapdir",
2920                                        ".snapshots");
2921         config->snapdir = talloc_strdup(config, snapdir);
2922         if (config->snapdir == NULL) {
2923                 DEBUG(0, ("talloc_strdup() failed\n"));
2924                 errno = ENOMEM;
2925                 return -1;
2926         }
2927
2928         snapprefix = lp_parm_const_string(SNUM(handle->conn),
2929                                        "shadow", "snapprefix",
2930                                        NULL);
2931         if (snapprefix != NULL) {
2932                 priv->snaps->regex = talloc_zero(priv->snaps, regex_t);
2933                 if (priv->snaps->regex == NULL) {
2934                         DBG_ERR("talloc_zero() failed\n");
2935                         errno = ENOMEM;
2936                         return -1;
2937                 }
2938
2939                 /* pre-compute regex rule for matching pattern later */
2940                 ret = regcomp(priv->snaps->regex, snapprefix, 0);
2941                 if (ret) {
2942                         DBG_ERR("Failed to create regex object\n");
2943                         return -1;
2944                 }
2945         }
2946
2947         delimiter = lp_parm_const_string(SNUM(handle->conn),
2948                                        "shadow", "delimiter",
2949                                        "_GMT");
2950         if (delimiter != NULL) {
2951                 priv->config->delimiter = talloc_strdup(priv->config, delimiter);
2952                 if (priv->config->delimiter == NULL) {
2953                         DBG_ERR("talloc_strdup() failed\n");
2954                         errno = ENOMEM;
2955                         return -1;
2956                 }
2957         }
2958
2959         config->snapdirseverywhere = lp_parm_bool(SNUM(handle->conn),
2960                                                   "shadow",
2961                                                   "snapdirseverywhere",
2962                                                   false);
2963
2964         config->crossmountpoints = lp_parm_bool(SNUM(handle->conn),
2965                                                 "shadow", "crossmountpoints",
2966                                                 false);
2967
2968         if (config->crossmountpoints && !config->snapdirseverywhere) {
2969                 DBG_WARNING("Warning: 'crossmountpoints' depends on "
2970                             "'snapdirseverywhere'. Disabling crossmountpoints.\n");
2971         }
2972
2973         config->fixinodes = lp_parm_bool(SNUM(handle->conn),
2974                                          "shadow", "fixinodes",
2975                                          false);
2976
2977         sort_order = lp_parm_const_string(SNUM(handle->conn),
2978                                           "shadow", "sort", "desc");
2979         config->sort_order = talloc_strdup(config, sort_order);
2980         if (config->sort_order == NULL) {
2981                 DEBUG(0, ("talloc_strdup() failed\n"));
2982                 errno = ENOMEM;
2983                 return -1;
2984         }
2985
2986         mount_point = lp_parm_const_string(SNUM(handle->conn),
2987                                            "shadow", "mountpoint", NULL);
2988         if (mount_point != NULL) {
2989                 if (mount_point[0] != '/') {
2990                         DEBUG(1, (__location__ " Warning: 'mountpoint' is "
2991                                   "relative ('%s'), but it has to be an "
2992                                   "absolute path. Ignoring provided value.\n",
2993                                   mount_point));
2994                         mount_point = NULL;
2995                 } else {
2996                         char *p;
2997                         p = strstr(handle->conn->connectpath, mount_point);
2998                         if (p != handle->conn->connectpath) {
2999                                 DBG_WARNING("Warning: the share root (%s) is "
3000                                             "not a subdirectory of the "
3001                                             "specified mountpoint (%s). "
3002                                             "Ignoring provided value.\n",
3003                                             handle->conn->connectpath,
3004                                             mount_point);
3005                                 mount_point = NULL;
3006                         }
3007                 }
3008         }
3009
3010         if (mount_point != NULL) {
3011                 config->mount_point = talloc_strdup(config, mount_point);
3012                 if (config->mount_point == NULL) {
3013                         DEBUG(0, (__location__ " talloc_strdup() failed\n"));
3014                         return -1;
3015                 }
3016         } else {
3017                 config->mount_point = shadow_copy2_find_mount_point(config,
3018                                                                     handle);
3019                 if (config->mount_point == NULL) {
3020                         DBG_WARNING("shadow_copy2_find_mount_point "
3021                                     "of the share root '%s' failed: %s\n",
3022                                     handle->conn->connectpath, strerror(errno));
3023                         return -1;
3024                 }
3025         }
3026
3027         basedir = lp_parm_const_string(SNUM(handle->conn),
3028                                        "shadow", "basedir", NULL);
3029
3030         if (basedir != NULL) {
3031                 if (basedir[0] != '/') {
3032                         DEBUG(1, (__location__ " Warning: 'basedir' is "
3033                                   "relative ('%s'), but it has to be an "
3034                                   "absolute path. Disabling basedir.\n",
3035                                   basedir));
3036                         basedir = NULL;
3037                 } else {
3038                         char *p;
3039                         p = strstr(basedir, config->mount_point);
3040                         if (p != basedir) {
3041                                 DEBUG(1, ("Warning: basedir (%s) is not a "
3042                                           "subdirectory of the share root's "
3043                                           "mount point (%s). "
3044                                           "Disabling basedir\n",
3045                                           basedir, config->mount_point));
3046                                 basedir = NULL;
3047                         }
3048                 }
3049         }
3050
3051         if (config->snapdirseverywhere && basedir != NULL) {
3052                 DEBUG(1, (__location__ " Warning: 'basedir' is incompatible "
3053                           "with 'snapdirseverywhere'. Disabling basedir.\n"));
3054                 basedir = NULL;
3055         }
3056
3057         snapsharepath = lp_parm_const_string(SNUM(handle->conn), "shadow",
3058                                              "snapsharepath", NULL);
3059         if (snapsharepath != NULL) {
3060                 if (snapsharepath[0] == '/') {
3061                         DBG_WARNING("Warning: 'snapsharepath' is "
3062                                     "absolute ('%s'), but it has to be a "
3063                                     "relative path. Disabling snapsharepath.\n",
3064                                     snapsharepath);
3065                         snapsharepath = NULL;
3066                 }
3067                 if (config->snapdirseverywhere && snapsharepath != NULL) {
3068                         DBG_WARNING("Warning: 'snapsharepath' is incompatible "
3069                                     "with 'snapdirseverywhere'. Disabling "
3070                                     "snapsharepath.\n");
3071                         snapsharepath = NULL;
3072                 }
3073         }
3074
3075         if (basedir != NULL && snapsharepath != NULL) {
3076                 DBG_WARNING("Warning: 'snapsharepath' is incompatible with "
3077                             "'basedir'. Disabling snapsharepath\n");
3078                 snapsharepath = NULL;
3079         }
3080
3081         if (snapsharepath != NULL) {
3082                 config->rel_connectpath = talloc_strdup(config, snapsharepath);
3083                 if (config->rel_connectpath == NULL) {
3084                         DBG_ERR("talloc_strdup() failed\n");
3085                         errno = ENOMEM;
3086                         return -1;
3087                 }
3088         }
3089
3090         if (basedir == NULL) {
3091                 basedir = config->mount_point;
3092         }
3093
3094         if (config->rel_connectpath == NULL &&
3095             strlen(basedir) < strlen(handle->conn->connectpath)) {
3096                 config->rel_connectpath = talloc_strdup(config,
3097                         handle->conn->connectpath + strlen(basedir));
3098                 if (config->rel_connectpath == NULL) {
3099                         DEBUG(0, ("talloc_strdup() failed\n"));
3100                         errno = ENOMEM;
3101                         return -1;
3102                 }
3103         }
3104
3105         if (config->snapdir[0] == '/') {
3106                 config->snapdir_absolute = true;
3107
3108                 if (config->snapdirseverywhere == true) {
3109                         DEBUG(1, (__location__ " Warning: An absolute snapdir "
3110                                   "is incompatible with 'snapdirseverywhere', "
3111                                   "setting 'snapdirseverywhere' to false.\n"));
3112                         config->snapdirseverywhere = false;
3113                 }
3114
3115                 if (config->crossmountpoints == true) {
3116                         DEBUG(1, (__location__ " Warning: 'crossmountpoints' "
3117                                   "is not supported with an absolute snapdir. "
3118                                   "Disabling it.\n"));
3119                         config->crossmountpoints = false;
3120                 }
3121
3122                 config->snapshot_basepath = config->snapdir;
3123         } else {
3124                 config->snapshot_basepath = talloc_asprintf(config, "%s/%s",
3125                                 config->mount_point, config->snapdir);
3126                 if (config->snapshot_basepath == NULL) {
3127                         DEBUG(0, ("talloc_asprintf() failed\n"));
3128                         errno = ENOMEM;
3129                         return -1;
3130                 }
3131         }
3132
3133         trim_string(config->mount_point, NULL, "/");
3134         trim_string(config->rel_connectpath, "/", "/");
3135         trim_string(config->snapdir, NULL, "/");
3136         trim_string(config->snapshot_basepath, NULL, "/");
3137
3138         DEBUG(10, ("shadow_copy2_connect: configuration:\n"
3139                    "  share root: '%s'\n"
3140                    "  mountpoint: '%s'\n"
3141                    "  rel share root: '%s'\n"
3142                    "  snapdir: '%s'\n"
3143                    "  snapprefix: '%s'\n"
3144                    "  delimiter: '%s'\n"
3145                    "  snapshot base path: '%s'\n"
3146                    "  format: '%s'\n"
3147                    "  use sscanf: %s\n"
3148                    "  snapdirs everywhere: %s\n"
3149                    "  cross mountpoints: %s\n"
3150                    "  fix inodes: %s\n"
3151                    "  sort order: %s\n"
3152                    "",
3153                    handle->conn->connectpath,
3154                    config->mount_point,
3155                    config->rel_connectpath,
3156                    config->snapdir,
3157                    snapprefix,
3158                    config->delimiter,
3159                    config->snapshot_basepath,
3160                    config->gmt_format,
3161                    config->use_sscanf ? "yes" : "no",
3162                    config->snapdirseverywhere ? "yes" : "no",
3163                    config->crossmountpoints ? "yes" : "no",
3164                    config->fixinodes ? "yes" : "no",
3165                    config->sort_order
3166                    ));
3167
3168
3169         SMB_VFS_HANDLE_SET_DATA(handle, priv,
3170                                 NULL, struct shadow_copy2_private,
3171                                 return -1);
3172
3173         return 0;
3174 }
3175
3176 static struct vfs_fn_pointers vfs_shadow_copy2_fns = {
3177         .connect_fn = shadow_copy2_connect,
3178         .opendir_fn = shadow_copy2_opendir,
3179         .disk_free_fn = shadow_copy2_disk_free,
3180         .get_quota_fn = shadow_copy2_get_quota,
3181         .renameat_fn = shadow_copy2_renameat,
3182         .linkat_fn = shadow_copy2_linkat,
3183         .symlinkat_fn = shadow_copy2_symlinkat,
3184         .stat_fn = shadow_copy2_stat,
3185         .lstat_fn = shadow_copy2_lstat,
3186         .fstat_fn = shadow_copy2_fstat,
3187         .open_fn = shadow_copy2_open,
3188         .unlink_fn = shadow_copy2_unlink,
3189         .chmod_fn = shadow_copy2_chmod,
3190         .chown_fn = shadow_copy2_chown,
3191         .chdir_fn = shadow_copy2_chdir,
3192         .ntimes_fn = shadow_copy2_ntimes,
3193         .readlinkat_fn = shadow_copy2_readlinkat,
3194         .mknodat_fn = shadow_copy2_mknodat,
3195         .realpath_fn = shadow_copy2_realpath,
3196         .get_nt_acl_fn = shadow_copy2_get_nt_acl,
3197         .fget_nt_acl_fn = shadow_copy2_fget_nt_acl,
3198         .get_shadow_copy_data_fn = shadow_copy2_get_shadow_copy_data,
3199         .mkdir_fn = shadow_copy2_mkdir,
3200         .mkdirat_fn = shadow_copy2_mkdirat,
3201         .rmdir_fn = shadow_copy2_rmdir,
3202         .getxattr_fn = shadow_copy2_getxattr,
3203         .getxattrat_send_fn = vfs_not_implemented_getxattrat_send,
3204         .getxattrat_recv_fn = vfs_not_implemented_getxattrat_recv,
3205         .listxattr_fn = shadow_copy2_listxattr,
3206         .removexattr_fn = shadow_copy2_removexattr,
3207         .setxattr_fn = shadow_copy2_setxattr,
3208         .chflags_fn = shadow_copy2_chflags,
3209         .get_real_filename_fn = shadow_copy2_get_real_filename,
3210         .pwrite_fn = shadow_copy2_pwrite,
3211         .pwrite_send_fn = shadow_copy2_pwrite_send,
3212         .pwrite_recv_fn = shadow_copy2_pwrite_recv,
3213         .connectpath_fn = shadow_copy2_connectpath,
3214 };
3215
3216 static_decl_vfs;
3217 NTSTATUS vfs_shadow_copy2_init(TALLOC_CTX *ctx)
3218 {
3219         return smb_register_vfs(SMB_VFS_INTERFACE_VERSION,
3220                                 "shadow_copy2", &vfs_shadow_copy2_fns);
3221 }