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