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