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