r13194: Don't do extra memcpy's unless we're asked to.
[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-2000
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 2 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, write to the Free Software
20    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21
22    Revision History:
23
24    12 aug 96: Erik.Devriendt@te6.siemens.be
25    added support for shared memory implementation of share mode locking
26
27    May 1997. Jeremy Allison (jallison@whistle.com). Modified share mode
28    locking to deal with multiple share modes per open file.
29
30    September 1997. Jeremy Allison (jallison@whistle.com). Added oplock
31    support.
32
33    rewrtten completely to use new tdb code. Tridge, Dec '99
34
35    Added POSIX locking support. Jeremy Allison (jeremy@valinux.com), Apr. 2000.
36 */
37
38 #include "includes.h"
39 uint16 global_smbpid;
40
41 #undef DBGC_CLASS
42 #define DBGC_CLASS DBGC_LOCKING
43
44 /* the locking database handle */
45 static TDB_CONTEXT *tdb;
46
47 struct locking_data {
48         union {
49                 struct {
50                         int num_share_mode_entries;
51                         BOOL delete_on_close;
52                 } s;
53                 struct share_mode_entry dummy; /* Needed for alignment. */
54         } u;
55         /* the following two entries are implicit
56            struct share_mode_entry modes[num_share_mode_entries];
57            char file_name[];
58         */
59 };
60
61 /****************************************************************************
62  Debugging aid :-).
63 ****************************************************************************/
64
65 static const char *lock_type_name(enum brl_type lock_type)
66 {
67         return (lock_type == READ_LOCK) ? "READ" : "WRITE";
68 }
69
70 /****************************************************************************
71  Utility function called to see if a file region is locked.
72 ****************************************************************************/
73
74 BOOL is_locked(files_struct *fsp,connection_struct *conn,
75                SMB_BIG_UINT count,SMB_BIG_UINT offset, 
76                enum brl_type lock_type)
77 {
78         int snum = SNUM(conn);
79         int strict_locking = lp_strict_locking(snum);
80         BOOL ret;
81         
82         if (count == 0)
83                 return(False);
84
85         if (!lp_locking(snum) || !strict_locking)
86                 return(False);
87
88         if (strict_locking == Auto) {
89                 if  (EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type) && (lock_type == READ_LOCK || lock_type == WRITE_LOCK)) {
90                         DEBUG(10,("is_locked: optimisation - exclusive oplock on file %s\n", fsp->fsp_name ));
91                         ret = 0;
92                 } else if ((fsp->oplock_type == LEVEL_II_OPLOCK) &&
93                            (lock_type == READ_LOCK)) {
94                         DEBUG(10,("is_locked: optimisation - level II oplock on file %s\n", fsp->fsp_name ));
95                         ret = 0;
96                 } else {
97                         ret = !brl_locktest(fsp->dev, fsp->inode, fsp->fnum,
98                                      global_smbpid, procid_self(), conn->cnum, 
99                                      offset, count, lock_type);
100                 }
101         } else {
102                 ret = !brl_locktest(fsp->dev, fsp->inode, fsp->fnum,
103                                 global_smbpid, procid_self(), conn->cnum,
104                                 offset, count, lock_type);
105         }
106
107         DEBUG(10,("is_locked: brl start=%.0f len=%.0f %s for file %s\n",
108                         (double)offset, (double)count, ret ? "locked" : "unlocked",
109                         fsp->fsp_name ));
110
111         /*
112          * There is no lock held by an SMB daemon, check to
113          * see if there is a POSIX lock from a UNIX or NFS process.
114          */
115
116         if(!ret && lp_posix_locking(snum)) {
117                 ret = is_posix_locked(fsp, offset, count, lock_type);
118
119                 DEBUG(10,("is_locked: posix start=%.0f len=%.0f %s for file %s\n",
120                                 (double)offset, (double)count, ret ? "locked" : "unlocked",
121                                 fsp->fsp_name ));
122         }
123
124         return ret;
125 }
126
127 /****************************************************************************
128  Utility function called by locking requests.
129 ****************************************************************************/
130
131 static NTSTATUS do_lock(files_struct *fsp,connection_struct *conn, uint16 lock_pid,
132                  SMB_BIG_UINT count,SMB_BIG_UINT offset,enum brl_type lock_type, BOOL *my_lock_ctx)
133 {
134         NTSTATUS status = NT_STATUS_LOCK_NOT_GRANTED;
135
136         if (!lp_locking(SNUM(conn)))
137                 return NT_STATUS_OK;
138
139         /* NOTE! 0 byte long ranges ARE allowed and should be stored  */
140
141         DEBUG(10,("do_lock: lock type %s start=%.0f len=%.0f requested for file %s\n",
142                   lock_type_name(lock_type), (double)offset, (double)count, fsp->fsp_name ));
143
144         if (OPEN_FSP(fsp) && fsp->can_lock && (fsp->conn == conn)) {
145                 status = brl_lock(fsp->dev, fsp->inode, fsp->fnum,
146                                   lock_pid, procid_self(), conn->cnum, 
147                                   offset, count, 
148                                   lock_type, my_lock_ctx);
149
150                 if (NT_STATUS_IS_OK(status) && lp_posix_locking(SNUM(conn))) {
151
152                         /*
153                          * Try and get a POSIX lock on this range.
154                          * Note that this is ok if it is a read lock
155                          * overlapping on a different fd. JRA.
156                          */
157
158                         if (!set_posix_lock(fsp, offset, count, lock_type)) {
159                                 if (errno == EACCES || errno == EAGAIN)
160                                         status = NT_STATUS_FILE_LOCK_CONFLICT;
161                                 else
162                                         status = map_nt_error_from_unix(errno);
163
164                                 /*
165                                  * We failed to map - we must now remove the brl
166                                  * lock entry.
167                                  */
168                                 (void)brl_unlock(fsp->dev, fsp->inode, fsp->fnum,
169                                                                 lock_pid, procid_self(), conn->cnum, 
170                                                                 offset, count, False,
171                                                                 NULL, NULL);
172                         }
173                 }
174         }
175
176         return status;
177 }
178
179 /****************************************************************************
180  Utility function called by locking requests. This is *DISGUSTING*. It also
181  appears to be "What Windows Does" (tm). Andrew, ever wonder why Windows 2000
182  is so slow on the locking tests...... ? This is the reason. Much though I hate
183  it, we need this. JRA.
184 ****************************************************************************/
185
186 NTSTATUS do_lock_spin(files_struct *fsp,connection_struct *conn, uint16 lock_pid,
187                  SMB_BIG_UINT count,SMB_BIG_UINT offset,enum brl_type lock_type, BOOL *my_lock_ctx)
188 {
189         int j, maxj = lp_lock_spin_count();
190         int sleeptime = lp_lock_sleep_time();
191         NTSTATUS status, ret;
192
193         if (maxj <= 0)
194                 maxj = 1;
195
196         ret = NT_STATUS_OK; /* to keep dumb compilers happy */
197
198         for (j = 0; j < maxj; j++) {
199                 status = do_lock(fsp, conn, lock_pid, count, offset, lock_type, my_lock_ctx);
200                 if (!NT_STATUS_EQUAL(status, NT_STATUS_LOCK_NOT_GRANTED) &&
201                     !NT_STATUS_EQUAL(status, NT_STATUS_FILE_LOCK_CONFLICT)) {
202                         return status;
203                 }
204                 /* if we do fail then return the first error code we got */
205                 if (j == 0) {
206                         ret = status;
207                         /* Don't spin if we blocked ourselves. */
208                         if (*my_lock_ctx)
209                                 return ret;
210                 }
211                 if (sleeptime)
212                         sys_usleep(sleeptime);
213         }
214         return ret;
215 }
216
217 /* Struct passed to brl_unlock. */
218 struct posix_unlock_data_struct {
219         files_struct *fsp;
220         SMB_BIG_UINT offset;
221         SMB_BIG_UINT count;
222 };
223
224 /****************************************************************************
225  Function passed to brl_unlock to allow POSIX unlock to be done first.
226 ****************************************************************************/
227
228 static void posix_unlock(void *pre_data)
229 {
230         struct posix_unlock_data_struct *pdata = (struct posix_unlock_data_struct *)pre_data;
231
232         if (lp_posix_locking(SNUM(pdata->fsp->conn)))
233                 release_posix_lock(pdata->fsp, pdata->offset, pdata->count);
234 }
235
236 /****************************************************************************
237  Utility function called by unlocking requests.
238 ****************************************************************************/
239
240 NTSTATUS do_unlock(files_struct *fsp,connection_struct *conn, uint16 lock_pid,
241                    SMB_BIG_UINT count,SMB_BIG_UINT offset)
242 {
243         BOOL ok = False;
244         struct posix_unlock_data_struct posix_data;
245         
246         if (!lp_locking(SNUM(conn)))
247                 return NT_STATUS_OK;
248         
249         if (!OPEN_FSP(fsp) || !fsp->can_lock || (fsp->conn != conn)) {
250                 return NT_STATUS_INVALID_HANDLE;
251         }
252         
253         DEBUG(10,("do_unlock: unlock start=%.0f len=%.0f requested for file %s\n",
254                   (double)offset, (double)count, fsp->fsp_name ));
255
256         /*
257          * Remove the existing lock record from the tdb lockdb
258          * before looking at POSIX locks. If this record doesn't
259          * match then don't bother looking to remove POSIX locks.
260          */
261
262         posix_data.fsp = fsp;
263         posix_data.offset = offset;
264         posix_data.count = count;
265
266         ok = brl_unlock(fsp->dev, fsp->inode, fsp->fnum,
267                         lock_pid, procid_self(), conn->cnum, offset, count,
268                         False, posix_unlock, (void *)&posix_data);
269    
270         if (!ok) {
271                 DEBUG(10,("do_unlock: returning ERRlock.\n" ));
272                 return NT_STATUS_RANGE_NOT_LOCKED;
273         }
274         return NT_STATUS_OK;
275 }
276
277 /****************************************************************************
278  Remove any locks on this fd. Called from file_close().
279 ****************************************************************************/
280
281 void locking_close_file(files_struct *fsp)
282 {
283         struct process_id pid = procid_self();
284
285         if (!lp_locking(SNUM(fsp->conn)))
286                 return;
287
288         /*
289          * Just release all the brl locks, no need to release individually.
290          */
291
292         brl_close(fsp->dev, fsp->inode, pid, fsp->conn->cnum, fsp->fnum);
293
294         if(lp_posix_locking(SNUM(fsp->conn))) {
295
296                 /* 
297                  * Release all the POSIX locks.
298                  */
299                 posix_locking_close_file(fsp);
300
301         }
302 }
303
304 /****************************************************************************
305  Initialise the locking functions.
306 ****************************************************************************/
307
308 static int open_read_only;
309
310 BOOL locking_init(int read_only)
311 {
312         brl_init(read_only);
313
314         if (tdb)
315                 return True;
316
317         tdb = tdb_open_log(lock_path("locking.tdb"), 
318                         SMB_OPEN_DATABASE_TDB_HASH_SIZE, TDB_DEFAULT|(read_only?0x0:TDB_CLEAR_IF_FIRST), 
319                         read_only?O_RDONLY:O_RDWR|O_CREAT,
320                         0644);
321
322         if (!tdb) {
323                 DEBUG(0,("ERROR: Failed to initialise locking database\n"));
324                 return False;
325         }
326
327         if (!posix_locking_init(read_only))
328                 return False;
329
330         open_read_only = read_only;
331
332         return True;
333 }
334
335 /*******************************************************************
336  Deinitialize the share_mode management.
337 ******************************************************************/
338
339 BOOL locking_end(void)
340 {
341         BOOL ret = True;
342
343         brl_shutdown(open_read_only);
344         if (tdb) {
345                 if (tdb_close(tdb) != 0)
346                         ret = False;
347         }
348
349         return ret;
350 }
351
352 /*******************************************************************
353  Form a static locking key for a dev/inode pair.
354 ******************************************************************/
355
356 /* key and data records in the tdb locking database */
357 struct locking_key {
358         SMB_DEV_T dev;
359         SMB_INO_T ino;
360 };
361
362 /*******************************************************************
363  Form a static locking key for a dev/inode pair.
364 ******************************************************************/
365
366 static TDB_DATA locking_key(SMB_DEV_T dev, SMB_INO_T inode)
367 {
368         static struct locking_key key;
369         TDB_DATA kbuf;
370
371         memset(&key, '\0', sizeof(key));
372         key.dev = dev;
373         key.ino = inode;
374         kbuf.dptr = (char *)&key;
375         kbuf.dsize = sizeof(key);
376         return kbuf;
377 }
378
379 /*******************************************************************
380  Print out a share mode.
381 ********************************************************************/
382
383 char *share_mode_str(int num, struct share_mode_entry *e)
384 {
385         static pstring share_str;
386
387         slprintf(share_str, sizeof(share_str)-1, "share_mode_entry[%d]: %s "
388                  "pid = %s, share_access = 0x%x, private_options = 0x%x, "
389                  "access_mask = 0x%x, mid = 0x%x, type= 0x%x, file_id = %lu, "
390                  "dev = 0x%x, inode = %.0f",
391                  num,
392                  e->op_type == UNUSED_SHARE_MODE_ENTRY ? "UNUSED" : "",
393                  procid_str_static(&e->pid),
394                  e->share_access, e->private_options,
395                  e->access_mask, e->op_mid, e->op_type, e->share_file_id,
396                  (unsigned int)e->dev, (double)e->inode );
397
398         return share_str;
399 }
400
401 /*******************************************************************
402  Print out a share mode table.
403 ********************************************************************/
404
405 static void print_share_mode_table(struct locking_data *data)
406 {
407         int num_share_modes = data->u.s.num_share_mode_entries;
408         struct share_mode_entry *shares =
409                 (struct share_mode_entry *)(data + 1);
410         int i;
411
412         for (i = 0; i < num_share_modes; i++) {
413                 struct share_mode_entry entry;
414
415                 memcpy(&entry, &shares[i], sizeof(struct share_mode_entry));
416                 DEBUG(10,("print_share_mode_table: %s\n",
417                           share_mode_str(i, &entry)));
418         }
419 }
420
421 /*******************************************************************
422  Get all share mode entries for a dev/inode pair.
423 ********************************************************************/
424
425 static BOOL parse_share_modes(TDB_DATA dbuf, struct share_mode_lock *lck)
426 {
427         struct locking_data *data;
428         int i;
429
430         if (dbuf.dsize < sizeof(struct locking_data)) {
431                 DEBUG(0, ("parse_share_modes: buffer too short\n"));
432                 return False;
433         }
434
435         data = (struct locking_data *)dbuf.dptr;
436
437         lck->delete_on_close = data->u.s.delete_on_close;
438         lck->num_share_modes = data->u.s.num_share_mode_entries;
439
440         DEBUG(10, ("parse_share_modes: delete_on_close: %d, "
441                    "num_share_modes: %d\n", lck->delete_on_close,
442                    lck->num_share_modes));
443
444         if ((lck->num_share_modes < 0) || (lck->num_share_modes > 1000000)) {
445                 DEBUG(0, ("invalid number of share modes: %d\n",
446                           lck->num_share_modes));
447                 return False;
448         }
449
450         lck->share_modes = NULL;
451
452         if (lck->num_share_modes != 0) {
453
454                 if (dbuf.dsize < (sizeof(struct locking_data) +
455                                   (lck->num_share_modes *
456                                    sizeof(struct share_mode_entry)))) {
457                         DEBUG(0, ("parse_share_modes: buffer too short\n"));
458                         return False;
459                 }
460                                   
461                 lck->share_modes = talloc_memdup(lck, dbuf.dptr+sizeof(*data),
462                                                  lck->num_share_modes *
463                                                  sizeof(struct share_mode_entry));
464
465                 if (lck->share_modes == NULL) {
466                         DEBUG(0, ("talloc failed\n"));
467                         return False;
468                 }
469         }
470
471         /* Save off the associated service path and filename. */
472         lck->servicepath = talloc_strdup(lck, dbuf.dptr + sizeof(*data) +
473                                       (lck->num_share_modes *
474                                       sizeof(struct share_mode_entry)));
475
476         lck->filename = talloc_strdup(lck, dbuf.dptr + sizeof(*data) +
477                                       (lck->num_share_modes *
478                                       sizeof(struct share_mode_entry)) +
479                                       strlen(lck->servicepath) + 1 );
480
481         /*
482          * Ensure that each entry has a real process attached.
483          */
484
485         for (i = 0; i < lck->num_share_modes; i++) {
486                 struct share_mode_entry *entry_p = &lck->share_modes[i];
487                 DEBUG(10,("parse_share_modes: %s\n",
488                           share_mode_str(i, entry_p) ));
489                 if (!process_exists(entry_p->pid)) {
490                         DEBUG(10,("parse_share_modes: deleted %s\n",
491                                   share_mode_str(i, entry_p) ));
492                         entry_p->op_type = UNUSED_SHARE_MODE_ENTRY;
493                         lck->modified = True;
494                 }
495         }
496
497         return True;
498 }
499
500 static TDB_DATA unparse_share_modes(struct share_mode_lock *lck)
501 {
502         TDB_DATA result;
503         int num_valid = 0;
504         int i;
505         struct locking_data *data;
506         ssize_t offset;
507         ssize_t sp_len;
508
509         result.dptr = NULL;
510         result.dsize = 0;
511
512         for (i=0; i<lck->num_share_modes; i++) {
513                 if (!is_unused_share_mode_entry(&lck->share_modes[i])) {
514                         num_valid += 1;
515                 }
516         }
517
518         if (num_valid == 0) {
519                 return result;
520         }
521
522         sp_len = strlen(lck->servicepath);
523
524         result.dsize = sizeof(*data) +
525                 lck->num_share_modes * sizeof(struct share_mode_entry) +
526                 sp_len + 1 +
527                 strlen(lck->filename) + 1;
528         result.dptr = talloc_size(lck, result.dsize);
529
530         if (result.dptr == NULL) {
531                 smb_panic("talloc failed\n");
532         }
533
534         data = (struct locking_data *)result.dptr;
535         ZERO_STRUCTP(data);
536         data->u.s.num_share_mode_entries = lck->num_share_modes;
537         data->u.s.delete_on_close = lck->delete_on_close;
538         DEBUG(10, ("unparse_share_modes: del: %d, num: %d\n",
539                    data->u.s.delete_on_close,
540                    data->u.s.num_share_mode_entries));
541         memcpy(result.dptr + sizeof(*data), lck->share_modes,
542                sizeof(struct share_mode_entry)*lck->num_share_modes);
543         offset = sizeof(*data) +
544                 sizeof(struct share_mode_entry)*lck->num_share_modes;
545         safe_strcpy(result.dptr + offset, lck->servicepath,
546                     result.dsize - offset - 1);
547         offset += sp_len + 1;
548         safe_strcpy(result.dptr + offset, lck->filename,
549                     result.dsize - offset - 1);
550
551         if (DEBUGLEVEL >= 10) {
552                 print_share_mode_table(data);
553         }
554
555         return result;
556 }
557
558 static int share_mode_lock_destructor(void *p)
559 {
560         struct share_mode_lock *lck =
561                 talloc_get_type_abort(p, struct share_mode_lock);
562         TDB_DATA key = locking_key(lck->dev, lck->ino);
563         TDB_DATA data;
564
565         if (!lck->modified) {
566                 goto done;
567         }
568
569         data = unparse_share_modes(lck);
570
571         if (data.dptr == NULL) {
572                 if (!lck->fresh) {
573                         /* There has been an entry before, delete it */
574                         if (tdb_delete(tdb, key) == -1) {
575                                 smb_panic("Could not delete share entry\n");
576                         }
577                 }
578                 goto done;
579         }
580
581         if (tdb_store(tdb, key, data, TDB_REPLACE) == -1) {
582                 smb_panic("Could not store share mode entry\n");
583         }
584
585  done:
586         tdb_chainunlock(tdb, key);
587
588         return 0;
589 }
590
591 struct share_mode_lock *get_share_mode_lock(TALLOC_CTX *mem_ctx,
592                                                 SMB_DEV_T dev, SMB_INO_T ino,
593                                                 const char *servicepath,
594                                                 const char *fname)
595 {
596         struct share_mode_lock *lck;
597         TDB_DATA key = locking_key(dev, ino);
598         TDB_DATA data;
599
600         lck = TALLOC_P(mem_ctx, struct share_mode_lock);
601         if (lck == NULL) {
602                 DEBUG(0, ("talloc failed\n"));
603                 return NULL;
604         }
605
606         /* Ensure we set every field here as the destructor must be
607            valid even if parse_share_modes fails. */
608
609         lck->servicepath = NULL;
610         lck->filename = NULL;
611         lck->dev = dev;
612         lck->ino = ino;
613         lck->num_share_modes = 0;
614         lck->share_modes = NULL;
615         lck->delete_on_close = False;
616         lck->fresh = False;
617         lck->modified = False;
618
619         if (tdb_chainlock(tdb, key) != 0) {
620                 DEBUG(3, ("Could not lock share entry\n"));
621                 talloc_free(lck);
622                 return NULL;
623         }
624
625         /* We must set the destructor immediately after the chainlock
626            ensure the lock is cleaned up on any of the error return
627            paths below. */
628
629         talloc_set_destructor(lck, share_mode_lock_destructor);
630
631         data = tdb_fetch(tdb, key);
632         lck->fresh = (data.dptr == NULL);
633
634         if (lck->fresh) {
635
636                 if (fname == NULL || servicepath == NULL) {
637                         talloc_free(lck);
638                         return NULL;
639                 }
640                 lck->filename = talloc_strdup(lck, fname);
641                 lck->servicepath = talloc_strdup(lck, servicepath);
642                 if (lck->filename == NULL || lck->servicepath == NULL) {
643                         DEBUG(0, ("talloc failed\n"));
644                         talloc_free(lck);
645                         return NULL;
646                 }
647         } else {
648                 if (!parse_share_modes(data, lck)) {
649                         DEBUG(0, ("Could not parse share modes\n"));
650                         talloc_free(lck);
651                         SAFE_FREE(data.dptr);
652                         return NULL;
653                 }
654         }
655
656         SAFE_FREE(data.dptr);
657
658         return lck;
659 }
660
661 /*******************************************************************
662  Sets the service name and filename for rename.
663  At this point we emit "file renamed" messages to all
664  process id's that have this file open.
665  Based on an initial code idea from SATOH Fumiyasu <fumiya@samba.gr.jp>
666 ********************************************************************/
667
668 BOOL rename_share_filename(struct share_mode_lock *lck,
669                         const char *servicepath,
670                         const char *newname)
671 {
672         size_t sp_len;
673         size_t fn_len;
674         size_t msg_len;
675         char *frm = NULL;
676         int i;
677
678         if (!lck) {
679                 return False;
680         }
681
682         DEBUG(10, ("rename_share_filename: servicepath %s newname %s\n",
683                 servicepath, newname));
684
685         /*
686          * rename_internal_fsp() and rename_internals() add './' to
687          * head of newname if newname does not contain a '/'.
688          */
689         while (newname[0] && newname[1] && newname[0] == '.' && newname[1] == '/') {
690                 newname += 2;
691         }
692
693         lck->servicepath = talloc_strdup(lck, servicepath);
694         lck->filename = talloc_strdup(lck, newname);
695         if (lck->filename == NULL || lck->servicepath == NULL) {
696                 DEBUG(0, ("rename_share_filename: talloc failed\n"));
697                 return False;
698         }
699         lck->modified = True;
700
701         sp_len = strlen(lck->servicepath);
702         fn_len = strlen(lck->filename);
703
704         msg_len = MSG_FILE_RENAMED_MIN_SIZE + sp_len + 1 + fn_len + 1;
705
706         /* Set up the name changed message. */
707         frm = TALLOC(lck, msg_len);
708         if (!frm) {
709                 return False;
710         }
711
712         SDEV_T_VAL(frm,0,lck->dev);
713         SINO_T_VAL(frm,8,lck->ino);
714
715         DEBUG(10,("rename_share_filename: msg_len = %d\n", msg_len ));
716
717         safe_strcpy(&frm[16], lck->servicepath, sp_len);
718         safe_strcpy(&frm[16 + sp_len + 1], lck->filename, fn_len);
719
720         /* Send the messages. */
721         for (i=0; i<lck->num_share_modes; i++) {
722                 struct share_mode_entry *se = &lck->share_modes[i];
723                 if (!is_valid_share_mode_entry(se)) {
724                         continue;
725                 }
726                 /* But not to ourselves... */
727                 if (procid_is_me(&se->pid)) {
728                         continue;
729                 }
730
731                 DEBUG(10,("rename_share_filename: sending rename message to pid %u "
732                         "dev %x, inode  %.0f sharepath %s newname %s\n",
733                         (unsigned int)procid_to_pid(&se->pid),
734                         (unsigned int)lck->dev, (double)lck->ino,
735                         lck->servicepath, lck->filename ));
736
737                 become_root();
738                 message_send_pid(se->pid, MSG_SMB_FILE_RENAME,
739                                 frm, msg_len, True);
740                 unbecome_root();
741         }
742
743         return True;
744 }
745
746 BOOL get_delete_on_close_flag(SMB_DEV_T dev, SMB_INO_T inode)
747 {
748         BOOL result;
749         struct share_mode_lock *lck = get_share_mode_lock(NULL, dev, inode, NULL, NULL);
750         if (!lck) {
751                 return False;
752         }
753         result = lck->delete_on_close;
754         talloc_free(lck);
755         return result;
756 }
757
758 BOOL is_valid_share_mode_entry(const struct share_mode_entry *e)
759 {
760         int num_props = 0;
761
762         num_props += ((e->op_type == NO_OPLOCK) ? 1 : 0);
763         num_props += (EXCLUSIVE_OPLOCK_TYPE(e->op_type) ? 1 : 0);
764         num_props += (LEVEL_II_OPLOCK_TYPE(e->op_type) ? 1 : 0);
765
766         SMB_ASSERT(num_props <= 1);
767         return (num_props != 0);
768 }
769
770 BOOL is_deferred_open_entry(const struct share_mode_entry *e)
771 {
772         return (e->op_type == DEFERRED_OPEN_ENTRY);
773 }
774
775 BOOL is_unused_share_mode_entry(const struct share_mode_entry *e)
776 {
777         return (e->op_type == UNUSED_SHARE_MODE_ENTRY);
778 }
779
780 /*******************************************************************
781  Fill a share mode entry.
782 ********************************************************************/
783
784 static void fill_share_mode_entry(struct share_mode_entry *e,
785                                   files_struct *fsp,
786                                   uint16 mid, uint16 op_type)
787 {
788         ZERO_STRUCTP(e);
789         e->pid = procid_self();
790         e->share_access = fsp->share_access;
791         e->private_options = fsp->fh->private_options;
792         e->access_mask = fsp->access_mask;
793         e->op_mid = mid;
794         e->op_type = op_type;
795         e->time.tv_sec = fsp->open_time.tv_sec;
796         e->time.tv_usec = fsp->open_time.tv_usec;
797         e->share_file_id = fsp->file_id;
798         e->dev = fsp->dev;
799         e->inode = fsp->inode;
800 }
801
802 static void fill_deferred_open_entry(struct share_mode_entry *e,
803                                      const struct timeval request_time,
804                                      SMB_DEV_T dev, SMB_INO_T ino, uint16 mid)
805 {
806         ZERO_STRUCTP(e);
807         e->pid = procid_self();
808         e->op_mid = mid;
809         e->op_type = DEFERRED_OPEN_ENTRY;
810         e->time.tv_sec = request_time.tv_sec;
811         e->time.tv_usec = request_time.tv_usec;
812         e->dev = dev;
813         e->inode = ino;
814 }
815
816 static void add_share_mode_entry(struct share_mode_lock *lck,
817                                  const struct share_mode_entry *entry)
818 {
819         int i;
820
821         for (i=0; i<lck->num_share_modes; i++) {
822                 struct share_mode_entry *e = &lck->share_modes[i];
823                 if (is_unused_share_mode_entry(e)) {
824                         *e = *entry;
825                         break;
826                 }
827         }
828
829         if (i == lck->num_share_modes) {
830                 /* No unused entry found */
831                 ADD_TO_ARRAY(lck, struct share_mode_entry, *entry,
832                              &lck->share_modes, &lck->num_share_modes);
833         }
834         lck->modified = True;
835 }
836
837 void set_share_mode(struct share_mode_lock *lck, files_struct *fsp,
838                     uint16 mid, uint16 op_type)
839 {
840         struct share_mode_entry entry;
841         fill_share_mode_entry(&entry, fsp, mid, op_type);
842         add_share_mode_entry(lck, &entry);
843 }
844
845 void add_deferred_open(struct share_mode_lock *lck, uint16 mid,
846                        struct timeval request_time,
847                        SMB_DEV_T dev, SMB_INO_T ino)
848 {
849         struct share_mode_entry entry;
850         fill_deferred_open_entry(&entry, request_time, dev, ino, mid);
851         add_share_mode_entry(lck, &entry);
852 }
853
854 /*******************************************************************
855  Check if two share mode entries are identical, ignoring oplock 
856  and mid info and desired_access.
857 ********************************************************************/
858
859 static BOOL share_modes_identical(struct share_mode_entry *e1,
860                                   struct share_mode_entry *e2)
861 {
862 #if 1 /* JRA PARANOIA TEST - REMOVE LATER */
863         if (procid_equal(&e1->pid, &e2->pid) &&
864             e1->share_file_id == e2->share_file_id &&
865             e1->dev == e2->dev &&
866             e1->inode == e2->inode &&
867             (e1->share_access) != (e2->share_access)) {
868                 DEBUG(0,("PANIC: share_modes_identical: share_mode "
869                          "mismatch (e1 = 0x%x, e2 = 0x%x). Logic error.\n",
870                          (unsigned int)e1->share_access,
871                          (unsigned int)e2->share_access ));
872                 smb_panic("PANIC: share_modes_identical logic error.\n");
873         }
874 #endif
875
876         return (procid_equal(&e1->pid, &e2->pid) &&
877                 (e1->share_access) == (e2->share_access) &&
878                 e1->dev == e2->dev &&
879                 e1->inode == e2->inode &&
880                 e1->share_file_id == e2->share_file_id );
881 }
882
883 static BOOL deferred_open_identical(struct share_mode_entry *e1,
884                                     struct share_mode_entry *e2)
885 {
886         return (procid_equal(&e1->pid, &e2->pid) &&
887                 (e1->op_mid == e2->op_mid) &&
888                 (e1->dev == e2->dev) &&
889                 (e1->inode == e2->inode));
890 }
891
892 static struct share_mode_entry *find_share_mode_entry(struct share_mode_lock *lck,
893                                                       struct share_mode_entry *entry)
894 {
895         int i;
896
897         for (i=0; i<lck->num_share_modes; i++) {
898                 struct share_mode_entry *e = &lck->share_modes[i];
899                 if (is_valid_share_mode_entry(entry) &&
900                     is_valid_share_mode_entry(e) &&
901                     share_modes_identical(e, entry)) {
902                         return e;
903                 }
904                 if (is_deferred_open_entry(entry) &&
905                     is_deferred_open_entry(e) &&
906                     deferred_open_identical(e, entry)) {
907                         return e;
908                 }
909         }
910         return NULL;
911 }
912
913 /*******************************************************************
914  Del the share mode of a file for this process. Return the number of
915  entries left.
916 ********************************************************************/
917
918 BOOL del_share_mode(struct share_mode_lock *lck, files_struct *fsp)
919 {
920         struct share_mode_entry entry, *e;
921
922         fill_share_mode_entry(&entry, fsp, 0, 0);
923
924         e = find_share_mode_entry(lck, &entry);
925         if (e == NULL) {
926                 return False;
927         }
928
929         e->op_type = UNUSED_SHARE_MODE_ENTRY;
930         lck->modified = True;
931         return True;
932 }
933
934 void del_deferred_open_entry(struct share_mode_lock *lck, uint16 mid)
935 {
936         struct share_mode_entry entry, *e;
937
938         fill_deferred_open_entry(&entry, timeval_zero(),
939                                  lck->dev, lck->ino, mid);
940
941         e = find_share_mode_entry(lck, &entry);
942         if (e == NULL) {
943                 return;
944         }
945
946         e->op_type = UNUSED_SHARE_MODE_ENTRY;
947         lck->modified = True;
948 }
949
950 /*******************************************************************
951  Remove an oplock mid and mode entry from a share mode.
952 ********************************************************************/
953
954 BOOL remove_share_oplock(struct share_mode_lock *lck, files_struct *fsp)
955 {
956         struct share_mode_entry entry, *e;
957
958         fill_share_mode_entry(&entry, fsp, 0, 0);
959
960         e = find_share_mode_entry(lck, &entry);
961         if (e == NULL) {
962                 return False;
963         }
964
965         e->op_mid = 0;
966         e->op_type = NO_OPLOCK;
967         lck->modified = True;
968         return True;
969 }
970
971 /*******************************************************************
972  Downgrade a oplock type from exclusive to level II.
973 ********************************************************************/
974
975 BOOL downgrade_share_oplock(struct share_mode_lock *lck, files_struct *fsp)
976 {
977         struct share_mode_entry entry, *e;
978
979         fill_share_mode_entry(&entry, fsp, 0, 0);
980
981         e = find_share_mode_entry(lck, &entry);
982         if (e == NULL) {
983                 return False;
984         }
985
986         e->op_type = LEVEL_II_OPLOCK;
987         lck->modified = True;
988         return True;
989 }
990
991
992 /*******************************************************************
993  We've just told all the smbd's that our level2 or fake level2 has been
994  written to.
995 ********************************************************************/
996 BOOL remove_all_share_oplocks(struct share_mode_lock *lck, files_struct *fsp)
997 {
998         int i;
999         for (i=0; i<lck->num_share_modes; i++) {
1000                 struct share_mode_entry *e = &lck->share_modes[i];
1001                 if (!is_valid_share_mode_entry(e)) {
1002                         continue;
1003                 }
1004                 if (e->op_type == NO_OPLOCK) {
1005                         continue;
1006                 }
1007                 e->op_type = NO_OPLOCK;
1008                 lck->modified = True;
1009         }
1010         return True;
1011 }
1012
1013 /****************************************************************************
1014  Deal with the internal needs of setting the delete on close flag. Note that
1015  as the tdb locking is recursive, it is safe to call this from within 
1016  open_file_shared. JRA.
1017 ****************************************************************************/
1018
1019 NTSTATUS can_set_delete_on_close(files_struct *fsp, BOOL delete_on_close,
1020                                  uint32 dosmode)
1021 {
1022         if (!delete_on_close) {
1023                 return NT_STATUS_OK;
1024         }
1025
1026         /*
1027          * Only allow delete on close for writable files.
1028          */
1029
1030         if ((dosmode & aRONLY) &&
1031             !lp_delete_readonly(SNUM(fsp->conn))) {
1032                 DEBUG(10,("can_set_delete_on_close: file %s delete on close "
1033                           "flag set but file attribute is readonly.\n",
1034                           fsp->fsp_name ));
1035                 return NT_STATUS_CANNOT_DELETE;
1036         }
1037
1038         /*
1039          * Only allow delete on close for writable shares.
1040          */
1041
1042         if (!CAN_WRITE(fsp->conn)) {
1043                 DEBUG(10,("can_set_delete_on_close: file %s delete on "
1044                           "close flag set but write access denied on share.\n",
1045                           fsp->fsp_name ));
1046                 return NT_STATUS_ACCESS_DENIED;
1047         }
1048
1049         /*
1050          * Only allow delete on close for files/directories opened with delete
1051          * intent.
1052          */
1053
1054         if (!(fsp->access_mask & DELETE_ACCESS)) {
1055                 DEBUG(10,("can_set_delete_on_close: file %s delete on "
1056                           "close flag set but delete access denied.\n",
1057                           fsp->fsp_name ));
1058                 return NT_STATUS_ACCESS_DENIED;
1059         }
1060
1061         return NT_STATUS_OK;
1062 }
1063
1064 /****************************************************************************
1065  Sets the delete on close flag over all share modes on this file.
1066  Modify the share mode entry for all files open
1067  on this device and inode to tell other smbds we have
1068  changed the delete on close flag. This will be noticed
1069  in the close code, the last closer will delete the file
1070  if flag is set.
1071 ****************************************************************************/
1072
1073 BOOL set_delete_on_close(files_struct *fsp, BOOL delete_on_close)
1074 {
1075         struct share_mode_lock *lck;
1076         
1077         DEBUG(10,("set_delete_on_close: %s delete on close flag for "
1078                   "fnum = %d, file %s\n",
1079                   delete_on_close ? "Adding" : "Removing", fsp->fnum,
1080                   fsp->fsp_name ));
1081
1082         if (fsp->is_stat) {
1083                 return True;
1084         }
1085
1086         lck = get_share_mode_lock(NULL, fsp->dev, fsp->inode, NULL, NULL);
1087         if (lck == NULL) {
1088                 return False;
1089         }
1090         if (lck->delete_on_close != delete_on_close) {
1091                 lck->delete_on_close = delete_on_close;
1092                 lck->modified = True;
1093         }
1094
1095         talloc_free(lck);
1096         return True;
1097 }
1098
1099 static int traverse_fn(TDB_CONTEXT *the_tdb, TDB_DATA kbuf, TDB_DATA dbuf, 
1100                        void *state)
1101 {
1102         struct locking_data *data;
1103         struct share_mode_entry *shares;
1104         const char *sharepath;
1105         const char *fname;
1106         int i;
1107         void (*traverse_callback)(struct share_mode_entry *, const char *, const char *) = state;
1108
1109         /* Ensure this is a locking_key record. */
1110         if (kbuf.dsize != sizeof(struct locking_key))
1111                 return 0;
1112
1113         data = (struct locking_data *)dbuf.dptr;
1114         shares = (struct share_mode_entry *)(dbuf.dptr + sizeof(*data));
1115         sharepath = dbuf.dptr + sizeof(*data) +
1116                 data->u.s.num_share_mode_entries*sizeof(*shares);
1117         fname = dbuf.dptr + sizeof(*data) +
1118                 data->u.s.num_share_mode_entries*sizeof(*shares) +
1119                 strlen(sharepath) + 1;
1120
1121         for (i=0;i<data->u.s.num_share_mode_entries;i++) {
1122                 traverse_callback(&shares[i], sharepath, fname);
1123         }
1124         return 0;
1125 }
1126
1127 /*******************************************************************
1128  Call the specified function on each entry under management by the
1129  share mode system.
1130 ********************************************************************/
1131
1132 int share_mode_forall(void (*fn)(const struct share_mode_entry *, const char *, const char *))
1133 {
1134         if (tdb == NULL)
1135                 return 0;
1136         return tdb_traverse(tdb, traverse_fn, fn);
1137 }