Add SMB_VFS_CONNECTPATH operation
[ira/wip.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 directory exists.
343 ********************************************************************/
344
345 bool vfs_directory_exist(connection_struct *conn, const char *dname, SMB_STRUCT_STAT *st)
346 {
347         SMB_STRUCT_STAT st2;
348         bool ret;
349
350         if (!st)
351                 st = &st2;
352
353         if (SMB_VFS_STAT(conn,dname,st) != 0)
354                 return(False);
355
356         ret = S_ISDIR(st->st_ex_mode);
357         if(!ret)
358                 errno = ENOTDIR;
359
360         return ret;
361 }
362
363 /*******************************************************************
364  Check if an object exists in the vfs.
365 ********************************************************************/
366
367 bool vfs_object_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 True;
379 }
380
381 /*******************************************************************
382  Check if a file exists in the vfs.
383 ********************************************************************/
384
385 bool vfs_file_exist(connection_struct *conn, const char *fname,SMB_STRUCT_STAT *sbuf)
386 {
387         SMB_STRUCT_STAT st;
388
389         if (!sbuf)
390                 sbuf = &st;
391
392         ZERO_STRUCTP(sbuf);
393
394         if (SMB_VFS_STAT(conn,fname,sbuf) == -1)
395                 return False;
396         return(S_ISREG(sbuf->st_ex_mode));
397 }
398
399 /****************************************************************************
400  Read data from fsp on the vfs. (note: EINTR re-read differs from vfs_write_data)
401 ****************************************************************************/
402
403 ssize_t vfs_read_data(files_struct *fsp, char *buf, size_t byte_count)
404 {
405         size_t total=0;
406
407         while (total < byte_count)
408         {
409                 ssize_t ret = SMB_VFS_READ(fsp, buf + total,
410                                            byte_count - total);
411
412                 if (ret == 0) return total;
413                 if (ret == -1) {
414                         if (errno == EINTR)
415                                 continue;
416                         else
417                                 return -1;
418                 }
419                 total += ret;
420         }
421         return (ssize_t)total;
422 }
423
424 ssize_t vfs_pread_data(files_struct *fsp, char *buf,
425                 size_t byte_count, SMB_OFF_T offset)
426 {
427         size_t total=0;
428
429         while (total < byte_count)
430         {
431                 ssize_t ret = SMB_VFS_PREAD(fsp, buf + total,
432                                         byte_count - total, offset + total);
433
434                 if (ret == 0) return total;
435                 if (ret == -1) {
436                         if (errno == EINTR)
437                                 continue;
438                         else
439                                 return -1;
440                 }
441                 total += ret;
442         }
443         return (ssize_t)total;
444 }
445
446 /****************************************************************************
447  Write data to a fd on the vfs.
448 ****************************************************************************/
449
450 ssize_t vfs_write_data(struct smb_request *req,
451                         files_struct *fsp,
452                         const char *buffer,
453                         size_t N)
454 {
455         size_t total=0;
456         ssize_t ret;
457
458         if (req && req->unread_bytes) {
459                 SMB_ASSERT(req->unread_bytes == N);
460                 /* VFS_RECVFILE must drain the socket
461                  * before returning. */
462                 req->unread_bytes = 0;
463                 return SMB_VFS_RECVFILE(smbd_server_fd(),
464                                         fsp,
465                                         (SMB_OFF_T)-1,
466                                         N);
467         }
468
469         while (total < N) {
470                 ret = SMB_VFS_WRITE(fsp, buffer + total, N - total);
471
472                 if (ret == -1)
473                         return -1;
474                 if (ret == 0)
475                         return total;
476
477                 total += ret;
478         }
479         return (ssize_t)total;
480 }
481
482 ssize_t vfs_pwrite_data(struct smb_request *req,
483                         files_struct *fsp,
484                         const char *buffer,
485                         size_t N,
486                         SMB_OFF_T offset)
487 {
488         size_t total=0;
489         ssize_t ret;
490
491         if (req && req->unread_bytes) {
492                 SMB_ASSERT(req->unread_bytes == N);
493                 /* VFS_RECVFILE must drain the socket
494                  * before returning. */
495                 req->unread_bytes = 0;
496                 return SMB_VFS_RECVFILE(smbd_server_fd(),
497                                         fsp,
498                                         offset,
499                                         N);
500         }
501
502         while (total < N) {
503                 ret = SMB_VFS_PWRITE(fsp, buffer + total, N - total,
504                                      offset + total);
505
506                 if (ret == -1)
507                         return -1;
508                 if (ret == 0)
509                         return total;
510
511                 total += ret;
512         }
513         return (ssize_t)total;
514 }
515 /****************************************************************************
516  An allocate file space call using the vfs interface.
517  Allocates space for a file from a filedescriptor.
518  Returns 0 on success, -1 on failure.
519 ****************************************************************************/
520
521 int vfs_allocate_file_space(files_struct *fsp, uint64_t len)
522 {
523         int ret;
524         SMB_STRUCT_STAT st;
525         connection_struct *conn = fsp->conn;
526         uint64_t space_avail;
527         uint64_t bsize,dfree,dsize;
528
529         /*
530          * Actually try and commit the space on disk....
531          */
532
533         DEBUG(10,("vfs_allocate_file_space: file %s, len %.0f\n", fsp->fsp_name, (double)len ));
534
535         if (((SMB_OFF_T)len) < 0) {
536                 DEBUG(0,("vfs_allocate_file_space: %s negative len requested.\n", fsp->fsp_name ));
537                 errno = EINVAL;
538                 return -1;
539         }
540
541         ret = SMB_VFS_FSTAT(fsp, &st);
542         if (ret == -1)
543                 return ret;
544
545         if (len == (uint64_t)st.st_ex_size)
546                 return 0;
547
548         if (len < (uint64_t)st.st_ex_size) {
549                 /* Shrink - use ftruncate. */
550
551                 DEBUG(10,("vfs_allocate_file_space: file %s, shrink. Current size %.0f\n",
552                                 fsp->fsp_name, (double)st.st_ex_size ));
553
554                 contend_level2_oplocks_begin(fsp, LEVEL2_CONTEND_ALLOC_SHRINK);
555
556                 flush_write_cache(fsp, SIZECHANGE_FLUSH);
557                 if ((ret = SMB_VFS_FTRUNCATE(fsp, (SMB_OFF_T)len)) != -1) {
558                         set_filelen_write_cache(fsp, len);
559                 }
560
561                 contend_level2_oplocks_end(fsp, LEVEL2_CONTEND_ALLOC_SHRINK);
562
563                 return ret;
564         }
565
566         /* Grow - we need to test if we have enough space. */
567
568         contend_level2_oplocks_begin(fsp, LEVEL2_CONTEND_ALLOC_GROW);
569         contend_level2_oplocks_end(fsp, LEVEL2_CONTEND_ALLOC_GROW);
570
571         if (!lp_strict_allocate(SNUM(fsp->conn)))
572                 return 0;
573
574         len -= st.st_ex_size;
575         len /= 1024; /* Len is now number of 1k blocks needed. */
576         space_avail = get_dfree_info(conn,fsp->fsp_name,False,&bsize,&dfree,&dsize);
577         if (space_avail == (uint64_t)-1) {
578                 return -1;
579         }
580
581         DEBUG(10,("vfs_allocate_file_space: file %s, grow. Current size %.0f, needed blocks = %.0f, space avail = %.0f\n",
582                         fsp->fsp_name, (double)st.st_ex_size, (double)len, (double)space_avail ));
583
584         if (len > space_avail) {
585                 errno = ENOSPC;
586                 return -1;
587         }
588
589         return 0;
590 }
591
592 /****************************************************************************
593  A vfs set_filelen call.
594  set the length of a file from a filedescriptor.
595  Returns 0 on success, -1 on failure.
596 ****************************************************************************/
597
598 int vfs_set_filelen(files_struct *fsp, SMB_OFF_T len)
599 {
600         int ret;
601
602         contend_level2_oplocks_begin(fsp, LEVEL2_CONTEND_SET_FILE_LEN);
603
604         DEBUG(10,("vfs_set_filelen: ftruncate %s to len %.0f\n", fsp->fsp_name, (double)len));
605         flush_write_cache(fsp, SIZECHANGE_FLUSH);
606         if ((ret = SMB_VFS_FTRUNCATE(fsp, len)) != -1) {
607                 set_filelen_write_cache(fsp, len);
608                 notify_fname(fsp->conn, NOTIFY_ACTION_MODIFIED,
609                              FILE_NOTIFY_CHANGE_SIZE
610                              | FILE_NOTIFY_CHANGE_ATTRIBUTES,
611                              fsp->fsp_name);
612         }
613
614         contend_level2_oplocks_end(fsp, LEVEL2_CONTEND_SET_FILE_LEN);
615
616         return ret;
617 }
618
619 /****************************************************************************
620  A vfs fill sparse call.
621  Writes zeros from the end of file to len, if len is greater than EOF.
622  Used only by strict_sync.
623  Returns 0 on success, -1 on failure.
624 ****************************************************************************/
625
626 #define SPARSE_BUF_WRITE_SIZE (32*1024)
627
628 int vfs_fill_sparse(files_struct *fsp, SMB_OFF_T len)
629 {
630         int ret;
631         SMB_STRUCT_STAT st;
632         SMB_OFF_T offset;
633         size_t total;
634         size_t num_to_write;
635         ssize_t pwrite_ret;
636
637         ret = SMB_VFS_FSTAT(fsp, &st);
638         if (ret == -1) {
639                 return ret;
640         }
641
642         if (len <= st.st_ex_size) {
643                 return 0;
644         }
645
646         DEBUG(10,("vfs_fill_sparse: write zeros in file %s from len %.0f to len %.0f (%.0f bytes)\n",
647                 fsp->fsp_name, (double)st.st_ex_size, (double)len, (double)(len - st.st_ex_size)));
648
649         contend_level2_oplocks_begin(fsp, LEVEL2_CONTEND_FILL_SPARSE);
650
651         flush_write_cache(fsp, SIZECHANGE_FLUSH);
652
653         if (!sparse_buf) {
654                 sparse_buf = SMB_CALLOC_ARRAY(char, SPARSE_BUF_WRITE_SIZE);
655                 if (!sparse_buf) {
656                         errno = ENOMEM;
657                         ret = -1;
658                         goto out;
659                 }
660         }
661
662         offset = st.st_ex_size;
663         num_to_write = len - st.st_ex_size;
664         total = 0;
665
666         while (total < num_to_write) {
667                 size_t curr_write_size = MIN(SPARSE_BUF_WRITE_SIZE, (num_to_write - total));
668
669                 pwrite_ret = SMB_VFS_PWRITE(fsp, sparse_buf, curr_write_size, offset + total);
670                 if (pwrite_ret == -1) {
671                         DEBUG(10,("vfs_fill_sparse: SMB_VFS_PWRITE for file %s failed with error %s\n",
672                                 fsp->fsp_name, strerror(errno) ));
673                         ret = -1;
674                         goto out;
675                 }
676                 if (pwrite_ret == 0) {
677                         ret = 0;
678                         goto out;
679                 }
680
681                 total += pwrite_ret;
682         }
683
684         set_filelen_write_cache(fsp, len);
685
686         ret = 0;
687  out:
688         contend_level2_oplocks_end(fsp, LEVEL2_CONTEND_FILL_SPARSE);
689         return ret;
690 }
691
692 /****************************************************************************
693  Transfer some data (n bytes) between two file_struct's.
694 ****************************************************************************/
695
696 static ssize_t vfs_read_fn(void *file, void *buf, size_t len)
697 {
698         struct files_struct *fsp = (struct files_struct *)file;
699
700         return SMB_VFS_READ(fsp, buf, len);
701 }
702
703 static ssize_t vfs_write_fn(void *file, const void *buf, size_t len)
704 {
705         struct files_struct *fsp = (struct files_struct *)file;
706
707         return SMB_VFS_WRITE(fsp, buf, len);
708 }
709
710 SMB_OFF_T vfs_transfer_file(files_struct *in, files_struct *out, SMB_OFF_T n)
711 {
712         return transfer_file_internal((void *)in, (void *)out, n,
713                                       vfs_read_fn, vfs_write_fn);
714 }
715
716 /*******************************************************************
717  A vfs_readdir wrapper which just returns the file name.
718 ********************************************************************/
719
720 char *vfs_readdirname(connection_struct *conn, void *p, SMB_STRUCT_STAT *sbuf)
721 {
722         SMB_STRUCT_DIRENT *ptr= NULL;
723         char *dname;
724
725         if (!p)
726                 return(NULL);
727
728         ptr = SMB_VFS_READDIR(conn, (DIR *)p, sbuf);
729         if (!ptr)
730                 return(NULL);
731
732         dname = ptr->d_name;
733
734 #ifdef NEXT2
735         if (telldir(p) < 0)
736                 return(NULL);
737 #endif
738
739 #ifdef HAVE_BROKEN_READDIR_NAME
740         /* using /usr/ucb/cc is BAD */
741         dname = dname - 2;
742 #endif
743
744         return(dname);
745 }
746
747 /*******************************************************************
748  A wrapper for vfs_chdir().
749 ********************************************************************/
750
751 int vfs_ChDir(connection_struct *conn, const char *path)
752 {
753         int res;
754
755         if (!LastDir) {
756                 LastDir = SMB_STRDUP("");
757         }
758
759         if (strcsequal(path,"."))
760                 return(0);
761
762         if (*path == '/' && strcsequal(LastDir,path))
763                 return(0);
764
765         DEBUG(4,("vfs_ChDir to %s\n",path));
766
767         res = SMB_VFS_CHDIR(conn,path);
768         if (!res) {
769                 SAFE_FREE(LastDir);
770                 LastDir = SMB_STRDUP(path);
771         }
772         return(res);
773 }
774
775 /*******************************************************************
776  Return the absolute current directory path - given a UNIX pathname.
777  Note that this path is returned in DOS format, not UNIX
778  format. Note this can be called with conn == NULL.
779 ********************************************************************/
780
781 char *vfs_GetWd(TALLOC_CTX *ctx, connection_struct *conn)
782 {
783         char s[PATH_MAX+1];
784         SMB_STRUCT_STAT st, st2;
785         char *result;
786         DATA_BLOB cache_value;
787         struct file_id key;
788
789         *s = 0;
790
791         if (!lp_getwd_cache()) {
792                 goto nocache;
793         }
794
795         SET_STAT_INVALID(st);
796
797         if (SMB_VFS_STAT(conn, ".",&st) == -1) {
798                 /*
799                  * Known to fail for root: the directory may be NFS-mounted
800                  * and exported with root_squash (so has no root access).
801                  */
802                 DEBUG(1,("vfs_GetWd: couldn't stat \".\" error %s "
803                          "(NFS problem ?)\n", strerror(errno) ));
804                 goto nocache;
805         }
806
807         key = vfs_file_id_from_sbuf(conn, &st);
808
809         if (!memcache_lookup(smbd_memcache(), GETWD_CACHE,
810                              data_blob_const(&key, sizeof(key)),
811                              &cache_value)) {
812                 goto nocache;
813         }
814
815         SMB_ASSERT((cache_value.length > 0)
816                    && (cache_value.data[cache_value.length-1] == '\0'));
817
818         if ((SMB_VFS_STAT(conn, (char *)cache_value.data, &st2) == 0)
819             && (st.st_ex_dev == st2.st_ex_dev) && (st.st_ex_ino == st2.st_ex_ino)
820             && (S_ISDIR(st.st_ex_mode))) {
821                 /*
822                  * Ok, we're done
823                  */
824                 result = talloc_strdup(ctx, (char *)cache_value.data);
825                 if (result == NULL) {
826                         errno = ENOMEM;
827                 }
828                 return result;
829         }
830
831  nocache:
832
833         /*
834          * We don't have the information to hand so rely on traditional
835          * methods. The very slow getcwd, which spawns a process on some
836          * systems, or the not quite so bad getwd.
837          */
838
839         if (!SMB_VFS_GETWD(conn,s)) {
840                 DEBUG(0, ("vfs_GetWd: SMB_VFS_GETWD call failed: %s\n",
841                           strerror(errno)));
842                 return NULL;
843         }
844
845         if (lp_getwd_cache() && VALID_STAT(st)) {
846                 key = vfs_file_id_from_sbuf(conn, &st);
847
848                 memcache_add(smbd_memcache(), GETWD_CACHE,
849                              data_blob_const(&key, sizeof(key)),
850                              data_blob_const(s, strlen(s)+1));
851         }
852
853         result = talloc_strdup(ctx, s);
854         if (result == NULL) {
855                 errno = ENOMEM;
856         }
857         return result;
858 }
859
860 /*******************************************************************
861  Reduce a file name, removing .. elements and checking that
862  it is below dir in the heirachy. This uses realpath.
863 ********************************************************************/
864
865 NTSTATUS check_reduced_name(connection_struct *conn, const char *fname)
866 {
867 #ifdef REALPATH_TAKES_NULL
868         bool free_resolved_name = True;
869 #else
870         char resolved_name_buf[PATH_MAX+1];
871         bool free_resolved_name = False;
872 #endif
873         char *resolved_name = NULL;
874         char *p = NULL;
875
876         DEBUG(3,("reduce_name [%s] [%s]\n", fname, conn->connectpath));
877
878 #ifdef REALPATH_TAKES_NULL
879         resolved_name = SMB_VFS_REALPATH(conn,fname,NULL);
880 #else
881         resolved_name = SMB_VFS_REALPATH(conn,fname,resolved_name_buf);
882 #endif
883
884         if (!resolved_name) {
885                 switch (errno) {
886                         case ENOTDIR:
887                                 DEBUG(3,("reduce_name: Component not a directory in getting realpath for %s\n", fname));
888                                 return map_nt_error_from_unix(errno);
889                         case ENOENT:
890                         {
891                                 TALLOC_CTX *ctx = talloc_tos();
892                                 char *tmp_fname = NULL;
893                                 char *last_component = NULL;
894                                 /* Last component didn't exist. Remove it and try and canonicalise the directory. */
895
896                                 tmp_fname = talloc_strdup(ctx, fname);
897                                 if (!tmp_fname) {
898                                         return NT_STATUS_NO_MEMORY;
899                                 }
900                                 p = strrchr_m(tmp_fname, '/');
901                                 if (p) {
902                                         *p++ = '\0';
903                                         last_component = p;
904                                 } else {
905                                         last_component = tmp_fname;
906                                         tmp_fname = talloc_strdup(ctx,
907                                                         ".");
908                                         if (!tmp_fname) {
909                                                 return NT_STATUS_NO_MEMORY;
910                                         }
911                                 }
912
913 #ifdef REALPATH_TAKES_NULL
914                                 resolved_name = SMB_VFS_REALPATH(conn,tmp_fname,NULL);
915 #else
916                                 resolved_name = SMB_VFS_REALPATH(conn,tmp_fname,resolved_name_buf);
917 #endif
918                                 if (!resolved_name) {
919                                         DEBUG(3,("reduce_name: couldn't get realpath for %s\n", fname));
920                                         return map_nt_error_from_unix(errno);
921                                 }
922                                 tmp_fname = talloc_asprintf(ctx,
923                                                 "%s/%s",
924                                                 resolved_name,
925                                                 last_component);
926                                 if (!tmp_fname) {
927                                         return NT_STATUS_NO_MEMORY;
928                                 }
929 #ifdef REALPATH_TAKES_NULL
930                                 SAFE_FREE(resolved_name);
931                                 resolved_name = SMB_STRDUP(tmp_fname);
932                                 if (!resolved_name) {
933                                         DEBUG(0,("reduce_name: malloc fail for %s\n", tmp_fname));
934                                         return NT_STATUS_NO_MEMORY;
935                                 }
936 #else
937                                 safe_strcpy(resolved_name_buf, tmp_fname, PATH_MAX);
938                                 resolved_name = resolved_name_buf;
939 #endif
940                                 break;
941                         }
942                         default:
943                                 DEBUG(1,("reduce_name: couldn't get realpath for %s\n", fname));
944                                 return map_nt_error_from_unix(errno);
945                 }
946         }
947
948         DEBUG(10,("reduce_name realpath [%s] -> [%s]\n", fname, resolved_name));
949
950         if (*resolved_name != '/') {
951                 DEBUG(0,("reduce_name: realpath doesn't return absolute paths !\n"));
952                 if (free_resolved_name) {
953                         SAFE_FREE(resolved_name);
954                 }
955                 return NT_STATUS_OBJECT_NAME_INVALID;
956         }
957
958         /* Check for widelinks allowed. */
959         if (!lp_widelinks(SNUM(conn))) {
960                     const char *conn_rootdir;
961
962                     conn_rootdir = SMB_VFS_CONNECTPATH(conn, fname);
963                     if (conn_rootdir == NULL) {
964                             DEBUG(2, ("check_reduced_name: Could not get conn_rootdir\n"));
965                             if (free_resolved_name) {
966                                     SAFE_FREE(resolved_name);
967                             }
968                             return NT_STATUS_ACCESS_DENIED;
969                     }
970
971                     if (strncmp(conn_rootdir, resolved_name,
972                                 strlen(conn_rootdir)) != 0) {
973                             DEBUG(2, ("reduce_name: Bad access attempt: %s is "
974                                       "a symlink outside the share path",
975                                       fname));
976                             if (free_resolved_name) {
977                                     SAFE_FREE(resolved_name);
978                             }
979                             return NT_STATUS_ACCESS_DENIED;
980                     }
981         }
982
983         /* Check if we are allowing users to follow symlinks */
984         /* Patch from David Clerc <David.Clerc@cui.unige.ch>
985                 University of Geneva */
986
987 #ifdef S_ISLNK
988         if (!lp_symlinks(SNUM(conn))) {
989                 SMB_STRUCT_STAT statbuf;
990                 if ( (SMB_VFS_LSTAT(conn,fname,&statbuf) != -1) &&
991                                 (S_ISLNK(statbuf.st_ex_mode)) ) {
992                         if (free_resolved_name) {
993                                 SAFE_FREE(resolved_name);
994                         }
995                         DEBUG(3,("reduce_name: denied: file path name %s is a symlink\n",resolved_name));
996                         return NT_STATUS_ACCESS_DENIED;
997                 }
998         }
999 #endif
1000
1001         DEBUG(3,("reduce_name: %s reduced to %s\n", fname, resolved_name));
1002         if (free_resolved_name) {
1003                 SAFE_FREE(resolved_name);
1004         }
1005         return NT_STATUS_OK;
1006 }