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