d89fe931ef644c1fadff08a2a0aac6bb34ccb30a
[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]: "
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, procid_str_static(&e->pid),
392                  e->share_access, e->private_options,
393                  e->access_mask, e->op_mid, e->op_type, e->share_file_id,
394                  (unsigned int)e->dev, (double)e->inode );
395
396         return share_str;
397 }
398
399 /*******************************************************************
400  Print out a share mode table.
401 ********************************************************************/
402
403 static void print_share_mode_table(struct locking_data *data)
404 {
405         int num_share_modes = data->u.s.num_share_mode_entries;
406         struct share_mode_entry *shares =
407                 (struct share_mode_entry *)(data + 1);
408         int i;
409
410         for (i = 0; i < num_share_modes; i++) {
411                 struct share_mode_entry *entry_p = &shares[i];
412                 DEBUG(10,("print_share_mode_table: %s\n",
413                           share_mode_str(i, entry_p)));
414         }
415 }
416
417 /*******************************************************************
418  Get all share mode entries for a dev/inode pair.
419 ********************************************************************/
420
421 static BOOL parse_share_modes(TDB_DATA dbuf, struct share_mode_lock *lck)
422 {
423         struct locking_data *data;
424         int i;
425
426         if (dbuf.dsize < sizeof(struct locking_data)) {
427                 DEBUG(0, ("parse_share_modes: buffer too short\n"));
428                 return False;
429         }
430
431         data = (struct locking_data *)dbuf.dptr;
432
433         lck->delete_on_close = data->u.s.delete_on_close;
434         lck->num_share_modes = data->u.s.num_share_mode_entries;
435
436         DEBUG(10, ("parse_share_modes: delete_on_close: %d, "
437                    "num_share_modes: %d\n", lck->delete_on_close,
438                    lck->num_share_modes));
439
440         if ((lck->num_share_modes < 0) || (lck->num_share_modes > 1000000)) {
441                 DEBUG(0, ("invalid number of share modes: %d\n",
442                           lck->num_share_modes));
443                 return False;
444         }
445
446         lck->share_modes = NULL;
447
448         if (lck->num_share_modes != 0) {
449
450                 if (dbuf.dsize < (sizeof(struct locking_data) +
451                                   (lck->num_share_modes *
452                                    sizeof(struct share_mode_entry)))) {
453                         DEBUG(0, ("parse_share_modes: buffer too short\n"));
454                         return False;
455                 }
456                                   
457                 lck->share_modes = talloc_memdup(lck, dbuf.dptr+sizeof(*data),
458                                                  lck->num_share_modes *
459                                                  sizeof(struct share_mode_entry));
460
461                 if (lck->share_modes == NULL) {
462                         DEBUG(0, ("talloc failed\n"));
463                         return False;
464                 }
465         }
466
467         /* Save off the associated service path and filename. */
468         lck->servicepath = talloc_strdup(lck, dbuf.dptr + sizeof(*data) +
469                                       (lck->num_share_modes *
470                                       sizeof(struct share_mode_entry)));
471
472         lck->filename = talloc_strdup(lck, dbuf.dptr + sizeof(*data) +
473                                       (lck->num_share_modes *
474                                       sizeof(struct share_mode_entry)) +
475                                       strlen(lck->servicepath) + 1 );
476
477         /*
478          * Ensure that each entry has a real process attached.
479          */
480
481         for (i = 0; i < lck->num_share_modes; i++) {
482                 struct share_mode_entry *entry_p = &lck->share_modes[i];
483                 DEBUG(10,("parse_share_modes: %s\n",
484                           share_mode_str(i, entry_p) ));
485                 if (!process_exists(entry_p->pid)) {
486                         DEBUG(10,("parse_share_modes: deleted %s\n",
487                                   share_mode_str(i, entry_p) ));
488                         entry_p->op_type = UNUSED_SHARE_MODE_ENTRY;
489                         lck->modified = True;
490                 }
491         }
492
493         return True;
494 }
495
496 static TDB_DATA unparse_share_modes(struct share_mode_lock *lck)
497 {
498         TDB_DATA result;
499         int num_valid = 0;
500         int i;
501         struct locking_data *data;
502         ssize_t offset;
503         ssize_t sp_len;
504
505         result.dptr = NULL;
506         result.dsize = 0;
507
508         for (i=0; i<lck->num_share_modes; i++) {
509                 if (!is_unused_share_mode_entry(&lck->share_modes[i])) {
510                         num_valid += 1;
511                 }
512         }
513
514         if (num_valid == 0) {
515                 return result;
516         }
517
518         sp_len = strlen(lck->servicepath);
519
520         result.dsize = sizeof(*data) +
521                 lck->num_share_modes * sizeof(struct share_mode_entry) +
522                 sp_len + 1 +
523                 strlen(lck->filename) + 1;
524         result.dptr = talloc_size(lck, result.dsize);
525
526         if (result.dptr == NULL) {
527                 smb_panic("talloc failed\n");
528         }
529
530         data = (struct locking_data *)result.dptr;
531         ZERO_STRUCTP(data);
532         data->u.s.num_share_mode_entries = lck->num_share_modes;
533         data->u.s.delete_on_close = lck->delete_on_close;
534         DEBUG(10, ("unparse_share_modes: del: %d, num: %d\n",
535                    data->u.s.delete_on_close,
536                    data->u.s.num_share_mode_entries));
537         memcpy(result.dptr + sizeof(*data), lck->share_modes,
538                sizeof(struct share_mode_entry)*lck->num_share_modes);
539         offset = sizeof(*data) +
540                 sizeof(struct share_mode_entry)*lck->num_share_modes;
541         safe_strcpy(result.dptr + offset, lck->servicepath,
542                     result.dsize - offset - 1);
543         offset += sp_len + 1;
544         safe_strcpy(result.dptr + offset, lck->filename,
545                     result.dsize - offset - 1);
546         print_share_mode_table(data);
547         return result;
548 }
549
550 static int share_mode_lock_destructor(void *p)
551 {
552         struct share_mode_lock *lck =
553                 talloc_get_type_abort(p, struct share_mode_lock);
554         TDB_DATA key = locking_key(lck->dev, lck->ino);
555         TDB_DATA data;
556
557         if (!lck->modified) {
558                 goto done;
559         }
560
561         data = unparse_share_modes(lck);
562
563         if (data.dptr == NULL) {
564                 if (!lck->fresh) {
565                         /* There has been an entry before, delete it */
566                         if (tdb_delete(tdb, key) == -1) {
567                                 smb_panic("Could not delete share entry\n");
568                         }
569                 }
570                 goto done;
571         }
572
573         if (tdb_store(tdb, key, data, TDB_REPLACE) == -1) {
574                 smb_panic("Could not store share mode entry\n");
575         }
576
577  done:
578         tdb_chainunlock(tdb, key);
579
580         return 0;
581 }
582
583 struct share_mode_lock *get_share_mode_lock(TALLOC_CTX *mem_ctx,
584                                                 SMB_DEV_T dev, SMB_INO_T ino,
585                                                 const char *servicepath,
586                                                 const char *fname)
587 {
588         struct share_mode_lock *lck;
589         TDB_DATA key = locking_key(dev, ino);
590         TDB_DATA data;
591
592         lck = TALLOC_P(mem_ctx, struct share_mode_lock);
593         if (lck == NULL) {
594                 DEBUG(0, ("talloc failed\n"));
595                 return NULL;
596         }
597
598         lck->dev = dev;
599         lck->ino = ino;
600         lck->delete_on_close = False;
601         lck->num_share_modes = 0;
602         lck->share_modes = NULL;
603         lck->modified = False;
604
605         if (tdb_chainlock(tdb, key) != 0) {
606                 DEBUG(3, ("Could not lock share entry\n"));
607                 talloc_free(lck);
608                 return NULL;
609         }
610
611         data = tdb_fetch(tdb, key);
612         lck->fresh = (data.dptr == NULL);
613
614         if (lck->fresh) {
615
616                 if (fname == NULL || servicepath == NULL) {
617                         DEBUG(0, ("New file, but no filename or servicepath supplied\n"));
618                         talloc_free(lck);
619                         return NULL;
620                 }
621                 lck->filename = talloc_strdup(lck, fname);
622                 lck->servicepath = talloc_strdup(lck, servicepath);
623                 if (lck->filename == NULL || lck->servicepath == NULL) {
624                         DEBUG(0, ("talloc failed\n"));
625                         talloc_free(lck);
626                         return NULL;
627                 }
628         } else {
629                 if (!parse_share_modes(data, lck)) {
630                         DEBUG(0, ("Could not parse share modes\n"));
631                         talloc_free(lck);
632                         SAFE_FREE(data.dptr);
633                         return NULL;
634                 }
635         }
636
637         talloc_set_destructor(lck, share_mode_lock_destructor);
638         SAFE_FREE(data.dptr);
639
640         return lck;
641 }
642
643 /*******************************************************************
644  Sets the service name and filename for rename.
645  At this point we emit "file renamed" messages to all
646  process id's that have this file open.
647  Based on an initial code idea from SATOH Fumiyasu <fumiya@samba.gr.jp>
648 ********************************************************************/
649
650 BOOL rename_share_filename(struct share_mode_lock *lck,
651                         const char *servicepath,
652                         const char *newname)
653 {
654         struct file_renamed_message *frm = NULL;
655         size_t sp_len;
656         size_t fn_len;
657         size_t msg_len;
658         int i;
659
660         DEBUG(10, ("rename_share_filename: servicepath %s newname %s\n",
661                 servicepath, newname));
662
663         /*
664          * rename_internal_fsp() and rename_internals() add './' to
665          * head of newname if newname does not contain a '/'.
666          */
667         while (newname[0] && newname[1] && newname[0] == '.' && newname[1] == '/') {
668                 newname += 2;
669         }
670
671         lck->servicepath = talloc_strdup(lck, servicepath);
672         lck->filename = talloc_strdup(lck, newname);
673         if (lck->filename == NULL || lck->servicepath == NULL) {
674                 DEBUG(0, ("rename_share_filename: talloc failed\n"));
675                 return False;
676         }
677         lck->modified = True;
678
679         sp_len = strlen(lck->servicepath);
680         fn_len = strlen(lck->filename);
681
682         msg_len = sizeof(*frm) + sp_len + 1 + fn_len + 1;
683
684         /* Set up the name changed message. */
685         frm = TALLOC(lck, msg_len);
686         if (!frm) {
687                 return False;
688         }
689         frm->dev = lck->dev;
690         frm->inode = lck->ino;
691
692         DEBUG(10,("rename_share_filename: msg_len = %d\n", msg_len ));
693
694         safe_strcpy(&frm->names[0], lck->servicepath, sp_len);
695         safe_strcpy(&frm->names[sp_len + 1], lck->filename, fn_len);
696
697         /* Send the messages. */
698         for (i=0; i<lck->num_share_modes; i++) {
699                 struct share_mode_entry *se = &lck->share_modes[i];
700                 if (!is_valid_share_mode_entry(se)) {
701                         continue;
702                 }
703                 /* But not to ourselves... */
704                 if (procid_is_me(&se->pid)) {
705                         continue;
706                 }
707
708                 DEBUG(10,("rename_share_filename: sending rename message to pid %u "
709                         "dev %x, inode  %.0f sharepath %s newname %s\n",
710                         (unsigned int)procid_to_pid(&se->pid),
711                         (unsigned int)frm->dev, (double)frm->inode,
712                         lck->servicepath, lck->filename ));
713
714                 message_send_pid(se->pid, MSG_SMB_FILE_RENAME,
715                                 frm, msg_len, True);
716         }
717
718         return True;
719 }
720
721 BOOL get_delete_on_close_flag(SMB_DEV_T dev, SMB_INO_T inode)
722 {
723         BOOL result;
724         struct share_mode_lock *lck = get_share_mode_lock(NULL, dev, inode, NULL, NULL);
725         if (!lck) {
726                 return False;
727         }
728         result = lck->delete_on_close;
729         talloc_free(lck);
730         return result;
731 }
732
733 BOOL is_valid_share_mode_entry(const struct share_mode_entry *e)
734 {
735         int num_props = 0;
736
737         num_props += ((e->op_type == NO_OPLOCK) ? 1 : 0);
738         num_props += (EXCLUSIVE_OPLOCK_TYPE(e->op_type) ? 1 : 0);
739         num_props += (LEVEL_II_OPLOCK_TYPE(e->op_type) ? 1 : 0);
740
741         SMB_ASSERT(num_props <= 1);
742         return (num_props != 0);
743 }
744
745 BOOL is_deferred_open_entry(const struct share_mode_entry *e)
746 {
747         return (e->op_type == DEFERRED_OPEN_ENTRY);
748 }
749
750 BOOL is_unused_share_mode_entry(const struct share_mode_entry *e)
751 {
752         return (e->op_type == UNUSED_SHARE_MODE_ENTRY);
753 }
754
755 /*******************************************************************
756  Fill a share mode entry.
757 ********************************************************************/
758
759 static void fill_share_mode_entry(struct share_mode_entry *e,
760                                   files_struct *fsp,
761                                   uint16 mid, uint16 op_type)
762 {
763         ZERO_STRUCTP(e);
764         e->pid = procid_self();
765         e->share_access = fsp->share_access;
766         e->private_options = fsp->fh->private_options;
767         e->access_mask = fsp->access_mask;
768         e->op_mid = mid;
769         e->op_type = op_type;
770         e->time.tv_sec = fsp->open_time.tv_sec;
771         e->time.tv_usec = fsp->open_time.tv_usec;
772         e->share_file_id = fsp->file_id;
773         e->dev = fsp->dev;
774         e->inode = fsp->inode;
775 }
776
777 static void fill_deferred_open_entry(struct share_mode_entry *e,
778                                      const struct timeval request_time,
779                                      SMB_DEV_T dev, SMB_INO_T ino, uint16 mid)
780 {
781         ZERO_STRUCTP(e);
782         e->pid = procid_self();
783         e->op_mid = mid;
784         e->op_type = DEFERRED_OPEN_ENTRY;
785         e->time.tv_sec = request_time.tv_sec;
786         e->time.tv_usec = request_time.tv_usec;
787         e->dev = dev;
788         e->inode = ino;
789 }
790
791 static void add_share_mode_entry(struct share_mode_lock *lck,
792                                  const struct share_mode_entry *entry)
793 {
794         int i;
795
796         for (i=0; i<lck->num_share_modes; i++) {
797                 struct share_mode_entry *e = &lck->share_modes[i];
798                 if (is_unused_share_mode_entry(e)) {
799                         *e = *entry;
800                         break;
801                 }
802         }
803
804         if (i == lck->num_share_modes) {
805                 /* No unused entry found */
806                 ADD_TO_ARRAY(lck, struct share_mode_entry, *entry,
807                              &lck->share_modes, &lck->num_share_modes);
808         }
809         lck->modified = True;
810 }
811
812 void set_share_mode(struct share_mode_lock *lck, files_struct *fsp,
813                     uint16 mid, uint16 op_type)
814 {
815         struct share_mode_entry entry;
816         fill_share_mode_entry(&entry, fsp, mid, op_type);
817         add_share_mode_entry(lck, &entry);
818 }
819
820 void add_deferred_open(struct share_mode_lock *lck, uint16 mid,
821                        struct timeval request_time,
822                        SMB_DEV_T dev, SMB_INO_T ino)
823 {
824         struct share_mode_entry entry;
825         fill_deferred_open_entry(&entry, request_time, dev, ino, mid);
826         add_share_mode_entry(lck, &entry);
827 }
828
829 /*******************************************************************
830  Check if two share mode entries are identical, ignoring oplock 
831  and mid info and desired_access.
832 ********************************************************************/
833
834 static BOOL share_modes_identical(struct share_mode_entry *e1,
835                                   struct share_mode_entry *e2)
836 {
837 #if 1 /* JRA PARANOIA TEST - REMOVE LATER */
838         if (procid_equal(&e1->pid, &e2->pid) &&
839             e1->share_file_id == e2->share_file_id &&
840             e1->dev == e2->dev &&
841             e1->inode == e2->inode &&
842             (e1->share_access) != (e2->share_access)) {
843                 DEBUG(0,("PANIC: share_modes_identical: share_mode "
844                          "mismatch (e1 = 0x%x, e2 = 0x%x). Logic error.\n",
845                          (unsigned int)e1->share_access,
846                          (unsigned int)e2->share_access ));
847                 smb_panic("PANIC: share_modes_identical logic error.\n");
848         }
849 #endif
850
851         return (procid_equal(&e1->pid, &e2->pid) &&
852                 (e1->share_access) == (e2->share_access) &&
853                 e1->dev == e2->dev &&
854                 e1->inode == e2->inode &&
855                 e1->share_file_id == e2->share_file_id );
856 }
857
858 static BOOL deferred_open_identical(struct share_mode_entry *e1,
859                                     struct share_mode_entry *e2)
860 {
861         return (procid_equal(&e1->pid, &e2->pid) &&
862                 (e1->op_mid == e2->op_mid) &&
863                 (e1->dev == e2->dev) &&
864                 (e1->inode == e2->inode));
865 }
866
867 static struct share_mode_entry *find_share_mode_entry(struct share_mode_lock *lck,
868                                                       struct share_mode_entry *entry)
869 {
870         int i;
871
872         for (i=0; i<lck->num_share_modes; i++) {
873                 struct share_mode_entry *e = &lck->share_modes[i];
874                 if (is_valid_share_mode_entry(entry) &&
875                     is_valid_share_mode_entry(e) &&
876                     share_modes_identical(e, entry)) {
877                         return e;
878                 }
879                 if (is_deferred_open_entry(entry) &&
880                     is_deferred_open_entry(e) &&
881                     deferred_open_identical(e, entry)) {
882                         return e;
883                 }
884         }
885         return NULL;
886 }
887
888 /*******************************************************************
889  Del the share mode of a file for this process. Return the number of
890  entries left.
891 ********************************************************************/
892
893 BOOL del_share_mode(struct share_mode_lock *lck, files_struct *fsp)
894 {
895         struct share_mode_entry entry, *e;
896
897         fill_share_mode_entry(&entry, fsp, 0, 0);
898
899         e = find_share_mode_entry(lck, &entry);
900         if (e == NULL) {
901                 return False;
902         }
903
904         e->op_type = UNUSED_SHARE_MODE_ENTRY;
905         lck->modified = True;
906         return True;
907 }
908
909 void del_deferred_open_entry(struct share_mode_lock *lck, uint16 mid)
910 {
911         struct share_mode_entry entry, *e;
912
913         fill_deferred_open_entry(&entry, timeval_zero(),
914                                  lck->dev, lck->ino, mid);
915
916         e = find_share_mode_entry(lck, &entry);
917         if (e == NULL) {
918                 return;
919         }
920
921         e->op_type = UNUSED_SHARE_MODE_ENTRY;
922         lck->modified = True;
923 }
924
925 /*******************************************************************
926  Remove an oplock mid and mode entry from a share mode.
927 ********************************************************************/
928
929 BOOL remove_share_oplock(struct share_mode_lock *lck, files_struct *fsp)
930 {
931         struct share_mode_entry entry, *e;
932
933         fill_share_mode_entry(&entry, fsp, 0, 0);
934
935         e = find_share_mode_entry(lck, &entry);
936         if (e == NULL) {
937                 return False;
938         }
939
940         e->op_mid = 0;
941         e->op_type = NO_OPLOCK;
942         lck->modified = True;
943         return True;
944 }
945
946 /*******************************************************************
947  Downgrade a oplock type from exclusive to level II.
948 ********************************************************************/
949
950 BOOL downgrade_share_oplock(struct share_mode_lock *lck, files_struct *fsp)
951 {
952         struct share_mode_entry entry, *e;
953
954         fill_share_mode_entry(&entry, fsp, 0, 0);
955
956         e = find_share_mode_entry(lck, &entry);
957         if (e == NULL) {
958                 return False;
959         }
960
961         e->op_type = LEVEL_II_OPLOCK;
962         lck->modified = True;
963         return True;
964 }
965
966
967 /*******************************************************************
968  We've just told all the smbd's that our level2 or fake level2 has been
969  written to.
970 ********************************************************************/
971 BOOL remove_all_share_oplocks(struct share_mode_lock *lck, files_struct *fsp)
972 {
973         int i;
974         for (i=0; i<lck->num_share_modes; i++) {
975                 struct share_mode_entry *e = &lck->share_modes[i];
976                 if (!is_valid_share_mode_entry(e)) {
977                         continue;
978                 }
979                 if (e->op_type == NO_OPLOCK) {
980                         continue;
981                 }
982                 e->op_type = NO_OPLOCK;
983                 lck->modified = True;
984         }
985         return True;
986 }
987
988 /****************************************************************************
989  Deal with the internal needs of setting the delete on close flag. Note that
990  as the tdb locking is recursive, it is safe to call this from within 
991  open_file_shared. JRA.
992 ****************************************************************************/
993
994 NTSTATUS can_set_delete_on_close(files_struct *fsp, BOOL delete_on_close,
995                                  uint32 dosmode)
996 {
997         if (!delete_on_close) {
998                 return NT_STATUS_OK;
999         }
1000
1001         /*
1002          * Only allow delete on close for writable files.
1003          */
1004
1005         if ((dosmode & aRONLY) &&
1006             !lp_delete_readonly(SNUM(fsp->conn))) {
1007                 DEBUG(10,("can_set_delete_on_close: file %s delete on close "
1008                           "flag set but file attribute is readonly.\n",
1009                           fsp->fsp_name ));
1010                 return NT_STATUS_CANNOT_DELETE;
1011         }
1012
1013         /*
1014          * Only allow delete on close for writable shares.
1015          */
1016
1017         if (!CAN_WRITE(fsp->conn)) {
1018                 DEBUG(10,("can_set_delete_on_close: file %s delete on "
1019                           "close flag set but write access denied on share.\n",
1020                           fsp->fsp_name ));
1021                 return NT_STATUS_ACCESS_DENIED;
1022         }
1023
1024         /*
1025          * Only allow delete on close for files/directories opened with delete
1026          * intent.
1027          */
1028
1029         if (!(fsp->access_mask & DELETE_ACCESS)) {
1030                 DEBUG(10,("can_set_delete_on_close: file %s delete on "
1031                           "close flag set but delete access denied.\n",
1032                           fsp->fsp_name ));
1033                 return NT_STATUS_ACCESS_DENIED;
1034         }
1035
1036         return NT_STATUS_OK;
1037 }
1038
1039 /****************************************************************************
1040  Sets the delete on close flag over all share modes on this file.
1041  Modify the share mode entry for all files open
1042  on this device and inode to tell other smbds we have
1043  changed the delete on close flag. This will be noticed
1044  in the close code, the last closer will delete the file
1045  if flag is set.
1046 ****************************************************************************/
1047
1048 BOOL set_delete_on_close(files_struct *fsp, BOOL delete_on_close)
1049 {
1050         struct share_mode_lock *lck;
1051         
1052         DEBUG(10,("set_delete_on_close: %s delete on close flag for "
1053                   "fnum = %d, file %s\n",
1054                   delete_on_close ? "Adding" : "Removing", fsp->fnum,
1055                   fsp->fsp_name ));
1056
1057         if (fsp->is_stat) {
1058                 return True;
1059         }
1060
1061         lck = get_share_mode_lock(NULL, fsp->dev, fsp->inode, NULL, NULL);
1062         if (lck == NULL) {
1063                 return False;
1064         }
1065         if (lck->delete_on_close != delete_on_close) {
1066                 lck->delete_on_close = delete_on_close;
1067                 lck->modified = True;
1068         }
1069
1070         talloc_free(lck);
1071         return True;
1072 }
1073
1074 static int traverse_fn(TDB_CONTEXT *the_tdb, TDB_DATA kbuf, TDB_DATA dbuf, 
1075                        void *state)
1076 {
1077         struct locking_data *data;
1078         struct share_mode_entry *shares;
1079         const char *sharepath;
1080         const char *fname;
1081         int i;
1082         void (*traverse_callback)(struct share_mode_entry *, const char *, const char *) = state;
1083
1084         /* Ensure this is a locking_key record. */
1085         if (kbuf.dsize != sizeof(struct locking_key))
1086                 return 0;
1087
1088         data = (struct locking_data *)dbuf.dptr;
1089         shares = (struct share_mode_entry *)(dbuf.dptr + sizeof(*data));
1090         sharepath = dbuf.dptr + sizeof(*data) +
1091                 data->u.s.num_share_mode_entries*sizeof(*shares);
1092         fname = dbuf.dptr + sizeof(*data) +
1093                 data->u.s.num_share_mode_entries*sizeof(*shares) +
1094                 strlen(sharepath) + 1;
1095
1096         for (i=0;i<data->u.s.num_share_mode_entries;i++) {
1097                 traverse_callback(&shares[i], sharepath, fname);
1098         }
1099         return 0;
1100 }
1101
1102 /*******************************************************************
1103  Call the specified function on each entry under management by the
1104  share mode system.
1105 ********************************************************************/
1106
1107 int share_mode_forall(void (*fn)(const struct share_mode_entry *, const char *, const char *))
1108 {
1109         if (tdb == NULL)
1110                 return 0;
1111         return tdb_traverse(tdb, traverse_fn, fn);
1112 }