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