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