s3:smbd: move all globals and static variables in globals.[ch]
[sfrench/samba-autobuild/.git] / source3 / smbd / vfs.c
1 /*
2    Unix SMB/Netbios implementation.
3    Version 1.9.
4    VFS initialisation and support functions
5    Copyright (C) Tim Potter 1999
6    Copyright (C) Alexander Bokovoy 2002
7    Copyright (C) James Peach 2006
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.
21
22    This work was sponsored by Optifacio Software Services, Inc.
23 */
24
25 #include "includes.h"
26 #include "smbd/globals.h"
27
28 #undef DBGC_CLASS
29 #define DBGC_CLASS DBGC_VFS
30
31 static_decl_vfs;
32
33 struct vfs_init_function_entry {
34         char *name;
35         const vfs_op_tuple *vfs_op_tuples;
36         struct vfs_init_function_entry *prev, *next;
37 };
38
39 /****************************************************************************
40     maintain the list of available backends
41 ****************************************************************************/
42
43 static struct vfs_init_function_entry *vfs_find_backend_entry(const char *name)
44 {
45         struct vfs_init_function_entry *entry = backends;
46
47         DEBUG(10, ("vfs_find_backend_entry called for %s\n", name));
48  
49         while(entry) {
50                 if (strcmp(entry->name, name)==0) return entry;
51                 entry = entry->next;
52         }
53
54         return NULL;
55 }
56
57 NTSTATUS smb_register_vfs(int version, const char *name, const vfs_op_tuple *vfs_op_tuples)
58 {
59         struct vfs_init_function_entry *entry = backends;
60
61         if ((version != SMB_VFS_INTERFACE_VERSION)) {
62                 DEBUG(0, ("Failed to register vfs module.\n"
63                           "The module was compiled against SMB_VFS_INTERFACE_VERSION %d,\n"
64                           "current SMB_VFS_INTERFACE_VERSION is %d.\n"
65                           "Please recompile against the current Samba Version!\n",  
66                           version, SMB_VFS_INTERFACE_VERSION));
67                 return NT_STATUS_OBJECT_TYPE_MISMATCH;
68         }
69
70         if (!name || !name[0] || !vfs_op_tuples) {
71                 DEBUG(0,("smb_register_vfs() called with NULL pointer or empty name!\n"));
72                 return NT_STATUS_INVALID_PARAMETER;
73         }
74
75         if (vfs_find_backend_entry(name)) {
76                 DEBUG(0,("VFS module %s already loaded!\n", name));
77                 return NT_STATUS_OBJECT_NAME_COLLISION;
78         }
79
80         entry = SMB_XMALLOC_P(struct vfs_init_function_entry);
81         entry->name = smb_xstrdup(name);
82         entry->vfs_op_tuples = vfs_op_tuples;
83
84         DLIST_ADD(backends, entry);
85         DEBUG(5, ("Successfully added vfs backend '%s'\n", name));
86         return NT_STATUS_OK;
87 }
88
89 /****************************************************************************
90   initialise default vfs hooks
91 ****************************************************************************/
92
93 static void vfs_init_default(connection_struct *conn)
94 {
95         DEBUG(3, ("Initialising default vfs hooks\n"));
96         vfs_init_custom(conn, DEFAULT_VFS_MODULE_NAME);
97 }
98
99 /****************************************************************************
100   initialise custom vfs hooks
101  ****************************************************************************/
102
103 static inline void vfs_set_operation(struct vfs_ops * vfs, vfs_op_type which,
104                                 struct vfs_handle_struct * handle, void * op)
105 {
106         ((struct vfs_handle_struct **)&vfs->handles)[which] = handle;
107         ((void **)(void *)&vfs->ops)[which] = op;
108 }
109
110 bool vfs_init_custom(connection_struct *conn, const char *vfs_object)
111 {
112         const vfs_op_tuple *ops;
113         char *module_path = NULL;
114         char *module_name = NULL;
115         char *module_param = NULL, *p;
116         int i;
117         vfs_handle_struct *handle;
118         const struct vfs_init_function_entry *entry;
119         
120         if (!conn||!vfs_object||!vfs_object[0]) {
121                 DEBUG(0,("vfs_init_custon() called with NULL pointer or emtpy vfs_object!\n"));
122                 return False;
123         }
124
125         if(!backends) {
126                 static_init_vfs;
127         }
128
129         DEBUG(3, ("Initialising custom vfs hooks from [%s]\n", vfs_object));
130
131         module_path = smb_xstrdup(vfs_object);
132
133         p = strchr_m(module_path, ':');
134
135         if (p) {
136                 *p = 0;
137                 module_param = p+1;
138                 trim_char(module_param, ' ', ' ');
139         }
140
141         trim_char(module_path, ' ', ' ');
142
143         module_name = smb_xstrdup(module_path);
144
145         if ((module_name[0] == '/') &&
146             (strcmp(module_path, DEFAULT_VFS_MODULE_NAME) != 0)) {
147
148                 /*
149                  * Extract the module name from the path. Just use the base
150                  * name of the last path component.
151                  */
152
153                 SAFE_FREE(module_name);
154                 module_name = smb_xstrdup(strrchr_m(module_path, '/')+1);
155
156                 p = strchr_m(module_name, '.');
157
158                 if (p != NULL) {
159                         *p = '\0';
160                 }
161         }
162
163         /* First, try to load the module with the new module system */
164         if((entry = vfs_find_backend_entry(module_name)) || 
165            (NT_STATUS_IS_OK(smb_probe_module("vfs", module_path)) &&
166                 (entry = vfs_find_backend_entry(module_name)))) {
167
168                 DEBUGADD(5,("Successfully loaded vfs module [%s] with the new modules system\n", vfs_object));
169                 
170                 if ((ops = entry->vfs_op_tuples) == NULL) {
171                         DEBUG(0, ("entry->vfs_op_tuples==NULL for [%s] failed\n", vfs_object));
172                         goto fail;
173                 }
174         } else {
175                 DEBUG(0,("Can't find a vfs module [%s]\n",vfs_object));
176                 goto fail;
177         }
178
179         handle = TALLOC_ZERO_P(conn, vfs_handle_struct);
180         if (!handle) {
181                 DEBUG(0,("TALLOC_ZERO() failed!\n"));
182                 goto fail;
183         }
184         memcpy(&handle->vfs_next, &conn->vfs, sizeof(struct vfs_ops));
185         handle->conn = conn;
186         if (module_param) {
187                 handle->param = talloc_strdup(conn, module_param);
188         }
189         DLIST_ADD(conn->vfs_handles, handle);
190
191         for(i=0; ops[i].op != NULL; i++) {
192                 DEBUG(5, ("Checking operation #%d (type %d, layer %d)\n", i, ops[i].type, ops[i].layer));
193                 if(ops[i].layer == SMB_VFS_LAYER_OPAQUE) {
194                         /* If this operation was already made opaque by different module, it
195                          * will be overridden here.
196                          */
197                         DEBUGADD(5, ("Making operation type %d opaque [module %s]\n", ops[i].type, vfs_object));
198                         vfs_set_operation(&conn->vfs_opaque, ops[i].type, handle, ops[i].op);
199                 }
200                 /* Change current VFS disposition*/
201                 DEBUGADD(5, ("Accepting operation type %d from module %s\n", ops[i].type, vfs_object));
202                 vfs_set_operation(&conn->vfs, ops[i].type, handle, ops[i].op);
203         }
204
205         SAFE_FREE(module_path);
206         SAFE_FREE(module_name);
207         return True;
208
209  fail:
210         SAFE_FREE(module_path);
211         SAFE_FREE(module_name);
212         return False;
213 }
214
215 /*****************************************************************
216  Allow VFS modules to extend files_struct with VFS-specific state.
217  This will be ok for small numbers of extensions, but might need to
218  be refactored if it becomes more widely used.
219 ******************************************************************/
220
221 #define EXT_DATA_AREA(e) ((uint8 *)(e) + sizeof(struct vfs_fsp_data))
222
223 void *vfs_add_fsp_extension_notype(vfs_handle_struct *handle, files_struct *fsp, size_t ext_size)
224 {
225         struct vfs_fsp_data *ext;
226         void * ext_data;
227
228         /* Prevent VFS modules adding multiple extensions. */
229         if ((ext_data = vfs_fetch_fsp_extension(handle, fsp))) {
230                 return ext_data;
231         }
232
233         ext = (struct vfs_fsp_data *)TALLOC_ZERO(
234                 handle->conn, sizeof(struct vfs_fsp_data) + ext_size);
235         if (ext == NULL) {
236                 return NULL;
237         }
238
239         ext->owner = handle;
240         ext->next = fsp->vfs_extension;
241         fsp->vfs_extension = ext;
242         return EXT_DATA_AREA(ext);
243 }
244
245 void vfs_remove_fsp_extension(vfs_handle_struct *handle, files_struct *fsp)
246 {
247         struct vfs_fsp_data *curr;
248         struct vfs_fsp_data *prev;
249
250         for (curr = fsp->vfs_extension, prev = NULL;
251              curr;
252              prev = curr, curr = curr->next) {
253                 if (curr->owner == handle) {
254                     if (prev) {
255                             prev->next = curr->next;
256                     } else {
257                             fsp->vfs_extension = curr->next;
258                     }
259                     TALLOC_FREE(curr);
260                     return;
261                 }
262         }
263 }
264
265 void *vfs_memctx_fsp_extension(vfs_handle_struct *handle, files_struct *fsp)
266 {
267         struct vfs_fsp_data *head;
268
269         for (head = fsp->vfs_extension; head; head = head->next) {
270                 if (head->owner == handle) {
271                         return head;
272                 }
273         }
274
275         return NULL;
276 }
277
278 void *vfs_fetch_fsp_extension(vfs_handle_struct *handle, files_struct *fsp)
279 {
280         struct vfs_fsp_data *head;
281
282         head = (struct vfs_fsp_data *)vfs_memctx_fsp_extension(handle, fsp);
283         if (head != NULL) {
284                 return EXT_DATA_AREA(head);
285         }
286
287         return NULL;
288 }
289
290 #undef EXT_DATA_AREA
291
292 /*****************************************************************
293  Generic VFS init.
294 ******************************************************************/
295
296 bool smbd_vfs_init(connection_struct *conn)
297 {
298         const char **vfs_objects;
299         unsigned int i = 0;
300         int j = 0;
301         
302         /* Normal share - initialise with disk access functions */
303         vfs_init_default(conn);
304         vfs_objects = lp_vfs_objects(SNUM(conn));
305
306         /* Override VFS functions if 'vfs object' was not specified*/
307         if (!vfs_objects || !vfs_objects[0])
308                 return True;
309         
310         for (i=0; vfs_objects[i] ;) {
311                 i++;
312         }
313
314         for (j=i-1; j >= 0; j--) {
315                 if (!vfs_init_custom(conn, vfs_objects[j])) {
316                         DEBUG(0, ("smbd_vfs_init: vfs_init_custom failed for %s\n", vfs_objects[j]));
317                         return False;
318                 }
319         }
320         return True;
321 }
322
323 /*******************************************************************
324  Check if directory exists.
325 ********************************************************************/
326
327 bool vfs_directory_exist(connection_struct *conn, const char *dname, SMB_STRUCT_STAT *st)
328 {
329         SMB_STRUCT_STAT st2;
330         bool ret;
331
332         if (!st)
333                 st = &st2;
334
335         if (SMB_VFS_STAT(conn,dname,st) != 0)
336                 return(False);
337
338         ret = S_ISDIR(st->st_mode);
339         if(!ret)
340                 errno = ENOTDIR;
341
342         return ret;
343 }
344
345 /*******************************************************************
346  Check if an object exists in the vfs.
347 ********************************************************************/
348
349 bool vfs_object_exist(connection_struct *conn,const char *fname,SMB_STRUCT_STAT *sbuf)
350 {
351         SMB_STRUCT_STAT st;
352
353         if (!sbuf)
354                 sbuf = &st;
355
356         ZERO_STRUCTP(sbuf);
357
358         if (SMB_VFS_STAT(conn,fname,sbuf) == -1)
359                 return(False);
360         return True;
361 }
362
363 /*******************************************************************
364  Check if a file exists in the vfs.
365 ********************************************************************/
366
367 bool vfs_file_exist(connection_struct *conn, const char *fname,SMB_STRUCT_STAT *sbuf)
368 {
369         SMB_STRUCT_STAT st;
370
371         if (!sbuf)
372                 sbuf = &st;
373
374         ZERO_STRUCTP(sbuf);
375
376         if (SMB_VFS_STAT(conn,fname,sbuf) == -1)
377                 return False;
378         return(S_ISREG(sbuf->st_mode));
379 }
380
381 /****************************************************************************
382  Read data from fsp on the vfs. (note: EINTR re-read differs from vfs_write_data)
383 ****************************************************************************/
384
385 ssize_t vfs_read_data(files_struct *fsp, char *buf, size_t byte_count)
386 {
387         size_t total=0;
388
389         while (total < byte_count)
390         {
391                 ssize_t ret = SMB_VFS_READ(fsp, buf + total,
392                                            byte_count - total);
393
394                 if (ret == 0) return total;
395                 if (ret == -1) {
396                         if (errno == EINTR)
397                                 continue;
398                         else
399                                 return -1;
400                 }
401                 total += ret;
402         }
403         return (ssize_t)total;
404 }
405
406 ssize_t vfs_pread_data(files_struct *fsp, char *buf,
407                 size_t byte_count, SMB_OFF_T offset)
408 {
409         size_t total=0;
410
411         while (total < byte_count)
412         {
413                 ssize_t ret = SMB_VFS_PREAD(fsp, buf + total,
414                                         byte_count - total, offset + total);
415
416                 if (ret == 0) return total;
417                 if (ret == -1) {
418                         if (errno == EINTR)
419                                 continue;
420                         else
421                                 return -1;
422                 }
423                 total += ret;
424         }
425         return (ssize_t)total;
426 }
427
428 /****************************************************************************
429  Write data to a fd on the vfs.
430 ****************************************************************************/
431
432 ssize_t vfs_write_data(struct smb_request *req,
433                         files_struct *fsp,
434                         const char *buffer,
435                         size_t N)
436 {
437         size_t total=0;
438         ssize_t ret;
439
440         if (req && req->unread_bytes) {
441                 SMB_ASSERT(req->unread_bytes == N);
442                 /* VFS_RECVFILE must drain the socket
443                  * before returning. */
444                 req->unread_bytes = 0;
445                 return SMB_VFS_RECVFILE(smbd_server_fd(),
446                                         fsp,
447                                         (SMB_OFF_T)-1,
448                                         N);
449         }
450
451         while (total < N) {
452                 ret = SMB_VFS_WRITE(fsp, buffer + total, N - total);
453
454                 if (ret == -1)
455                         return -1;
456                 if (ret == 0)
457                         return total;
458
459                 total += ret;
460         }
461         return (ssize_t)total;
462 }
463
464 ssize_t vfs_pwrite_data(struct smb_request *req,
465                         files_struct *fsp,
466                         const char *buffer,
467                         size_t N,
468                         SMB_OFF_T offset)
469 {
470         size_t total=0;
471         ssize_t ret;
472
473         if (req && req->unread_bytes) {
474                 SMB_ASSERT(req->unread_bytes == N);
475                 /* VFS_RECVFILE must drain the socket
476                  * before returning. */
477                 req->unread_bytes = 0;
478                 return SMB_VFS_RECVFILE(smbd_server_fd(),
479                                         fsp,
480                                         offset,
481                                         N);
482         }
483
484         while (total < N) {
485                 ret = SMB_VFS_PWRITE(fsp, buffer + total, N - total,
486                                      offset + total);
487
488                 if (ret == -1)
489                         return -1;
490                 if (ret == 0)
491                         return total;
492
493                 total += ret;
494         }
495         return (ssize_t)total;
496 }
497 /****************************************************************************
498  An allocate file space call using the vfs interface.
499  Allocates space for a file from a filedescriptor.
500  Returns 0 on success, -1 on failure.
501 ****************************************************************************/
502
503 int vfs_allocate_file_space(files_struct *fsp, uint64_t len)
504 {
505         int ret;
506         SMB_STRUCT_STAT st;
507         connection_struct *conn = fsp->conn;
508         uint64_t space_avail;
509         uint64_t bsize,dfree,dsize;
510
511         release_level_2_oplocks_on_change(fsp);
512
513         /*
514          * Actually try and commit the space on disk....
515          */
516
517         DEBUG(10,("vfs_allocate_file_space: file %s, len %.0f\n", fsp->fsp_name, (double)len ));
518
519         if (((SMB_OFF_T)len) < 0) {
520                 DEBUG(0,("vfs_allocate_file_space: %s negative len requested.\n", fsp->fsp_name ));
521                 errno = EINVAL;
522                 return -1;
523         }
524
525         ret = SMB_VFS_FSTAT(fsp, &st);
526         if (ret == -1)
527                 return ret;
528
529         if (len == (uint64_t)st.st_size)
530                 return 0;
531
532         if (len < (uint64_t)st.st_size) {
533                 /* Shrink - use ftruncate. */
534
535                 DEBUG(10,("vfs_allocate_file_space: file %s, shrink. Current size %.0f\n",
536                                 fsp->fsp_name, (double)st.st_size ));
537
538                 flush_write_cache(fsp, SIZECHANGE_FLUSH);
539                 if ((ret = SMB_VFS_FTRUNCATE(fsp, (SMB_OFF_T)len)) != -1) {
540                         set_filelen_write_cache(fsp, len);
541                 }
542                 return ret;
543         }
544
545         /* Grow - we need to test if we have enough space. */
546
547         if (!lp_strict_allocate(SNUM(fsp->conn)))
548                 return 0;
549
550         len -= st.st_size;
551         len /= 1024; /* Len is now number of 1k blocks needed. */
552         space_avail = get_dfree_info(conn,fsp->fsp_name,False,&bsize,&dfree,&dsize);
553         if (space_avail == (uint64_t)-1) {
554                 return -1;
555         }
556
557         DEBUG(10,("vfs_allocate_file_space: file %s, grow. Current size %.0f, needed blocks = %.0f, space avail = %.0f\n",
558                         fsp->fsp_name, (double)st.st_size, (double)len, (double)space_avail ));
559
560         if (len > space_avail) {
561                 errno = ENOSPC;
562                 return -1;
563         }
564
565         return 0;
566 }
567
568 /****************************************************************************
569  A vfs set_filelen call.
570  set the length of a file from a filedescriptor.
571  Returns 0 on success, -1 on failure.
572 ****************************************************************************/
573
574 int vfs_set_filelen(files_struct *fsp, SMB_OFF_T len)
575 {
576         int ret;
577
578         release_level_2_oplocks_on_change(fsp);
579         DEBUG(10,("vfs_set_filelen: ftruncate %s to len %.0f\n", fsp->fsp_name, (double)len));
580         flush_write_cache(fsp, SIZECHANGE_FLUSH);
581         if ((ret = SMB_VFS_FTRUNCATE(fsp, len)) != -1) {
582                 set_filelen_write_cache(fsp, len);
583                 notify_fname(fsp->conn, NOTIFY_ACTION_MODIFIED,
584                              FILE_NOTIFY_CHANGE_SIZE
585                              | FILE_NOTIFY_CHANGE_ATTRIBUTES,
586                              fsp->fsp_name);
587         }
588
589         return ret;
590 }
591
592 /****************************************************************************
593  A vfs fill sparse call.
594  Writes zeros from the end of file to len, if len is greater than EOF.
595  Used only by strict_sync.
596  Returns 0 on success, -1 on failure.
597 ****************************************************************************/
598
599 #define SPARSE_BUF_WRITE_SIZE (32*1024)
600
601 int vfs_fill_sparse(files_struct *fsp, SMB_OFF_T len)
602 {
603         int ret;
604         SMB_STRUCT_STAT st;
605         SMB_OFF_T offset;
606         size_t total;
607         size_t num_to_write;
608         ssize_t pwrite_ret;
609
610         release_level_2_oplocks_on_change(fsp);
611         ret = SMB_VFS_FSTAT(fsp, &st);
612         if (ret == -1) {
613                 return ret;
614         }
615
616         if (len <= st.st_size) {
617                 return 0;
618         }
619
620         DEBUG(10,("vfs_fill_sparse: write zeros in file %s from len %.0f to len %.0f (%.0f bytes)\n",
621                 fsp->fsp_name, (double)st.st_size, (double)len, (double)(len - st.st_size)));
622
623         flush_write_cache(fsp, SIZECHANGE_FLUSH);
624
625         if (!sparse_buf) {
626                 sparse_buf = SMB_CALLOC_ARRAY(char, SPARSE_BUF_WRITE_SIZE);
627                 if (!sparse_buf) {
628                         errno = ENOMEM;
629                         return -1;
630                 }
631         }
632
633         offset = st.st_size;
634         num_to_write = len - st.st_size;
635         total = 0;
636
637         while (total < num_to_write) {
638                 size_t curr_write_size = MIN(SPARSE_BUF_WRITE_SIZE, (num_to_write - total));
639
640                 pwrite_ret = SMB_VFS_PWRITE(fsp, sparse_buf, curr_write_size, offset + total);
641                 if (pwrite_ret == -1) {
642                         DEBUG(10,("vfs_fill_sparse: SMB_VFS_PWRITE for file %s failed with error %s\n",
643                                 fsp->fsp_name, strerror(errno) ));
644                         return -1;
645                 }
646                 if (pwrite_ret == 0) {
647                         return 0;
648                 }
649
650                 total += pwrite_ret;
651         }
652
653         set_filelen_write_cache(fsp, len);
654         return 0;
655 }
656
657 /****************************************************************************
658  Transfer some data (n bytes) between two file_struct's.
659 ****************************************************************************/
660
661 static ssize_t vfs_read_fn(void *file, void *buf, size_t len)
662 {
663         struct files_struct *fsp = (struct files_struct *)file;
664
665         return SMB_VFS_READ(fsp, buf, len);
666 }
667
668 static ssize_t vfs_write_fn(void *file, const void *buf, size_t len)
669 {
670         struct files_struct *fsp = (struct files_struct *)file;
671
672         return SMB_VFS_WRITE(fsp, buf, len);
673 }
674
675 SMB_OFF_T vfs_transfer_file(files_struct *in, files_struct *out, SMB_OFF_T n)
676 {
677         return transfer_file_internal((void *)in, (void *)out, n,
678                                       vfs_read_fn, vfs_write_fn);
679 }
680
681 /*******************************************************************
682  A vfs_readdir wrapper which just returns the file name.
683 ********************************************************************/
684
685 char *vfs_readdirname(connection_struct *conn, void *p)
686 {
687         SMB_STRUCT_DIRENT *ptr= NULL;
688         char *dname;
689
690         if (!p)
691                 return(NULL);
692
693         ptr = SMB_VFS_READDIR(conn, (DIR *)p);
694         if (!ptr)
695                 return(NULL);
696
697         dname = ptr->d_name;
698
699 #ifdef NEXT2
700         if (telldir(p) < 0)
701                 return(NULL);
702 #endif
703
704 #ifdef HAVE_BROKEN_READDIR_NAME
705         /* using /usr/ucb/cc is BAD */
706         dname = dname - 2;
707 #endif
708
709         return(dname);
710 }
711
712 /*******************************************************************
713  A wrapper for vfs_chdir().
714 ********************************************************************/
715
716 int vfs_ChDir(connection_struct *conn, const char *path)
717 {
718         int res;
719
720         if (!LastDir) {
721                 LastDir = SMB_STRDUP("");
722         }
723
724         if (strcsequal(path,"."))
725                 return(0);
726
727         if (*path == '/' && strcsequal(LastDir,path))
728                 return(0);
729
730         DEBUG(4,("vfs_ChDir to %s\n",path));
731
732         res = SMB_VFS_CHDIR(conn,path);
733         if (!res) {
734                 SAFE_FREE(LastDir);
735                 LastDir = SMB_STRDUP(path);
736         }
737         return(res);
738 }
739
740 /*******************************************************************
741  Return the absolute current directory path - given a UNIX pathname.
742  Note that this path is returned in DOS format, not UNIX
743  format. Note this can be called with conn == NULL.
744 ********************************************************************/
745
746 struct getwd_cache_key {
747         SMB_DEV_T dev;
748         SMB_INO_T ino;
749 };
750
751 char *vfs_GetWd(TALLOC_CTX *ctx, connection_struct *conn)
752 {
753         char s[PATH_MAX+1];
754         SMB_STRUCT_STAT st, st2;
755         char *result;
756         DATA_BLOB cache_value;
757         struct getwd_cache_key key;
758
759         *s = 0;
760
761         if (!lp_getwd_cache()) {
762                 goto nocache;
763         }
764
765         SET_STAT_INVALID(st);
766
767         if (SMB_VFS_STAT(conn, ".",&st) == -1) {
768                 /*
769                  * Known to fail for root: the directory may be NFS-mounted
770                  * and exported with root_squash (so has no root access).
771                  */
772                 DEBUG(1,("vfs_GetWd: couldn't stat \".\" error %s "
773                          "(NFS problem ?)\n", strerror(errno) ));
774                 goto nocache;
775         }
776
777         ZERO_STRUCT(key); /* unlikely, but possible padding */
778         key.dev = st.st_dev;
779         key.ino = st.st_ino;
780
781         if (!memcache_lookup(smbd_memcache(), GETWD_CACHE,
782                              data_blob_const(&key, sizeof(key)),
783                              &cache_value)) {
784                 goto nocache;
785         }
786
787         SMB_ASSERT((cache_value.length > 0)
788                    && (cache_value.data[cache_value.length-1] == '\0'));
789
790         if ((SMB_VFS_STAT(conn, (char *)cache_value.data, &st2) == 0)
791             && (st.st_dev == st2.st_dev) && (st.st_ino == st2.st_ino)
792             && (S_ISDIR(st.st_mode))) {
793                 /*
794                  * Ok, we're done
795                  */
796                 result = talloc_strdup(ctx, (char *)cache_value.data);
797                 if (result == NULL) {
798                         errno = ENOMEM;
799                 }
800                 return result;
801         }
802
803  nocache:
804
805         /*
806          * We don't have the information to hand so rely on traditional
807          * methods. The very slow getcwd, which spawns a process on some
808          * systems, or the not quite so bad getwd.
809          */
810
811         if (!SMB_VFS_GETWD(conn,s)) {
812                 DEBUG(0, ("vfs_GetWd: SMB_VFS_GETWD call failed: %s\n",
813                           strerror(errno)));
814                 return NULL;
815         }
816
817         if (lp_getwd_cache() && VALID_STAT(st)) {
818                 ZERO_STRUCT(key); /* unlikely, but possible padding */
819                 key.dev = st.st_dev;
820                 key.ino = st.st_ino;
821
822                 memcache_add(smbd_memcache(), GETWD_CACHE,
823                              data_blob_const(&key, sizeof(key)),
824                              data_blob_const(s, strlen(s)+1));
825         }
826
827         result = talloc_strdup(ctx, s);
828         if (result == NULL) {
829                 errno = ENOMEM;
830         }
831         return result;
832 }
833
834 /*******************************************************************
835  Reduce a file name, removing .. elements and checking that
836  it is below dir in the heirachy. This uses realpath.
837 ********************************************************************/
838
839 NTSTATUS check_reduced_name(connection_struct *conn, const char *fname)
840 {
841 #ifdef REALPATH_TAKES_NULL
842         bool free_resolved_name = True;
843 #else
844         char resolved_name_buf[PATH_MAX+1];
845         bool free_resolved_name = False;
846 #endif
847         char *resolved_name = NULL;
848         size_t con_path_len = strlen(conn->connectpath);
849         char *p = NULL;
850
851         DEBUG(3,("reduce_name [%s] [%s]\n", fname, conn->connectpath));
852
853 #ifdef REALPATH_TAKES_NULL
854         resolved_name = SMB_VFS_REALPATH(conn,fname,NULL);
855 #else
856         resolved_name = SMB_VFS_REALPATH(conn,fname,resolved_name_buf);
857 #endif
858
859         if (!resolved_name) {
860                 switch (errno) {
861                         case ENOTDIR:
862                                 DEBUG(3,("reduce_name: Component not a directory in getting realpath for %s\n", fname));
863                                 return map_nt_error_from_unix(errno);
864                         case ENOENT:
865                         {
866                                 TALLOC_CTX *ctx = talloc_tos();
867                                 char *tmp_fname = NULL;
868                                 char *last_component = NULL;
869                                 /* Last component didn't exist. Remove it and try and canonicalise the directory. */
870
871                                 tmp_fname = talloc_strdup(ctx, fname);
872                                 if (!tmp_fname) {
873                                         return NT_STATUS_NO_MEMORY;
874                                 }
875                                 p = strrchr_m(tmp_fname, '/');
876                                 if (p) {
877                                         *p++ = '\0';
878                                         last_component = p;
879                                 } else {
880                                         last_component = tmp_fname;
881                                         tmp_fname = talloc_strdup(ctx,
882                                                         ".");
883                                         if (!tmp_fname) {
884                                                 return NT_STATUS_NO_MEMORY;
885                                         }
886                                 }
887
888 #ifdef REALPATH_TAKES_NULL
889                                 resolved_name = SMB_VFS_REALPATH(conn,tmp_fname,NULL);
890 #else
891                                 resolved_name = SMB_VFS_REALPATH(conn,tmp_fname,resolved_name_buf);
892 #endif
893                                 if (!resolved_name) {
894                                         DEBUG(3,("reduce_name: couldn't get realpath for %s\n", fname));
895                                         return map_nt_error_from_unix(errno);
896                                 }
897                                 tmp_fname = talloc_asprintf(ctx,
898                                                 "%s/%s",
899                                                 resolved_name,
900                                                 last_component);
901                                 if (!tmp_fname) {
902                                         return NT_STATUS_NO_MEMORY;
903                                 }
904 #ifdef REALPATH_TAKES_NULL
905                                 SAFE_FREE(resolved_name);
906                                 resolved_name = SMB_STRDUP(tmp_fname);
907                                 if (!resolved_name) {
908                                         DEBUG(0,("reduce_name: malloc fail for %s\n", tmp_fname));
909                                         return NT_STATUS_NO_MEMORY;
910                                 }
911 #else
912                                 safe_strcpy(resolved_name_buf, tmp_fname, PATH_MAX);
913                                 resolved_name = resolved_name_buf;
914 #endif
915                                 break;
916                         }
917                         default:
918                                 DEBUG(1,("reduce_name: couldn't get realpath for %s\n", fname));
919                                 return map_nt_error_from_unix(errno);
920                 }
921         }
922
923         DEBUG(10,("reduce_name realpath [%s] -> [%s]\n", fname, resolved_name));
924
925         if (*resolved_name != '/') {
926                 DEBUG(0,("reduce_name: realpath doesn't return absolute paths !\n"));
927                 if (free_resolved_name) {
928                         SAFE_FREE(resolved_name);
929                 }
930                 return NT_STATUS_OBJECT_NAME_INVALID;
931         }
932
933         /* Check for widelinks allowed. */
934         if (!lp_widelinks(SNUM(conn)) && (strncmp(conn->connectpath, resolved_name, con_path_len) != 0)) {
935                 DEBUG(2, ("reduce_name: Bad access attempt: %s is a symlink outside the share path", fname));
936                 if (free_resolved_name) {
937                         SAFE_FREE(resolved_name);
938                 }
939                 return NT_STATUS_ACCESS_DENIED;
940         }
941
942         /* Check if we are allowing users to follow symlinks */
943         /* Patch from David Clerc <David.Clerc@cui.unige.ch>
944                 University of Geneva */
945
946 #ifdef S_ISLNK
947         if (!lp_symlinks(SNUM(conn))) {
948                 SMB_STRUCT_STAT statbuf;
949                 if ( (SMB_VFS_LSTAT(conn,fname,&statbuf) != -1) &&
950                                 (S_ISLNK(statbuf.st_mode)) ) {
951                         if (free_resolved_name) {
952                                 SAFE_FREE(resolved_name);
953                         }
954                         DEBUG(3,("reduce_name: denied: file path name %s is a symlink\n",resolved_name));
955                         return NT_STATUS_ACCESS_DENIED;
956                 }
957         }
958 #endif
959
960         DEBUG(3,("reduce_name: %s reduced to %s\n", fname, resolved_name));
961         if (free_resolved_name) {
962                 SAFE_FREE(resolved_name);
963         }
964         return NT_STATUS_OK;
965 }