Slightly simplify logic in cancel_pending_lock_requests_by_fid()
[amitay/samba.git] / source3 / smbd / blocking.c
1 /* 
2    Unix SMB/CIFS implementation.
3    Blocking Locking functions
4    Copyright (C) Jeremy Allison 1998-2003
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include "includes.h"
21 #undef DBGC_CLASS
22 #define DBGC_CLASS DBGC_LOCKING
23
24 /****************************************************************************
25  This is the structure to queue to implement blocking locks.
26  notify. It consists of the requesting SMB and the expiry time.
27 *****************************************************************************/
28
29 typedef struct blocking_lock_record {
30         struct blocking_lock_record *next;
31         struct blocking_lock_record *prev;
32         int com_type;
33         files_struct *fsp;
34         struct timeval expire_time;
35         int lock_num;
36         uint64_t offset;
37         uint64_t count;
38         uint32_t lock_pid;
39         uint32_t blocking_pid; /* PID that blocks us. */
40         enum brl_flavour lock_flav;
41         enum brl_type lock_type;
42         char *inbuf;
43         int length;
44         bool encrypted;
45 } blocking_lock_record;
46
47 /* dlink list we store pending lock records on. */
48 static blocking_lock_record *blocking_lock_queue;
49
50 /* dlink list we move cancelled lock records onto. */
51 static blocking_lock_record *blocking_lock_cancelled_queue;
52
53 /* The event that makes us process our blocking lock queue */
54 static struct timed_event *brl_timeout;
55
56 /****************************************************************************
57  Determine if this is a secondary element of a chained SMB.
58   **************************************************************************/
59
60 static bool in_chained_smb(void)
61 {
62         return (chain_size != 0);
63 }
64
65 static void received_unlock_msg(struct messaging_context *msg,
66                                 void *private_data,
67                                 uint32_t msg_type,
68                                 struct server_id server_id,
69                                 DATA_BLOB *data);
70 static void process_blocking_lock_queue(void);
71
72 static void brl_timeout_fn(struct event_context *event_ctx,
73                            struct timed_event *te,
74                            const struct timeval *now,
75                            void *private_data)
76 {
77         SMB_ASSERT(brl_timeout == te);
78         TALLOC_FREE(brl_timeout);
79
80         change_to_root_user();  /* TODO: Possibly run all timed events as
81                                  * root */
82
83         process_blocking_lock_queue();
84 }
85
86 /****************************************************************************
87  After a change to blocking_lock_queue, recalculate the timed_event for the
88  next processing.
89 ****************************************************************************/
90
91 static bool recalc_brl_timeout(void)
92 {
93         blocking_lock_record *brl;
94         struct timeval next_timeout;
95
96         TALLOC_FREE(brl_timeout);
97
98         next_timeout = timeval_zero();  
99
100         for (brl = blocking_lock_queue; brl; brl = brl->next) {
101                 if (timeval_is_zero(&brl->expire_time)) {
102                         /*
103                          * If we're blocked on pid 0xFFFFFFFF this is
104                          * a POSIX lock, so calculate a timeout of
105                          * 10 seconds into the future.
106                          */
107                         if (brl->blocking_pid == 0xFFFFFFFF) {
108                                 struct timeval psx_to = timeval_current_ofs(10, 0);
109                                 next_timeout = timeval_min(&next_timeout, &psx_to);
110                         }
111
112                         continue;
113                 }
114
115                 if (timeval_is_zero(&next_timeout)) {
116                         next_timeout = brl->expire_time;
117                 }
118                 else {
119                         next_timeout = timeval_min(&next_timeout,
120                                                    &brl->expire_time);
121                 }
122         }
123
124         if (timeval_is_zero(&next_timeout)) {
125                 return True;
126         }
127
128         if (!(brl_timeout = event_add_timed(smbd_event_context(), NULL,
129                                             next_timeout, "brl_timeout",
130                                             brl_timeout_fn, NULL))) {
131                 return False;
132         }
133
134         return True;
135 }
136
137
138 /****************************************************************************
139  Function to push a blocking lock request onto the lock queue.
140 ****************************************************************************/
141
142 bool push_blocking_lock_request( struct byte_range_lock *br_lck,
143                 const struct smb_request *req,
144                 files_struct *fsp,
145                 int lock_timeout,
146                 int lock_num,
147                 uint32_t lock_pid,
148                 enum brl_type lock_type,
149                 enum brl_flavour lock_flav,
150                 uint64_t offset,
151                 uint64_t count,
152                 uint32_t blocking_pid)
153 {
154         static bool set_lock_msg;
155         size_t length = smb_len(req->inbuf)+4;
156         blocking_lock_record *blr;
157         NTSTATUS status;
158
159         if(in_chained_smb() ) {
160                 DEBUG(0,("push_blocking_lock_request: cannot queue a chained request (currently).\n"));
161                 return False;
162         }
163
164         /*
165          * Now queue an entry on the blocking lock queue. We setup
166          * the expiration time here.
167          */
168
169         blr = talloc(NULL, struct blocking_lock_record);
170         if (blr == NULL) {
171                 DEBUG(0,("push_blocking_lock_request: Malloc fail !\n" ));
172                 return False;
173         }
174
175         blr->next = NULL;
176         blr->prev = NULL;
177
178         blr->inbuf = TALLOC_ARRAY(blr, char, length);
179         if (blr->inbuf == NULL) {
180                 DEBUG(0,("push_blocking_lock_request: Malloc fail (2)!\n" ));
181                 TALLOC_FREE(blr);
182                 return False;
183         }
184
185         blr->com_type = req->cmd;
186         blr->fsp = fsp;
187         if (lock_timeout == -1) {
188                 blr->expire_time.tv_sec = 0;
189                 blr->expire_time.tv_usec = 0; /* Never expire. */
190         } else {
191                 blr->expire_time = timeval_current_ofs(lock_timeout/1000,
192                                         (lock_timeout % 1000) * 1000);
193         }
194         blr->lock_num = lock_num;
195         blr->lock_pid = lock_pid;
196         blr->blocking_pid = blocking_pid;
197         blr->lock_flav = lock_flav;
198         blr->lock_type = lock_type;
199         blr->offset = offset;
200         blr->count = count;
201         memcpy(blr->inbuf, req->inbuf, length);
202         blr->length = length;
203         blr->encrypted = req->encrypted;
204
205         /* Add a pending lock record for this. */
206         status = brl_lock(smbd_messaging_context(), br_lck,
207                         lock_pid,
208                         procid_self(),
209                         offset,
210                         count,
211                         lock_type == READ_LOCK ? PENDING_READ_LOCK : PENDING_WRITE_LOCK,
212                         blr->lock_flav,
213                         lock_timeout ? True : False, /* blocking_lock. */
214                         NULL);
215
216         if (!NT_STATUS_IS_OK(status)) {
217                 DEBUG(0,("push_blocking_lock_request: failed to add PENDING_LOCK record.\n"));
218                 DLIST_REMOVE(blocking_lock_queue, blr);
219                 TALLOC_FREE(blr);
220                 return False;
221         }
222
223         DLIST_ADD_END(blocking_lock_queue, blr, blocking_lock_record *);
224         recalc_brl_timeout();
225
226         /* Ensure we'll receive messages when this is unlocked. */
227         if (!set_lock_msg) {
228                 messaging_register(smbd_messaging_context(), NULL,
229                                    MSG_SMB_UNLOCK, received_unlock_msg);
230                 set_lock_msg = True;
231         }
232
233         DEBUG(3,("push_blocking_lock_request: lock request length=%u blocked with "
234                 "expiry time (%u sec. %u usec) (+%d msec) for fnum = %d, name = %s\n",
235                 (unsigned int)length, (unsigned int)blr->expire_time.tv_sec,
236                 (unsigned int)blr->expire_time.tv_usec, lock_timeout,
237                 blr->fsp->fnum, blr->fsp->fsp_name ));
238
239         /* Push the MID of this packet on the signing queue. */
240         srv_defer_sign_response(SVAL(req->inbuf,smb_mid));
241
242         return True;
243 }
244
245 /****************************************************************************
246  Return a lockingX success SMB.
247 *****************************************************************************/
248
249 static void reply_lockingX_success(blocking_lock_record *blr)
250 {
251         struct smb_request *req;
252
253         if (!(req = talloc(talloc_tos(), struct smb_request))) {
254                 smb_panic("Could not allocate smb_request");
255         }
256
257         init_smb_request(req, (uint8 *)blr->inbuf, 0, blr->encrypted);
258         req->inbuf = (uint8_t *)(blr->inbuf);
259         reply_outbuf(req, 2, 0);
260
261         /*
262          * As this message is a lockingX call we must handle
263          * any following chained message correctly.
264          * This is normally handled in construct_reply(),
265          * but as that calls switch_message, we can't use
266          * that here and must set up the chain info manually.
267          */
268
269         chain_reply(req);
270
271         if (!srv_send_smb(smbd_server_fd(),
272                         (char *)req->outbuf,
273                         IS_CONN_ENCRYPTED(blr->fsp->conn))) {
274                 exit_server_cleanly("send_blocking_reply: srv_send_smb failed.");
275         }
276 }
277
278 /****************************************************************************
279  Return a generic lock fail error blocking call.
280 *****************************************************************************/
281
282 static void generic_blocking_lock_error(blocking_lock_record *blr, NTSTATUS status)
283 {
284         char outbuf[smb_size];
285         char *inbuf = blr->inbuf;
286
287         construct_reply_common(inbuf, outbuf);
288
289         /* whenever a timeout is given w2k maps LOCK_NOT_GRANTED to
290            FILE_LOCK_CONFLICT! (tridge) */
291         if (NT_STATUS_EQUAL(status, NT_STATUS_LOCK_NOT_GRANTED)) {
292                 status = NT_STATUS_FILE_LOCK_CONFLICT;
293         }
294
295         if (NT_STATUS_EQUAL(status, NT_STATUS_FILE_LOCK_CONFLICT)) {
296                 /* Store the last lock error. */
297                 files_struct *fsp = blr->fsp;
298
299                 if (fsp) {
300                         fsp->last_lock_failure.context.smbpid = blr->lock_pid;
301                         fsp->last_lock_failure.context.tid = fsp->conn->cnum;
302                         fsp->last_lock_failure.context.pid = procid_self();
303                         fsp->last_lock_failure.start = blr->offset;
304                         fsp->last_lock_failure.size = blr->count;
305                         fsp->last_lock_failure.fnum = fsp->fnum;
306                         fsp->last_lock_failure.lock_type = READ_LOCK; /* Don't care. */
307                         fsp->last_lock_failure.lock_flav = blr->lock_flav;
308                 }
309         }
310
311         ERROR_NT(status);
312         if (!srv_send_smb(smbd_server_fd(),outbuf, blr->encrypted)) {
313                 exit_server_cleanly("generic_blocking_lock_error: srv_send_smb failed.");
314         }
315 }
316
317 /****************************************************************************
318  Return a lock fail error for a lockingX call. Undo all the locks we have 
319  obtained first.
320 *****************************************************************************/
321
322 static void reply_lockingX_error(blocking_lock_record *blr, NTSTATUS status)
323 {
324         char *inbuf = blr->inbuf;
325         files_struct *fsp = blr->fsp;
326         uint16 num_ulocks = SVAL(inbuf,smb_vwv6);
327         uint64_t count = (uint64_t)0, offset = (uint64_t) 0;
328         uint32 lock_pid;
329         unsigned char locktype = CVAL(inbuf,smb_vwv3);
330         bool large_file_format = (locktype & LOCKING_ANDX_LARGE_FILES);
331         uint8_t *data;
332         int i;
333
334         data = (uint8_t *)smb_buf(inbuf)
335                 + ((large_file_format ? 20 : 10)*num_ulocks);
336
337         /* 
338          * Data now points at the beginning of the list
339          * of smb_lkrng structs.
340          */
341
342         /*
343          * Ensure we don't do a remove on the lock that just failed,
344          * as under POSIX rules, if we have a lock already there, we
345          * will delete it (and we shouldn't) .....
346          */
347
348         for(i = blr->lock_num - 1; i >= 0; i--) {
349                 bool err;
350
351                 lock_pid = get_lock_pid( data, i, large_file_format);
352                 count = get_lock_count( data, i, large_file_format);
353                 offset = get_lock_offset( data, i, large_file_format, &err);
354
355                 /*
356                  * We know err cannot be set as if it was the lock
357                  * request would never have been queued. JRA.
358                  */
359
360                 do_unlock(smbd_messaging_context(),
361                         fsp,
362                         lock_pid,
363                         count,
364                         offset,
365                         WINDOWS_LOCK);
366         }
367
368         generic_blocking_lock_error(blr, status);
369 }
370
371 /****************************************************************************
372  Return a lock fail error.
373 *****************************************************************************/
374
375 static void blocking_lock_reply_error(blocking_lock_record *blr, NTSTATUS status)
376 {
377         switch(blr->com_type) {
378         case SMBlockingX:
379                 reply_lockingX_error(blr, status);
380                 break;
381         case SMBtrans2:
382         case SMBtranss2:
383                 {
384                         char outbuf[smb_size];
385                         char *inbuf = blr->inbuf;
386                         construct_reply_common(inbuf, outbuf);
387                         /* construct_reply_common has done us the favor to pre-fill the
388                          * command field with SMBtranss2 which is wrong :-)
389                          */
390                         SCVAL(outbuf,smb_com,SMBtrans2);
391                         ERROR_NT(status);
392                         if (!srv_send_smb(smbd_server_fd(),
393                                         outbuf,
394                                         IS_CONN_ENCRYPTED(blr->fsp->conn))) {
395                                 exit_server_cleanly("blocking_lock_reply_error: srv_send_smb failed.");
396                         }
397                         break;
398                 }
399         default:
400                 DEBUG(0,("blocking_lock_reply_error: PANIC - unknown type on blocking lock queue - exiting.!\n"));
401                 exit_server("PANIC - unknown type on blocking lock queue");
402         }
403 }
404
405 /****************************************************************************
406  Attempt to finish off getting all pending blocking locks for a lockingX call.
407  Returns True if we want to be removed from the list.
408 *****************************************************************************/
409
410 static bool process_lockingX(blocking_lock_record *blr)
411 {
412         char *inbuf = blr->inbuf;
413         unsigned char locktype = CVAL(inbuf,smb_vwv3);
414         files_struct *fsp = blr->fsp;
415         uint16 num_ulocks = SVAL(inbuf,smb_vwv6);
416         uint16 num_locks = SVAL(inbuf,smb_vwv7);
417         uint64_t count = (uint64_t)0, offset = (uint64_t)0;
418         uint32 lock_pid;
419         bool large_file_format = (locktype & LOCKING_ANDX_LARGE_FILES);
420         uint8_t *data;
421         NTSTATUS status = NT_STATUS_OK;
422
423         data = (uint8_t *)smb_buf(inbuf)
424                 + ((large_file_format ? 20 : 10)*num_ulocks);
425
426         /* 
427          * Data now points at the beginning of the list
428          * of smb_lkrng structs.
429          */
430
431         for(; blr->lock_num < num_locks; blr->lock_num++) {
432                 struct byte_range_lock *br_lck = NULL;
433                 bool err;
434
435                 lock_pid = get_lock_pid( data, blr->lock_num, large_file_format);
436                 count = get_lock_count( data, blr->lock_num, large_file_format);
437                 offset = get_lock_offset( data, blr->lock_num, large_file_format, &err);
438
439                 /*
440                  * We know err cannot be set as if it was the lock
441                  * request would never have been queued. JRA.
442                  */
443                 errno = 0;
444                 br_lck = do_lock(smbd_messaging_context(),
445                                 fsp,
446                                 lock_pid,
447                                 count,
448                                 offset, 
449                                 ((locktype & LOCKING_ANDX_SHARED_LOCK) ?
450                                         READ_LOCK : WRITE_LOCK),
451                                 WINDOWS_LOCK,
452                                 True,
453                                 &status,
454                                 &blr->blocking_pid);
455
456                 TALLOC_FREE(br_lck);
457
458                 if (NT_STATUS_IS_ERR(status)) {
459                         break;
460                 }
461         }
462
463         if(blr->lock_num == num_locks) {
464                 /*
465                  * Success - we got all the locks.
466                  */
467
468                 DEBUG(3,("process_lockingX file = %s, fnum=%d type=%d num_locks=%d\n",
469                          fsp->fsp_name, fsp->fnum, (unsigned int)locktype, num_locks) );
470
471                 reply_lockingX_success(blr);
472                 return True;
473         } else if (!NT_STATUS_EQUAL(status,NT_STATUS_LOCK_NOT_GRANTED) &&
474                         !NT_STATUS_EQUAL(status,NT_STATUS_FILE_LOCK_CONFLICT)) {
475                         /*
476                          * We have other than a "can't get lock"
477                          * error. Free any locks we had and return an error.
478                          * Return True so we get dequeued.
479                          */
480
481                 blocking_lock_reply_error(blr, status);
482                 return True;
483         }
484
485         /*
486          * Still can't get all the locks - keep waiting.
487          */
488
489         DEBUG(10,("process_lockingX: only got %d locks of %d needed for file %s, fnum = %d. \
490 Waiting....\n", 
491                   blr->lock_num, num_locks, fsp->fsp_name, fsp->fnum));
492
493         return False;
494 }
495
496 /****************************************************************************
497  Attempt to get the posix lock request from a SMBtrans2 call.
498  Returns True if we want to be removed from the list.
499 *****************************************************************************/
500
501 static bool process_trans2(blocking_lock_record *blr)
502 {
503         struct smb_request *req;
504         char params[2];
505         NTSTATUS status;
506         struct byte_range_lock *br_lck = do_lock(smbd_messaging_context(),
507                                                 blr->fsp,
508                                                 blr->lock_pid,
509                                                 blr->count,
510                                                 blr->offset,
511                                                 blr->lock_type,
512                                                 blr->lock_flav,
513                                                 True,
514                                                 &status,
515                                                 &blr->blocking_pid);
516         TALLOC_FREE(br_lck);
517
518         if (!NT_STATUS_IS_OK(status)) {
519                 if (ERROR_WAS_LOCK_DENIED(status)) {
520                         /* Still can't get the lock, just keep waiting. */
521                         return False;
522                 }       
523                 /*
524                  * We have other than a "can't get lock"
525                  * error. Send an error and return True so we get dequeued.
526                  */
527                 blocking_lock_reply_error(blr, status);
528                 return True;
529         }
530
531         /* We finally got the lock, return success. */
532
533         if (!(req = talloc(talloc_tos(), struct smb_request))) {
534                 blocking_lock_reply_error(blr, NT_STATUS_NO_MEMORY);
535                 return True;
536         }
537
538         init_smb_request(req, (uint8 *)blr->inbuf, 0, blr->encrypted);
539         req->inbuf = (uint8_t *)(blr->inbuf);
540
541         SCVAL(req->inbuf, smb_com, SMBtrans2);
542         SSVAL(params,0,0);
543         /* Fake up max_data_bytes here - we know it fits. */
544         send_trans2_replies(blr->fsp->conn, req, params, 2, NULL, 0, 0xffff);
545         return True;
546 }
547
548
549 /****************************************************************************
550  Process a blocking lock SMB.
551  Returns True if we want to be removed from the list.
552 *****************************************************************************/
553
554 static bool blocking_lock_record_process(blocking_lock_record *blr)
555 {
556         switch(blr->com_type) {
557                 case SMBlockingX:
558                         return process_lockingX(blr);
559                 case SMBtrans2:
560                 case SMBtranss2:
561                         return process_trans2(blr);
562                 default:
563                         DEBUG(0,("blocking_lock_record_process: PANIC - unknown type on blocking lock queue - exiting.!\n"));
564                         exit_server("PANIC - unknown type on blocking lock queue");
565         }
566         return False; /* Keep compiler happy. */
567 }
568
569 /****************************************************************************
570  Cancel entries by fnum from the blocking lock pending queue.
571 *****************************************************************************/
572
573 void cancel_pending_lock_requests_by_fid(files_struct *fsp, struct byte_range_lock *br_lck)
574 {
575         blocking_lock_record *blr, *next = NULL;
576
577         for(blr = blocking_lock_queue; blr; blr = next) {
578                 unsigned char locktype = 0;
579
580                 next = blr->next;
581                 if (blr->fsp->fnum != fsp->fnum) {
582                         continue;
583                 }
584
585                 if (blr->com_type == SMBlockingX) {
586                         locktype = CVAL(blr->inbuf,smb_vwv3);
587                 }
588
589                 if (br_lck) {
590                         DEBUG(10, ("remove_pending_lock_requests_by_fid - "
591                                    "removing request type %d for file %s fnum "
592                                    "= %d\n", blr->com_type, fsp->fsp_name,
593                                    fsp->fnum));
594
595                         brl_lock_cancel(br_lck,
596                                         blr->lock_pid,
597                                         procid_self(),
598                                         blr->offset,
599                                         blr->count,
600                                         blr->lock_flav);
601
602                         blocking_lock_cancel(fsp,
603                                              blr->lock_pid,
604                                              blr->offset,
605                                              blr->count,
606                                              blr->lock_flav,
607                                              locktype,
608                                              NT_STATUS_RANGE_NOT_LOCKED);
609                 }
610                 /* We're closing the file fsp here, so ensure
611                  * we don't have a dangling pointer. */
612                 blr->fsp = NULL;
613         }
614 }
615
616 /****************************************************************************
617  Delete entries by mid from the blocking lock pending queue. Always send reply.
618 *****************************************************************************/
619
620 void remove_pending_lock_requests_by_mid(int mid)
621 {
622         blocking_lock_record *blr, *next = NULL;
623
624         for(blr = blocking_lock_queue; blr; blr = next) {
625                 next = blr->next;
626                 if(SVAL(blr->inbuf,smb_mid) == mid) {
627                         files_struct *fsp = blr->fsp;
628                         struct byte_range_lock *br_lck = brl_get_locks(talloc_tos(), fsp);
629
630                         if (br_lck) {
631                                 DEBUG(10,("remove_pending_lock_requests_by_mid - removing request type %d for \
632 file %s fnum = %d\n", blr->com_type, fsp->fsp_name, fsp->fnum ));
633
634                                 brl_lock_cancel(br_lck,
635                                         blr->lock_pid,
636                                         procid_self(),
637                                         blr->offset,
638                                         blr->count,
639                                         blr->lock_flav);
640                                 TALLOC_FREE(br_lck);
641                         }
642
643                         blocking_lock_reply_error(blr,NT_STATUS_FILE_LOCK_CONFLICT);
644                         DLIST_REMOVE(blocking_lock_queue, blr);
645                         TALLOC_FREE(blr);
646                 }
647         }
648 }
649
650 /****************************************************************************
651  Is this mid a blocking lock request on the queue ?
652 *****************************************************************************/
653
654 bool blocking_lock_was_deferred(int mid)
655 {
656         blocking_lock_record *blr, *next = NULL;
657
658         for(blr = blocking_lock_queue; blr; blr = next) {
659                 next = blr->next;
660                 if(SVAL(blr->inbuf,smb_mid) == mid) {
661                         return True;
662                 }
663         }
664         return False;
665 }
666
667 /****************************************************************************
668   Set a flag as an unlock request affects one of our pending locks.
669 *****************************************************************************/
670
671 static void received_unlock_msg(struct messaging_context *msg,
672                                 void *private_data,
673                                 uint32_t msg_type,
674                                 struct server_id server_id,
675                                 DATA_BLOB *data)
676 {
677         DEBUG(10,("received_unlock_msg\n"));
678         process_blocking_lock_queue();
679 }
680
681 /****************************************************************************
682  Process the blocking lock queue. Note that this is only called as root.
683 *****************************************************************************/
684
685 static void process_blocking_lock_queue(void)
686 {
687         struct timeval tv_curr = timeval_current();
688         blocking_lock_record *blr, *next = NULL;
689         bool recalc_timeout = False;
690
691         /*
692          * Go through the queue and see if we can get any of the locks.
693          */
694
695         for (blr = blocking_lock_queue; blr; blr = next) {
696                 connection_struct *conn = NULL;
697                 uint16 vuid;
698                 files_struct *fsp = NULL;
699
700                 next = blr->next;
701
702                 /*
703                  * Ensure we don't have any old chain_fsp values
704                  * sitting around....
705                  */
706                 chain_size = 0;
707                 fsp = blr->fsp;
708
709                 conn = conn_find(SVAL(blr->inbuf,smb_tid));
710                 vuid = (lp_security() == SEC_SHARE) ? UID_FIELD_INVALID :
711                                 SVAL(blr->inbuf,smb_uid);
712
713                 DEBUG(5,("process_blocking_lock_queue: examining pending lock fnum = %d for file %s\n",
714                         fsp->fnum, fsp->fsp_name ));
715
716                 if(!change_to_user(conn,vuid)) {
717                         struct byte_range_lock *br_lck = brl_get_locks(talloc_tos(), fsp);
718
719                         /*
720                          * Remove the entry and return an error to the client.
721                          */
722
723                         if (br_lck) {
724                                 brl_lock_cancel(br_lck,
725                                         blr->lock_pid,
726                                         procid_self(),
727                                         blr->offset,
728                                         blr->count,
729                                         blr->lock_flav);
730                                 TALLOC_FREE(br_lck);
731                         }
732
733                         DEBUG(0,("process_blocking_lock_queue: Unable to become user vuid=%d.\n",
734                                 vuid ));
735                         blocking_lock_reply_error(blr,NT_STATUS_ACCESS_DENIED);
736                         DLIST_REMOVE(blocking_lock_queue, blr);
737                         TALLOC_FREE(blr);
738                         recalc_timeout = True;
739                         continue;
740                 }
741
742                 if(!set_current_service(conn,SVAL(blr->inbuf,smb_flg),True)) {
743                         struct byte_range_lock *br_lck = brl_get_locks(talloc_tos(), fsp);
744
745                         /*
746                          * Remove the entry and return an error to the client.
747                          */
748
749                         if (br_lck) {
750                                 brl_lock_cancel(br_lck,
751                                         blr->lock_pid,
752                                         procid_self(),
753                                         blr->offset,
754                                         blr->count,
755                                         blr->lock_flav);
756                                 TALLOC_FREE(br_lck);
757                         }
758
759                         DEBUG(0,("process_blocking_lock_queue: Unable to become service Error was %s.\n", strerror(errno) ));
760                         blocking_lock_reply_error(blr,NT_STATUS_ACCESS_DENIED);
761                         DLIST_REMOVE(blocking_lock_queue, blr);
762                         TALLOC_FREE(blr);
763                         recalc_timeout = True;
764                         change_to_root_user();
765                         continue;
766                 }
767
768                 /*
769                  * Go through the remaining locks and try and obtain them.
770                  * The call returns True if all locks were obtained successfully
771                  * and False if we still need to wait.
772                  */
773
774                 if(blocking_lock_record_process(blr)) {
775                         struct byte_range_lock *br_lck = brl_get_locks(talloc_tos(), fsp);
776
777                         if (br_lck) {
778                                 brl_lock_cancel(br_lck,
779                                         blr->lock_pid,
780                                         procid_self(),
781                                         blr->offset,
782                                         blr->count,
783                                         blr->lock_flav);
784                                 TALLOC_FREE(br_lck);
785                         }
786
787                         DLIST_REMOVE(blocking_lock_queue, blr);
788                         TALLOC_FREE(blr);
789                         recalc_timeout = True;
790                         change_to_root_user();
791                         continue;
792                 }
793
794                 change_to_root_user();
795
796                 /*
797                  * We couldn't get the locks for this record on the list.
798                  * If the time has expired, return a lock error.
799                  */
800
801                 if (!timeval_is_zero(&blr->expire_time) && timeval_compare(&blr->expire_time, &tv_curr) <= 0) {
802                         struct byte_range_lock *br_lck = brl_get_locks(talloc_tos(), fsp);
803
804                         /*
805                          * Lock expired - throw away all previously
806                          * obtained locks and return lock error.
807                          */
808
809                         if (br_lck) {
810                                 DEBUG(5,("process_blocking_lock_queue: pending lock fnum = %d for file %s timed out.\n",
811                                         fsp->fnum, fsp->fsp_name ));
812
813                                 brl_lock_cancel(br_lck,
814                                         blr->lock_pid,
815                                         procid_self(),
816                                         blr->offset,
817                                         blr->count,
818                                         blr->lock_flav);
819                                 TALLOC_FREE(br_lck);
820                         }
821
822                         blocking_lock_reply_error(blr,NT_STATUS_FILE_LOCK_CONFLICT);
823                         DLIST_REMOVE(blocking_lock_queue, blr);
824                         TALLOC_FREE(blr);
825                         recalc_timeout = True;
826                 }
827         }
828
829         if (recalc_timeout) {
830                 recalc_brl_timeout();
831         }
832 }
833
834 /****************************************************************************
835  Handle a cancel message. Lock already moved onto the cancel queue.
836 *****************************************************************************/
837
838 #define MSG_BLOCKING_LOCK_CANCEL_SIZE (sizeof(blocking_lock_record *) + sizeof(NTSTATUS))
839
840 static void process_blocking_lock_cancel_message(struct messaging_context *ctx,
841                                                  void *private_data,
842                                                  uint32_t msg_type,
843                                                  struct server_id server_id,
844                                                  DATA_BLOB *data)
845 {
846         NTSTATUS err;
847         const char *msg = (const char *)data->data;
848         blocking_lock_record *blr;
849
850         if (data->data == NULL) {
851                 smb_panic("process_blocking_lock_cancel_message: null msg");
852         }
853
854         if (data->length != MSG_BLOCKING_LOCK_CANCEL_SIZE) {
855                 DEBUG(0, ("process_blocking_lock_cancel_message: "
856                           "Got invalid msg len %d\n", (int)data->length));
857                 smb_panic("process_blocking_lock_cancel_message: bad msg");
858         }
859
860         memcpy(&blr, msg, sizeof(blr));
861         memcpy(&err, &msg[sizeof(blr)], sizeof(NTSTATUS));
862
863         DEBUG(10,("process_blocking_lock_cancel_message: returning error %s\n",
864                 nt_errstr(err) ));
865
866         blocking_lock_reply_error(blr, err);
867         DLIST_REMOVE(blocking_lock_cancelled_queue, blr);
868         TALLOC_FREE(blr);
869 }
870
871 /****************************************************************************
872  Send ourselves a blocking lock cancelled message. Handled asynchronously above.
873 *****************************************************************************/
874
875 bool blocking_lock_cancel(files_struct *fsp,
876                         uint32 lock_pid,
877                         uint64_t offset,
878                         uint64_t count,
879                         enum brl_flavour lock_flav,
880                         unsigned char locktype,
881                         NTSTATUS err)
882 {
883         static bool initialized;
884         char msg[MSG_BLOCKING_LOCK_CANCEL_SIZE];
885         blocking_lock_record *blr;
886
887         if (!initialized) {
888                 /* Register our message. */
889                 messaging_register(smbd_messaging_context(), NULL,
890                                    MSG_SMB_BLOCKING_LOCK_CANCEL,
891                                    process_blocking_lock_cancel_message);
892
893                 initialized = True;
894         }
895
896         for (blr = blocking_lock_queue; blr; blr = blr->next) {
897                 if (fsp == blr->fsp &&
898                                 lock_pid == blr->lock_pid &&
899                                 offset == blr->offset &&
900                                 count == blr->count &&
901                                 lock_flav == blr->lock_flav) {
902                         break;
903                 }
904         }
905
906         if (!blr) {
907                 return False;
908         }
909
910         /* Check the flags are right. */
911         if (blr->com_type == SMBlockingX &&
912                 (locktype & LOCKING_ANDX_LARGE_FILES) !=
913                         (CVAL(blr->inbuf,smb_vwv3) & LOCKING_ANDX_LARGE_FILES)) {
914                 return False;
915         }
916
917         /* Move to cancelled queue. */
918         DLIST_REMOVE(blocking_lock_queue, blr);
919         DLIST_ADD(blocking_lock_cancelled_queue, blr);
920
921         /* Create the message. */
922         memcpy(msg, &blr, sizeof(blr));
923         memcpy(&msg[sizeof(blr)], &err, sizeof(NTSTATUS));
924
925         messaging_send_buf(smbd_messaging_context(), procid_self(),
926                            MSG_SMB_BLOCKING_LOCK_CANCEL,
927                            (uint8 *)&msg, sizeof(msg));
928
929         return True;
930 }