vfs: remove SMB_VFS_OPENDIR()
[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                          * .snapshots/@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 int shadow_copy2_renameat(vfs_handle_struct *handle,
1091                                 files_struct *srcfsp,
1092                                 const struct smb_filename *smb_fname_src,
1093                                 files_struct *dstfsp,
1094                                 const struct smb_filename *smb_fname_dst)
1095 {
1096         time_t timestamp_src = 0;
1097         time_t timestamp_dst = 0;
1098         char *snappath_src = NULL;
1099         char *snappath_dst = NULL;
1100
1101         if (!shadow_copy2_strip_snapshot_internal(talloc_tos(), handle,
1102                                          smb_fname_src->base_name,
1103                                          &timestamp_src, NULL, &snappath_src,
1104                                          NULL)) {
1105                 return -1;
1106         }
1107         if (!shadow_copy2_strip_snapshot_internal(talloc_tos(), handle,
1108                                          smb_fname_dst->base_name,
1109                                          &timestamp_dst, NULL, &snappath_dst,
1110                                          NULL)) {
1111                 return -1;
1112         }
1113         if (timestamp_src != 0) {
1114                 errno = EXDEV;
1115                 return -1;
1116         }
1117         if (timestamp_dst != 0) {
1118                 errno = EROFS;
1119                 return -1;
1120         }
1121         /*
1122          * Don't allow rename on already converted paths.
1123          */
1124         if (snappath_src != NULL) {
1125                 errno = EXDEV;
1126                 return -1;
1127         }
1128         if (snappath_dst != NULL) {
1129                 errno = EROFS;
1130                 return -1;
1131         }
1132         return SMB_VFS_NEXT_RENAMEAT(handle,
1133                         srcfsp,
1134                         smb_fname_src,
1135                         dstfsp,
1136                         smb_fname_dst);
1137 }
1138
1139 static int shadow_copy2_symlinkat(vfs_handle_struct *handle,
1140                         const char *link_contents,
1141                         struct files_struct *dirfsp,
1142                         const struct smb_filename *new_smb_fname)
1143 {
1144         time_t timestamp_old = 0;
1145         time_t timestamp_new = 0;
1146         char *snappath_old = NULL;
1147         char *snappath_new = NULL;
1148
1149         if (!shadow_copy2_strip_snapshot_internal(talloc_tos(),
1150                                 handle,
1151                                 link_contents,
1152                                 &timestamp_old,
1153                                 NULL,
1154                                 &snappath_old,
1155                                 NULL)) {
1156                 return -1;
1157         }
1158         if (!shadow_copy2_strip_snapshot_internal(talloc_tos(),
1159                                 handle,
1160                                 new_smb_fname->base_name,
1161                                 &timestamp_new,
1162                                 NULL,
1163                                 &snappath_new,
1164                                 NULL)) {
1165                 return -1;
1166         }
1167         if ((timestamp_old != 0) || (timestamp_new != 0)) {
1168                 errno = EROFS;
1169                 return -1;
1170         }
1171         /*
1172          * Don't allow symlinks on already converted paths.
1173          */
1174         if ((snappath_old != NULL) || (snappath_new != NULL)) {
1175                 errno = EROFS;
1176                 return -1;
1177         }
1178         return SMB_VFS_NEXT_SYMLINKAT(handle,
1179                                 link_contents,
1180                                 dirfsp,
1181                                 new_smb_fname);
1182 }
1183
1184 static int shadow_copy2_linkat(vfs_handle_struct *handle,
1185                         files_struct *srcfsp,
1186                         const struct smb_filename *old_smb_fname,
1187                         files_struct *dstfsp,
1188                         const struct smb_filename *new_smb_fname,
1189                         int flags)
1190 {
1191         time_t timestamp_old = 0;
1192         time_t timestamp_new = 0;
1193         char *snappath_old = NULL;
1194         char *snappath_new = NULL;
1195
1196         if (!shadow_copy2_strip_snapshot_internal(talloc_tos(),
1197                                 handle,
1198                                 old_smb_fname->base_name,
1199                                 &timestamp_old,
1200                                 NULL,
1201                                 &snappath_old,
1202                                 NULL)) {
1203                 return -1;
1204         }
1205         if (!shadow_copy2_strip_snapshot_internal(talloc_tos(),
1206                                 handle,
1207                                 new_smb_fname->base_name,
1208                                 &timestamp_new,
1209                                 NULL,
1210                                 &snappath_new,
1211                                 NULL)) {
1212                 return -1;
1213         }
1214         if ((timestamp_old != 0) || (timestamp_new != 0)) {
1215                 errno = EROFS;
1216                 return -1;
1217         }
1218         /*
1219          * Don't allow links on already converted paths.
1220          */
1221         if ((snappath_old != NULL) || (snappath_new != NULL)) {
1222                 errno = EROFS;
1223                 return -1;
1224         }
1225         return SMB_VFS_NEXT_LINKAT(handle,
1226                         srcfsp,
1227                         old_smb_fname,
1228                         dstfsp,
1229                         new_smb_fname,
1230                         flags);
1231 }
1232
1233 static int shadow_copy2_stat(vfs_handle_struct *handle,
1234                              struct smb_filename *smb_fname)
1235 {
1236         time_t timestamp = 0;
1237         char *stripped = NULL;
1238         char *tmp;
1239         int saved_errno = 0;
1240         int ret;
1241
1242         if (!shadow_copy2_strip_snapshot(talloc_tos(), handle,
1243                                          smb_fname->base_name,
1244                                          &timestamp, &stripped)) {
1245                 return -1;
1246         }
1247         if (timestamp == 0) {
1248                 return SMB_VFS_NEXT_STAT(handle, smb_fname);
1249         }
1250
1251         tmp = smb_fname->base_name;
1252         smb_fname->base_name = shadow_copy2_convert(
1253                 talloc_tos(), handle, stripped, timestamp);
1254         TALLOC_FREE(stripped);
1255
1256         if (smb_fname->base_name == NULL) {
1257                 smb_fname->base_name = tmp;
1258                 return -1;
1259         }
1260
1261         ret = SMB_VFS_NEXT_STAT(handle, smb_fname);
1262         if (ret == -1) {
1263                 saved_errno = errno;
1264         }
1265
1266         TALLOC_FREE(smb_fname->base_name);
1267         smb_fname->base_name = tmp;
1268
1269         if (ret == 0) {
1270                 convert_sbuf(handle, smb_fname->base_name, &smb_fname->st);
1271         }
1272         if (saved_errno != 0) {
1273                 errno = saved_errno;
1274         }
1275         return ret;
1276 }
1277
1278 static int shadow_copy2_lstat(vfs_handle_struct *handle,
1279                               struct smb_filename *smb_fname)
1280 {
1281         time_t timestamp = 0;
1282         char *stripped = NULL;
1283         char *tmp;
1284         int saved_errno = 0;
1285         int ret;
1286
1287         if (!shadow_copy2_strip_snapshot(talloc_tos(), handle,
1288                                          smb_fname->base_name,
1289                                          &timestamp, &stripped)) {
1290                 return -1;
1291         }
1292         if (timestamp == 0) {
1293                 return SMB_VFS_NEXT_LSTAT(handle, smb_fname);
1294         }
1295
1296         tmp = smb_fname->base_name;
1297         smb_fname->base_name = shadow_copy2_convert(
1298                 talloc_tos(), handle, stripped, timestamp);
1299         TALLOC_FREE(stripped);
1300
1301         if (smb_fname->base_name == NULL) {
1302                 smb_fname->base_name = tmp;
1303                 return -1;
1304         }
1305
1306         ret = SMB_VFS_NEXT_LSTAT(handle, smb_fname);
1307         if (ret == -1) {
1308                 saved_errno = errno;
1309         }
1310
1311         TALLOC_FREE(smb_fname->base_name);
1312         smb_fname->base_name = tmp;
1313
1314         if (ret == 0) {
1315                 convert_sbuf(handle, smb_fname->base_name, &smb_fname->st);
1316         }
1317         if (saved_errno != 0) {
1318                 errno = saved_errno;
1319         }
1320         return ret;
1321 }
1322
1323 static int shadow_copy2_fstat(vfs_handle_struct *handle, files_struct *fsp,
1324                               SMB_STRUCT_STAT *sbuf)
1325 {
1326         time_t timestamp = 0;
1327         struct smb_filename *orig_smb_fname = NULL;
1328         struct smb_filename vss_smb_fname;
1329         struct smb_filename *orig_base_smb_fname = NULL;
1330         struct smb_filename vss_base_smb_fname;
1331         char *stripped = NULL;
1332         int saved_errno = 0;
1333         bool ok;
1334         int ret;
1335
1336         ok = shadow_copy2_strip_snapshot(talloc_tos(), handle,
1337                                          fsp->fsp_name->base_name,
1338                                          &timestamp, &stripped);
1339         if (!ok) {
1340                 return -1;
1341         }
1342
1343         if (timestamp == 0) {
1344                 TALLOC_FREE(stripped);
1345                 return SMB_VFS_NEXT_FSTAT(handle, fsp, sbuf);
1346         }
1347
1348         vss_smb_fname = *fsp->fsp_name;
1349         vss_smb_fname.base_name = shadow_copy2_convert(talloc_tos(),
1350                                                        handle,
1351                                                        stripped,
1352                                                        timestamp);
1353         TALLOC_FREE(stripped);
1354         if (vss_smb_fname.base_name == NULL) {
1355                 return -1;
1356         }
1357
1358         orig_smb_fname = fsp->fsp_name;
1359         fsp->fsp_name = &vss_smb_fname;
1360
1361         if (fsp->base_fsp != NULL) {
1362                 vss_base_smb_fname = *fsp->base_fsp->fsp_name;
1363                 vss_base_smb_fname.base_name = vss_smb_fname.base_name;
1364                 orig_base_smb_fname = fsp->base_fsp->fsp_name;
1365                 fsp->base_fsp->fsp_name = &vss_base_smb_fname;
1366         }
1367
1368         ret = SMB_VFS_NEXT_FSTAT(handle, fsp, sbuf);
1369         fsp->fsp_name = orig_smb_fname;
1370         if (fsp->base_fsp != NULL) {
1371                 fsp->base_fsp->fsp_name = orig_base_smb_fname;
1372         }
1373         if (ret == -1) {
1374                 saved_errno = errno;
1375         }
1376
1377         if (ret == 0) {
1378                 convert_sbuf(handle, fsp->fsp_name->base_name, sbuf);
1379         }
1380         if (saved_errno != 0) {
1381                 errno = saved_errno;
1382         }
1383         return ret;
1384 }
1385
1386 static int shadow_copy2_open(vfs_handle_struct *handle,
1387                              struct smb_filename *smb_fname, files_struct *fsp,
1388                              int flags, mode_t mode)
1389 {
1390         time_t timestamp = 0;
1391         char *stripped = NULL;
1392         char *tmp;
1393         bool is_converted = false;
1394         int saved_errno = 0;
1395         int ret;
1396
1397         if (!shadow_copy2_strip_snapshot_converted(talloc_tos(), handle,
1398                                          smb_fname->base_name,
1399                                          &timestamp, &stripped,
1400                                          &is_converted)) {
1401                 return -1;
1402         }
1403         if (timestamp == 0) {
1404                 if (is_converted) {
1405                         /*
1406                          * Just pave over the user requested mode and use
1407                          * O_RDONLY. Later attempts by the client to write on
1408                          * the handle will fail in the pwrite() syscall with
1409                          * EINVAL which we carefully map to EROFS. In sum, this
1410                          * matches Windows behaviour.
1411                          */
1412                         flags = O_RDONLY;
1413                 }
1414                 return SMB_VFS_NEXT_OPEN(handle, smb_fname, fsp, flags, mode);
1415         }
1416
1417         tmp = smb_fname->base_name;
1418         smb_fname->base_name = shadow_copy2_convert(
1419                 talloc_tos(), handle, stripped, timestamp);
1420         TALLOC_FREE(stripped);
1421
1422         if (smb_fname->base_name == NULL) {
1423                 smb_fname->base_name = tmp;
1424                 return -1;
1425         }
1426
1427         /*
1428          * Just pave over the user requested mode and use O_RDONLY. Later
1429          * attempts by the client to write on the handle will fail in the
1430          * pwrite() syscall with EINVAL which we carefully map to EROFS. In sum,
1431          * this matches Windows behaviour.
1432          */
1433         flags = O_RDONLY;
1434
1435         ret = SMB_VFS_NEXT_OPEN(handle, smb_fname, fsp, flags, mode);
1436         if (ret == -1) {
1437                 saved_errno = errno;
1438         }
1439
1440         TALLOC_FREE(smb_fname->base_name);
1441         smb_fname->base_name = tmp;
1442
1443         if (saved_errno != 0) {
1444                 errno = saved_errno;
1445         }
1446         return ret;
1447 }
1448
1449 static int shadow_copy2_unlinkat(vfs_handle_struct *handle,
1450                         struct files_struct *dirfsp,
1451                         const struct smb_filename *smb_fname,
1452                         int flags)
1453 {
1454         time_t timestamp = 0;
1455
1456         if (!shadow_copy2_strip_snapshot(talloc_tos(), handle,
1457                                          smb_fname->base_name,
1458                                          &timestamp, NULL)) {
1459                 return -1;
1460         }
1461         if (timestamp != 0) {
1462                 errno = EROFS;
1463                 return -1;
1464         }
1465         return SMB_VFS_NEXT_UNLINKAT(handle,
1466                         dirfsp,
1467                         smb_fname,
1468                         flags);
1469 }
1470
1471 static int shadow_copy2_chmod(vfs_handle_struct *handle,
1472                         const struct smb_filename *smb_fname,
1473                         mode_t mode)
1474 {
1475         time_t timestamp = 0;
1476
1477         if (!shadow_copy2_strip_snapshot(talloc_tos(),
1478                                 handle,
1479                                 smb_fname->base_name,
1480                                 &timestamp,
1481                                 NULL)) {
1482                 return -1;
1483         }
1484         if (timestamp != 0) {
1485                 errno = EROFS;
1486                 return -1;
1487         }
1488         return SMB_VFS_NEXT_CHMOD(handle, smb_fname, mode);
1489 }
1490
1491 static void store_cwd_data(vfs_handle_struct *handle,
1492                                 const char *connectpath)
1493 {
1494         struct shadow_copy2_private *priv = NULL;
1495         struct smb_filename *cwd_fname = NULL;
1496
1497         SMB_VFS_HANDLE_GET_DATA(handle, priv, struct shadow_copy2_private,
1498                                 return);
1499
1500         TALLOC_FREE(priv->shadow_cwd);
1501         cwd_fname = SMB_VFS_NEXT_GETWD(handle, talloc_tos());
1502         if (cwd_fname == NULL) {
1503                 smb_panic("getwd failed\n");
1504         }
1505         DBG_DEBUG("shadow cwd = %s\n", cwd_fname->base_name);
1506         priv->shadow_cwd = talloc_strdup(priv, cwd_fname->base_name);
1507         TALLOC_FREE(cwd_fname);
1508         if (priv->shadow_cwd == NULL) {
1509                 smb_panic("talloc failed\n");
1510         }
1511         TALLOC_FREE(priv->shadow_connectpath);
1512         if (connectpath) {
1513                 DBG_DEBUG("shadow connectpath = %s\n", connectpath);
1514                 priv->shadow_connectpath = talloc_strdup(priv, connectpath);
1515                 if (priv->shadow_connectpath == NULL) {
1516                         smb_panic("talloc failed\n");
1517                 }
1518         }
1519 }
1520
1521 static int shadow_copy2_chdir(vfs_handle_struct *handle,
1522                                const struct smb_filename *smb_fname)
1523 {
1524         time_t timestamp = 0;
1525         char *stripped = NULL;
1526         char *snappath = NULL;
1527         int ret = -1;
1528         int saved_errno = 0;
1529         char *conv = NULL;
1530         size_t rootpath_len = 0;
1531         struct smb_filename *conv_smb_fname = NULL;
1532
1533         if (!shadow_copy2_strip_snapshot_internal(talloc_tos(),
1534                                         handle,
1535                                         smb_fname->base_name,
1536                                         &timestamp,
1537                                         &stripped,
1538                                         &snappath,
1539                                         NULL)) {
1540                 return -1;
1541         }
1542         if (stripped != NULL) {
1543                 conv = shadow_copy2_do_convert(talloc_tos(),
1544                                                 handle,
1545                                                 stripped,
1546                                                 timestamp,
1547                                                 &rootpath_len);
1548                 TALLOC_FREE(stripped);
1549                 if (conv == NULL) {
1550                         return -1;
1551                 }
1552                 conv_smb_fname = synthetic_smb_fname(talloc_tos(),
1553                                         conv,
1554                                         NULL,
1555                                         NULL,
1556                                         smb_fname->flags);
1557         } else {
1558                 conv_smb_fname = cp_smb_filename(talloc_tos(), smb_fname);
1559         }
1560
1561         if (conv_smb_fname == NULL) {
1562                 TALLOC_FREE(conv);
1563                 errno = ENOMEM;
1564                 return -1;
1565         }
1566
1567         ret = SMB_VFS_NEXT_CHDIR(handle, conv_smb_fname);
1568         if (ret == -1) {
1569                 saved_errno = errno;
1570         }
1571
1572         if (ret == 0) {
1573                 if (conv != NULL && rootpath_len != 0) {
1574                         conv[rootpath_len] = '\0';
1575                 } else if (snappath != 0) {
1576                         TALLOC_FREE(conv);
1577                         conv = snappath;
1578                 }
1579                 store_cwd_data(handle, conv);
1580         }
1581
1582         TALLOC_FREE(stripped);
1583         TALLOC_FREE(conv);
1584         TALLOC_FREE(conv_smb_fname);
1585
1586         if (saved_errno != 0) {
1587                 errno = saved_errno;
1588         }
1589         return ret;
1590 }
1591
1592 static int shadow_copy2_ntimes(vfs_handle_struct *handle,
1593                                const struct smb_filename *smb_fname,
1594                                struct smb_file_time *ft)
1595 {
1596         time_t timestamp = 0;
1597
1598         if (!shadow_copy2_strip_snapshot(talloc_tos(), handle,
1599                                          smb_fname->base_name,
1600                                          &timestamp, NULL)) {
1601                 return -1;
1602         }
1603         if (timestamp != 0) {
1604                 errno = EROFS;
1605                 return -1;
1606         }
1607         return SMB_VFS_NEXT_NTIMES(handle, smb_fname, ft);
1608 }
1609
1610 static int shadow_copy2_readlinkat(vfs_handle_struct *handle,
1611                                 files_struct *dirfsp,
1612                                 const struct smb_filename *smb_fname,
1613                                 char *buf,
1614                                 size_t bufsiz)
1615 {
1616         time_t timestamp = 0;
1617         char *stripped = NULL;
1618         int saved_errno = 0;
1619         int ret;
1620         struct smb_filename *conv = NULL;
1621
1622         if (!shadow_copy2_strip_snapshot(talloc_tos(), handle,
1623                                          smb_fname->base_name,
1624                                          &timestamp, &stripped)) {
1625                 return -1;
1626         }
1627         if (timestamp == 0) {
1628                 return SMB_VFS_NEXT_READLINKAT(handle,
1629                                 dirfsp,
1630                                 smb_fname,
1631                                 buf,
1632                                 bufsiz);
1633         }
1634         conv = cp_smb_filename(talloc_tos(), smb_fname);
1635         if (conv == NULL) {
1636                 TALLOC_FREE(stripped);
1637                 errno = ENOMEM;
1638                 return -1;
1639         }
1640         conv->base_name = shadow_copy2_convert(
1641                 conv, handle, stripped, timestamp);
1642         TALLOC_FREE(stripped);
1643         if (conv->base_name == NULL) {
1644                 return -1;
1645         }
1646         ret = SMB_VFS_NEXT_READLINKAT(handle,
1647                                 dirfsp,
1648                                 conv,
1649                                 buf,
1650                                 bufsiz);
1651         if (ret == -1) {
1652                 saved_errno = errno;
1653         }
1654         TALLOC_FREE(conv);
1655         if (saved_errno != 0) {
1656                 errno = saved_errno;
1657         }
1658         return ret;
1659 }
1660
1661 static int shadow_copy2_mknodat(vfs_handle_struct *handle,
1662                         files_struct *dirfsp,
1663                         const struct smb_filename *smb_fname,
1664                         mode_t mode,
1665                         SMB_DEV_T dev)
1666 {
1667         time_t timestamp = 0;
1668
1669         if (!shadow_copy2_strip_snapshot(talloc_tos(), handle,
1670                                          smb_fname->base_name,
1671                                          &timestamp, NULL)) {
1672                 return -1;
1673         }
1674         if (timestamp != 0) {
1675                 errno = EROFS;
1676                 return -1;
1677         }
1678         return SMB_VFS_NEXT_MKNODAT(handle,
1679                         dirfsp,
1680                         smb_fname,
1681                         mode,
1682                         dev);
1683 }
1684
1685 static struct smb_filename *shadow_copy2_realpath(vfs_handle_struct *handle,
1686                                 TALLOC_CTX *ctx,
1687                                 const struct smb_filename *smb_fname)
1688 {
1689         time_t timestamp = 0;
1690         char *stripped = NULL;
1691         struct smb_filename *result_fname = NULL;
1692         struct smb_filename *conv_fname = NULL;
1693         int saved_errno = 0;
1694
1695         if (!shadow_copy2_strip_snapshot(talloc_tos(), handle,
1696                                 smb_fname->base_name,
1697                                 &timestamp, &stripped)) {
1698                 goto done;
1699         }
1700         if (timestamp == 0) {
1701                 return SMB_VFS_NEXT_REALPATH(handle, ctx, smb_fname);
1702         }
1703
1704         conv_fname = cp_smb_filename(talloc_tos(), smb_fname);
1705         if (conv_fname == NULL) {
1706                 goto done;
1707         }
1708         conv_fname->base_name = shadow_copy2_convert(
1709                 conv_fname, handle, stripped, timestamp);
1710         if (conv_fname->base_name == NULL) {
1711                 goto done;
1712         }
1713
1714         result_fname = SMB_VFS_NEXT_REALPATH(handle, ctx, conv_fname);
1715
1716 done:
1717         if (result_fname == NULL) {
1718                 saved_errno = errno;
1719         }
1720         TALLOC_FREE(conv_fname);
1721         TALLOC_FREE(stripped);
1722         if (saved_errno != 0) {
1723                 errno = saved_errno;
1724         }
1725         return result_fname;
1726 }
1727
1728 /**
1729  * Check whether a given directory contains a
1730  * snapshot directory as direct subdirectory.
1731  * If yes, return the path of the snapshot-subdir,
1732  * otherwise return NULL.
1733  */
1734 static char *have_snapdir(struct vfs_handle_struct *handle,
1735                           const char *path)
1736 {
1737         struct smb_filename smb_fname;
1738         int ret;
1739         struct shadow_copy2_private *priv;
1740
1741         SMB_VFS_HANDLE_GET_DATA(handle, priv, struct shadow_copy2_private,
1742                                 return NULL);
1743
1744         ZERO_STRUCT(smb_fname);
1745         smb_fname.base_name = talloc_asprintf(talloc_tos(), "%s/%s",
1746                                               path, priv->config->snapdir);
1747         if (smb_fname.base_name == NULL) {
1748                 return NULL;
1749         }
1750
1751         ret = SMB_VFS_NEXT_STAT(handle, &smb_fname);
1752         if ((ret == 0) && (S_ISDIR(smb_fname.st.st_ex_mode))) {
1753                 return smb_fname.base_name;
1754         }
1755         TALLOC_FREE(smb_fname.base_name);
1756         return NULL;
1757 }
1758
1759 static bool check_access_snapdir(struct vfs_handle_struct *handle,
1760                                 const char *path)
1761 {
1762         struct smb_filename smb_fname;
1763         int ret;
1764         NTSTATUS status;
1765
1766         ZERO_STRUCT(smb_fname);
1767         smb_fname.base_name = talloc_asprintf(talloc_tos(),
1768                                                 "%s",
1769                                                 path);
1770         if (smb_fname.base_name == NULL) {
1771                 return false;
1772         }
1773
1774         ret = SMB_VFS_NEXT_STAT(handle, &smb_fname);
1775         if (ret != 0 || !S_ISDIR(smb_fname.st.st_ex_mode)) {
1776                 TALLOC_FREE(smb_fname.base_name);
1777                 return false;
1778         }
1779
1780         status = smbd_check_access_rights(handle->conn,
1781                                         &smb_fname,
1782                                         false,
1783                                         SEC_DIR_LIST);
1784         if (!NT_STATUS_IS_OK(status)) {
1785                 DEBUG(0,("user does not have list permission "
1786                         "on snapdir %s\n",
1787                         smb_fname.base_name));
1788                 TALLOC_FREE(smb_fname.base_name);
1789                 return false;
1790         }
1791         TALLOC_FREE(smb_fname.base_name);
1792         return true;
1793 }
1794
1795 /**
1796  * Find the snapshot directory (if any) for the given
1797  * filename (which is relative to the share).
1798  */
1799 static const char *shadow_copy2_find_snapdir(TALLOC_CTX *mem_ctx,
1800                                              struct vfs_handle_struct *handle,
1801                                              struct smb_filename *smb_fname)
1802 {
1803         char *path, *p;
1804         const char *snapdir;
1805         struct shadow_copy2_config *config;
1806         struct shadow_copy2_private *priv;
1807
1808         SMB_VFS_HANDLE_GET_DATA(handle, priv, struct shadow_copy2_private,
1809                                 return NULL);
1810
1811         config = priv->config;
1812
1813         /*
1814          * If the non-snapdisrseverywhere mode, we should not search!
1815          */
1816         if (!config->snapdirseverywhere) {
1817                 return config->snapshot_basepath;
1818         }
1819
1820         path = talloc_asprintf(mem_ctx, "%s/%s",
1821                                handle->conn->connectpath,
1822                                smb_fname->base_name);
1823         if (path == NULL) {
1824                 return NULL;
1825         }
1826
1827         snapdir = have_snapdir(handle, path);
1828         if (snapdir != NULL) {
1829                 TALLOC_FREE(path);
1830                 return snapdir;
1831         }
1832
1833         while ((p = strrchr(path, '/')) && (p > path)) {
1834
1835                 p[0] = '\0';
1836
1837                 snapdir = have_snapdir(handle, path);
1838                 if (snapdir != NULL) {
1839                         TALLOC_FREE(path);
1840                         return snapdir;
1841                 }
1842         }
1843         TALLOC_FREE(path);
1844         return NULL;
1845 }
1846
1847 static bool shadow_copy2_snapshot_to_gmt(vfs_handle_struct *handle,
1848                                          const char *name,
1849                                          char *gmt, size_t gmt_len)
1850 {
1851         struct tm timestamp;
1852         time_t timestamp_t;
1853         unsigned long int timestamp_long;
1854         const char *fmt;
1855         struct shadow_copy2_config *config;
1856         struct shadow_copy2_private *priv;
1857         char *tmpstr = NULL;
1858         char *tmp = NULL;
1859         bool converted = false;
1860         int ret = -1;
1861
1862         SMB_VFS_HANDLE_GET_DATA(handle, priv, struct shadow_copy2_private,
1863                                 return NULL);
1864
1865         config = priv->config;
1866
1867         fmt = config->gmt_format;
1868
1869         /*
1870          * If regex is provided, then we will have to parse the
1871          * filename which will contain both the prefix and the time format.
1872          * e.g. <prefix><delimiter><time_format>
1873          */
1874         if (priv->snaps->regex != NULL) {
1875                 tmpstr = talloc_strdup(talloc_tos(), name);
1876                 /* point "name" to the time format */
1877                 name = strstr(name, priv->config->delimiter);
1878                 if (name == NULL) {
1879                         goto done;
1880                 }
1881                 /* Extract the prefix */
1882                 tmp = strstr(tmpstr, priv->config->delimiter);
1883                 if (tmp == NULL) {
1884                         goto done;
1885                 }
1886                 *tmp = '\0';
1887
1888                 /* Parse regex */
1889                 ret = regexec(priv->snaps->regex, tmpstr, 0, NULL, 0);
1890                 if (ret) {
1891                         DBG_DEBUG("shadow_copy2_snapshot_to_gmt: "
1892                                   "no regex match for %s\n", tmpstr);
1893                         goto done;
1894                 }
1895         }
1896
1897         ZERO_STRUCT(timestamp);
1898         if (config->use_sscanf) {
1899                 if (sscanf(name, fmt, &timestamp_long) != 1) {
1900                         DEBUG(10, ("shadow_copy2_snapshot_to_gmt: "
1901                                    "no sscanf match %s: %s\n",
1902                                    fmt, name));
1903                         goto done;
1904                 }
1905                 timestamp_t = timestamp_long;
1906                 gmtime_r(&timestamp_t, &timestamp);
1907         } else {
1908                 if (strptime(name, fmt, &timestamp) == NULL) {
1909                         DEBUG(10, ("shadow_copy2_snapshot_to_gmt: "
1910                                    "no match %s: %s\n",
1911                                    fmt, name));
1912                         goto done;
1913                 }
1914                 DEBUG(10, ("shadow_copy2_snapshot_to_gmt: match %s: %s\n",
1915                            fmt, name));
1916                 
1917                 if (config->use_localtime) {
1918                         timestamp.tm_isdst = -1;
1919                         timestamp_t = mktime(&timestamp);
1920                         gmtime_r(&timestamp_t, &timestamp);
1921                 }
1922         }
1923
1924         strftime(gmt, gmt_len, GMT_FORMAT, &timestamp);
1925         converted = true;
1926
1927 done:
1928         TALLOC_FREE(tmpstr);
1929         return converted;
1930 }
1931
1932 static int shadow_copy2_label_cmp_asc(const void *x, const void *y)
1933 {
1934         return strncmp((const char *)x, (const char *)y, sizeof(SHADOW_COPY_LABEL));
1935 }
1936
1937 static int shadow_copy2_label_cmp_desc(const void *x, const void *y)
1938 {
1939         return -strncmp((const char *)x, (const char *)y, sizeof(SHADOW_COPY_LABEL));
1940 }
1941
1942 /*
1943   sort the shadow copy data in ascending or descending order
1944  */
1945 static void shadow_copy2_sort_data(vfs_handle_struct *handle,
1946                                    struct shadow_copy_data *shadow_copy2_data)
1947 {
1948         int (*cmpfunc)(const void *, const void *);
1949         const char *sort;
1950         struct shadow_copy2_private *priv;
1951
1952         SMB_VFS_HANDLE_GET_DATA(handle, priv, struct shadow_copy2_private,
1953                                 return);
1954
1955         sort = priv->config->sort_order;
1956         if (sort == NULL) {
1957                 return;
1958         }
1959
1960         if (strcmp(sort, "asc") == 0) {
1961                 cmpfunc = shadow_copy2_label_cmp_asc;
1962         } else if (strcmp(sort, "desc") == 0) {
1963                 cmpfunc = shadow_copy2_label_cmp_desc;
1964         } else {
1965                 return;
1966         }
1967
1968         if (shadow_copy2_data && shadow_copy2_data->num_volumes > 0 &&
1969             shadow_copy2_data->labels)
1970         {
1971                 TYPESAFE_QSORT(shadow_copy2_data->labels,
1972                                shadow_copy2_data->num_volumes,
1973                                cmpfunc);
1974         }
1975 }
1976
1977 static int shadow_copy2_get_shadow_copy_data(
1978         vfs_handle_struct *handle, files_struct *fsp,
1979         struct shadow_copy_data *shadow_copy2_data,
1980         bool labels)
1981 {
1982         DIR *p = NULL;
1983         const char *snapdir;
1984         struct smb_filename *snapdir_smb_fname = NULL;
1985         struct files_struct *dirfsp = NULL;
1986         struct dirent *d;
1987         TALLOC_CTX *tmp_ctx = talloc_stackframe();
1988         struct shadow_copy2_private *priv = NULL;
1989         struct shadow_copy2_snapentry *tmpentry = NULL;
1990         bool get_snaplist = false;
1991         bool access_granted = false;
1992         int open_flags = O_RDONLY;
1993         int ret = -1;
1994         NTSTATUS status;
1995
1996         snapdir = shadow_copy2_find_snapdir(tmp_ctx, handle, fsp->fsp_name);
1997         if (snapdir == NULL) {
1998                 DEBUG(0,("shadow:snapdir not found for %s in get_shadow_copy_data\n",
1999                          handle->conn->connectpath));
2000                 errno = EINVAL;
2001                 goto done;
2002         }
2003
2004         access_granted = check_access_snapdir(handle, snapdir);
2005         if (!access_granted) {
2006                 DEBUG(0,("access denied on listing snapdir %s\n", snapdir));
2007                 errno = EACCES;
2008                 goto done;
2009         }
2010
2011         snapdir_smb_fname = synthetic_smb_fname(talloc_tos(),
2012                                         snapdir,
2013                                         NULL,
2014                                         NULL,
2015                                         fsp->fsp_name->flags);
2016         if (snapdir_smb_fname == NULL) {
2017                 errno = ENOMEM;
2018                 goto done;
2019         }
2020
2021         status = create_internal_dirfsp_at(handle->conn,
2022                                            handle->conn->cwd_fsp,
2023                                            snapdir_smb_fname,
2024                                            &dirfsp);
2025         if (!NT_STATUS_IS_OK(status)) {
2026                 DBG_WARNING("create_internal_dir_fsp() failed for '%s'"
2027                             " - %s\n", snapdir, nt_errstr(status));
2028                 errno = ENOSYS;
2029                 goto done;
2030         }
2031
2032 #ifdef O_DIRECTORY
2033         open_flags |= O_DIRECTORY;
2034 #endif
2035
2036         dirfsp->fh->fd = SMB_VFS_NEXT_OPEN(handle,
2037                                            snapdir_smb_fname,
2038                                            dirfsp,
2039                                            open_flags,
2040                                            0);
2041         if (dirfsp->fh->fd == -1) {
2042                 DBG_WARNING("SMB_VFS_NEXT_OPEN failed for '%s'"
2043                             " - %s\n", snapdir, strerror(errno));
2044                 errno = ENOSYS;
2045                 goto done;
2046         }
2047
2048         p = SMB_VFS_NEXT_FDOPENDIR(handle, dirfsp, NULL, 0);
2049         if (!p) {
2050                 DEBUG(2,("shadow_copy2: SMB_VFS_NEXT_OPENDIR() failed for '%s'"
2051                          " - %s\n", snapdir, strerror(errno)));
2052                 errno = ENOSYS;
2053                 goto done;
2054         }
2055
2056         if (shadow_copy2_data != NULL) {
2057                 shadow_copy2_data->num_volumes = 0;
2058                 shadow_copy2_data->labels      = NULL;
2059         }
2060
2061         SMB_VFS_HANDLE_GET_DATA(handle, priv, struct shadow_copy2_private,
2062                                 goto done);
2063
2064         /*
2065          * Normally this function is called twice once with labels = false and
2066          * then with labels = true. When labels is false it will return the
2067          * number of volumes so that the caller can allocate memory for that
2068          * many labels. Therefore to eliminate snaplist both the times it is
2069          * good to check if labels is set or not.
2070          *
2071          * shadow_copy2_data is NULL when we only want to update the list and
2072          * don't want any labels.
2073          */
2074         if ((priv->snaps->regex != NULL) && (labels || shadow_copy2_data == NULL)) {
2075                 get_snaplist = true;
2076                 /* Reset the global snaplist */
2077                 shadow_copy2_delete_snaplist(priv);
2078
2079                 /* Set the current time as snaplist update time */
2080                 time(&(priv->snaps->fetch_time));
2081         }
2082
2083         while ((d = SMB_VFS_NEXT_READDIR(handle, p, NULL))) {
2084                 char snapshot[GMT_NAME_LEN+1];
2085                 SHADOW_COPY_LABEL *tlabels;
2086
2087                 /*
2088                  * ignore names not of the right form in the snapshot
2089                  * directory
2090                  */
2091                 if (!shadow_copy2_snapshot_to_gmt(
2092                             handle, d->d_name,
2093                             snapshot, sizeof(snapshot))) {
2094
2095                         DEBUG(6, ("shadow_copy2_get_shadow_copy_data: "
2096                                   "ignoring %s\n", d->d_name));
2097                         continue;
2098                 }
2099                 DEBUG(6,("shadow_copy2_get_shadow_copy_data: %s -> %s\n",
2100                          d->d_name, snapshot));
2101
2102                 if (get_snaplist) {
2103                         /*
2104                          * Create a snap entry for each successful
2105                          * pattern match.
2106                          */
2107                         tmpentry = shadow_copy2_create_snapentry(priv);
2108                         if (tmpentry == NULL) {
2109                                 DBG_ERR("talloc_zero() failed\n");
2110                                 goto done;
2111                         }
2112                         tmpentry->snapname = talloc_strdup(tmpentry, d->d_name);
2113                         tmpentry->time_fmt = talloc_strdup(tmpentry, snapshot);
2114                 }
2115
2116                 if (shadow_copy2_data == NULL) {
2117                         continue;
2118                 }
2119
2120                 if (!labels) {
2121                         /* the caller doesn't want the labels */
2122                         shadow_copy2_data->num_volumes++;
2123                         continue;
2124                 }
2125
2126                 tlabels = talloc_realloc(shadow_copy2_data,
2127                                          shadow_copy2_data->labels,
2128                                          SHADOW_COPY_LABEL,
2129                                          shadow_copy2_data->num_volumes+1);
2130                 if (tlabels == NULL) {
2131                         DEBUG(0,("shadow_copy2: out of memory\n"));
2132                         goto done;
2133                 }
2134
2135                 strlcpy(tlabels[shadow_copy2_data->num_volumes], snapshot,
2136                         sizeof(*tlabels));
2137
2138                 shadow_copy2_data->num_volumes++;
2139                 shadow_copy2_data->labels = tlabels;
2140         }
2141
2142         shadow_copy2_sort_data(handle, shadow_copy2_data);
2143         ret = 0;
2144
2145 done:
2146         if (p != NULL) {
2147                 SMB_VFS_NEXT_CLOSEDIR(handle, p);
2148                 p = NULL;
2149         }
2150         if (dirfsp != NULL) {
2151                 fd_close(dirfsp);
2152                 file_free(NULL, dirfsp);
2153         }
2154         TALLOC_FREE(tmp_ctx);
2155         return ret;
2156 }
2157
2158 static NTSTATUS shadow_copy2_fget_nt_acl(vfs_handle_struct *handle,
2159                                         struct files_struct *fsp,
2160                                         uint32_t security_info,
2161                                          TALLOC_CTX *mem_ctx,
2162                                         struct security_descriptor **ppdesc)
2163 {
2164         time_t timestamp = 0;
2165         char *stripped = NULL;
2166         NTSTATUS status;
2167         char *conv;
2168         struct smb_filename *smb_fname = NULL;
2169
2170         if (!shadow_copy2_strip_snapshot(talloc_tos(), handle,
2171                                          fsp->fsp_name->base_name,
2172                                          &timestamp, &stripped)) {
2173                 return map_nt_error_from_unix(errno);
2174         }
2175         if (timestamp == 0) {
2176                 return SMB_VFS_NEXT_FGET_NT_ACL(handle, fsp, security_info,
2177                                                 mem_ctx,
2178                                                 ppdesc);
2179         }
2180         conv = shadow_copy2_convert(talloc_tos(), handle, stripped, timestamp);
2181         TALLOC_FREE(stripped);
2182         if (conv == NULL) {
2183                 return map_nt_error_from_unix(errno);
2184         }
2185         smb_fname = synthetic_smb_fname(talloc_tos(),
2186                                         conv,
2187                                         NULL,
2188                                         NULL,
2189                                         fsp->fsp_name->flags);
2190         if (smb_fname == NULL) {
2191                 TALLOC_FREE(conv);
2192                 return NT_STATUS_NO_MEMORY;
2193         }
2194
2195         status = SMB_VFS_NEXT_GET_NT_ACL(handle, smb_fname, security_info,
2196                                          mem_ctx, ppdesc);
2197         TALLOC_FREE(conv);
2198         TALLOC_FREE(smb_fname);
2199         return status;
2200 }
2201
2202 static NTSTATUS shadow_copy2_get_nt_acl(vfs_handle_struct *handle,
2203                                         const struct smb_filename *smb_fname,
2204                                         uint32_t security_info,
2205                                         TALLOC_CTX *mem_ctx,
2206                                         struct security_descriptor **ppdesc)
2207 {
2208         time_t timestamp = 0;
2209         char *stripped = NULL;
2210         NTSTATUS status;
2211         char *conv;
2212         struct smb_filename *conv_smb_fname = NULL;
2213
2214         if (!shadow_copy2_strip_snapshot(talloc_tos(),
2215                                         handle,
2216                                         smb_fname->base_name,
2217                                         &timestamp,
2218                                         &stripped)) {
2219                 return map_nt_error_from_unix(errno);
2220         }
2221         if (timestamp == 0) {
2222                 return SMB_VFS_NEXT_GET_NT_ACL(handle, smb_fname, security_info,
2223                                                mem_ctx, ppdesc);
2224         }
2225         conv = shadow_copy2_convert(talloc_tos(), handle, stripped, timestamp);
2226         TALLOC_FREE(stripped);
2227         if (conv == NULL) {
2228                 return map_nt_error_from_unix(errno);
2229         }
2230         conv_smb_fname = synthetic_smb_fname(talloc_tos(),
2231                                         conv,
2232                                         NULL,
2233                                         NULL,
2234                                         smb_fname->flags);
2235         if (conv_smb_fname == NULL) {
2236                 TALLOC_FREE(conv);
2237                 return NT_STATUS_NO_MEMORY;
2238         }
2239         status = SMB_VFS_NEXT_GET_NT_ACL(handle, conv_smb_fname, security_info,
2240                                          mem_ctx, ppdesc);
2241         TALLOC_FREE(conv);
2242         TALLOC_FREE(conv_smb_fname);
2243         return status;
2244 }
2245
2246 static int shadow_copy2_mkdirat(vfs_handle_struct *handle,
2247                                 struct files_struct *dirfsp,
2248                                 const struct smb_filename *smb_fname,
2249                                 mode_t mode)
2250 {
2251         time_t timestamp = 0;
2252
2253         if (!shadow_copy2_strip_snapshot(talloc_tos(),
2254                                         handle,
2255                                         smb_fname->base_name,
2256                                         &timestamp,
2257                                         NULL)) {
2258                 return -1;
2259         }
2260         if (timestamp != 0) {
2261                 errno = EROFS;
2262                 return -1;
2263         }
2264         return SMB_VFS_NEXT_MKDIRAT(handle,
2265                         dirfsp,
2266                         smb_fname,
2267                         mode);
2268 }
2269
2270 static int shadow_copy2_chflags(vfs_handle_struct *handle,
2271                                 const struct smb_filename *smb_fname,
2272                                 unsigned int flags)
2273 {
2274         time_t timestamp = 0;
2275
2276         if (!shadow_copy2_strip_snapshot(talloc_tos(),
2277                                         handle,
2278                                         smb_fname->base_name,
2279                                         &timestamp,
2280                                         NULL)) {
2281                 return -1;
2282         }
2283         if (timestamp != 0) {
2284                 errno = EROFS;
2285                 return -1;
2286         }
2287         return SMB_VFS_NEXT_CHFLAGS(handle, smb_fname, flags);
2288 }
2289
2290 static ssize_t shadow_copy2_getxattr(vfs_handle_struct *handle,
2291                                 const struct smb_filename *smb_fname,
2292                                 const char *aname,
2293                                 void *value,
2294                                 size_t size)
2295 {
2296         time_t timestamp = 0;
2297         char *stripped = NULL;
2298         ssize_t ret;
2299         int saved_errno = 0;
2300         char *conv;
2301         struct smb_filename *conv_smb_fname = NULL;
2302
2303         if (!shadow_copy2_strip_snapshot(talloc_tos(),
2304                                 handle,
2305                                 smb_fname->base_name,
2306                                 &timestamp,
2307                                 &stripped)) {
2308                 return -1;
2309         }
2310         if (timestamp == 0) {
2311                 return SMB_VFS_NEXT_GETXATTR(handle, smb_fname, aname, value,
2312                                              size);
2313         }
2314         conv = shadow_copy2_convert(talloc_tos(), handle, stripped, timestamp);
2315         TALLOC_FREE(stripped);
2316         if (conv == NULL) {
2317                 return -1;
2318         }
2319
2320         conv_smb_fname = synthetic_smb_fname(talloc_tos(),
2321                                         conv,
2322                                         NULL,
2323                                         NULL,
2324                                         smb_fname->flags);
2325         if (conv_smb_fname == NULL) {
2326                 TALLOC_FREE(conv);
2327                 return -1;
2328         }
2329
2330         ret = SMB_VFS_NEXT_GETXATTR(handle, conv_smb_fname, aname, value, size);
2331         if (ret == -1) {
2332                 saved_errno = errno;
2333         }
2334         TALLOC_FREE(conv_smb_fname);
2335         TALLOC_FREE(conv);
2336         if (saved_errno != 0) {
2337                 errno = saved_errno;
2338         }
2339         return ret;
2340 }
2341
2342 static ssize_t shadow_copy2_listxattr(struct vfs_handle_struct *handle,
2343                                       const struct smb_filename *smb_fname,
2344                                       char *list, size_t size)
2345 {
2346         time_t timestamp = 0;
2347         char *stripped = NULL;
2348         ssize_t ret;
2349         int saved_errno = 0;
2350         char *conv;
2351         struct smb_filename *conv_smb_fname = NULL;
2352
2353         if (!shadow_copy2_strip_snapshot(talloc_tos(),
2354                                 handle,
2355                                 smb_fname->base_name,
2356                                 &timestamp,
2357                                 &stripped)) {
2358                 return -1;
2359         }
2360         if (timestamp == 0) {
2361                 return SMB_VFS_NEXT_LISTXATTR(handle, smb_fname, list, size);
2362         }
2363         conv = shadow_copy2_convert(talloc_tos(), handle, stripped, timestamp);
2364         TALLOC_FREE(stripped);
2365         if (conv == NULL) {
2366                 return -1;
2367         }
2368         conv_smb_fname = synthetic_smb_fname(talloc_tos(),
2369                                         conv,
2370                                         NULL,
2371                                         NULL,
2372                                         smb_fname->flags);
2373         if (conv_smb_fname == NULL) {
2374                 TALLOC_FREE(conv);
2375                 return -1;
2376         }
2377         ret = SMB_VFS_NEXT_LISTXATTR(handle, conv_smb_fname, list, size);
2378         if (ret == -1) {
2379                 saved_errno = errno;
2380         }
2381         TALLOC_FREE(conv_smb_fname);
2382         TALLOC_FREE(conv);
2383         if (saved_errno != 0) {
2384                 errno = saved_errno;
2385         }
2386         return ret;
2387 }
2388
2389 static int shadow_copy2_removexattr(vfs_handle_struct *handle,
2390                                 const struct smb_filename *smb_fname,
2391                                 const char *aname)
2392 {
2393         time_t timestamp = 0;
2394
2395         if (!shadow_copy2_strip_snapshot(talloc_tos(),
2396                                 handle,
2397                                 smb_fname->base_name,
2398                                 &timestamp,
2399                                 NULL)) {
2400                 return -1;
2401         }
2402         if (timestamp != 0) {
2403                 errno = EROFS;
2404                 return -1;
2405         }
2406         return SMB_VFS_NEXT_REMOVEXATTR(handle, smb_fname, aname);
2407 }
2408
2409 static int shadow_copy2_setxattr(struct vfs_handle_struct *handle,
2410                                  const struct smb_filename *smb_fname,
2411                                  const char *aname, const void *value,
2412                                  size_t size, int flags)
2413 {
2414         time_t timestamp = 0;
2415
2416         if (!shadow_copy2_strip_snapshot(talloc_tos(),
2417                                 handle,
2418                                 smb_fname->base_name,
2419                                 &timestamp,
2420                                 NULL)) {
2421                 return -1;
2422         }
2423         if (timestamp != 0) {
2424                 errno = EROFS;
2425                 return -1;
2426         }
2427         return SMB_VFS_NEXT_SETXATTR(handle, smb_fname,
2428                                 aname, value, size, flags);
2429 }
2430
2431 static NTSTATUS shadow_copy2_create_dfs_pathat(struct vfs_handle_struct *handle,
2432                                 struct files_struct *dirfsp,
2433                                 const struct smb_filename *smb_fname,
2434                                 const struct referral *reflist,
2435                                 size_t referral_count)
2436 {
2437         time_t timestamp = 0;
2438
2439         if (!shadow_copy2_strip_snapshot(talloc_tos(),
2440                                         handle,
2441                                         smb_fname->base_name,
2442                                         &timestamp,
2443                                         NULL)) {
2444                 return NT_STATUS_NO_MEMORY;
2445         }
2446         if (timestamp != 0) {
2447                 return NT_STATUS_MEDIA_WRITE_PROTECTED;
2448         }
2449         return SMB_VFS_NEXT_CREATE_DFS_PATHAT(handle,
2450                         dirfsp,
2451                         smb_fname,
2452                         reflist,
2453                         referral_count);
2454 }
2455
2456 static NTSTATUS shadow_copy2_read_dfs_pathat(struct vfs_handle_struct *handle,
2457                                 TALLOC_CTX *mem_ctx,
2458                                 struct files_struct *dirfsp,
2459                                 const struct smb_filename *smb_fname,
2460                                 struct referral **ppreflist,
2461                                 size_t *preferral_count)
2462 {
2463         time_t timestamp = 0;
2464         char *stripped = NULL;
2465         struct smb_filename *conv = NULL;
2466         NTSTATUS status;
2467
2468         if (!shadow_copy2_strip_snapshot(mem_ctx,
2469                                         handle,
2470                                         smb_fname->base_name,
2471                                         &timestamp,
2472                                         &stripped)) {
2473                 return NT_STATUS_NO_MEMORY;
2474         }
2475         if (timestamp == 0) {
2476                 return SMB_VFS_NEXT_READ_DFS_PATHAT(handle,
2477                                         mem_ctx,
2478                                         dirfsp,
2479                                         smb_fname,
2480                                         ppreflist,
2481                                         preferral_count);
2482         }
2483
2484         conv = cp_smb_filename(mem_ctx, smb_fname);
2485         if (conv == NULL) {
2486                 TALLOC_FREE(stripped);
2487                 return NT_STATUS_NO_MEMORY;
2488         }
2489         conv->base_name = shadow_copy2_convert(conv,
2490                                         handle,
2491                                         stripped,
2492                                         timestamp);
2493         TALLOC_FREE(stripped);
2494         if (conv->base_name == NULL) {
2495                 TALLOC_FREE(conv);
2496                 return NT_STATUS_NO_MEMORY;
2497         }
2498
2499         status = SMB_VFS_NEXT_READ_DFS_PATHAT(handle,
2500                                 mem_ctx,
2501                                 dirfsp,
2502                                 conv,
2503                                 ppreflist,
2504                                 preferral_count);
2505
2506         TALLOC_FREE(conv);
2507         return status;
2508 }
2509
2510 static int shadow_copy2_get_real_filename(struct vfs_handle_struct *handle,
2511                                           const char *path,
2512                                           const char *name,
2513                                           TALLOC_CTX *mem_ctx,
2514                                           char **found_name)
2515 {
2516         time_t timestamp = 0;
2517         char *stripped = NULL;
2518         ssize_t ret;
2519         int saved_errno = 0;
2520         char *conv;
2521
2522         DEBUG(10, ("shadow_copy2_get_real_filename called for path=[%s], "
2523                    "name=[%s]\n", path, name));
2524
2525         if (!shadow_copy2_strip_snapshot(talloc_tos(), handle, path,
2526                                          &timestamp, &stripped)) {
2527                 DEBUG(10, ("shadow_copy2_strip_snapshot failed\n"));
2528                 return -1;
2529         }
2530         if (timestamp == 0) {
2531                 DEBUG(10, ("timestamp == 0\n"));
2532                 return SMB_VFS_NEXT_GET_REAL_FILENAME(handle, path, name,
2533                                                       mem_ctx, found_name);
2534         }
2535         conv = shadow_copy2_convert(talloc_tos(), handle, stripped, timestamp);
2536         TALLOC_FREE(stripped);
2537         if (conv == NULL) {
2538                 DEBUG(10, ("shadow_copy2_convert failed\n"));
2539                 return -1;
2540         }
2541         DEBUG(10, ("Calling NEXT_GET_REAL_FILE_NAME for conv=[%s], "
2542                    "name=[%s]\n", conv, name));
2543         ret = SMB_VFS_NEXT_GET_REAL_FILENAME(handle, conv, name,
2544                                              mem_ctx, found_name);
2545         DEBUG(10, ("NEXT_REAL_FILE_NAME returned %d\n", (int)ret));
2546         if (ret == -1) {
2547                 saved_errno = errno;
2548         }
2549         TALLOC_FREE(conv);
2550         if (saved_errno != 0) {
2551                 errno = saved_errno;
2552         }
2553         return ret;
2554 }
2555
2556 static const char *shadow_copy2_connectpath(struct vfs_handle_struct *handle,
2557                                         const struct smb_filename *smb_fname_in)
2558 {
2559         time_t timestamp = 0;
2560         char *stripped = NULL;
2561         char *tmp = NULL;
2562         const char *fname = smb_fname_in->base_name;
2563         struct smb_filename smb_fname = {0};
2564         struct smb_filename *result_fname = NULL;
2565         char *result = NULL;
2566         char *parent_dir = NULL;
2567         int saved_errno = 0;
2568         size_t rootpath_len = 0;
2569         struct shadow_copy2_private *priv = NULL;
2570
2571         SMB_VFS_HANDLE_GET_DATA(handle, priv, struct shadow_copy2_private,
2572                                 return NULL);
2573
2574         DBG_DEBUG("Calc connect path for [%s]\n", fname);
2575
2576         if (priv->shadow_connectpath != NULL) {
2577                 DBG_DEBUG("cached connect path is [%s]\n",
2578                         priv->shadow_connectpath);
2579                 return priv->shadow_connectpath;
2580         }
2581
2582         if (!shadow_copy2_strip_snapshot(talloc_tos(), handle, fname,
2583                                          &timestamp, &stripped)) {
2584                 goto done;
2585         }
2586         if (timestamp == 0) {
2587                 return SMB_VFS_NEXT_CONNECTPATH(handle, smb_fname_in);
2588         }
2589
2590         tmp = shadow_copy2_do_convert(talloc_tos(), handle, stripped, timestamp,
2591                                       &rootpath_len);
2592         if (tmp == NULL) {
2593                 if (errno != ENOENT) {
2594                         goto done;
2595                 }
2596
2597                 /*
2598                  * If the converted path does not exist, and converting
2599                  * the parent yields something that does exist, then
2600                  * this path refers to something that has not been
2601                  * created yet, relative to the parent path.
2602                  * The snapshot finding is relative to the parent.
2603                  * (usually snapshots are read/only but this is not
2604                  * necessarily true).
2605                  * This code also covers getting a wildcard in the
2606                  * last component, because this function is called
2607                  * prior to sanitizing the path, and in SMB1 we may
2608                  * get wildcards in path names.
2609                  */
2610                 if (!parent_dirname(talloc_tos(), stripped, &parent_dir,
2611                                     NULL)) {
2612                         errno = ENOMEM;
2613                         goto done;
2614                 }
2615
2616                 tmp = shadow_copy2_do_convert(talloc_tos(), handle, parent_dir,
2617                                               timestamp, &rootpath_len);
2618                 if (tmp == NULL) {
2619                         goto done;
2620                 }
2621         }
2622
2623         DBG_DEBUG("converted path is [%s] root path is [%.*s]\n", tmp,
2624                   (int)rootpath_len, tmp);
2625
2626         tmp[rootpath_len] = '\0';
2627         smb_fname = (struct smb_filename) { .base_name = tmp };
2628
2629         result_fname = SMB_VFS_NEXT_REALPATH(handle, priv, &smb_fname);
2630         if (result_fname == NULL) {
2631                 goto done;
2632         }
2633
2634         /*
2635          * SMB_VFS_NEXT_REALPATH returns a talloc'ed string.
2636          * Don't leak memory.
2637          */
2638         TALLOC_FREE(priv->shadow_realpath);
2639         priv->shadow_realpath = result_fname;
2640         result = priv->shadow_realpath->base_name;
2641
2642         DBG_DEBUG("connect path is [%s]\n", result);
2643
2644 done:
2645         if (result == NULL) {
2646                 saved_errno = errno;
2647         }
2648         TALLOC_FREE(tmp);
2649         TALLOC_FREE(stripped);
2650         TALLOC_FREE(parent_dir);
2651         if (saved_errno != 0) {
2652                 errno = saved_errno;
2653         }
2654         return result;
2655 }
2656
2657 static uint64_t shadow_copy2_disk_free(vfs_handle_struct *handle,
2658                                 const struct smb_filename *smb_fname,
2659                                 uint64_t *bsize,
2660                                 uint64_t *dfree,
2661                                 uint64_t *dsize)
2662 {
2663         time_t timestamp = 0;
2664         char *stripped = NULL;
2665         int saved_errno = 0;
2666         char *conv = NULL;
2667         struct smb_filename *conv_smb_fname = NULL;
2668         uint64_t ret = (uint64_t)-1;
2669
2670         if (!shadow_copy2_strip_snapshot(talloc_tos(),
2671                                 handle,
2672                                 smb_fname->base_name,
2673                                 &timestamp,
2674                                 &stripped)) {
2675                 return (uint64_t)-1;
2676         }
2677         if (timestamp == 0) {
2678                 return SMB_VFS_NEXT_DISK_FREE(handle, smb_fname,
2679                                               bsize, dfree, dsize);
2680         }
2681         conv = shadow_copy2_convert(talloc_tos(), handle, stripped, timestamp);
2682         TALLOC_FREE(stripped);
2683         if (conv == NULL) {
2684                 return (uint64_t)-1;
2685         }
2686         conv_smb_fname = synthetic_smb_fname(talloc_tos(),
2687                                         conv,
2688                                         NULL,
2689                                         NULL,
2690                                         smb_fname->flags);
2691         if (conv_smb_fname == NULL) {
2692                 TALLOC_FREE(conv);
2693                 return (uint64_t)-1;
2694         }
2695         ret = SMB_VFS_NEXT_DISK_FREE(handle, conv_smb_fname,
2696                                 bsize, dfree, dsize);
2697         if (ret == (uint64_t)-1) {
2698                 saved_errno = errno;
2699         }
2700         TALLOC_FREE(conv);
2701         TALLOC_FREE(conv_smb_fname);
2702         if (saved_errno != 0) {
2703                 errno = saved_errno;
2704         }
2705         return ret;
2706 }
2707
2708 static int shadow_copy2_get_quota(vfs_handle_struct *handle,
2709                                 const struct smb_filename *smb_fname,
2710                                 enum SMB_QUOTA_TYPE qtype,
2711                                 unid_t id,
2712                                 SMB_DISK_QUOTA *dq)
2713 {
2714         time_t timestamp = 0;
2715         char *stripped = NULL;
2716         int ret;
2717         int saved_errno = 0;
2718         char *conv;
2719         struct smb_filename *conv_smb_fname = NULL;
2720
2721         if (!shadow_copy2_strip_snapshot(talloc_tos(),
2722                                 handle,
2723                                 smb_fname->base_name,
2724                                 &timestamp,
2725                                 &stripped)) {
2726                 return -1;
2727         }
2728         if (timestamp == 0) {
2729                 return SMB_VFS_NEXT_GET_QUOTA(handle, smb_fname, qtype, id, dq);
2730         }
2731
2732         conv = shadow_copy2_convert(talloc_tos(), handle, stripped, timestamp);
2733         TALLOC_FREE(stripped);
2734         if (conv == NULL) {
2735                 return -1;
2736         }
2737         conv_smb_fname = synthetic_smb_fname(talloc_tos(),
2738                                         conv,
2739                                         NULL,
2740                                         NULL,
2741                                         smb_fname->flags);
2742         if (conv_smb_fname == NULL) {
2743                 TALLOC_FREE(conv);
2744                 return -1;
2745         }
2746         ret = SMB_VFS_NEXT_GET_QUOTA(handle, conv_smb_fname, qtype, id, dq);
2747
2748         if (ret == -1) {
2749                 saved_errno = errno;
2750         }
2751         TALLOC_FREE(conv);
2752         TALLOC_FREE(conv_smb_fname);
2753         if (saved_errno != 0) {
2754                 errno = saved_errno;
2755         }
2756
2757         return ret;
2758 }
2759
2760 static ssize_t shadow_copy2_pwrite(vfs_handle_struct *handle,
2761                                    files_struct *fsp,
2762                                    const void *data,
2763                                    size_t n,
2764                                    off_t offset)
2765 {
2766         ssize_t nwritten;
2767
2768         nwritten = SMB_VFS_NEXT_PWRITE(handle, fsp, data, n, offset);
2769         if (nwritten == -1) {
2770                 if (errno == EBADF && fsp->can_write) {
2771                         errno = EROFS;
2772                 }
2773         }
2774
2775         return nwritten;
2776 }
2777
2778 struct shadow_copy2_pwrite_state {
2779         vfs_handle_struct *handle;
2780         files_struct *fsp;
2781         ssize_t ret;
2782         struct vfs_aio_state vfs_aio_state;
2783 };
2784
2785 static void shadow_copy2_pwrite_done(struct tevent_req *subreq);
2786
2787 static struct tevent_req *shadow_copy2_pwrite_send(
2788         struct vfs_handle_struct *handle, TALLOC_CTX *mem_ctx,
2789         struct tevent_context *ev, struct files_struct *fsp,
2790         const void *data, size_t n, off_t offset)
2791 {
2792         struct tevent_req *req = NULL, *subreq = NULL;
2793         struct shadow_copy2_pwrite_state *state = NULL;
2794
2795         req = tevent_req_create(mem_ctx, &state,
2796                                 struct shadow_copy2_pwrite_state);
2797         if (req == NULL) {
2798                 return NULL;
2799         }
2800         state->handle = handle;
2801         state->fsp = fsp;
2802
2803         subreq = SMB_VFS_NEXT_PWRITE_SEND(state,
2804                                           ev,
2805                                           handle,
2806                                           fsp,
2807                                           data,
2808                                           n,
2809                                           offset);
2810         if (tevent_req_nomem(subreq, req)) {
2811                 return tevent_req_post(req, ev);
2812         }
2813         tevent_req_set_callback(subreq, shadow_copy2_pwrite_done, req);
2814
2815         return req;
2816 }
2817
2818 static void shadow_copy2_pwrite_done(struct tevent_req *subreq)
2819 {
2820         struct tevent_req *req = tevent_req_callback_data(
2821                 subreq, struct tevent_req);
2822         struct shadow_copy2_pwrite_state *state = tevent_req_data(
2823                 req, struct shadow_copy2_pwrite_state);
2824
2825         state->ret = SMB_VFS_PWRITE_RECV(subreq, &state->vfs_aio_state);
2826         TALLOC_FREE(subreq);
2827         if (state->ret == -1) {
2828                 tevent_req_error(req, state->vfs_aio_state.error);
2829                 return;
2830         }
2831
2832         tevent_req_done(req);
2833 }
2834
2835 static ssize_t shadow_copy2_pwrite_recv(struct tevent_req *req,
2836                                           struct vfs_aio_state *vfs_aio_state)
2837 {
2838         struct shadow_copy2_pwrite_state *state = tevent_req_data(
2839                 req, struct shadow_copy2_pwrite_state);
2840
2841         if (tevent_req_is_unix_error(req, &vfs_aio_state->error)) {
2842                 if ((vfs_aio_state->error == EBADF) &&
2843                     state->fsp->can_write)
2844                 {
2845                         vfs_aio_state->error = EROFS;
2846                         errno = EROFS;
2847                 }
2848                 return -1;
2849         }
2850
2851         *vfs_aio_state = state->vfs_aio_state;
2852         return state->ret;
2853 }
2854
2855 static int shadow_copy2_connect(struct vfs_handle_struct *handle,
2856                                 const char *service, const char *user)
2857 {
2858         struct shadow_copy2_config *config;
2859         struct shadow_copy2_private *priv;
2860         int ret;
2861         const char *snapdir;
2862         const char *snapprefix = NULL;
2863         const char *delimiter;
2864         const char *gmt_format;
2865         const char *sort_order;
2866         const char *basedir = NULL;
2867         const char *snapsharepath = NULL;
2868         const char *mount_point;
2869
2870         DEBUG(10, (__location__ ": cnum[%u], connectpath[%s]\n",
2871                    (unsigned)handle->conn->cnum,
2872                    handle->conn->connectpath));
2873
2874         ret = SMB_VFS_NEXT_CONNECT(handle, service, user);
2875         if (ret < 0) {
2876                 return ret;
2877         }
2878
2879         priv = talloc_zero(handle->conn, struct shadow_copy2_private);
2880         if (priv == NULL) {
2881                 DBG_ERR("talloc_zero() failed\n");
2882                 errno = ENOMEM;
2883                 return -1;
2884         }
2885
2886         priv->snaps = talloc_zero(priv, struct shadow_copy2_snaplist_info);
2887         if (priv->snaps == NULL) {
2888                 DBG_ERR("talloc_zero() failed\n");
2889                 errno = ENOMEM;
2890                 return -1;
2891         }
2892
2893         config = talloc_zero(priv, struct shadow_copy2_config);
2894         if (config == NULL) {
2895                 DEBUG(0, ("talloc_zero() failed\n"));
2896                 errno = ENOMEM;
2897                 return -1;
2898         }
2899
2900         priv->config = config;
2901
2902         gmt_format = lp_parm_const_string(SNUM(handle->conn),
2903                                           "shadow", "format",
2904                                           GMT_FORMAT);
2905         config->gmt_format = talloc_strdup(config, gmt_format);
2906         if (config->gmt_format == NULL) {
2907                 DEBUG(0, ("talloc_strdup() failed\n"));
2908                 errno = ENOMEM;
2909                 return -1;
2910         }
2911
2912         /* config->gmt_format must not contain a path separator. */
2913         if (strchr(config->gmt_format, '/') != NULL) {
2914                 DEBUG(0, ("shadow:format %s must not contain a /"
2915                         "character. Unable to initialize module.\n",
2916                         config->gmt_format));
2917                 errno = EINVAL;
2918                 return -1;
2919         }
2920
2921         config->use_sscanf = lp_parm_bool(SNUM(handle->conn),
2922                                           "shadow", "sscanf", false);
2923
2924         config->use_localtime = lp_parm_bool(SNUM(handle->conn),
2925                                              "shadow", "localtime",
2926                                              false);
2927
2928         snapdir = lp_parm_const_string(SNUM(handle->conn),
2929                                        "shadow", "snapdir",
2930                                        ".snapshots");
2931         config->snapdir = talloc_strdup(config, snapdir);
2932         if (config->snapdir == NULL) {
2933                 DEBUG(0, ("talloc_strdup() failed\n"));
2934                 errno = ENOMEM;
2935                 return -1;
2936         }
2937
2938         snapprefix = lp_parm_const_string(SNUM(handle->conn),
2939                                        "shadow", "snapprefix",
2940                                        NULL);
2941         if (snapprefix != NULL) {
2942                 priv->snaps->regex = talloc_zero(priv->snaps, regex_t);
2943                 if (priv->snaps->regex == NULL) {
2944                         DBG_ERR("talloc_zero() failed\n");
2945                         errno = ENOMEM;
2946                         return -1;
2947                 }
2948
2949                 /* pre-compute regex rule for matching pattern later */
2950                 ret = regcomp(priv->snaps->regex, snapprefix, 0);
2951                 if (ret) {
2952                         DBG_ERR("Failed to create regex object\n");
2953                         return -1;
2954                 }
2955         }
2956
2957         delimiter = lp_parm_const_string(SNUM(handle->conn),
2958                                        "shadow", "delimiter",
2959                                        "_GMT");
2960         if (delimiter != NULL) {
2961                 priv->config->delimiter = talloc_strdup(priv->config, delimiter);
2962                 if (priv->config->delimiter == NULL) {
2963                         DBG_ERR("talloc_strdup() failed\n");
2964                         errno = ENOMEM;
2965                         return -1;
2966                 }
2967         }
2968
2969         config->snapdirseverywhere = lp_parm_bool(SNUM(handle->conn),
2970                                                   "shadow",
2971                                                   "snapdirseverywhere",
2972                                                   false);
2973
2974         config->crossmountpoints = lp_parm_bool(SNUM(handle->conn),
2975                                                 "shadow", "crossmountpoints",
2976                                                 false);
2977
2978         if (config->crossmountpoints && !config->snapdirseverywhere) {
2979                 DBG_WARNING("Warning: 'crossmountpoints' depends on "
2980                             "'snapdirseverywhere'. Disabling crossmountpoints.\n");
2981         }
2982
2983         config->fixinodes = lp_parm_bool(SNUM(handle->conn),
2984                                          "shadow", "fixinodes",
2985                                          false);
2986
2987         sort_order = lp_parm_const_string(SNUM(handle->conn),
2988                                           "shadow", "sort", "desc");
2989         config->sort_order = talloc_strdup(config, sort_order);
2990         if (config->sort_order == NULL) {
2991                 DEBUG(0, ("talloc_strdup() failed\n"));
2992                 errno = ENOMEM;
2993                 return -1;
2994         }
2995
2996         mount_point = lp_parm_const_string(SNUM(handle->conn),
2997                                            "shadow", "mountpoint", NULL);
2998         if (mount_point != NULL) {
2999                 if (mount_point[0] != '/') {
3000                         DEBUG(1, (__location__ " Warning: 'mountpoint' is "
3001                                   "relative ('%s'), but it has to be an "
3002                                   "absolute path. Ignoring provided value.\n",
3003                                   mount_point));
3004                         mount_point = NULL;
3005                 } else {
3006                         char *p;
3007                         p = strstr(handle->conn->connectpath, mount_point);
3008                         if (p != handle->conn->connectpath) {
3009                                 DBG_WARNING("Warning: the share root (%s) is "
3010                                             "not a subdirectory of the "
3011                                             "specified mountpoint (%s). "
3012                                             "Ignoring provided value.\n",
3013                                             handle->conn->connectpath,
3014                                             mount_point);
3015                                 mount_point = NULL;
3016                         }
3017                 }
3018         }
3019
3020         if (mount_point != NULL) {
3021                 config->mount_point = talloc_strdup(config, mount_point);
3022                 if (config->mount_point == NULL) {
3023                         DEBUG(0, (__location__ " talloc_strdup() failed\n"));
3024                         return -1;
3025                 }
3026         } else {
3027                 config->mount_point = shadow_copy2_find_mount_point(config,
3028                                                                     handle);
3029                 if (config->mount_point == NULL) {
3030                         DBG_WARNING("shadow_copy2_find_mount_point "
3031                                     "of the share root '%s' failed: %s\n",
3032                                     handle->conn->connectpath, strerror(errno));
3033                         return -1;
3034                 }
3035         }
3036
3037         basedir = lp_parm_const_string(SNUM(handle->conn),
3038                                        "shadow", "basedir", NULL);
3039
3040         if (basedir != NULL) {
3041                 if (basedir[0] != '/') {
3042                         DEBUG(1, (__location__ " Warning: 'basedir' is "
3043                                   "relative ('%s'), but it has to be an "
3044                                   "absolute path. Disabling basedir.\n",
3045                                   basedir));
3046                         basedir = NULL;
3047                 } else {
3048                         char *p;
3049                         p = strstr(basedir, config->mount_point);
3050                         if (p != basedir) {
3051                                 DEBUG(1, ("Warning: basedir (%s) is not a "
3052                                           "subdirectory of the share root's "
3053                                           "mount point (%s). "
3054                                           "Disabling basedir\n",
3055                                           basedir, config->mount_point));
3056                                 basedir = NULL;
3057                         }
3058                 }
3059         }
3060
3061         if (config->snapdirseverywhere && basedir != NULL) {
3062                 DEBUG(1, (__location__ " Warning: 'basedir' is incompatible "
3063                           "with 'snapdirseverywhere'. Disabling basedir.\n"));
3064                 basedir = NULL;
3065         }
3066
3067         snapsharepath = lp_parm_const_string(SNUM(handle->conn), "shadow",
3068                                              "snapsharepath", NULL);
3069         if (snapsharepath != NULL) {
3070                 if (snapsharepath[0] == '/') {
3071                         DBG_WARNING("Warning: 'snapsharepath' is "
3072                                     "absolute ('%s'), but it has to be a "
3073                                     "relative path. Disabling snapsharepath.\n",
3074                                     snapsharepath);
3075                         snapsharepath = NULL;
3076                 }
3077                 if (config->snapdirseverywhere && snapsharepath != NULL) {
3078                         DBG_WARNING("Warning: 'snapsharepath' is incompatible "
3079                                     "with 'snapdirseverywhere'. Disabling "
3080                                     "snapsharepath.\n");
3081                         snapsharepath = NULL;
3082                 }
3083         }
3084
3085         if (basedir != NULL && snapsharepath != NULL) {
3086                 DBG_WARNING("Warning: 'snapsharepath' is incompatible with "
3087                             "'basedir'. Disabling snapsharepath\n");
3088                 snapsharepath = NULL;
3089         }
3090
3091         if (snapsharepath != NULL) {
3092                 config->rel_connectpath = talloc_strdup(config, snapsharepath);
3093                 if (config->rel_connectpath == NULL) {
3094                         DBG_ERR("talloc_strdup() failed\n");
3095                         errno = ENOMEM;
3096                         return -1;
3097                 }
3098         }
3099
3100         if (basedir == NULL) {
3101                 basedir = config->mount_point;
3102         }
3103
3104         if (config->rel_connectpath == NULL &&
3105             strlen(basedir) < strlen(handle->conn->connectpath)) {
3106                 config->rel_connectpath = talloc_strdup(config,
3107                         handle->conn->connectpath + strlen(basedir));
3108                 if (config->rel_connectpath == NULL) {
3109                         DEBUG(0, ("talloc_strdup() failed\n"));
3110                         errno = ENOMEM;
3111                         return -1;
3112                 }
3113         }
3114
3115         if (config->snapdir[0] == '/') {
3116                 config->snapdir_absolute = true;
3117
3118                 if (config->snapdirseverywhere == true) {
3119                         DEBUG(1, (__location__ " Warning: An absolute snapdir "
3120                                   "is incompatible with 'snapdirseverywhere', "
3121                                   "setting 'snapdirseverywhere' to false.\n"));
3122                         config->snapdirseverywhere = false;
3123                 }
3124
3125                 if (config->crossmountpoints == true) {
3126                         DEBUG(1, (__location__ " Warning: 'crossmountpoints' "
3127                                   "is not supported with an absolute snapdir. "
3128                                   "Disabling it.\n"));
3129                         config->crossmountpoints = false;
3130                 }
3131
3132                 config->snapshot_basepath = config->snapdir;
3133         } else {
3134                 config->snapshot_basepath = talloc_asprintf(config, "%s/%s",
3135                                 config->mount_point, config->snapdir);
3136                 if (config->snapshot_basepath == NULL) {
3137                         DEBUG(0, ("talloc_asprintf() failed\n"));
3138                         errno = ENOMEM;
3139                         return -1;
3140                 }
3141         }
3142
3143         trim_string(config->mount_point, NULL, "/");
3144         trim_string(config->rel_connectpath, "/", "/");
3145         trim_string(config->snapdir, NULL, "/");
3146         trim_string(config->snapshot_basepath, NULL, "/");
3147
3148         DEBUG(10, ("shadow_copy2_connect: configuration:\n"
3149                    "  share root: '%s'\n"
3150                    "  mountpoint: '%s'\n"
3151                    "  rel share root: '%s'\n"
3152                    "  snapdir: '%s'\n"
3153                    "  snapprefix: '%s'\n"
3154                    "  delimiter: '%s'\n"
3155                    "  snapshot base path: '%s'\n"
3156                    "  format: '%s'\n"
3157                    "  use sscanf: %s\n"
3158                    "  snapdirs everywhere: %s\n"
3159                    "  cross mountpoints: %s\n"
3160                    "  fix inodes: %s\n"
3161                    "  sort order: %s\n"
3162                    "",
3163                    handle->conn->connectpath,
3164                    config->mount_point,
3165                    config->rel_connectpath,
3166                    config->snapdir,
3167                    snapprefix,
3168                    config->delimiter,
3169                    config->snapshot_basepath,
3170                    config->gmt_format,
3171                    config->use_sscanf ? "yes" : "no",
3172                    config->snapdirseverywhere ? "yes" : "no",
3173                    config->crossmountpoints ? "yes" : "no",
3174                    config->fixinodes ? "yes" : "no",
3175                    config->sort_order
3176                    ));
3177
3178
3179         SMB_VFS_HANDLE_SET_DATA(handle, priv,
3180                                 NULL, struct shadow_copy2_private,
3181                                 return -1);
3182
3183         return 0;
3184 }
3185
3186 static struct vfs_fn_pointers vfs_shadow_copy2_fns = {
3187         .connect_fn = shadow_copy2_connect,
3188         .disk_free_fn = shadow_copy2_disk_free,
3189         .get_quota_fn = shadow_copy2_get_quota,
3190         .create_dfs_pathat_fn = shadow_copy2_create_dfs_pathat,
3191         .read_dfs_pathat_fn = shadow_copy2_read_dfs_pathat,
3192         .renameat_fn = shadow_copy2_renameat,
3193         .linkat_fn = shadow_copy2_linkat,
3194         .symlinkat_fn = shadow_copy2_symlinkat,
3195         .stat_fn = shadow_copy2_stat,
3196         .lstat_fn = shadow_copy2_lstat,
3197         .fstat_fn = shadow_copy2_fstat,
3198         .open_fn = shadow_copy2_open,
3199         .unlinkat_fn = shadow_copy2_unlinkat,
3200         .chmod_fn = shadow_copy2_chmod,
3201         .chdir_fn = shadow_copy2_chdir,
3202         .ntimes_fn = shadow_copy2_ntimes,
3203         .readlinkat_fn = shadow_copy2_readlinkat,
3204         .mknodat_fn = shadow_copy2_mknodat,
3205         .realpath_fn = shadow_copy2_realpath,
3206         .get_nt_acl_fn = shadow_copy2_get_nt_acl,
3207         .fget_nt_acl_fn = shadow_copy2_fget_nt_acl,
3208         .get_shadow_copy_data_fn = shadow_copy2_get_shadow_copy_data,
3209         .mkdirat_fn = shadow_copy2_mkdirat,
3210         .getxattr_fn = shadow_copy2_getxattr,
3211         .getxattrat_send_fn = vfs_not_implemented_getxattrat_send,
3212         .getxattrat_recv_fn = vfs_not_implemented_getxattrat_recv,
3213         .listxattr_fn = shadow_copy2_listxattr,
3214         .removexattr_fn = shadow_copy2_removexattr,
3215         .setxattr_fn = shadow_copy2_setxattr,
3216         .chflags_fn = shadow_copy2_chflags,
3217         .get_real_filename_fn = shadow_copy2_get_real_filename,
3218         .pwrite_fn = shadow_copy2_pwrite,
3219         .pwrite_send_fn = shadow_copy2_pwrite_send,
3220         .pwrite_recv_fn = shadow_copy2_pwrite_recv,
3221         .connectpath_fn = shadow_copy2_connectpath,
3222 };
3223
3224 static_decl_vfs;
3225 NTSTATUS vfs_shadow_copy2_init(TALLOC_CTX *ctx)
3226 {
3227         return smb_register_vfs(SMB_VFS_INTERFACE_VERSION,
3228                                 "shadow_copy2", &vfs_shadow_copy2_fns);
3229 }