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