s3: Change fsp->fsp_name to be an smb_filename struct!
[nivanova/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         entry = vfs_find_backend_entry(module_name);
165         if (!entry) {
166                 NTSTATUS status;
167
168                 DEBUG(5, ("vfs module [%s] not loaded - trying to load...\n",
169                           vfs_object));
170
171                 status = smb_probe_module("vfs", module_path);
172                 if (!NT_STATUS_IS_OK(status)) {
173                         DEBUG(0, ("error probing vfs module '%s': %s\n",
174                                   module_path, nt_errstr(status)));
175                         goto fail;
176                 }
177
178                 entry = vfs_find_backend_entry(module_name);
179                 if (!entry) {
180                         DEBUG(0,("Can't find a vfs module [%s]\n",vfs_object));
181                         goto fail;
182                 }
183         }
184
185         DEBUGADD(5,("Successfully loaded vfs module [%s] with the new modules system\n", vfs_object));
186         if ((ops = entry->vfs_op_tuples) == NULL) {
187                 DEBUG(0, ("entry->vfs_op_tuples==NULL for [%s] failed\n", vfs_object));
188                 goto fail;
189         }
190
191         handle = TALLOC_ZERO_P(conn, vfs_handle_struct);
192         if (!handle) {
193                 DEBUG(0,("TALLOC_ZERO() failed!\n"));
194                 goto fail;
195         }
196         memcpy(&handle->vfs_next, &conn->vfs, sizeof(struct vfs_ops));
197         handle->conn = conn;
198         if (module_param) {
199                 handle->param = talloc_strdup(conn, module_param);
200         }
201         DLIST_ADD(conn->vfs_handles, handle);
202
203         for(i=0; ops[i].op != NULL; i++) {
204                 DEBUG(5, ("Checking operation #%d (type %d, layer %d)\n", i, ops[i].type, ops[i].layer));
205                 if(ops[i].layer == SMB_VFS_LAYER_OPAQUE) {
206                         /* If this operation was already made opaque by different module, it
207                          * will be overridden here.
208                          */
209                         DEBUGADD(5, ("Making operation type %d opaque [module %s]\n", ops[i].type, vfs_object));
210                         vfs_set_operation(&conn->vfs_opaque, ops[i].type, handle, ops[i].op);
211                 }
212                 /* Change current VFS disposition*/
213                 DEBUGADD(5, ("Accepting operation type %d from module %s\n", ops[i].type, vfs_object));
214                 vfs_set_operation(&conn->vfs, ops[i].type, handle, ops[i].op);
215         }
216
217         SAFE_FREE(module_path);
218         SAFE_FREE(module_name);
219         return True;
220
221  fail:
222         SAFE_FREE(module_path);
223         SAFE_FREE(module_name);
224         return False;
225 }
226
227 /*****************************************************************
228  Allow VFS modules to extend files_struct with VFS-specific state.
229  This will be ok for small numbers of extensions, but might need to
230  be refactored if it becomes more widely used.
231 ******************************************************************/
232
233 #define EXT_DATA_AREA(e) ((uint8 *)(e) + sizeof(struct vfs_fsp_data))
234
235 void *vfs_add_fsp_extension_notype(vfs_handle_struct *handle,
236                                    files_struct *fsp, size_t ext_size,
237                                    void (*destroy_fn)(void *p_data))
238 {
239         struct vfs_fsp_data *ext;
240         void * ext_data;
241
242         /* Prevent VFS modules adding multiple extensions. */
243         if ((ext_data = vfs_fetch_fsp_extension(handle, fsp))) {
244                 return ext_data;
245         }
246
247         ext = (struct vfs_fsp_data *)TALLOC_ZERO(
248                 handle->conn, sizeof(struct vfs_fsp_data) + ext_size);
249         if (ext == NULL) {
250                 return NULL;
251         }
252
253         ext->owner = handle;
254         ext->next = fsp->vfs_extension;
255         ext->destroy = destroy_fn;
256         fsp->vfs_extension = ext;
257         return EXT_DATA_AREA(ext);
258 }
259
260 void vfs_remove_fsp_extension(vfs_handle_struct *handle, files_struct *fsp)
261 {
262         struct vfs_fsp_data *curr;
263         struct vfs_fsp_data *prev;
264
265         for (curr = fsp->vfs_extension, prev = NULL;
266              curr;
267              prev = curr, curr = curr->next) {
268                 if (curr->owner == handle) {
269                     if (prev) {
270                             prev->next = curr->next;
271                     } else {
272                             fsp->vfs_extension = curr->next;
273                     }
274                     if (curr->destroy) {
275                             curr->destroy(EXT_DATA_AREA(curr));
276                     }
277                     TALLOC_FREE(curr);
278                     return;
279                 }
280         }
281 }
282
283 void *vfs_memctx_fsp_extension(vfs_handle_struct *handle, files_struct *fsp)
284 {
285         struct vfs_fsp_data *head;
286
287         for (head = fsp->vfs_extension; head; head = head->next) {
288                 if (head->owner == handle) {
289                         return head;
290                 }
291         }
292
293         return NULL;
294 }
295
296 void *vfs_fetch_fsp_extension(vfs_handle_struct *handle, files_struct *fsp)
297 {
298         struct vfs_fsp_data *head;
299
300         head = (struct vfs_fsp_data *)vfs_memctx_fsp_extension(handle, fsp);
301         if (head != NULL) {
302                 return EXT_DATA_AREA(head);
303         }
304
305         return NULL;
306 }
307
308 #undef EXT_DATA_AREA
309
310 /*****************************************************************
311  Generic VFS init.
312 ******************************************************************/
313
314 bool smbd_vfs_init(connection_struct *conn)
315 {
316         const char **vfs_objects;
317         unsigned int i = 0;
318         int j = 0;
319         
320         /* Normal share - initialise with disk access functions */
321         vfs_init_default(conn);
322         vfs_objects = lp_vfs_objects(SNUM(conn));
323
324         /* Override VFS functions if 'vfs object' was not specified*/
325         if (!vfs_objects || !vfs_objects[0])
326                 return True;
327         
328         for (i=0; vfs_objects[i] ;) {
329                 i++;
330         }
331
332         for (j=i-1; j >= 0; j--) {
333                 if (!vfs_init_custom(conn, vfs_objects[j])) {
334                         DEBUG(0, ("smbd_vfs_init: vfs_init_custom failed for %s\n", vfs_objects[j]));
335                         return False;
336                 }
337         }
338         return True;
339 }
340
341 /*******************************************************************
342  Check if a file exists in the vfs.
343 ********************************************************************/
344
345 NTSTATUS vfs_file_exist(connection_struct *conn, struct smb_filename *smb_fname)
346 {
347         /* Only return OK if stat was successful and S_ISREG */
348         if ((SMB_VFS_STAT(conn, smb_fname) != -1) &&
349             S_ISREG(smb_fname->st.st_ex_mode)) {
350                 return NT_STATUS_OK;
351         }
352
353         return NT_STATUS_OBJECT_NAME_NOT_FOUND;
354 }
355
356 /****************************************************************************
357  Read data from fsp on the vfs. (note: EINTR re-read differs from vfs_write_data)
358 ****************************************************************************/
359
360 ssize_t vfs_read_data(files_struct *fsp, char *buf, size_t byte_count)
361 {
362         size_t total=0;
363
364         while (total < byte_count)
365         {
366                 ssize_t ret = SMB_VFS_READ(fsp, buf + total,
367                                            byte_count - total);
368
369                 if (ret == 0) return total;
370                 if (ret == -1) {
371                         if (errno == EINTR)
372                                 continue;
373                         else
374                                 return -1;
375                 }
376                 total += ret;
377         }
378         return (ssize_t)total;
379 }
380
381 ssize_t vfs_pread_data(files_struct *fsp, char *buf,
382                 size_t byte_count, SMB_OFF_T offset)
383 {
384         size_t total=0;
385
386         while (total < byte_count)
387         {
388                 ssize_t ret = SMB_VFS_PREAD(fsp, buf + total,
389                                         byte_count - total, offset + total);
390
391                 if (ret == 0) return total;
392                 if (ret == -1) {
393                         if (errno == EINTR)
394                                 continue;
395                         else
396                                 return -1;
397                 }
398                 total += ret;
399         }
400         return (ssize_t)total;
401 }
402
403 /****************************************************************************
404  Write data to a fd on the vfs.
405 ****************************************************************************/
406
407 ssize_t vfs_write_data(struct smb_request *req,
408                         files_struct *fsp,
409                         const char *buffer,
410                         size_t N)
411 {
412         size_t total=0;
413         ssize_t ret;
414
415         if (req && req->unread_bytes) {
416                 SMB_ASSERT(req->unread_bytes == N);
417                 /* VFS_RECVFILE must drain the socket
418                  * before returning. */
419                 req->unread_bytes = 0;
420                 return SMB_VFS_RECVFILE(smbd_server_fd(),
421                                         fsp,
422                                         (SMB_OFF_T)-1,
423                                         N);
424         }
425
426         while (total < N) {
427                 ret = SMB_VFS_WRITE(fsp, buffer + total, N - total);
428
429                 if (ret == -1)
430                         return -1;
431                 if (ret == 0)
432                         return total;
433
434                 total += ret;
435         }
436         return (ssize_t)total;
437 }
438
439 ssize_t vfs_pwrite_data(struct smb_request *req,
440                         files_struct *fsp,
441                         const char *buffer,
442                         size_t N,
443                         SMB_OFF_T offset)
444 {
445         size_t total=0;
446         ssize_t ret;
447
448         if (req && req->unread_bytes) {
449                 SMB_ASSERT(req->unread_bytes == N);
450                 /* VFS_RECVFILE must drain the socket
451                  * before returning. */
452                 req->unread_bytes = 0;
453                 return SMB_VFS_RECVFILE(smbd_server_fd(),
454                                         fsp,
455                                         offset,
456                                         N);
457         }
458
459         while (total < N) {
460                 ret = SMB_VFS_PWRITE(fsp, buffer + total, N - total,
461                                      offset + total);
462
463                 if (ret == -1)
464                         return -1;
465                 if (ret == 0)
466                         return total;
467
468                 total += ret;
469         }
470         return (ssize_t)total;
471 }
472 /****************************************************************************
473  An allocate file space call using the vfs interface.
474  Allocates space for a file from a filedescriptor.
475  Returns 0 on success, -1 on failure.
476 ****************************************************************************/
477
478 int vfs_allocate_file_space(files_struct *fsp, uint64_t len)
479 {
480         int ret;
481         SMB_STRUCT_STAT st;
482         connection_struct *conn = fsp->conn;
483         uint64_t space_avail;
484         uint64_t bsize,dfree,dsize;
485
486         /*
487          * Actually try and commit the space on disk....
488          */
489
490         DEBUG(10,("vfs_allocate_file_space: file %s, len %.0f\n",
491                   fsp_str_dbg(fsp), (double)len));
492
493         if (((SMB_OFF_T)len) < 0) {
494                 DEBUG(0,("vfs_allocate_file_space: %s negative len "
495                          "requested.\n", fsp_str_dbg(fsp)));
496                 errno = EINVAL;
497                 return -1;
498         }
499
500         ret = SMB_VFS_FSTAT(fsp, &st);
501         if (ret == -1)
502                 return ret;
503
504         if (len == (uint64_t)st.st_ex_size)
505                 return 0;
506
507         if (len < (uint64_t)st.st_ex_size) {
508                 /* Shrink - use ftruncate. */
509
510                 DEBUG(10,("vfs_allocate_file_space: file %s, shrink. Current "
511                           "size %.0f\n", fsp_str_dbg(fsp),
512                           (double)st.st_ex_size));
513
514                 contend_level2_oplocks_begin(fsp, LEVEL2_CONTEND_ALLOC_SHRINK);
515
516                 flush_write_cache(fsp, SIZECHANGE_FLUSH);
517                 if ((ret = SMB_VFS_FTRUNCATE(fsp, (SMB_OFF_T)len)) != -1) {
518                         set_filelen_write_cache(fsp, len);
519                 }
520
521                 contend_level2_oplocks_end(fsp, LEVEL2_CONTEND_ALLOC_SHRINK);
522
523                 return ret;
524         }
525
526         /* Grow - we need to test if we have enough space. */
527
528         contend_level2_oplocks_begin(fsp, LEVEL2_CONTEND_ALLOC_GROW);
529         contend_level2_oplocks_end(fsp, LEVEL2_CONTEND_ALLOC_GROW);
530
531         if (!lp_strict_allocate(SNUM(fsp->conn)))
532                 return 0;
533
534         len -= st.st_ex_size;
535         len /= 1024; /* Len is now number of 1k blocks needed. */
536         space_avail = get_dfree_info(conn, fsp->fsp_name->base_name, false,
537                                      &bsize, &dfree, &dsize);
538         if (space_avail == (uint64_t)-1) {
539                 return -1;
540         }
541
542         DEBUG(10,("vfs_allocate_file_space: file %s, grow. Current size %.0f, "
543                   "needed blocks = %.0f, space avail = %.0f\n",
544                   fsp_str_dbg(fsp), (double)st.st_ex_size, (double)len,
545                   (double)space_avail));
546
547         if (len > space_avail) {
548                 errno = ENOSPC;
549                 return -1;
550         }
551
552         return 0;
553 }
554
555 /****************************************************************************
556  A vfs set_filelen call.
557  set the length of a file from a filedescriptor.
558  Returns 0 on success, -1 on failure.
559 ****************************************************************************/
560
561 int vfs_set_filelen(files_struct *fsp, SMB_OFF_T len)
562 {
563         int ret;
564
565         contend_level2_oplocks_begin(fsp, LEVEL2_CONTEND_SET_FILE_LEN);
566
567         DEBUG(10,("vfs_set_filelen: ftruncate %s to len %.0f\n",
568                   fsp_str_dbg(fsp), (double)len));
569         flush_write_cache(fsp, SIZECHANGE_FLUSH);
570         if ((ret = SMB_VFS_FTRUNCATE(fsp, len)) != -1) {
571                 set_filelen_write_cache(fsp, len);
572                 notify_fname(fsp->conn, NOTIFY_ACTION_MODIFIED,
573                              FILE_NOTIFY_CHANGE_SIZE
574                              | FILE_NOTIFY_CHANGE_ATTRIBUTES,
575                              fsp->fsp_name->base_name);
576         }
577
578         contend_level2_oplocks_end(fsp, LEVEL2_CONTEND_SET_FILE_LEN);
579
580         return ret;
581 }
582
583 /****************************************************************************
584  A vfs fill sparse call.
585  Writes zeros from the end of file to len, if len is greater than EOF.
586  Used only by strict_sync.
587  Returns 0 on success, -1 on failure.
588 ****************************************************************************/
589
590 #define SPARSE_BUF_WRITE_SIZE (32*1024)
591
592 int vfs_fill_sparse(files_struct *fsp, SMB_OFF_T len)
593 {
594         int ret;
595         SMB_STRUCT_STAT st;
596         SMB_OFF_T offset;
597         size_t total;
598         size_t num_to_write;
599         ssize_t pwrite_ret;
600
601         ret = SMB_VFS_FSTAT(fsp, &st);
602         if (ret == -1) {
603                 return ret;
604         }
605
606         if (len <= st.st_ex_size) {
607                 return 0;
608         }
609
610         DEBUG(10,("vfs_fill_sparse: write zeros in file %s from len %.0f to "
611                   "len %.0f (%.0f bytes)\n", fsp_str_dbg(fsp),
612                   (double)st.st_ex_size, (double)len,
613                   (double)(len - st.st_ex_size)));
614
615         contend_level2_oplocks_begin(fsp, LEVEL2_CONTEND_FILL_SPARSE);
616
617         flush_write_cache(fsp, SIZECHANGE_FLUSH);
618
619         if (!sparse_buf) {
620                 sparse_buf = SMB_CALLOC_ARRAY(char, SPARSE_BUF_WRITE_SIZE);
621                 if (!sparse_buf) {
622                         errno = ENOMEM;
623                         ret = -1;
624                         goto out;
625                 }
626         }
627
628         offset = st.st_ex_size;
629         num_to_write = len - st.st_ex_size;
630         total = 0;
631
632         while (total < num_to_write) {
633                 size_t curr_write_size = MIN(SPARSE_BUF_WRITE_SIZE, (num_to_write - total));
634
635                 pwrite_ret = SMB_VFS_PWRITE(fsp, sparse_buf, curr_write_size, offset + total);
636                 if (pwrite_ret == -1) {
637                         DEBUG(10,("vfs_fill_sparse: SMB_VFS_PWRITE for file "
638                                   "%s failed with error %s\n",
639                                   fsp_str_dbg(fsp), strerror(errno)));
640                         ret = -1;
641                         goto out;
642                 }
643                 if (pwrite_ret == 0) {
644                         ret = 0;
645                         goto out;
646                 }
647
648                 total += pwrite_ret;
649         }
650
651         set_filelen_write_cache(fsp, len);
652
653         ret = 0;
654  out:
655         contend_level2_oplocks_end(fsp, LEVEL2_CONTEND_FILL_SPARSE);
656         return ret;
657 }
658
659 /****************************************************************************
660  Transfer some data (n bytes) between two file_struct's.
661 ****************************************************************************/
662
663 static ssize_t vfs_read_fn(void *file, void *buf, size_t len)
664 {
665         struct files_struct *fsp = (struct files_struct *)file;
666
667         return SMB_VFS_READ(fsp, buf, len);
668 }
669
670 static ssize_t vfs_write_fn(void *file, const void *buf, size_t len)
671 {
672         struct files_struct *fsp = (struct files_struct *)file;
673
674         return SMB_VFS_WRITE(fsp, buf, len);
675 }
676
677 SMB_OFF_T vfs_transfer_file(files_struct *in, files_struct *out, SMB_OFF_T n)
678 {
679         return transfer_file_internal((void *)in, (void *)out, n,
680                                       vfs_read_fn, vfs_write_fn);
681 }
682
683 /*******************************************************************
684  A vfs_readdir wrapper which just returns the file name.
685 ********************************************************************/
686
687 char *vfs_readdirname(connection_struct *conn, void *p, SMB_STRUCT_STAT *sbuf)
688 {
689         SMB_STRUCT_DIRENT *ptr= NULL;
690         char *dname;
691
692         if (!p)
693                 return(NULL);
694
695         ptr = SMB_VFS_READDIR(conn, (DIR *)p, sbuf);
696         if (!ptr)
697                 return(NULL);
698
699         dname = ptr->d_name;
700
701 #ifdef NEXT2
702         if (telldir(p) < 0)
703                 return(NULL);
704 #endif
705
706 #ifdef HAVE_BROKEN_READDIR_NAME
707         /* using /usr/ucb/cc is BAD */
708         dname = dname - 2;
709 #endif
710
711         return(dname);
712 }
713
714 /*******************************************************************
715  A wrapper for vfs_chdir().
716 ********************************************************************/
717
718 int vfs_ChDir(connection_struct *conn, const char *path)
719 {
720         int res;
721
722         if (!LastDir) {
723                 LastDir = SMB_STRDUP("");
724         }
725
726         if (strcsequal(path,"."))
727                 return(0);
728
729         if (*path == '/' && strcsequal(LastDir,path))
730                 return(0);
731
732         DEBUG(4,("vfs_ChDir to %s\n",path));
733
734         res = SMB_VFS_CHDIR(conn,path);
735         if (!res) {
736                 SAFE_FREE(LastDir);
737                 LastDir = SMB_STRDUP(path);
738         }
739         return(res);
740 }
741
742 /*******************************************************************
743  Return the absolute current directory path - given a UNIX pathname.
744  Note that this path is returned in DOS format, not UNIX
745  format. Note this can be called with conn == NULL.
746 ********************************************************************/
747
748 char *vfs_GetWd(TALLOC_CTX *ctx, connection_struct *conn)
749 {
750         char s[PATH_MAX+1];
751         char *result = NULL;
752         DATA_BLOB cache_value;
753         struct file_id key;
754         struct smb_filename *smb_fname_dot = NULL;
755         struct smb_filename *smb_fname_full = NULL;
756         NTSTATUS status;
757
758         *s = 0;
759
760         if (!lp_getwd_cache()) {
761                 goto nocache;
762         }
763
764         status = create_synthetic_smb_fname(ctx, ".", NULL, NULL,
765                                             &smb_fname_dot);
766         if (!NT_STATUS_IS_OK(status)) {
767                 errno = map_errno_from_nt_status(status);
768                 goto out;
769         }
770
771         if (SMB_VFS_STAT(conn, smb_fname_dot) == -1) {
772                 /*
773                  * Known to fail for root: the directory may be NFS-mounted
774                  * and exported with root_squash (so has no root access).
775                  */
776                 DEBUG(1,("vfs_GetWd: couldn't stat \".\" error %s "
777                          "(NFS problem ?)\n", strerror(errno) ));
778                 goto nocache;
779         }
780
781         key = vfs_file_id_from_sbuf(conn, &smb_fname_dot->st);
782
783         if (!memcache_lookup(smbd_memcache(), GETWD_CACHE,
784                              data_blob_const(&key, sizeof(key)),
785                              &cache_value)) {
786                 goto nocache;
787         }
788
789         SMB_ASSERT((cache_value.length > 0)
790                    && (cache_value.data[cache_value.length-1] == '\0'));
791
792         status = create_synthetic_smb_fname(ctx, (char *)cache_value.data,
793                                             NULL, NULL, &smb_fname_full);
794         if (!NT_STATUS_IS_OK(status)) {
795                 errno = map_errno_from_nt_status(status);
796                 goto out;
797         }
798
799         if ((SMB_VFS_STAT(conn, smb_fname_full) == 0) &&
800             (smb_fname_dot->st.st_ex_dev == smb_fname_full->st.st_ex_dev) &&
801             (smb_fname_dot->st.st_ex_ino == smb_fname_full->st.st_ex_ino) &&
802             (S_ISDIR(smb_fname_dot->st.st_ex_mode))) {
803                 /*
804                  * Ok, we're done
805                  */
806                 result = talloc_strdup(ctx, smb_fname_full->base_name);
807                 if (result == NULL) {
808                         errno = ENOMEM;
809                 }
810                 goto out;
811         }
812
813  nocache:
814
815         /*
816          * We don't have the information to hand so rely on traditional
817          * methods. The very slow getcwd, which spawns a process on some
818          * systems, or the not quite so bad getwd.
819          */
820
821         if (!SMB_VFS_GETWD(conn,s)) {
822                 DEBUG(0, ("vfs_GetWd: SMB_VFS_GETWD call failed: %s\n",
823                           strerror(errno)));
824                 goto out;
825         }
826
827         if (lp_getwd_cache() && VALID_STAT(smb_fname_dot->st)) {
828                 key = vfs_file_id_from_sbuf(conn, &smb_fname_dot->st);
829
830                 memcache_add(smbd_memcache(), GETWD_CACHE,
831                              data_blob_const(&key, sizeof(key)),
832                              data_blob_const(s, strlen(s)+1));
833         }
834
835         result = talloc_strdup(ctx, s);
836         if (result == NULL) {
837                 errno = ENOMEM;
838         }
839
840  out:
841         TALLOC_FREE(smb_fname_dot);
842         TALLOC_FREE(smb_fname_full);
843         return result;
844 }
845
846 /*******************************************************************
847  Reduce a file name, removing .. elements and checking that
848  it is below dir in the heirachy. This uses realpath.
849 ********************************************************************/
850
851 NTSTATUS check_reduced_name(connection_struct *conn, const char *fname)
852 {
853 #ifdef REALPATH_TAKES_NULL
854         bool free_resolved_name = True;
855 #else
856         char resolved_name_buf[PATH_MAX+1];
857         bool free_resolved_name = False;
858 #endif
859         char *resolved_name = NULL;
860         char *p = NULL;
861
862         DEBUG(3,("reduce_name [%s] [%s]\n", fname, conn->connectpath));
863
864 #ifdef REALPATH_TAKES_NULL
865         resolved_name = SMB_VFS_REALPATH(conn,fname,NULL);
866 #else
867         resolved_name = SMB_VFS_REALPATH(conn,fname,resolved_name_buf);
868 #endif
869
870         if (!resolved_name) {
871                 switch (errno) {
872                         case ENOTDIR:
873                                 DEBUG(3,("reduce_name: Component not a directory in getting realpath for %s\n", fname));
874                                 return map_nt_error_from_unix(errno);
875                         case ENOENT:
876                         {
877                                 TALLOC_CTX *ctx = talloc_tos();
878                                 char *tmp_fname = NULL;
879                                 char *last_component = NULL;
880                                 /* Last component didn't exist. Remove it and try and canonicalise the directory. */
881
882                                 tmp_fname = talloc_strdup(ctx, fname);
883                                 if (!tmp_fname) {
884                                         return NT_STATUS_NO_MEMORY;
885                                 }
886                                 p = strrchr_m(tmp_fname, '/');
887                                 if (p) {
888                                         *p++ = '\0';
889                                         last_component = p;
890                                 } else {
891                                         last_component = tmp_fname;
892                                         tmp_fname = talloc_strdup(ctx,
893                                                         ".");
894                                         if (!tmp_fname) {
895                                                 return NT_STATUS_NO_MEMORY;
896                                         }
897                                 }
898
899 #ifdef REALPATH_TAKES_NULL
900                                 resolved_name = SMB_VFS_REALPATH(conn,tmp_fname,NULL);
901 #else
902                                 resolved_name = SMB_VFS_REALPATH(conn,tmp_fname,resolved_name_buf);
903 #endif
904                                 if (!resolved_name) {
905                                         DEBUG(3,("reduce_name: couldn't get realpath for %s\n", fname));
906                                         return map_nt_error_from_unix(errno);
907                                 }
908                                 tmp_fname = talloc_asprintf(ctx,
909                                                 "%s/%s",
910                                                 resolved_name,
911                                                 last_component);
912                                 if (!tmp_fname) {
913                                         return NT_STATUS_NO_MEMORY;
914                                 }
915 #ifdef REALPATH_TAKES_NULL
916                                 SAFE_FREE(resolved_name);
917                                 resolved_name = SMB_STRDUP(tmp_fname);
918                                 if (!resolved_name) {
919                                         DEBUG(0,("reduce_name: malloc fail for %s\n", tmp_fname));
920                                         return NT_STATUS_NO_MEMORY;
921                                 }
922 #else
923                                 safe_strcpy(resolved_name_buf, tmp_fname, PATH_MAX);
924                                 resolved_name = resolved_name_buf;
925 #endif
926                                 break;
927                         }
928                         default:
929                                 DEBUG(1,("reduce_name: couldn't get realpath for %s\n", fname));
930                                 return map_nt_error_from_unix(errno);
931                 }
932         }
933
934         DEBUG(10,("reduce_name realpath [%s] -> [%s]\n", fname, resolved_name));
935
936         if (*resolved_name != '/') {
937                 DEBUG(0,("reduce_name: realpath doesn't return absolute paths !\n"));
938                 if (free_resolved_name) {
939                         SAFE_FREE(resolved_name);
940                 }
941                 return NT_STATUS_OBJECT_NAME_INVALID;
942         }
943
944         /* Check for widelinks allowed. */
945         if (!lp_widelinks(SNUM(conn))) {
946                     const char *conn_rootdir;
947
948                     conn_rootdir = SMB_VFS_CONNECTPATH(conn, fname);
949                     if (conn_rootdir == NULL) {
950                             DEBUG(2, ("check_reduced_name: Could not get conn_rootdir\n"));
951                             if (free_resolved_name) {
952                                     SAFE_FREE(resolved_name);
953                             }
954                             return NT_STATUS_ACCESS_DENIED;
955                     }
956
957                     if (strncmp(conn_rootdir, resolved_name,
958                                 strlen(conn_rootdir)) != 0) {
959                             DEBUG(2, ("reduce_name: Bad access attempt: %s is "
960                                       "a symlink outside the share path",
961                                       fname));
962                             if (free_resolved_name) {
963                                     SAFE_FREE(resolved_name);
964                             }
965                             return NT_STATUS_ACCESS_DENIED;
966                     }
967         }
968
969         /* Check if we are allowing users to follow symlinks */
970         /* Patch from David Clerc <David.Clerc@cui.unige.ch>
971                 University of Geneva */
972
973 #ifdef S_ISLNK
974         if (!lp_symlinks(SNUM(conn))) {
975                 SMB_STRUCT_STAT statbuf;
976                 if ( (vfs_lstat_smb_fname(conn,fname,&statbuf) != -1) &&
977                                 (S_ISLNK(statbuf.st_ex_mode)) ) {
978                         if (free_resolved_name) {
979                                 SAFE_FREE(resolved_name);
980                         }
981                         DEBUG(3,("reduce_name: denied: file path name %s is a symlink\n",resolved_name));
982                         return NT_STATUS_ACCESS_DENIED;
983                 }
984         }
985 #endif
986
987         DEBUG(3,("reduce_name: %s reduced to %s\n", fname, resolved_name));
988         if (free_resolved_name) {
989                 SAFE_FREE(resolved_name);
990         }
991         return NT_STATUS_OK;
992 }