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