Fix bug 6494 - Incorrect FileStatus returned in NT_CREATE_ANDX.
[ira/wip.git] / source3 / smbd / files.c
1 /* 
2    Unix SMB/CIFS implementation.
3    Files[] structure handling
4    Copyright (C) Andrew Tridgell 1998
5    
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10    
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15    
16    You should have received a copy of the GNU General Public License
17    along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include "includes.h"
21 #include "smbd/globals.h"
22
23 #define VALID_FNUM(fnum)   (((fnum) >= 0) && ((fnum) < real_max_open_files))
24
25 #define FILE_HANDLE_OFFSET 0x1000
26
27 /****************************************************************************
28  Return a unique number identifying this fsp over the life of this pid.
29 ****************************************************************************/
30
31 static unsigned long get_gen_count(void)
32 {
33         if ((++file_gen_counter) == 0)
34                 return ++file_gen_counter;
35         return file_gen_counter;
36 }
37
38 /****************************************************************************
39  Find first available file slot.
40 ****************************************************************************/
41
42 NTSTATUS file_new(struct smb_request *req, connection_struct *conn,
43                   files_struct **result)
44 {
45         int i;
46         files_struct *fsp;
47         NTSTATUS status;
48
49         /* we want to give out file handles differently on each new
50            connection because of a common bug in MS clients where they try to
51            reuse a file descriptor from an earlier smb connection. This code
52            increases the chance that the errant client will get an error rather
53            than causing corruption */
54         if (first_file == 0) {
55                 first_file = (sys_getpid() ^ (int)time(NULL)) % real_max_open_files;
56         }
57
58         /* TODO: Port the id-tree implementation from Samba4 */
59
60         i = bitmap_find(file_bmap, first_file);
61         if (i == -1) {
62                 DEBUG(0,("ERROR! Out of file structures\n"));
63                 /* TODO: We have to unconditionally return a DOS error here,
64                  * W2k3 even returns ERRDOS/ERRnofids for ntcreate&x with
65                  * NTSTATUS negotiated */
66                 return NT_STATUS_TOO_MANY_OPENED_FILES;
67         }
68
69         /*
70          * Make a child of the connection_struct as an fsp can't exist
71          * indepenedent of a connection.
72          */
73         fsp = talloc_zero(conn, struct files_struct);
74         if (!fsp) {
75                 return NT_STATUS_NO_MEMORY;
76         }
77
78         /*
79          * This can't be a child of fsp because the file_handle can be ref'd
80          * when doing a dos/fcb open, which will then share the file_handle
81          * across multiple fsps.
82          */
83         fsp->fh = talloc_zero(conn, struct fd_handle);
84         if (!fsp->fh) {
85                 TALLOC_FREE(fsp);
86                 return NT_STATUS_NO_MEMORY;
87         }
88
89         fsp->fh->ref_count = 1;
90         fsp->fh->fd = -1;
91
92         fsp->conn = conn;
93         fsp->fh->gen_id = get_gen_count();
94         GetTimeOfDay(&fsp->open_time);
95
96         first_file = (i+1) % real_max_open_files;
97
98         bitmap_set(file_bmap, i);
99         files_used++;
100
101         fsp->fnum = i + FILE_HANDLE_OFFSET;
102         SMB_ASSERT(fsp->fnum < 65536);
103
104         /*
105          * Create an smb_filename with "" for the base_name.  There are very
106          * few NULL checks, so make sure it's initialized with something. to
107          * be safe until an audit can be done.
108          */
109         status = create_synthetic_smb_fname(fsp, "", NULL, NULL,
110                                             &fsp->fsp_name);
111         if (!NT_STATUS_IS_OK(status)) {
112                 TALLOC_FREE(fsp);
113                 TALLOC_FREE(fsp->fh);
114         }
115
116         DLIST_ADD(Files, fsp);
117
118         DEBUG(5,("allocated file structure %d, fnum = %d (%d used)\n",
119                  i, fsp->fnum, files_used));
120
121         if (req != NULL) {
122                 req->chain_fsp = fsp;
123         }
124
125         /* A new fsp invalidates the positive and
126           negative fsp_fi_cache as the new fsp is pushed
127           at the start of the list and we search from
128           a cache hit to the *end* of the list. */
129
130         ZERO_STRUCT(fsp_fi_cache);
131
132         conn->num_files_open++;
133
134         *result = fsp;
135         return NT_STATUS_OK;
136 }
137
138 /****************************************************************************
139  Close all open files for a connection.
140 ****************************************************************************/
141
142 void file_close_conn(connection_struct *conn)
143 {
144         files_struct *fsp, *next;
145         
146         for (fsp=Files;fsp;fsp=next) {
147                 next = fsp->next;
148                 if (fsp->conn == conn) {
149                         close_file(NULL, fsp, SHUTDOWN_CLOSE);
150                 }
151         }
152 }
153
154 /****************************************************************************
155  Close all open files for a pid and a vuid.
156 ****************************************************************************/
157
158 void file_close_pid(uint16 smbpid, int vuid)
159 {
160         files_struct *fsp, *next;
161         
162         for (fsp=Files;fsp;fsp=next) {
163                 next = fsp->next;
164                 if ((fsp->file_pid == smbpid) && (fsp->vuid == vuid)) {
165                         close_file(NULL, fsp, SHUTDOWN_CLOSE);
166                 }
167         }
168 }
169
170 /****************************************************************************
171  Initialise file structures.
172 ****************************************************************************/
173
174 #define MAX_OPEN_FUDGEFACTOR 20
175
176 void file_init(void)
177 {
178         int request_max_open_files = lp_max_open_files();
179         int real_lim;
180
181         /*
182          * Set the max_open files to be the requested
183          * max plus a fudgefactor to allow for the extra
184          * fd's we need such as log files etc...
185          */
186         real_lim = set_maxfiles(request_max_open_files + MAX_OPEN_FUDGEFACTOR);
187
188         real_max_open_files = real_lim - MAX_OPEN_FUDGEFACTOR;
189
190         if (real_max_open_files + FILE_HANDLE_OFFSET + MAX_OPEN_PIPES > 65536)
191                 real_max_open_files = 65536 - FILE_HANDLE_OFFSET - MAX_OPEN_PIPES;
192
193         if(real_max_open_files != request_max_open_files) {
194                 DEBUG(1,("file_init: Information only: requested %d \
195 open files, %d are available.\n", request_max_open_files, real_max_open_files));
196         }
197
198         SMB_ASSERT(real_max_open_files > 100);
199
200         file_bmap = bitmap_allocate(real_max_open_files);
201         
202         if (!file_bmap) {
203                 exit_server("out of memory in file_init");
204         }
205 }
206
207 /****************************************************************************
208  Close files open by a specified vuid.
209 ****************************************************************************/
210
211 void file_close_user(int vuid)
212 {
213         files_struct *fsp, *next;
214
215         for (fsp=Files;fsp;fsp=next) {
216                 next=fsp->next;
217                 if (fsp->vuid == vuid) {
218                         close_file(NULL, fsp, SHUTDOWN_CLOSE);
219                 }
220         }
221 }
222
223 /*
224  * Walk the files table until "fn" returns non-NULL
225  */
226
227 struct files_struct *file_walk_table(
228         struct files_struct *(*fn)(struct files_struct *fsp,
229                                    void *private_data),
230         void *private_data)
231 {
232         struct files_struct *fsp, *next;
233
234         for (fsp = Files; fsp; fsp = next) {
235                 struct files_struct *ret;
236                 next = fsp->next;
237                 ret = fn(fsp, private_data);
238                 if (ret != NULL) {
239                         return ret;
240                 }
241         }
242         return NULL;
243 }
244
245 /****************************************************************************
246  Debug to enumerate all open files in the smbd.
247 ****************************************************************************/
248
249 void file_dump_open_table(void)
250 {
251         int count=0;
252         files_struct *fsp;
253
254         for (fsp=Files;fsp;fsp=fsp->next,count++) {
255                 DEBUG(10,("Files[%d], fnum = %d, name %s, fd = %d, gen = %lu, "
256                           "fileid=%s\n", count, fsp->fnum, fsp_str_dbg(fsp),
257                           fsp->fh->fd, (unsigned long)fsp->fh->gen_id,
258                           file_id_string_tos(&fsp->file_id)));
259         }
260 }
261
262 /****************************************************************************
263  Find a fsp given a file descriptor.
264 ****************************************************************************/
265
266 files_struct *file_find_fd(int fd)
267 {
268         int count=0;
269         files_struct *fsp;
270
271         for (fsp=Files;fsp;fsp=fsp->next,count++) {
272                 if (fsp->fh->fd == fd) {
273                         if (count > 10) {
274                                 DLIST_PROMOTE(Files, fsp);
275                         }
276                         return fsp;
277                 }
278         }
279
280         return NULL;
281 }
282
283 /****************************************************************************
284  Find a fsp given a device, inode and file_id.
285 ****************************************************************************/
286
287 files_struct *file_find_dif(struct file_id id, unsigned long gen_id)
288 {
289         int count=0;
290         files_struct *fsp;
291
292         for (fsp=Files;fsp;fsp=fsp->next,count++) {
293                 /* We can have a fsp->fh->fd == -1 here as it could be a stat open. */
294                 if (file_id_equal(&fsp->file_id, &id) &&
295                     fsp->fh->gen_id == gen_id ) {
296                         if (count > 10) {
297                                 DLIST_PROMOTE(Files, fsp);
298                         }
299                         /* Paranoia check. */
300                         if ((fsp->fh->fd == -1) &&
301                             (fsp->oplock_type != NO_OPLOCK) &&
302                             (fsp->oplock_type != FAKE_LEVEL_II_OPLOCK)) {
303                                 DEBUG(0,("file_find_dif: file %s file_id = "
304                                          "%s, gen = %u oplock_type = %u is a "
305                                          "stat open with oplock type !\n",
306                                          fsp_str_dbg(fsp),
307                                          file_id_string_tos(&fsp->file_id),
308                                          (unsigned int)fsp->fh->gen_id,
309                                          (unsigned int)fsp->oplock_type ));
310                                 smb_panic("file_find_dif");
311                         }
312                         return fsp;
313                 }
314         }
315
316         return NULL;
317 }
318
319 /****************************************************************************
320  Check if an fsp still exists.
321 ****************************************************************************/
322
323 files_struct *file_find_fsp(files_struct *orig_fsp)
324 {
325         files_struct *fsp;
326
327         for (fsp=Files;fsp;fsp=fsp->next) {
328                 if (fsp == orig_fsp)
329                         return fsp;
330         }
331
332         return NULL;
333 }
334
335 /****************************************************************************
336  Find the first fsp given a device and inode.
337  We use a singleton cache here to speed up searching from getfilepathinfo
338  calls.
339 ****************************************************************************/
340
341 files_struct *file_find_di_first(struct file_id id)
342 {
343         files_struct *fsp;
344
345         if (file_id_equal(&fsp_fi_cache.id, &id)) {
346                 /* Positive or negative cache hit. */
347                 return fsp_fi_cache.fsp;
348         }
349
350         fsp_fi_cache.id = id;
351
352         for (fsp=Files;fsp;fsp=fsp->next) {
353                 if (file_id_equal(&fsp->file_id, &id)) {
354                         /* Setup positive cache. */
355                         fsp_fi_cache.fsp = fsp;
356                         return fsp;
357                 }
358         }
359
360         /* Setup negative cache. */
361         fsp_fi_cache.fsp = NULL;
362         return NULL;
363 }
364
365 /****************************************************************************
366  Find the next fsp having the same device and inode.
367 ****************************************************************************/
368
369 files_struct *file_find_di_next(files_struct *start_fsp)
370 {
371         files_struct *fsp;
372
373         for (fsp = start_fsp->next;fsp;fsp=fsp->next) {
374                 if (file_id_equal(&fsp->file_id, &start_fsp->file_id)) {
375                         return fsp;
376                 }
377         }
378
379         return NULL;
380 }
381
382 /****************************************************************************
383  Find a fsp that is open for printing.
384 ****************************************************************************/
385
386 files_struct *file_find_print(void)
387 {
388         files_struct *fsp;
389
390         for (fsp=Files;fsp;fsp=fsp->next) {
391                 if (fsp->print_file) {
392                         return fsp;
393                 }
394         } 
395
396         return NULL;
397 }
398
399 /****************************************************************************
400  Find any fsp open with a pathname below that of an already open path.
401 ****************************************************************************/
402
403 bool file_find_subpath(files_struct *dir_fsp)
404 {
405         files_struct *fsp;
406         size_t dlen;
407         char *d_fullname = NULL;
408         bool ret = false;
409
410         d_fullname = talloc_asprintf(talloc_tos(), "%s/%s",
411                                      dir_fsp->conn->connectpath,
412                                      dir_fsp->fsp_name->base_name);
413
414         if (!d_fullname) {
415                 goto out;
416         }
417
418         dlen = strlen(d_fullname);
419
420         for (fsp=Files;fsp;fsp=fsp->next) {
421                 char *d1_fullname;
422
423                 if (fsp == dir_fsp) {
424                         continue;
425                 }
426
427                 d1_fullname = talloc_asprintf(talloc_tos(),
428                                         "%s/%s",
429                                         fsp->conn->connectpath,
430                                         fsp->fsp_name->base_name);
431
432                 if (strnequal(d_fullname, d1_fullname, dlen)) {
433                         int d1_len = strlen(d1_fullname);
434
435                         /*
436                          * If the open file is a second file handle to the
437                          * same name or is a stream on the original file, then
438                          * don't return true.
439                          */
440                         if (d1_len == dlen) {
441                                 TALLOC_FREE(d1_fullname);
442                                 continue;
443                         }
444
445                         TALLOC_FREE(d1_fullname);
446                         ret = true;
447                         goto out;
448                 }
449                 TALLOC_FREE(d1_fullname);
450         } 
451  out:
452         TALLOC_FREE(d_fullname);
453         return ret;
454 }
455
456 /****************************************************************************
457  Sync open files on a connection.
458 ****************************************************************************/
459
460 void file_sync_all(connection_struct *conn)
461 {
462         files_struct *fsp, *next;
463
464         for (fsp=Files;fsp;fsp=next) {
465                 next=fsp->next;
466                 if ((conn == fsp->conn) && (fsp->fh->fd != -1)) {
467                         sync_file(conn, fsp, True /* write through */);
468                 }
469         }
470 }
471
472 /****************************************************************************
473  Free up a fsp.
474 ****************************************************************************/
475
476 void file_free(struct smb_request *req, files_struct *fsp)
477 {
478         DLIST_REMOVE(Files, fsp);
479
480         TALLOC_FREE(fsp->fake_file_handle);
481
482         if (fsp->fh->ref_count == 1) {
483                 TALLOC_FREE(fsp->fh);
484         } else {
485                 fsp->fh->ref_count--;
486         }
487
488         if (fsp->notify) {
489                 if (fsp->is_directory) {
490                         notify_remove_onelevel(fsp->conn->notify_ctx,
491                                                &fsp->file_id, fsp);
492                 }
493                 notify_remove(fsp->conn->notify_ctx, fsp);
494                 TALLOC_FREE(fsp->notify);
495         }
496
497         /* Ensure this event will never fire. */
498         TALLOC_FREE(fsp->oplock_timeout);
499
500         /* Ensure this event will never fire. */
501         TALLOC_FREE(fsp->update_write_time_event);
502
503         bitmap_clear(file_bmap, fsp->fnum - FILE_HANDLE_OFFSET);
504         files_used--;
505
506         DEBUG(5,("freed files structure %d (%d used)\n",
507                  fsp->fnum, files_used));
508
509         fsp->conn->num_files_open--;
510
511         if ((req != NULL) && (fsp == req->chain_fsp)) {
512                 req->chain_fsp = NULL;
513         }
514
515         /* Closing a file can invalidate the positive cache. */
516         if (fsp == fsp_fi_cache.fsp) {
517                 ZERO_STRUCT(fsp_fi_cache);
518         }
519
520         /* Drop all remaining extensions. */
521         while (fsp->vfs_extension) {
522                 vfs_remove_fsp_extension(fsp->vfs_extension->owner, fsp);
523         }
524
525         /* this is paranoia, just in case someone tries to reuse the
526            information */
527         ZERO_STRUCTP(fsp);
528
529         /* fsp->fsp_name is a talloc child and is free'd automatically. */
530         TALLOC_FREE(fsp);
531 }
532
533 /****************************************************************************
534  Get an fsp from a 16 bit fnum.
535 ****************************************************************************/
536
537 files_struct *file_fnum(uint16 fnum)
538 {
539         files_struct *fsp;
540         int count=0;
541
542         for (fsp=Files;fsp;fsp=fsp->next, count++) {
543                 if (fsp->fnum == fnum) {
544                         if (count > 10) {
545                                 DLIST_PROMOTE(Files, fsp);
546                         }
547                         return fsp;
548                 }
549         }
550         return NULL;
551 }
552
553 /****************************************************************************
554  Get an fsp from a packet given the offset of a 16 bit fnum.
555 ****************************************************************************/
556
557 files_struct *file_fsp(struct smb_request *req, uint16 fid)
558 {
559         files_struct *fsp;
560
561         if ((req != NULL) && (req->chain_fsp != NULL)) {
562                 return req->chain_fsp;
563         }
564
565         fsp = file_fnum(fid);
566         if ((fsp != NULL) && (req != NULL)) {
567                 req->chain_fsp = fsp;
568         }
569         return fsp;
570 }
571
572 /****************************************************************************
573  Duplicate the file handle part for a DOS or FCB open.
574 ****************************************************************************/
575
576 NTSTATUS dup_file_fsp(struct smb_request *req, files_struct *from,
577                       uint32 access_mask, uint32 share_access,
578                       uint32 create_options, files_struct *to)
579 {
580         TALLOC_FREE(to->fh);
581
582         to->fh = from->fh;
583         to->fh->ref_count++;
584
585         to->file_id = from->file_id;
586         to->initial_allocation_size = from->initial_allocation_size;
587         to->mode = from->mode;
588         to->file_pid = from->file_pid;
589         to->vuid = from->vuid;
590         to->open_time = from->open_time;
591         to->access_mask = access_mask;
592         to->share_access = share_access;
593         to->oplock_type = from->oplock_type;
594         to->can_lock = from->can_lock;
595         to->can_read = (access_mask & (FILE_READ_DATA)) ? True : False;
596         if (!CAN_WRITE(from->conn)) {
597                 to->can_write = False;
598         } else {
599                 to->can_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) ? True : False;
600         }
601         to->print_file = from->print_file;
602         to->modified = from->modified;
603         to->is_directory = from->is_directory;
604         to->aio_write_behind = from->aio_write_behind;
605         return fsp_set_smb_fname(to, from->fsp_name);
606 }
607
608 /**
609  * The only way that the fsp->fsp_name field should ever be set.
610  */
611 NTSTATUS fsp_set_smb_fname(struct files_struct *fsp,
612                            const struct smb_filename *smb_fname_in)
613 {
614         NTSTATUS status;
615         struct smb_filename *smb_fname_new;
616
617         status = copy_smb_filename(fsp, smb_fname_in, &smb_fname_new);
618         if (!NT_STATUS_IS_OK(status)) {
619                 return status;
620         }
621
622         TALLOC_FREE(fsp->fsp_name);
623         fsp->fsp_name = smb_fname_new;
624
625         return NT_STATUS_OK;
626 }