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