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