s3: Slightly simplify file_fnum
[kai/samba-autobuild/.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          * independent 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(conn->sconn->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=conn->sconn->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(struct smbd_server_connection *sconn, uint16 smbpid,
159                     int vuid)
160 {
161         files_struct *fsp, *next;
162
163         for (fsp=sconn->files;fsp;fsp=next) {
164                 next = fsp->next;
165                 if ((fsp->file_pid == smbpid) && (fsp->vuid == vuid)) {
166                         close_file(NULL, fsp, SHUTDOWN_CLOSE);
167                 }
168         }
169 }
170
171 /****************************************************************************
172  Initialise file structures.
173 ****************************************************************************/
174
175 void file_init(void)
176 {
177         int request_max_open_files = lp_max_open_files();
178         int real_lim;
179
180         /*
181          * Set the max_open files to be the requested
182          * max plus a fudgefactor to allow for the extra
183          * fd's we need such as log files etc...
184          */
185         real_lim = set_maxfiles(request_max_open_files + MAX_OPEN_FUDGEFACTOR);
186
187         real_max_open_files = real_lim - MAX_OPEN_FUDGEFACTOR;
188
189         if (real_max_open_files + FILE_HANDLE_OFFSET + MAX_OPEN_PIPES > 65536)
190                 real_max_open_files = 65536 - FILE_HANDLE_OFFSET - MAX_OPEN_PIPES;
191
192         if(real_max_open_files != request_max_open_files) {
193                 DEBUG(1, ("file_init: Information only: requested %d "
194                           "open files, %d are available.\n",
195                           request_max_open_files, real_max_open_files));
196         }
197
198         SMB_ASSERT(real_max_open_files > 100);
199
200         file_bmap = bitmap_talloc(talloc_autofree_context(),
201                                   real_max_open_files);
202
203         if (!file_bmap) {
204                 exit_server("out of memory in file_init");
205         }
206 }
207
208 /****************************************************************************
209  Close files open by a specified vuid.
210 ****************************************************************************/
211
212 void file_close_user(struct smbd_server_connection *sconn, int vuid)
213 {
214         files_struct *fsp, *next;
215
216         for (fsp=sconn->files; fsp; fsp=next) {
217                 next=fsp->next;
218                 if (fsp->vuid == vuid) {
219                         close_file(NULL, fsp, SHUTDOWN_CLOSE);
220                 }
221         }
222 }
223
224 /*
225  * Walk the files table until "fn" returns non-NULL
226  */
227
228 struct files_struct *files_forall(
229         struct smbd_server_connection *sconn,
230         struct files_struct *(*fn)(struct files_struct *fsp,
231                                    void *private_data),
232         void *private_data)
233 {
234         struct files_struct *fsp, *next;
235
236         for (fsp = sconn->files; fsp; fsp = next) {
237                 struct files_struct *ret;
238                 next = fsp->next;
239                 ret = fn(fsp, private_data);
240                 if (ret != NULL) {
241                         return ret;
242                 }
243         }
244         return NULL;
245 }
246
247 /****************************************************************************
248  Find a fsp given a file descriptor.
249 ****************************************************************************/
250
251 files_struct *file_find_fd(int fd)
252 {
253         int count=0;
254         files_struct *fsp;
255
256         for (fsp=smbd_server_conn->files;fsp;fsp=fsp->next,count++) {
257                 if (fsp->fh->fd == fd) {
258                         if (count > 10) {
259                                 DLIST_PROMOTE(smbd_server_conn->files, fsp);
260                         }
261                         return fsp;
262                 }
263         }
264
265         return NULL;
266 }
267
268 /****************************************************************************
269  Find a fsp given a device, inode and file_id.
270 ****************************************************************************/
271
272 files_struct *file_find_dif(struct smbd_server_connection *sconn,
273                             struct file_id id, unsigned long gen_id)
274 {
275         int count=0;
276         files_struct *fsp;
277
278         for (fsp=sconn->files; fsp; fsp=fsp->next,count++) {
279                 /* We can have a fsp->fh->fd == -1 here as it could be a stat open. */
280                 if (file_id_equal(&fsp->file_id, &id) &&
281                     fsp->fh->gen_id == gen_id ) {
282                         if (count > 10) {
283                                 DLIST_PROMOTE(sconn->files, fsp);
284                         }
285                         /* Paranoia check. */
286                         if ((fsp->fh->fd == -1) &&
287                             (fsp->oplock_type != NO_OPLOCK) &&
288                             (fsp->oplock_type != FAKE_LEVEL_II_OPLOCK)) {
289                                 DEBUG(0,("file_find_dif: file %s file_id = "
290                                          "%s, gen = %u oplock_type = %u is a "
291                                          "stat open with oplock type !\n",
292                                          fsp_str_dbg(fsp),
293                                          file_id_string_tos(&fsp->file_id),
294                                          (unsigned int)fsp->fh->gen_id,
295                                          (unsigned int)fsp->oplock_type ));
296                                 smb_panic("file_find_dif");
297                         }
298                         return fsp;
299                 }
300         }
301
302         return NULL;
303 }
304
305 /****************************************************************************
306  Find the first fsp given a device and inode.
307  We use a singleton cache here to speed up searching from getfilepathinfo
308  calls.
309 ****************************************************************************/
310
311 files_struct *file_find_di_first(struct smbd_server_connection *sconn,
312                                  struct file_id id)
313 {
314         files_struct *fsp;
315
316         if (file_id_equal(&fsp_fi_cache.id, &id)) {
317                 /* Positive or negative cache hit. */
318                 return fsp_fi_cache.fsp;
319         }
320
321         fsp_fi_cache.id = id;
322
323         for (fsp=sconn->files;fsp;fsp=fsp->next) {
324                 if (file_id_equal(&fsp->file_id, &id)) {
325                         /* Setup positive cache. */
326                         fsp_fi_cache.fsp = fsp;
327                         return fsp;
328                 }
329         }
330
331         /* Setup negative cache. */
332         fsp_fi_cache.fsp = NULL;
333         return NULL;
334 }
335
336 /****************************************************************************
337  Find the next fsp having the same device and inode.
338 ****************************************************************************/
339
340 files_struct *file_find_di_next(files_struct *start_fsp)
341 {
342         files_struct *fsp;
343
344         for (fsp = start_fsp->next;fsp;fsp=fsp->next) {
345                 if (file_id_equal(&fsp->file_id, &start_fsp->file_id)) {
346                         return fsp;
347                 }
348         }
349
350         return NULL;
351 }
352
353 /****************************************************************************
354  Find any fsp open with a pathname below that of an already open path.
355 ****************************************************************************/
356
357 bool file_find_subpath(files_struct *dir_fsp)
358 {
359         files_struct *fsp;
360         size_t dlen;
361         char *d_fullname = NULL;
362
363         d_fullname = talloc_asprintf(talloc_tos(), "%s/%s",
364                                      dir_fsp->conn->connectpath,
365                                      dir_fsp->fsp_name->base_name);
366
367         if (!d_fullname) {
368                 return false;
369         }
370
371         dlen = strlen(d_fullname);
372
373         for (fsp=dir_fsp->conn->sconn->files; fsp; fsp=fsp->next) {
374                 char *d1_fullname;
375
376                 if (fsp == dir_fsp) {
377                         continue;
378                 }
379
380                 d1_fullname = talloc_asprintf(talloc_tos(),
381                                         "%s/%s",
382                                         fsp->conn->connectpath,
383                                         fsp->fsp_name->base_name);
384
385                 /*
386                  * If the open file has a path that is a longer
387                  * component, then it's a subpath.
388                  */
389                 if (strnequal(d_fullname, d1_fullname, dlen) &&
390                                 (d1_fullname[dlen] == '/')) {
391                         TALLOC_FREE(d1_fullname);
392                         TALLOC_FREE(d_fullname);
393                         return true;
394                 }
395                 TALLOC_FREE(d1_fullname);
396         }
397
398         TALLOC_FREE(d_fullname);
399         return false;
400 }
401
402 /****************************************************************************
403  Sync open files on a connection.
404 ****************************************************************************/
405
406 void file_sync_all(connection_struct *conn)
407 {
408         files_struct *fsp, *next;
409
410         for (fsp=conn->sconn->files; fsp; fsp=next) {
411                 next=fsp->next;
412                 if ((conn == fsp->conn) && (fsp->fh->fd != -1)) {
413                         sync_file(conn, fsp, True /* write through */);
414                 }
415         }
416 }
417
418 /****************************************************************************
419  Free up a fsp.
420 ****************************************************************************/
421
422 void file_free(struct smb_request *req, files_struct *fsp)
423 {
424         DLIST_REMOVE(fsp->conn->sconn->files, fsp);
425
426         TALLOC_FREE(fsp->fake_file_handle);
427
428         if (fsp->fh->ref_count == 1) {
429                 TALLOC_FREE(fsp->fh);
430         } else {
431                 fsp->fh->ref_count--;
432         }
433
434         if (fsp->notify) {
435                 if (fsp->is_directory) {
436                         notify_remove_onelevel(fsp->conn->notify_ctx,
437                                                &fsp->file_id, fsp);
438                 }
439                 notify_remove(fsp->conn->notify_ctx, fsp);
440                 TALLOC_FREE(fsp->notify);
441         }
442
443         /* Ensure this event will never fire. */
444         TALLOC_FREE(fsp->oplock_timeout);
445
446         /* Ensure this event will never fire. */
447         TALLOC_FREE(fsp->update_write_time_event);
448
449         bitmap_clear(file_bmap, fsp->fnum - FILE_HANDLE_OFFSET);
450         files_used--;
451
452         DEBUG(5,("freed files structure %d (%d used)\n",
453                  fsp->fnum, files_used));
454
455         fsp->conn->num_files_open--;
456
457         if ((req != NULL) && (fsp == req->chain_fsp)) {
458                 req->chain_fsp = NULL;
459         }
460
461         /*
462          * Clear all possible chained fsp
463          * pointers in the SMB2 request queue.
464          */
465         if (req != NULL && req->smb2req) {
466                 remove_smb2_chained_fsp(fsp);
467         }
468
469         /* Closing a file can invalidate the positive cache. */
470         if (fsp == fsp_fi_cache.fsp) {
471                 ZERO_STRUCT(fsp_fi_cache);
472         }
473
474         /* Drop all remaining extensions. */
475         while (fsp->vfs_extension) {
476                 vfs_remove_fsp_extension(fsp->vfs_extension->owner, fsp);
477         }
478
479         /* this is paranoia, just in case someone tries to reuse the
480            information */
481         ZERO_STRUCTP(fsp);
482
483         /* fsp->fsp_name is a talloc child and is free'd automatically. */
484         TALLOC_FREE(fsp);
485 }
486
487 /****************************************************************************
488  Get an fsp from a 16 bit fnum.
489 ****************************************************************************/
490
491 static struct files_struct *file_fnum(struct smbd_server_connection *sconn,
492                                       uint16 fnum)
493 {
494         files_struct *fsp;
495         int count=0;
496
497         for (fsp=sconn->files; fsp; fsp=fsp->next, count++) {
498                 if (fsp->fnum == fnum) {
499                         if (count > 10) {
500                                 DLIST_PROMOTE(sconn->files, fsp);
501                         }
502                         return fsp;
503                 }
504         }
505         return NULL;
506 }
507
508 /****************************************************************************
509  Get an fsp from a packet given a 16 bit fnum.
510 ****************************************************************************/
511
512 files_struct *file_fsp(struct smb_request *req, uint16 fid)
513 {
514         files_struct *fsp;
515
516         if (req == NULL) {
517                 /*
518                  * We should never get here. req==NULL could in theory
519                  * only happen from internal opens with a non-zero
520                  * root_dir_fid. Internal opens just don't do that, at
521                  * least they are not supposed to do so. And if they
522                  * start to do so, they better fake up a smb_request
523                  * from which we get the right smbd_server_conn. While
524                  * this should never happen, let's return NULL here.
525                  */
526                 return NULL;
527         }
528
529         if (req->chain_fsp != NULL) {
530                 return req->chain_fsp;
531         }
532
533         fsp = file_fnum(smbd_server_conn, fid);
534         if (fsp != NULL) {
535                 req->chain_fsp = fsp;
536         }
537         return fsp;
538 }
539
540 /****************************************************************************
541  Duplicate the file handle part for a DOS or FCB open.
542 ****************************************************************************/
543
544 NTSTATUS dup_file_fsp(struct smb_request *req, files_struct *from,
545                       uint32 access_mask, uint32 share_access,
546                       uint32 create_options, files_struct *to)
547 {
548         TALLOC_FREE(to->fh);
549
550         to->fh = from->fh;
551         to->fh->ref_count++;
552
553         to->file_id = from->file_id;
554         to->initial_allocation_size = from->initial_allocation_size;
555         to->mode = from->mode;
556         to->file_pid = from->file_pid;
557         to->vuid = from->vuid;
558         to->open_time = from->open_time;
559         to->access_mask = access_mask;
560         to->share_access = share_access;
561         to->oplock_type = from->oplock_type;
562         to->can_lock = from->can_lock;
563         to->can_read = (access_mask & (FILE_READ_DATA)) ? True : False;
564         if (!CAN_WRITE(from->conn)) {
565                 to->can_write = False;
566         } else {
567                 to->can_write = (access_mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) ? True : False;
568         }
569         to->modified = from->modified;
570         to->is_directory = from->is_directory;
571         to->aio_write_behind = from->aio_write_behind;
572
573         if (from->print_file) {
574                 to->print_file = talloc(to, struct print_file_data);
575                 if (!to->print_file) return NT_STATUS_NO_MEMORY;
576                 to->print_file->rap_jobid = from->print_file->rap_jobid;
577         } else {
578                 to->print_file = NULL;
579         }
580
581         return fsp_set_smb_fname(to, from->fsp_name);
582 }
583
584 /**
585  * The only way that the fsp->fsp_name field should ever be set.
586  */
587 NTSTATUS fsp_set_smb_fname(struct files_struct *fsp,
588                            const struct smb_filename *smb_fname_in)
589 {
590         NTSTATUS status;
591         struct smb_filename *smb_fname_new;
592
593         status = copy_smb_filename(fsp, smb_fname_in, &smb_fname_new);
594         if (!NT_STATUS_IS_OK(status)) {
595                 return status;
596         }
597
598         TALLOC_FREE(fsp->fsp_name);
599         fsp->fsp_name = smb_fname_new;
600
601         return NT_STATUS_OK;
602 }