s3: Change the share_mode_lock struct to store a base_name and stream_name
[samba.git] / source3 / locking / locking.c
1 /* 
2    Unix SMB/CIFS implementation.
3    Locking functions
4    Copyright (C) Andrew Tridgell 1992-2000
5    Copyright (C) Jeremy Allison 1992-2006
6    Copyright (C) Volker Lendecke 2005
7    
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12    
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17    
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20
21    Revision History:
22
23    12 aug 96: Erik.Devriendt@te6.siemens.be
24    added support for shared memory implementation of share mode locking
25
26    May 1997. Jeremy Allison (jallison@whistle.com). Modified share mode
27    locking to deal with multiple share modes per open file.
28
29    September 1997. Jeremy Allison (jallison@whistle.com). Added oplock
30    support.
31
32    rewrtten completely to use new tdb code. Tridge, Dec '99
33
34    Added POSIX locking support. Jeremy Allison (jeremy@valinux.com), Apr. 2000.
35    Added Unix Extensions POSIX locking support. Jeremy Allison Mar 2006.
36 */
37
38 #include "includes.h"
39
40 #undef DBGC_CLASS
41 #define DBGC_CLASS DBGC_LOCKING
42
43 #define NO_LOCKING_COUNT (-1)
44
45 /* the locking database handle */
46 static struct db_context *lock_db;
47
48 /****************************************************************************
49  Debugging aids :-).
50 ****************************************************************************/
51
52 const char *lock_type_name(enum brl_type lock_type)
53 {
54         switch (lock_type) {
55                 case READ_LOCK:
56                         return "READ";
57                 case WRITE_LOCK:
58                         return "WRITE";
59                 case PENDING_READ_LOCK:
60                         return "PENDING_READ";
61                 case PENDING_WRITE_LOCK:
62                         return "PENDING_WRITE";
63                 default:
64                         return "other";
65         }
66 }
67
68 const char *lock_flav_name(enum brl_flavour lock_flav)
69 {
70         return (lock_flav == WINDOWS_LOCK) ? "WINDOWS_LOCK" : "POSIX_LOCK";
71 }
72
73 /****************************************************************************
74  Utility function called to see if a file region is locked.
75  Called in the read/write codepath.
76 ****************************************************************************/
77
78 void init_strict_lock_struct(files_struct *fsp,
79                                 uint32 smbpid,
80                                 br_off start,
81                                 br_off size,
82                                 enum brl_type lock_type,
83                                 struct lock_struct *plock)
84 {
85         SMB_ASSERT(lock_type == READ_LOCK || lock_type == WRITE_LOCK);
86
87         plock->context.smbpid = smbpid;
88         plock->context.tid = fsp->conn->cnum;
89         plock->context.pid = procid_self();
90         plock->start = start;
91         plock->size = size;
92         plock->fnum = fsp->fnum;
93         plock->lock_type = lock_type;
94         plock->lock_flav = lp_posix_cifsu_locktype(fsp);
95 }
96
97 bool strict_lock_default(files_struct *fsp, struct lock_struct *plock)
98 {
99         int strict_locking = lp_strict_locking(fsp->conn->params);
100         bool ret = False;
101
102         if (plock->size == 0) {
103                 return True;
104         }
105
106         if (!lp_locking(fsp->conn->params) || !strict_locking) {
107                 return True;
108         }
109
110         if (strict_locking == Auto) {
111                 if  (EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type) && (plock->lock_type == READ_LOCK || plock->lock_type == WRITE_LOCK)) {
112                         DEBUG(10,("is_locked: optimisation - exclusive oplock on file %s\n", fsp->fsp_name ));
113                         ret = True;
114                 } else if ((fsp->oplock_type == LEVEL_II_OPLOCK) &&
115                            (plock->lock_type == READ_LOCK)) {
116                         DEBUG(10,("is_locked: optimisation - level II oplock on file %s\n", fsp->fsp_name ));
117                         ret = True;
118                 } else {
119                         struct byte_range_lock *br_lck = brl_get_locks_readonly(talloc_tos(), fsp);
120                         if (!br_lck) {
121                                 return True;
122                         }
123                         ret = brl_locktest(br_lck,
124                                         plock->context.smbpid,
125                                         plock->context.pid,
126                                         plock->start,
127                                         plock->size,
128                                         plock->lock_type,
129                                         plock->lock_flav);
130                         TALLOC_FREE(br_lck);
131                 }
132         } else {
133                 struct byte_range_lock *br_lck = brl_get_locks_readonly(talloc_tos(), fsp);
134                 if (!br_lck) {
135                         return True;
136                 }
137                 ret = brl_locktest(br_lck,
138                                 plock->context.smbpid,
139                                 plock->context.pid,
140                                 plock->start,
141                                 plock->size,
142                                 plock->lock_type,
143                                 plock->lock_flav);
144                 TALLOC_FREE(br_lck);
145         }
146
147         DEBUG(10,("strict_lock_default: flavour = %s brl start=%.0f "
148                         "len=%.0f %s for fnum %d file %s\n",
149                         lock_flav_name(plock->lock_flav),
150                         (double)plock->start, (double)plock->size,
151                         ret ? "unlocked" : "locked",
152                         plock->fnum, fsp->fsp_name ));
153
154         return ret;
155 }
156
157 void strict_unlock_default(files_struct *fsp, struct lock_struct *plock)
158 {
159 }
160
161 /****************************************************************************
162  Find out if a lock could be granted - return who is blocking us if we can't.
163 ****************************************************************************/
164
165 NTSTATUS query_lock(files_struct *fsp,
166                         uint32 *psmbpid,
167                         uint64_t *pcount,
168                         uint64_t *poffset,
169                         enum brl_type *plock_type,
170                         enum brl_flavour lock_flav)
171 {
172         struct byte_range_lock *br_lck = NULL;
173         NTSTATUS status = NT_STATUS_LOCK_NOT_GRANTED;
174
175         if (!fsp->can_lock) {
176                 return fsp->is_directory ? NT_STATUS_INVALID_DEVICE_REQUEST : NT_STATUS_INVALID_HANDLE;
177         }
178
179         if (!lp_locking(fsp->conn->params)) {
180                 return NT_STATUS_OK;
181         }
182
183         br_lck = brl_get_locks_readonly(talloc_tos(), fsp);
184         if (!br_lck) {
185                 return NT_STATUS_NO_MEMORY;
186         }
187
188         status = brl_lockquery(br_lck,
189                         psmbpid,
190                         procid_self(),
191                         poffset,
192                         pcount,
193                         plock_type,
194                         lock_flav);
195
196         TALLOC_FREE(br_lck);
197         return status;
198 }
199
200 static void increment_current_lock_count(files_struct *fsp,
201     enum brl_flavour lock_flav)
202 {
203         if (lock_flav == WINDOWS_LOCK &&
204             fsp->current_lock_count != NO_LOCKING_COUNT) {
205                 /* blocking ie. pending, locks also count here,
206                  * as this is an efficiency counter to avoid checking
207                  * the lock db. on close. JRA. */
208
209                 fsp->current_lock_count++;
210         } else {
211                 /* Notice that this has had a POSIX lock request.
212                  * We can't count locks after this so forget them.
213                  */
214                 fsp->current_lock_count = NO_LOCKING_COUNT;
215         }
216 }
217
218 static void decrement_current_lock_count(files_struct *fsp,
219     enum brl_flavour lock_flav)
220 {
221         if (lock_flav == WINDOWS_LOCK &&
222             fsp->current_lock_count != NO_LOCKING_COUNT) {
223                 SMB_ASSERT(fsp->current_lock_count > 0);
224                 fsp->current_lock_count--;
225         }
226 }
227
228 /****************************************************************************
229  Utility function called by locking requests.
230 ****************************************************************************/
231
232 struct byte_range_lock *do_lock(struct messaging_context *msg_ctx,
233                         files_struct *fsp,
234                         uint32 lock_pid,
235                         uint64_t count,
236                         uint64_t offset,
237                         enum brl_type lock_type,
238                         enum brl_flavour lock_flav,
239                         bool blocking_lock,
240                         NTSTATUS *perr,
241                         uint32 *plock_pid,
242                         struct blocking_lock_record *blr)
243 {
244         struct byte_range_lock *br_lck = NULL;
245
246         if (!fsp->can_lock) {
247                 *perr = fsp->is_directory ? NT_STATUS_INVALID_DEVICE_REQUEST : NT_STATUS_INVALID_HANDLE;
248                 return NULL;
249         }
250
251         if (!lp_locking(fsp->conn->params)) {
252                 *perr = NT_STATUS_OK;
253                 return NULL;
254         }
255
256         /* NOTE! 0 byte long ranges ARE allowed and should be stored  */
257
258         DEBUG(10,("do_lock: lock flavour %s lock type %s start=%.0f len=%.0f "
259                 "blocking_lock=%s requested for fnum %d file %s\n",
260                 lock_flav_name(lock_flav), lock_type_name(lock_type),
261                 (double)offset, (double)count, blocking_lock ? "true" :
262                 "false", fsp->fnum, fsp->fsp_name));
263
264         br_lck = brl_get_locks(talloc_tos(), fsp);
265         if (!br_lck) {
266                 *perr = NT_STATUS_NO_MEMORY;
267                 return NULL;
268         }
269
270         *perr = brl_lock(msg_ctx,
271                         br_lck,
272                         lock_pid,
273                         procid_self(),
274                         offset,
275                         count, 
276                         lock_type,
277                         lock_flav,
278                         blocking_lock,
279                         plock_pid,
280                         blr);
281
282         DEBUG(10, ("do_lock: returning status=%s\n", nt_errstr(*perr)));
283
284         increment_current_lock_count(fsp, lock_flav);
285         return br_lck;
286 }
287
288 /****************************************************************************
289  Utility function called by unlocking requests.
290 ****************************************************************************/
291
292 NTSTATUS do_unlock(struct messaging_context *msg_ctx,
293                         files_struct *fsp,
294                         uint32 lock_pid,
295                         uint64_t count,
296                         uint64_t offset,
297                         enum brl_flavour lock_flav)
298 {
299         bool ok = False;
300         struct byte_range_lock *br_lck = NULL;
301         
302         if (!fsp->can_lock) {
303                 return fsp->is_directory ? NT_STATUS_INVALID_DEVICE_REQUEST : NT_STATUS_INVALID_HANDLE;
304         }
305         
306         if (!lp_locking(fsp->conn->params)) {
307                 return NT_STATUS_OK;
308         }
309         
310         DEBUG(10,("do_unlock: unlock start=%.0f len=%.0f requested for fnum %d file %s\n",
311                   (double)offset, (double)count, fsp->fnum, fsp->fsp_name ));
312
313         br_lck = brl_get_locks(talloc_tos(), fsp);
314         if (!br_lck) {
315                 return NT_STATUS_NO_MEMORY;
316         }
317
318         ok = brl_unlock(msg_ctx,
319                         br_lck,
320                         lock_pid,
321                         procid_self(),
322                         offset,
323                         count,
324                         lock_flav);
325    
326         TALLOC_FREE(br_lck);
327
328         if (!ok) {
329                 DEBUG(10,("do_unlock: returning ERRlock.\n" ));
330                 return NT_STATUS_RANGE_NOT_LOCKED;
331         }
332
333         decrement_current_lock_count(fsp, lock_flav);
334         return NT_STATUS_OK;
335 }
336
337 /****************************************************************************
338  Cancel any pending blocked locks.
339 ****************************************************************************/
340
341 NTSTATUS do_lock_cancel(files_struct *fsp,
342                         uint32 lock_pid,
343                         uint64_t count,
344                         uint64_t offset,
345                         enum brl_flavour lock_flav,
346                         struct blocking_lock_record *blr)
347 {
348         bool ok = False;
349         struct byte_range_lock *br_lck = NULL;
350
351         if (!fsp->can_lock) {
352                 return fsp->is_directory ?
353                         NT_STATUS_INVALID_DEVICE_REQUEST : NT_STATUS_INVALID_HANDLE;
354         }
355         
356         if (!lp_locking(fsp->conn->params)) {
357                 return NT_STATUS_DOS(ERRDOS, ERRcancelviolation);
358         }
359
360         DEBUG(10,("do_lock_cancel: cancel start=%.0f len=%.0f requested for fnum %d file %s\n",
361                   (double)offset, (double)count, fsp->fnum, fsp->fsp_name ));
362
363         br_lck = brl_get_locks(talloc_tos(), fsp);
364         if (!br_lck) {
365                 return NT_STATUS_NO_MEMORY;
366         }
367
368         ok = brl_lock_cancel(br_lck,
369                         lock_pid,
370                         procid_self(),
371                         offset,
372                         count,
373                         lock_flav,
374                         blr);
375
376         TALLOC_FREE(br_lck);
377
378         if (!ok) {
379                 DEBUG(10,("do_lock_cancel: returning ERRcancelviolation.\n" ));
380                 return NT_STATUS_DOS(ERRDOS, ERRcancelviolation);
381         }
382
383         decrement_current_lock_count(fsp, lock_flav);
384         return NT_STATUS_OK;
385 }
386
387 /****************************************************************************
388  Remove any locks on this fd. Called from file_close().
389 ****************************************************************************/
390
391 void locking_close_file(struct messaging_context *msg_ctx,
392                         files_struct *fsp)
393 {
394         struct byte_range_lock *br_lck;
395
396         if (!lp_locking(fsp->conn->params)) {
397                 return;
398         }
399
400         /* If we have not outstanding locks or pending
401          * locks then we don't need to look in the lock db.
402          */
403
404         if (fsp->current_lock_count == 0) {
405                 return;
406         }
407
408         br_lck = brl_get_locks(talloc_tos(),fsp);
409
410         if (br_lck) {
411                 cancel_pending_lock_requests_by_fid(fsp, br_lck);
412                 brl_close_fnum(msg_ctx, br_lck);
413                 TALLOC_FREE(br_lck);
414         }
415 }
416
417 /****************************************************************************
418  Initialise the locking functions.
419 ****************************************************************************/
420
421 static bool locking_init_internal(bool read_only)
422 {
423         brl_init(read_only);
424
425         if (lock_db)
426                 return True;
427
428         lock_db = db_open(NULL, lock_path("locking.tdb"),
429                           lp_open_files_db_hash_size(),
430                           TDB_DEFAULT|TDB_VOLATILE|TDB_CLEAR_IF_FIRST,
431                           read_only?O_RDONLY:O_RDWR|O_CREAT, 0644);
432
433         if (!lock_db) {
434                 DEBUG(0,("ERROR: Failed to initialise locking database\n"));
435                 return False;
436         }
437
438         if (!posix_locking_init(read_only))
439                 return False;
440
441         return True;
442 }
443
444 bool locking_init(void)
445 {
446         return locking_init_internal(false);
447 }
448
449 bool locking_init_readonly(void)
450 {
451         return locking_init_internal(true);
452 }
453
454 /*******************************************************************
455  Deinitialize the share_mode management.
456 ******************************************************************/
457
458 bool locking_end(void)
459 {
460         brl_shutdown();
461         TALLOC_FREE(lock_db);
462         return true;
463 }
464
465 /*******************************************************************
466  Form a static locking key for a dev/inode pair.
467 ******************************************************************/
468
469 static TDB_DATA locking_key(const struct file_id *id, struct file_id *tmp)
470 {
471         *tmp = *id;
472         return make_tdb_data((const uint8_t *)tmp, sizeof(*tmp));
473 }
474
475 /*******************************************************************
476  Print out a share mode.
477 ********************************************************************/
478
479 char *share_mode_str(TALLOC_CTX *ctx, int num, const struct share_mode_entry *e)
480 {
481         return talloc_asprintf(ctx, "share_mode_entry[%d]: %s "
482                  "pid = %s, share_access = 0x%x, private_options = 0x%x, "
483                  "access_mask = 0x%x, mid = 0x%x, type= 0x%x, gen_id = %lu, "
484                  "uid = %u, flags = %u, file_id %s",
485                  num,
486                  e->op_type == UNUSED_SHARE_MODE_ENTRY ? "UNUSED" : "",
487                  procid_str_static(&e->pid),
488                  e->share_access, e->private_options,
489                  e->access_mask, e->op_mid, e->op_type, e->share_file_id,
490                  (unsigned int)e->uid, (unsigned int)e->flags,
491                  file_id_string_tos(&e->id));
492 }
493
494 /*******************************************************************
495  Print out a share mode table.
496 ********************************************************************/
497
498 static void print_share_mode_table(struct locking_data *data)
499 {
500         int num_share_modes = data->u.s.num_share_mode_entries;
501         struct share_mode_entry *shares =
502                 (struct share_mode_entry *)(data + 1);
503         int i;
504
505         for (i = 0; i < num_share_modes; i++) {
506                 struct share_mode_entry entry;
507                 char *str;
508
509                 /*
510                  * We need to memcpy the entry here due to alignment
511                  * restrictions that are not met when directly accessing
512                  * shares[i]
513                  */
514
515                 memcpy(&entry, &shares[i], sizeof(struct share_mode_entry));
516                 str = share_mode_str(talloc_tos(), i, &entry);
517
518                 DEBUG(10,("print_share_mode_table: %s\n", str ? str : ""));
519                 TALLOC_FREE(str);
520         }
521 }
522
523 /*******************************************************************
524  Get all share mode entries for a dev/inode pair.
525 ********************************************************************/
526
527 static bool parse_share_modes(const TDB_DATA dbuf, struct share_mode_lock *lck)
528 {
529         struct locking_data data;
530         int i;
531
532         if (dbuf.dsize < sizeof(struct locking_data)) {
533                 smb_panic("parse_share_modes: buffer too short");
534         }
535
536         memcpy(&data, dbuf.dptr, sizeof(data));
537
538         lck->delete_on_close = data.u.s.delete_on_close;
539         lck->old_write_time = data.u.s.old_write_time;
540         lck->changed_write_time = data.u.s.changed_write_time;
541         lck->num_share_modes = data.u.s.num_share_mode_entries;
542
543         DEBUG(10, ("parse_share_modes: delete_on_close: %d, owrt: %s, "
544                    "cwrt: %s, tok: %u, num_share_modes: %d\n",
545                    lck->delete_on_close,
546                    timestring(debug_ctx(),
547                               convert_timespec_to_time_t(lck->old_write_time)),
548                    timestring(debug_ctx(),
549                               convert_timespec_to_time_t(
550                                       lck->changed_write_time)),
551                    (unsigned int)data.u.s.delete_token_size,
552                    lck->num_share_modes));
553
554         if ((lck->num_share_modes < 0) || (lck->num_share_modes > 1000000)) {
555                 DEBUG(0, ("invalid number of share modes: %d\n",
556                           lck->num_share_modes));
557                 smb_panic("parse_share_modes: invalid number of share modes");
558         }
559
560         lck->share_modes = NULL;
561         
562         if (lck->num_share_modes != 0) {
563
564                 if (dbuf.dsize < (sizeof(struct locking_data) +
565                                   (lck->num_share_modes *
566                                    sizeof(struct share_mode_entry)))) {
567                         smb_panic("parse_share_modes: buffer too short");
568                 }
569                                   
570                 lck->share_modes = (struct share_mode_entry *)
571                         TALLOC_MEMDUP(lck,
572                                       dbuf.dptr+sizeof(struct locking_data),
573                                       lck->num_share_modes *
574                                       sizeof(struct share_mode_entry));
575
576                 if (lck->share_modes == NULL) {
577                         smb_panic("parse_share_modes: talloc failed");
578                 }
579         }
580
581         /* Get any delete token. */
582         if (data.u.s.delete_token_size) {
583                 uint8 *p = dbuf.dptr + sizeof(struct locking_data) +
584                                 (lck->num_share_modes *
585                                 sizeof(struct share_mode_entry));
586
587                 if ((data.u.s.delete_token_size < sizeof(uid_t) + sizeof(gid_t)) ||
588                                 ((data.u.s.delete_token_size - sizeof(uid_t)) % sizeof(gid_t)) != 0) {
589                         DEBUG(0, ("parse_share_modes: invalid token size %d\n",
590                                 data.u.s.delete_token_size));
591                         smb_panic("parse_share_modes: invalid token size");
592                 }
593
594                 lck->delete_token = TALLOC_P(lck, UNIX_USER_TOKEN);
595                 if (!lck->delete_token) {
596                         smb_panic("parse_share_modes: talloc failed");
597                 }
598
599                 /* Copy out the uid and gid. */
600                 memcpy(&lck->delete_token->uid, p, sizeof(uid_t));
601                 p += sizeof(uid_t);
602                 memcpy(&lck->delete_token->gid, p, sizeof(gid_t));
603                 p += sizeof(gid_t);
604
605                 /* Any supplementary groups ? */
606                 lck->delete_token->ngroups = (data.u.s.delete_token_size > (sizeof(uid_t) + sizeof(gid_t))) ?
607                                         ((data.u.s.delete_token_size -
608                                                 (sizeof(uid_t) + sizeof(gid_t)))/sizeof(gid_t)) : 0;
609
610                 if (lck->delete_token->ngroups) {
611                         /* Make this a talloc child of lck->delete_token. */
612                         lck->delete_token->groups = TALLOC_ARRAY(lck->delete_token, gid_t,
613                                                         lck->delete_token->ngroups);
614                         if (!lck->delete_token) {
615                                 smb_panic("parse_share_modes: talloc failed");
616                         }
617
618                         for (i = 0; i < lck->delete_token->ngroups; i++) {
619                                 memcpy(&lck->delete_token->groups[i], p, sizeof(gid_t));
620                                 p += sizeof(gid_t);
621                         }
622                 }
623
624         } else {
625                 lck->delete_token = NULL;
626         }
627
628         /* Save off the associated service path and filename. */
629         lck->servicepath = (const char *)dbuf.dptr + sizeof(struct locking_data) +
630                 (lck->num_share_modes * sizeof(struct share_mode_entry)) +
631                 data.u.s.delete_token_size;
632
633         lck->base_name = (const char *)dbuf.dptr + sizeof(struct locking_data) +
634                 (lck->num_share_modes * sizeof(struct share_mode_entry)) +
635                 data.u.s.delete_token_size +
636                 strlen(lck->servicepath) + 1;
637
638         lck->stream_name = (const char *)dbuf.dptr + sizeof(struct locking_data) +
639                 (lck->num_share_modes * sizeof(struct share_mode_entry)) +
640                 data.u.s.delete_token_size +
641                 strlen(lck->servicepath) + 1 +
642                 strlen(lck->base_name) + 1;
643
644         /*
645          * Ensure that each entry has a real process attached.
646          */
647
648         for (i = 0; i < lck->num_share_modes; i++) {
649                 struct share_mode_entry *entry_p = &lck->share_modes[i];
650                 char *str = NULL;
651                 if (DEBUGLEVEL >= 10) {
652                         str = share_mode_str(NULL, i, entry_p);
653                 }
654                 DEBUG(10,("parse_share_modes: %s\n",
655                         str ? str : ""));
656                 if (!process_exists(entry_p->pid)) {
657                         DEBUG(10,("parse_share_modes: deleted %s\n",
658                                 str ? str : ""));
659                         entry_p->op_type = UNUSED_SHARE_MODE_ENTRY;
660                         lck->modified = True;
661                 }
662                 TALLOC_FREE(str);
663         }
664
665         return True;
666 }
667
668 static TDB_DATA unparse_share_modes(const struct share_mode_lock *lck)
669 {
670         TDB_DATA result;
671         int num_valid = 0;
672         int i;
673         struct locking_data *data;
674         ssize_t offset;
675         ssize_t sp_len, bn_len, sn_len;
676         uint32 delete_token_size;
677
678         result.dptr = NULL;
679         result.dsize = 0;
680
681         for (i=0; i<lck->num_share_modes; i++) {
682                 if (!is_unused_share_mode_entry(&lck->share_modes[i])) {
683                         num_valid += 1;
684                 }
685         }
686
687         if (num_valid == 0) {
688                 return result;
689         }
690
691         sp_len = strlen(lck->servicepath);
692         bn_len = strlen(lck->base_name);
693         sn_len = lck->stream_name != NULL ? strlen(lck->stream_name) : 0;
694
695         delete_token_size = (lck->delete_token ?
696                         (sizeof(uid_t) + sizeof(gid_t) + (lck->delete_token->ngroups*sizeof(gid_t))) : 0);
697
698         result.dsize = sizeof(*data) +
699                 lck->num_share_modes * sizeof(struct share_mode_entry) +
700                 delete_token_size +
701                 sp_len + 1 +
702                 bn_len + 1 +
703                 sn_len + 1;
704         result.dptr = TALLOC_ARRAY(lck, uint8, result.dsize);
705
706         if (result.dptr == NULL) {
707                 smb_panic("talloc failed");
708         }
709
710         data = (struct locking_data *)result.dptr;
711         ZERO_STRUCTP(data);
712         data->u.s.num_share_mode_entries = lck->num_share_modes;
713         data->u.s.delete_on_close = lck->delete_on_close;
714         data->u.s.old_write_time = lck->old_write_time;
715         data->u.s.changed_write_time = lck->changed_write_time;
716         data->u.s.delete_token_size = delete_token_size;
717
718         DEBUG(10,("unparse_share_modes: del: %d, owrt: %s cwrt: %s, tok: %u, "
719                   "num: %d\n", data->u.s.delete_on_close,
720                   timestring(debug_ctx(),
721                              convert_timespec_to_time_t(lck->old_write_time)),
722                   timestring(debug_ctx(),
723                              convert_timespec_to_time_t(
724                                      lck->changed_write_time)),
725                   (unsigned int)data->u.s.delete_token_size,
726                   data->u.s.num_share_mode_entries));
727
728         memcpy(result.dptr + sizeof(*data), lck->share_modes,
729                sizeof(struct share_mode_entry)*lck->num_share_modes);
730         offset = sizeof(*data) +
731                 sizeof(struct share_mode_entry)*lck->num_share_modes;
732
733         /* Store any delete on close token. */
734         if (lck->delete_token) {
735                 uint8 *p = result.dptr + offset;
736
737                 memcpy(p, &lck->delete_token->uid, sizeof(uid_t));
738                 p += sizeof(uid_t);
739
740                 memcpy(p, &lck->delete_token->gid, sizeof(gid_t));
741                 p += sizeof(gid_t);
742
743                 for (i = 0; i < lck->delete_token->ngroups; i++) {
744                         memcpy(p, &lck->delete_token->groups[i], sizeof(gid_t));
745                         p += sizeof(gid_t);
746                 }
747                 offset = p - result.dptr;
748         }
749
750         safe_strcpy((char *)result.dptr + offset, lck->servicepath,
751                     result.dsize - offset - 1);
752         offset += sp_len + 1;
753         safe_strcpy((char *)result.dptr + offset, lck->base_name,
754                     result.dsize - offset - 1);
755         offset += bn_len + 1;
756         safe_strcpy((char *)result.dptr + offset, lck->stream_name,
757                     result.dsize - offset - 1);
758
759         if (DEBUGLEVEL >= 10) {
760                 print_share_mode_table(data);
761         }
762
763         return result;
764 }
765
766 static int share_mode_lock_destructor(struct share_mode_lock *lck)
767 {
768         NTSTATUS status;
769         TDB_DATA data;
770
771         if (!lck->modified) {
772                 return 0;
773         }
774
775         data = unparse_share_modes(lck);
776
777         if (data.dptr == NULL) {
778                 if (!lck->fresh) {
779                         /* There has been an entry before, delete it */
780
781                         status = lck->record->delete_rec(lck->record);
782                         if (!NT_STATUS_IS_OK(status)) {
783                                 DEBUG(0, ("delete_rec returned %s\n",
784                                           nt_errstr(status)));
785                                 smb_panic("could not delete share entry");
786                         }
787                 }
788                 goto done;
789         }
790
791         status = lck->record->store(lck->record, data, TDB_REPLACE);
792         if (!NT_STATUS_IS_OK(status)) {
793                 DEBUG(0, ("store returned %s\n", nt_errstr(status)));
794                 smb_panic("could not store share mode entry");
795         }
796
797  done:
798
799         return 0;
800 }
801
802 static bool fill_share_mode_lock(struct share_mode_lock *lck,
803                                  struct file_id id,
804                                  const char *servicepath,
805                                  const struct smb_filename *smb_fname,
806                                  TDB_DATA share_mode_data,
807                                  const struct timespec *old_write_time)
808 {
809         /* Ensure we set every field here as the destructor must be
810            valid even if parse_share_modes fails. */
811
812         lck->servicepath = NULL;
813         lck->base_name = NULL;
814         lck->stream_name = NULL;
815         lck->id = id;
816         lck->num_share_modes = 0;
817         lck->share_modes = NULL;
818         lck->delete_token = NULL;
819         lck->delete_on_close = False;
820         ZERO_STRUCT(lck->old_write_time);
821         ZERO_STRUCT(lck->changed_write_time);
822         lck->fresh = False;
823         lck->modified = False;
824
825         lck->fresh = (share_mode_data.dptr == NULL);
826
827         if (lck->fresh) {
828                 bool has_stream;
829                 if (smb_fname == NULL || servicepath == NULL
830                     || old_write_time == NULL) {
831                         return False;
832                 }
833
834                 has_stream = smb_fname->stream_name != NULL;
835
836                 lck->base_name = talloc_strdup(lck, smb_fname->base_name);
837                 lck->stream_name = talloc_strdup(lck, smb_fname->stream_name);
838                 lck->servicepath = talloc_strdup(lck, servicepath);
839                 if (lck->base_name == NULL ||
840                     (has_stream && lck->stream_name == NULL) ||
841                     lck->servicepath == NULL) {
842                         DEBUG(0, ("talloc failed\n"));
843                         return False;
844                 }
845                 lck->old_write_time = *old_write_time;
846         } else {
847                 if (!parse_share_modes(share_mode_data, lck)) {
848                         DEBUG(0, ("Could not parse share modes\n"));
849                         return False;
850                 }
851         }
852
853         return True;
854 }
855
856 struct share_mode_lock *get_share_mode_lock(TALLOC_CTX *mem_ctx,
857                                             const struct file_id id,
858                                             const char *servicepath,
859                                             const struct smb_filename *smb_fname,
860                                             const struct timespec *old_write_time)
861 {
862         struct share_mode_lock *lck;
863         struct file_id tmp;
864         TDB_DATA key = locking_key(&id, &tmp);
865
866         if (!(lck = TALLOC_P(mem_ctx, struct share_mode_lock))) {
867                 DEBUG(0, ("talloc failed\n"));
868                 return NULL;
869         }
870
871         if (!(lck->record = lock_db->fetch_locked(lock_db, lck, key))) {
872                 DEBUG(3, ("Could not lock share entry\n"));
873                 TALLOC_FREE(lck);
874                 return NULL;
875         }
876
877         if (!fill_share_mode_lock(lck, id, servicepath, smb_fname,
878                                   lck->record->value, old_write_time)) {
879                 DEBUG(3, ("fill_share_mode_lock failed\n"));
880                 TALLOC_FREE(lck);
881                 return NULL;
882         }
883
884         talloc_set_destructor(lck, share_mode_lock_destructor);
885
886         return lck;
887 }
888
889 struct share_mode_lock *fetch_share_mode_unlocked(TALLOC_CTX *mem_ctx,
890                                                   const struct file_id id)
891 {
892         struct share_mode_lock *lck;
893         struct file_id tmp;
894         TDB_DATA key = locking_key(&id, &tmp);
895         TDB_DATA data;
896
897         if (!(lck = TALLOC_P(mem_ctx, struct share_mode_lock))) {
898                 DEBUG(0, ("talloc failed\n"));
899                 return NULL;
900         }
901
902         if (lock_db->fetch(lock_db, lck, key, &data) == -1) {
903                 DEBUG(3, ("Could not fetch share entry\n"));
904                 TALLOC_FREE(lck);
905                 return NULL;
906         }
907
908         if (!fill_share_mode_lock(lck, id, NULL, NULL, data, NULL)) {
909                 DEBUG(10, ("fetch_share_mode_unlocked: no share_mode record "
910                            "around (file not open)\n"));
911                 TALLOC_FREE(lck);
912                 return NULL;
913         }
914
915         return lck;
916 }
917
918 /*******************************************************************
919  Sets the service name and filename for rename.
920  At this point we emit "file renamed" messages to all
921  process id's that have this file open.
922  Based on an initial code idea from SATOH Fumiyasu <fumiya@samba.gr.jp>
923 ********************************************************************/
924
925 bool rename_share_filename(struct messaging_context *msg_ctx,
926                         struct share_mode_lock *lck,
927                         const char *servicepath,
928                         const struct smb_filename *smb_fname_dst)
929 {
930         size_t sp_len;
931         size_t bn_len;
932         size_t sn_len;
933         size_t msg_len;
934         char *frm = NULL;
935         int i;
936         bool strip_two_chars = false;
937         bool has_stream = smb_fname_dst->stream_name != NULL;
938
939         DEBUG(10, ("rename_share_filename: servicepath %s newname %s\n",
940                    servicepath, smb_fname_dst->base_name));
941
942         /*
943          * rename_internal_fsp() and rename_internals() add './' to
944          * head of newname if newname does not contain a '/'.
945          */
946         if (smb_fname_dst->base_name[0] &&
947             smb_fname_dst->base_name[1] &&
948             smb_fname_dst->base_name[0] == '.' &&
949             smb_fname_dst->base_name[1] == '/') {
950                 strip_two_chars = true;
951         }
952
953         lck->servicepath = talloc_strdup(lck, servicepath);
954         lck->base_name = talloc_strdup(lck, smb_fname_dst->base_name +
955                                        (strip_two_chars ? 2 : 0));
956         lck->stream_name = talloc_strdup(lck, smb_fname_dst->stream_name);
957         if (lck->base_name == NULL ||
958             (has_stream && lck->stream_name == NULL) ||
959             lck->servicepath == NULL) {
960                 DEBUG(0, ("rename_share_filename: talloc failed\n"));
961                 return False;
962         }
963         lck->modified = True;
964
965         sp_len = strlen(lck->servicepath);
966         bn_len = strlen(lck->base_name);
967         sn_len = has_stream ? strlen(lck->stream_name) : 0;
968
969         msg_len = MSG_FILE_RENAMED_MIN_SIZE + sp_len + 1 + bn_len + 1 +
970             sn_len + 1;
971
972         /* Set up the name changed message. */
973         frm = TALLOC_ARRAY(lck, char, msg_len);
974         if (!frm) {
975                 return False;
976         }
977
978         push_file_id_24(frm, &lck->id);
979
980         DEBUG(10,("rename_share_filename: msg_len = %u\n", (unsigned int)msg_len ));
981
982         safe_strcpy(&frm[24], lck->servicepath, sp_len);
983         safe_strcpy(&frm[24 + sp_len + 1], lck->base_name, bn_len);
984         safe_strcpy(&frm[24 + sp_len + 1 + bn_len + 1], lck->stream_name,
985                     sn_len);
986
987         /* Send the messages. */
988         for (i=0; i<lck->num_share_modes; i++) {
989                 struct share_mode_entry *se = &lck->share_modes[i];
990                 if (!is_valid_share_mode_entry(se)) {
991                         continue;
992                 }
993                 /* But not to ourselves... */
994                 if (procid_is_me(&se->pid)) {
995                         continue;
996                 }
997
998                 DEBUG(10,("rename_share_filename: sending rename message to "
999                           "pid %s file_id %s sharepath %s base_name %s "
1000                           "stream_name %s\n",
1001                           procid_str_static(&se->pid),
1002                           file_id_string_tos(&lck->id),
1003                           lck->servicepath, lck->base_name,
1004                         has_stream ? lck->stream_name : ""));
1005
1006                 messaging_send_buf(msg_ctx, se->pid, MSG_SMB_FILE_RENAME,
1007                                    (uint8 *)frm, msg_len);
1008         }
1009
1010         return True;
1011 }
1012
1013 void get_file_infos(struct file_id id,
1014                     bool *delete_on_close,
1015                     struct timespec *write_time)
1016 {
1017         struct share_mode_lock *lck;
1018
1019         if (delete_on_close) {
1020                 *delete_on_close = false;
1021         }
1022
1023         if (write_time) {
1024                 ZERO_STRUCTP(write_time);
1025         }
1026
1027         if (!(lck = fetch_share_mode_unlocked(talloc_tos(), id))) {
1028                 return;
1029         }
1030
1031         if (delete_on_close) {
1032                 *delete_on_close = lck->delete_on_close;
1033         }
1034
1035         if (write_time) {
1036                 struct timespec wt;
1037
1038                 wt = lck->changed_write_time;
1039                 if (null_timespec(wt)) {
1040                         wt = lck->old_write_time;
1041                 }
1042
1043                 *write_time = wt;
1044         }
1045
1046         TALLOC_FREE(lck);
1047 }
1048
1049 bool is_valid_share_mode_entry(const struct share_mode_entry *e)
1050 {
1051         int num_props = 0;
1052
1053         if (e->op_type == UNUSED_SHARE_MODE_ENTRY) {
1054                 /* cope with dead entries from the process not
1055                    existing. These should not be considered valid,
1056                    otherwise we end up doing zero timeout sharing
1057                    violation */
1058                 return False;
1059         }
1060
1061         num_props += ((e->op_type == NO_OPLOCK) ? 1 : 0);
1062         num_props += (EXCLUSIVE_OPLOCK_TYPE(e->op_type) ? 1 : 0);
1063         num_props += (LEVEL_II_OPLOCK_TYPE(e->op_type) ? 1 : 0);
1064
1065         SMB_ASSERT(num_props <= 1);
1066         return (num_props != 0);
1067 }
1068
1069 bool is_deferred_open_entry(const struct share_mode_entry *e)
1070 {
1071         return (e->op_type == DEFERRED_OPEN_ENTRY);
1072 }
1073
1074 bool is_unused_share_mode_entry(const struct share_mode_entry *e)
1075 {
1076         return (e->op_type == UNUSED_SHARE_MODE_ENTRY);
1077 }
1078
1079 /*******************************************************************
1080  Fill a share mode entry.
1081 ********************************************************************/
1082
1083 static void fill_share_mode_entry(struct share_mode_entry *e,
1084                                   files_struct *fsp,
1085                                   uid_t uid, uint16 mid, uint16 op_type)
1086 {
1087         ZERO_STRUCTP(e);
1088         e->pid = procid_self();
1089         e->share_access = fsp->share_access;
1090         e->private_options = fsp->fh->private_options;
1091         e->access_mask = fsp->access_mask;
1092         e->op_mid = mid;
1093         e->op_type = op_type;
1094         e->time.tv_sec = fsp->open_time.tv_sec;
1095         e->time.tv_usec = fsp->open_time.tv_usec;
1096         e->id = fsp->file_id;
1097         e->share_file_id = fsp->fh->gen_id;
1098         e->uid = (uint32)uid;
1099         e->flags = fsp->posix_open ? SHARE_MODE_FLAG_POSIX_OPEN : 0;
1100 }
1101
1102 static void fill_deferred_open_entry(struct share_mode_entry *e,
1103                                      const struct timeval request_time,
1104                                      struct file_id id, uint16 mid)
1105 {
1106         ZERO_STRUCTP(e);
1107         e->pid = procid_self();
1108         e->op_mid = mid;
1109         e->op_type = DEFERRED_OPEN_ENTRY;
1110         e->time.tv_sec = request_time.tv_sec;
1111         e->time.tv_usec = request_time.tv_usec;
1112         e->id = id;
1113         e->uid = (uint32)-1;
1114         e->flags = 0;
1115 }
1116
1117 static void add_share_mode_entry(struct share_mode_lock *lck,
1118                                  const struct share_mode_entry *entry)
1119 {
1120         int i;
1121
1122         for (i=0; i<lck->num_share_modes; i++) {
1123                 struct share_mode_entry *e = &lck->share_modes[i];
1124                 if (is_unused_share_mode_entry(e)) {
1125                         *e = *entry;
1126                         break;
1127                 }
1128         }
1129
1130         if (i == lck->num_share_modes) {
1131                 /* No unused entry found */
1132                 ADD_TO_ARRAY(lck, struct share_mode_entry, *entry,
1133                              &lck->share_modes, &lck->num_share_modes);
1134         }
1135         lck->modified = True;
1136 }
1137
1138 void set_share_mode(struct share_mode_lock *lck, files_struct *fsp,
1139                     uid_t uid, uint16 mid, uint16 op_type)
1140 {
1141         struct share_mode_entry entry;
1142         fill_share_mode_entry(&entry, fsp, uid, mid, op_type);
1143         add_share_mode_entry(lck, &entry);
1144 }
1145
1146 void add_deferred_open(struct share_mode_lock *lck, uint16 mid,
1147                        struct timeval request_time,
1148                        struct file_id id)
1149 {
1150         struct share_mode_entry entry;
1151         fill_deferred_open_entry(&entry, request_time, id, mid);
1152         add_share_mode_entry(lck, &entry);
1153 }
1154
1155 /*******************************************************************
1156  Check if two share mode entries are identical, ignoring oplock 
1157  and mid info and desired_access. (Removed paranoia test - it's
1158  not automatically a logic error if they are identical. JRA.)
1159 ********************************************************************/
1160
1161 static bool share_modes_identical(struct share_mode_entry *e1,
1162                                   struct share_mode_entry *e2)
1163 {
1164         /* We used to check for e1->share_access == e2->share_access here
1165            as well as the other fields but 2 different DOS or FCB opens
1166            sharing the same share mode entry may validly differ in
1167            fsp->share_access field. */
1168
1169         return (procid_equal(&e1->pid, &e2->pid) &&
1170                 file_id_equal(&e1->id, &e2->id) &&
1171                 e1->share_file_id == e2->share_file_id );
1172 }
1173
1174 static bool deferred_open_identical(struct share_mode_entry *e1,
1175                                     struct share_mode_entry *e2)
1176 {
1177         return (procid_equal(&e1->pid, &e2->pid) &&
1178                 (e1->op_mid == e2->op_mid) &&
1179                 file_id_equal(&e1->id, &e2->id));
1180 }
1181
1182 static struct share_mode_entry *find_share_mode_entry(struct share_mode_lock *lck,
1183                                                       struct share_mode_entry *entry)
1184 {
1185         int i;
1186
1187         for (i=0; i<lck->num_share_modes; i++) {
1188                 struct share_mode_entry *e = &lck->share_modes[i];
1189                 if (is_valid_share_mode_entry(entry) &&
1190                     is_valid_share_mode_entry(e) &&
1191                     share_modes_identical(e, entry)) {
1192                         return e;
1193                 }
1194                 if (is_deferred_open_entry(entry) &&
1195                     is_deferred_open_entry(e) &&
1196                     deferred_open_identical(e, entry)) {
1197                         return e;
1198                 }
1199         }
1200         return NULL;
1201 }
1202
1203 /*******************************************************************
1204  Del the share mode of a file for this process. Return the number of
1205  entries left.
1206 ********************************************************************/
1207
1208 bool del_share_mode(struct share_mode_lock *lck, files_struct *fsp)
1209 {
1210         struct share_mode_entry entry, *e;
1211
1212         /* Don't care about the pid owner being correct here - just a search. */
1213         fill_share_mode_entry(&entry, fsp, (uid_t)-1, 0, NO_OPLOCK);
1214
1215         e = find_share_mode_entry(lck, &entry);
1216         if (e == NULL) {
1217                 return False;
1218         }
1219
1220         e->op_type = UNUSED_SHARE_MODE_ENTRY;
1221         lck->modified = True;
1222         return True;
1223 }
1224
1225 void del_deferred_open_entry(struct share_mode_lock *lck, uint16 mid)
1226 {
1227         struct share_mode_entry entry, *e;
1228
1229         fill_deferred_open_entry(&entry, timeval_zero(),
1230                                  lck->id, mid);
1231
1232         e = find_share_mode_entry(lck, &entry);
1233         if (e == NULL) {
1234                 return;
1235         }
1236
1237         e->op_type = UNUSED_SHARE_MODE_ENTRY;
1238         lck->modified = True;
1239 }
1240
1241 /*******************************************************************
1242  Remove an oplock mid and mode entry from a share mode.
1243 ********************************************************************/
1244
1245 bool remove_share_oplock(struct share_mode_lock *lck, files_struct *fsp)
1246 {
1247         struct share_mode_entry entry, *e;
1248
1249         /* Don't care about the pid owner being correct here - just a search. */
1250         fill_share_mode_entry(&entry, fsp, (uid_t)-1, 0, NO_OPLOCK);
1251
1252         e = find_share_mode_entry(lck, &entry);
1253         if (e == NULL) {
1254                 return False;
1255         }
1256
1257         e->op_mid = 0;
1258         if (EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type)) {
1259                 /*
1260                  * Going from exclusive or batch,
1261                  * we always go through FAKE_LEVEL_II
1262                  * first.
1263                  */
1264                 e->op_type = FAKE_LEVEL_II_OPLOCK;
1265         } else {
1266                 e->op_type = NO_OPLOCK;
1267         }
1268         lck->modified = True;
1269         return True;
1270 }
1271
1272 /*******************************************************************
1273  Downgrade a oplock type from exclusive to level II.
1274 ********************************************************************/
1275
1276 bool downgrade_share_oplock(struct share_mode_lock *lck, files_struct *fsp)
1277 {
1278         struct share_mode_entry entry, *e;
1279
1280         /* Don't care about the pid owner being correct here - just a search. */
1281         fill_share_mode_entry(&entry, fsp, (uid_t)-1, 0, NO_OPLOCK);
1282
1283         e = find_share_mode_entry(lck, &entry);
1284         if (e == NULL) {
1285                 return False;
1286         }
1287
1288         e->op_type = LEVEL_II_OPLOCK;
1289         lck->modified = True;
1290         return True;
1291 }
1292
1293 /****************************************************************************
1294  Deal with the internal needs of setting the delete on close flag. Note that
1295  as the tdb locking is recursive, it is safe to call this from within 
1296  open_file_ntcreate. JRA.
1297 ****************************************************************************/
1298
1299 NTSTATUS can_set_delete_on_close(files_struct *fsp, bool delete_on_close,
1300                                  uint32 dosmode)
1301 {
1302         if (!delete_on_close) {
1303                 return NT_STATUS_OK;
1304         }
1305
1306         /*
1307          * Only allow delete on close for writable files.
1308          */
1309
1310         if ((dosmode & aRONLY) &&
1311             !lp_delete_readonly(SNUM(fsp->conn))) {
1312                 DEBUG(10,("can_set_delete_on_close: file %s delete on close "
1313                           "flag set but file attribute is readonly.\n",
1314                           fsp->fsp_name ));
1315                 return NT_STATUS_CANNOT_DELETE;
1316         }
1317
1318         /*
1319          * Only allow delete on close for writable shares.
1320          */
1321
1322         if (!CAN_WRITE(fsp->conn)) {
1323                 DEBUG(10,("can_set_delete_on_close: file %s delete on "
1324                           "close flag set but write access denied on share.\n",
1325                           fsp->fsp_name ));
1326                 return NT_STATUS_ACCESS_DENIED;
1327         }
1328
1329         /*
1330          * Only allow delete on close for files/directories opened with delete
1331          * intent.
1332          */
1333
1334         if (!(fsp->access_mask & DELETE_ACCESS)) {
1335                 DEBUG(10,("can_set_delete_on_close: file %s delete on "
1336                           "close flag set but delete access denied.\n",
1337                           fsp->fsp_name ));
1338                 return NT_STATUS_ACCESS_DENIED;
1339         }
1340
1341         /* Don't allow delete on close for non-empty directories. */
1342         if (fsp->is_directory) {
1343                 return can_delete_directory(fsp->conn, fsp->fsp_name);
1344         }
1345
1346         return NT_STATUS_OK;
1347 }
1348
1349 /*************************************************************************
1350  Return a talloced copy of a UNIX_USER_TOKEN. NULL on fail.
1351  (Should this be in locking.c.... ?).
1352 *************************************************************************/
1353
1354 static UNIX_USER_TOKEN *copy_unix_token(TALLOC_CTX *ctx, const UNIX_USER_TOKEN *tok)
1355 {
1356         UNIX_USER_TOKEN *cpy;
1357
1358         if (tok == NULL) {
1359                 return NULL;
1360         }
1361
1362         cpy = TALLOC_P(ctx, UNIX_USER_TOKEN);
1363         if (!cpy) {
1364                 return NULL;
1365         }
1366
1367         cpy->uid = tok->uid;
1368         cpy->gid = tok->gid;
1369         cpy->ngroups = tok->ngroups;
1370         if (tok->ngroups) {
1371                 /* Make this a talloc child of cpy. */
1372                 cpy->groups = TALLOC_ARRAY(cpy, gid_t, tok->ngroups);
1373                 if (!cpy->groups) {
1374                         return NULL;
1375                 }
1376                 memcpy(cpy->groups, tok->groups, tok->ngroups * sizeof(gid_t));
1377         }
1378         return cpy;
1379 }
1380
1381 /****************************************************************************
1382  Replace the delete on close token.
1383 ****************************************************************************/
1384
1385 void set_delete_on_close_token(struct share_mode_lock *lck, const UNIX_USER_TOKEN *tok)
1386 {
1387         TALLOC_FREE(lck->delete_token); /* Also deletes groups... */
1388
1389         /* Copy the new token (can be NULL). */
1390         lck->delete_token = copy_unix_token(lck, tok);
1391         lck->modified = True;
1392 }
1393
1394 /****************************************************************************
1395  Sets the delete on close flag over all share modes on this file.
1396  Modify the share mode entry for all files open
1397  on this device and inode to tell other smbds we have
1398  changed the delete on close flag. This will be noticed
1399  in the close code, the last closer will delete the file
1400  if flag is set.
1401  This makes a copy of any UNIX_USER_TOKEN into the
1402  lck entry. This function is used when the lock is already granted.
1403 ****************************************************************************/
1404
1405 void set_delete_on_close_lck(struct share_mode_lock *lck, bool delete_on_close, const UNIX_USER_TOKEN *tok)
1406 {
1407         if (lck->delete_on_close != delete_on_close) {
1408                 set_delete_on_close_token(lck, tok);
1409                 lck->delete_on_close = delete_on_close;
1410                 if (delete_on_close) {
1411                         SMB_ASSERT(lck->delete_token != NULL);
1412                 }
1413                 lck->modified = True;
1414         }
1415 }
1416
1417 bool set_delete_on_close(files_struct *fsp, bool delete_on_close, const UNIX_USER_TOKEN *tok)
1418 {
1419         UNIX_USER_TOKEN *tok_copy = NULL;
1420         struct share_mode_lock *lck;
1421         
1422         DEBUG(10,("set_delete_on_close: %s delete on close flag for "
1423                   "fnum = %d, file %s\n",
1424                   delete_on_close ? "Adding" : "Removing", fsp->fnum,
1425                   fsp->fsp_name ));
1426
1427         lck = get_share_mode_lock(talloc_tos(), fsp->file_id, NULL, NULL,
1428                                   NULL);
1429         if (lck == NULL) {
1430                 return False;
1431         }
1432
1433         if (fsp->conn->admin_user) {
1434                 tok_copy = copy_unix_token(lck, tok);
1435                 if (tok_copy == NULL) {
1436                         TALLOC_FREE(lck);
1437                         return false;
1438                 }
1439                 tok_copy->uid = (uid_t)0;
1440                 tok = tok_copy;
1441         }
1442
1443         set_delete_on_close_lck(lck, delete_on_close, tok);
1444
1445         if (fsp->is_directory) {
1446                 send_stat_cache_delete_message(fsp->fsp_name);
1447         }
1448
1449         TALLOC_FREE(lck);
1450         return True;
1451 }
1452
1453 bool set_sticky_write_time(struct file_id fileid, struct timespec write_time)
1454 {
1455         struct share_mode_lock *lck;
1456
1457         DEBUG(5,("set_sticky_write_time: %s id=%s\n",
1458                  timestring(debug_ctx(),
1459                             convert_timespec_to_time_t(write_time)),
1460                  file_id_string_tos(&fileid)));
1461
1462         lck = get_share_mode_lock(NULL, fileid, NULL, NULL, NULL);
1463         if (lck == NULL) {
1464                 return False;
1465         }
1466
1467         if (timespec_compare(&lck->changed_write_time, &write_time) != 0) {
1468                 lck->modified = True;
1469                 lck->changed_write_time = write_time;
1470         }
1471
1472         TALLOC_FREE(lck);
1473         return True;
1474 }
1475
1476 bool set_write_time(struct file_id fileid, struct timespec write_time)
1477 {
1478         struct share_mode_lock *lck;
1479
1480         DEBUG(5,("set_write_time: %s id=%s\n",
1481                  timestring(debug_ctx(),
1482                             convert_timespec_to_time_t(write_time)),
1483                  file_id_string_tos(&fileid)));
1484
1485         lck = get_share_mode_lock(NULL, fileid, NULL, NULL, NULL);
1486         if (lck == NULL) {
1487                 return False;
1488         }
1489
1490         if (timespec_compare(&lck->old_write_time, &write_time) != 0) {
1491                 lck->modified = True;
1492                 lck->old_write_time = write_time;
1493         }
1494
1495         TALLOC_FREE(lck);
1496         return True;
1497 }
1498
1499
1500 struct forall_state {
1501         void (*fn)(const struct share_mode_entry *entry,
1502                    const char *sharepath,
1503                    const char *fname,
1504                    void *private_data);
1505         void *private_data;
1506 };
1507
1508 static int traverse_fn(struct db_record *rec, void *_state)
1509 {
1510         struct forall_state *state = (struct forall_state *)_state;
1511         struct locking_data *data;
1512         struct share_mode_entry *shares;
1513         const char *sharepath;
1514         const char *fname;
1515         int i;
1516
1517         /* Ensure this is a locking_key record. */
1518         if (rec->key.dsize != sizeof(struct file_id))
1519                 return 0;
1520
1521         data = (struct locking_data *)rec->value.dptr;
1522         shares = (struct share_mode_entry *)(rec->value.dptr + sizeof(*data));
1523         sharepath = (const char *)rec->value.dptr + sizeof(*data) +
1524                 data->u.s.num_share_mode_entries*sizeof(*shares) +
1525                 data->u.s.delete_token_size;
1526         fname = (const char *)rec->value.dptr + sizeof(*data) +
1527                 data->u.s.num_share_mode_entries*sizeof(*shares) +
1528                 data->u.s.delete_token_size +
1529                 strlen(sharepath) + 1;
1530
1531         for (i=0;i<data->u.s.num_share_mode_entries;i++) {
1532                 state->fn(&shares[i], sharepath, fname,
1533                           state->private_data);
1534         }
1535         return 0;
1536 }
1537
1538 /*******************************************************************
1539  Call the specified function on each entry under management by the
1540  share mode system.
1541 ********************************************************************/
1542
1543 int share_mode_forall(void (*fn)(const struct share_mode_entry *, const char *,
1544                                  const char *, void *),
1545                       void *private_data)
1546 {
1547         struct forall_state state;
1548
1549         if (lock_db == NULL)
1550                 return 0;
1551
1552         state.fn = fn;
1553         state.private_data = private_data;
1554
1555         return lock_db->traverse_read(lock_db, traverse_fn, (void *)&state);
1556 }