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