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