first pass at updating head branch to be to be the same as the SAMBA_2_0 branch
[nivanova/samba-autobuild/.git] / source3 / smbd / oplock.c
1 /* 
2    Unix SMB/Netbios implementation.
3    Version 1.9.
4    oplock processing
5    Copyright (C) Andrew Tridgell 1992-1998
6    
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 */
21
22 #include "includes.h"
23
24 extern int DEBUGLEVEL;
25
26 /* Oplock ipc UDP socket. */
27 static int oplock_sock = -1;
28 uint16 global_oplock_port = 0;
29 static int oplock_pipe_read = -1;
30
31 #if defined(HAVE_KERNEL_OPLOCKS)
32 static int oplock_pipe_write = -1;
33 #endif
34
35 /* Current number of oplocks we have outstanding. */
36 static int32 exclusive_oplocks_open = 0;
37 static int32 level_II_oplocks_open = 0;
38 BOOL global_client_failed_oplock_break = False;
39 BOOL global_oplock_break = False;
40
41 extern int smb_read_error;
42
43 static BOOL oplock_break(SMB_DEV_T dev, SMB_INO_T inode, struct timeval *tval, BOOL local);
44
45 /****************************************************************************
46  Get the number of current exclusive oplocks.
47 ****************************************************************************/
48
49 int32 get_number_of_exclusive_open_oplocks(void)
50 {
51   return exclusive_oplocks_open;
52 }
53
54 /****************************************************************************
55  Setup the kernel level oplock backchannel for this process.
56 ****************************************************************************/
57
58 BOOL setup_kernel_oplock_pipe(void)
59 {
60 #if defined(HAVE_KERNEL_OPLOCKS)
61   if(lp_kernel_oplocks()) {
62     int pfd[2];
63
64     if(pipe(pfd) != 0) {
65       DEBUG(0,("setup_kernel_oplock_pipe: Unable to create pipe. Error was %s\n",
66             strerror(errno) ));
67       return False;
68     }
69
70     oplock_pipe_read = pfd[0];
71     oplock_pipe_write = pfd[1];
72   }
73 #endif /* HAVE_KERNEL_OPLOCKS */
74   return True;
75 }
76
77 /****************************************************************************
78  Open the oplock IPC socket communication.
79 ****************************************************************************/
80
81 BOOL open_oplock_ipc(void)
82 {
83   struct sockaddr_in sock_name;
84   int len = sizeof(sock_name);
85
86   DEBUG(3,("open_oplock_ipc: opening loopback UDP socket.\n"));
87
88   /* Open a lookback UDP socket on a random port. */
89   oplock_sock = open_socket_in(SOCK_DGRAM, 0, 0, htonl(INADDR_LOOPBACK),False);
90   if (oplock_sock == -1)
91   {
92     DEBUG(0,("open_oplock_ipc: Failed to get local UDP socket for \
93 address %lx. Error was %s\n", (long)htonl(INADDR_LOOPBACK), strerror(errno)));
94     global_oplock_port = 0;
95     return(False);
96   }
97
98   /* Find out the transient UDP port we have been allocated. */
99   if(getsockname(oplock_sock, (struct sockaddr *)&sock_name, &len)<0)
100   {
101     DEBUG(0,("open_oplock_ipc: Failed to get local UDP port. Error was %s\n",
102             strerror(errno)));
103     close(oplock_sock);
104     oplock_sock = -1;
105     global_oplock_port = 0;
106     return False;
107   }
108   global_oplock_port = ntohs(sock_name.sin_port);
109
110   if(!setup_kernel_oplock_pipe())
111     return False;
112
113   DEBUG(3,("open_oplock ipc: pid = %d, global_oplock_port = %u\n", 
114             (int)getpid(), global_oplock_port));
115
116   return True;
117 }
118
119 /****************************************************************************
120  Read an oplock break message from the either the oplock UDP fd
121  or the kernel oplock pipe fd (if kernel oplocks are supported).
122
123  If timeout is zero then *fds contains the file descriptors that
124  are ready to be read and acted upon. If timeout is non-zero then
125  *fds contains the file descriptors to be selected on for read.
126  The timeout is in milliseconds
127
128 ****************************************************************************/
129
130 BOOL receive_local_message(fd_set *fds, char *buffer, int buffer_len, int timeout)
131 {
132   struct sockaddr_in from;
133   int fromlen = sizeof(from);
134   int32 msg_len = 0;
135
136   smb_read_error = 0;
137
138   if(timeout != 0) {
139     struct timeval to;
140     int selrtn;
141     int maxfd = oplock_sock;
142
143     if(lp_kernel_oplocks() && (oplock_pipe_read != -1))
144       maxfd = MAX(maxfd, oplock_pipe_read);
145
146     to.tv_sec = timeout / 1000;
147     to.tv_usec = (timeout % 1000) * 1000;
148
149     selrtn = sys_select(maxfd+1,fds,&to);
150
151     /* Check if error */
152     if(selrtn == -1) {
153       /* something is wrong. Maybe the socket is dead? */
154       smb_read_error = READ_ERROR;
155       return False;
156     }
157
158     /* Did we timeout ? */
159     if (selrtn == 0) {
160       smb_read_error = READ_TIMEOUT;
161       return False;
162     }
163   }
164
165 #if defined(HAVE_KERNEL_OPLOCKS)
166   if(FD_ISSET(oplock_pipe_read,fds)) {
167     /*
168      * Deal with the kernel <--> smbd
169      * oplock break protocol.
170      */
171
172     oplock_stat_t os;
173     SMB_DEV_T dev;
174     SMB_INO_T inode;
175     char dummy;
176
177     /*
178      * Read one byte of zero to clear the
179      * kernel break notify message.
180      */
181
182     if(read(oplock_pipe_read, &dummy, 1) != 1) {
183       DEBUG(0,("receive_local_message: read of kernel notification failed. \
184 Error was %s.\n", strerror(errno) ));
185       smb_read_error = READ_ERROR;
186       return False;
187     }
188
189     /*
190      * Do a query to get the
191      * device and inode of the file that has the break
192      * request outstanding.
193      */
194
195     if(fcntl(oplock_pipe_read, F_OPLKSTAT, &os) < 0) {
196       DEBUG(0,("receive_local_message: fcntl of kernel notification failed. \
197 Error was %s.\n", strerror(errno) ));
198       if(errno == EAGAIN) {
199         /*
200          * Duplicate kernel break message - ignore.
201          */
202         memset(buffer, '\0', KERNEL_OPLOCK_BREAK_MSG_LEN);
203         return True;
204       }
205       smb_read_error = READ_ERROR;
206       return False;
207     }
208
209     dev = (SMB_DEV_T)os.os_dev;
210     inode = (SMB_INO_T)os.os_ino;
211
212     DEBUG(5,("receive_local_message: kernel oplock break request received for \
213 dev = %x, inode = %.0f\n", (unsigned int)dev, (double)inode ));
214
215     /*
216      * Create a kernel oplock break message.
217      */
218
219     /* Setup the message header */
220     SIVAL(buffer,OPBRK_CMD_LEN_OFFSET,KERNEL_OPLOCK_BREAK_MSG_LEN);
221     SSVAL(buffer,OPBRK_CMD_PORT_OFFSET,0);
222
223     buffer += OPBRK_CMD_HEADER_LEN;
224
225     SSVAL(buffer,OPBRK_MESSAGE_CMD_OFFSET,KERNEL_OPLOCK_BREAK_CMD);
226
227     memcpy(buffer + KERNEL_OPLOCK_BREAK_DEV_OFFSET, (char *)&dev, sizeof(dev));
228     memcpy(buffer + KERNEL_OPLOCK_BREAK_INODE_OFFSET, (char *)&inode, sizeof(inode));   
229
230     return True;
231   }
232 #endif /* HAVE_KERNEL_OPLOCKS */
233
234   /*
235    * From here down we deal with the smbd <--> smbd
236    * oplock break protocol only.
237    */
238
239   /*
240    * Read a loopback udp message.
241    */
242   msg_len = recvfrom(oplock_sock, &buffer[OPBRK_CMD_HEADER_LEN],
243                      buffer_len - OPBRK_CMD_HEADER_LEN, 0,
244                      (struct sockaddr *)&from, &fromlen);
245
246   if(msg_len < 0) {
247     DEBUG(0,("receive_local_message. Error in recvfrom. (%s).\n",strerror(errno)));
248     return False;
249   }
250
251   /* Validate message length. */
252   if(msg_len > (buffer_len - OPBRK_CMD_HEADER_LEN)) {
253     DEBUG(0,("receive_local_message: invalid msg_len (%d) max can be %d\n",
254               msg_len,
255               buffer_len  - OPBRK_CMD_HEADER_LEN));
256     return False;
257   }
258
259   /* Validate message from address (must be localhost). */
260   if(from.sin_addr.s_addr != htonl(INADDR_LOOPBACK)) {
261     DEBUG(0,("receive_local_message: invalid 'from' address \
262 (was %lx should be 127.0.0.1\n", (long)from.sin_addr.s_addr));
263    return False;
264   }
265
266   /* Setup the message header */
267   SIVAL(buffer,OPBRK_CMD_LEN_OFFSET,msg_len);
268   SSVAL(buffer,OPBRK_CMD_PORT_OFFSET,ntohs(from.sin_port));
269
270   return True;
271 }
272
273 /****************************************************************************
274  Attempt to set an kernel oplock on a file. Always returns True if kernel
275  oplocks not available.
276 ****************************************************************************/
277
278 static BOOL set_kernel_oplock(files_struct *fsp, int oplock_type)
279 {
280 #if defined(HAVE_KERNEL_OPLOCKS)
281   if(lp_kernel_oplocks()) {
282
283     if(fcntl(fsp->fd_ptr->fd, F_OPLKREG, oplock_pipe_write) < 0 ) {
284       if(errno != EAGAIN) {
285         DEBUG(0,("set_file_oplock: Unable to get kernel oplock on file %s, dev = %x, \
286 inode = %.0f. Error was %s\n", 
287               fsp->fsp_name, (unsigned int)fsp->fd_ptr->dev, (double)fsp->fd_ptr->inode,
288                strerror(errno) ));
289       } else {
290         DEBUG(5,("set_file_oplock: Refused oplock on file %s, fd = %d, dev = %x, \
291 inode = %.0f. Another process had the file open.\n",
292               fsp->fsp_name, fsp->fd_ptr->fd, (unsigned int)fsp->fd_ptr->dev, (double)fsp->fd_ptr->inode ));
293       }
294       return False;
295     }
296
297     DEBUG(10,("set_file_oplock: got kernel oplock on file %s, dev = %x, inode = %.0f\n",
298           fsp->fsp_name, (unsigned int)fsp->fd_ptr->dev, (double)fsp->fd_ptr->inode));
299
300   }
301 #endif /* HAVE_KERNEL_OPLOCKS */
302   return True;
303 }
304
305 /****************************************************************************
306  Attempt to set an oplock on a file. Always succeeds if kernel oplocks are
307  disabled (just sets flags). Returns True if oplock set.
308 ****************************************************************************/
309
310 BOOL set_file_oplock(files_struct *fsp, int oplock_type)
311 {
312   if (!set_kernel_oplock(fsp, oplock_type))
313     return False;
314
315   fsp->oplock_type = oplock_type;
316   fsp->sent_oplock_break = NO_BREAK_SENT;
317   if ( oplock_type == LEVEL_II_OPLOCK)
318     level_II_oplocks_open++;
319   else
320     exclusive_oplocks_open++;
321
322   DEBUG(5,("set_file_oplock: granted oplock on file %s, dev = %x, inode = %.0f, tv_sec = %x, tv_usec = %x\n",
323         fsp->fsp_name, (unsigned int)fsp->fd_ptr->dev, (double)fsp->fd_ptr->inode,
324         (int)fsp->open_time.tv_sec, (int)fsp->open_time.tv_usec ));
325
326   return True;
327 }
328
329 /****************************************************************************
330  Release a kernel oplock on a file.
331 ****************************************************************************/
332
333 static void release_kernel_oplock(files_struct *fsp)
334 {
335 #if defined(HAVE_KERNEL_OPLOCKS)
336
337   if(lp_kernel_oplocks())
338   {
339     if( DEBUGLVL( 10 ))
340     {
341       /*
342        * Check and print out the current kernel
343        * oplock state of this file.
344        */
345       int state = fcntl(fsp->fd_ptr->fd, F_OPLKACK, -1);
346       dbgtext("release_kernel_oplock: file %s, dev = %x, inode = %.0f has kernel \
347 oplock state of %x.\n", fsp->fsp_name, (unsigned int)fsp->fd_ptr->dev,
348                         (double)fsp->fd_ptr->inode, state );
349     }
350
351     /*
352      * Remove the kernel oplock on this file.
353      */
354
355     if(fcntl(fsp->fd_ptr->fd, F_OPLKACK, OP_REVOKE) < 0)
356     {
357       if( DEBUGLVL( 0 ))
358       {
359         dbgtext("release_kernel_oplock: Error when removing kernel oplock on file " );
360         dbgtext("%s, dev = %x, inode = %.0f. Error was %s\n",
361                  fsp->fsp_name, (unsigned int)fsp->fd_ptr->dev, 
362                  (double)fsp->fd_ptr->inode, strerror(errno) );
363       }
364     }
365   }
366 #endif /* HAVE_KERNEL_OPLOCKS */
367 }
368
369
370 /****************************************************************************
371  Attempt to release an oplock on a file. Decrements oplock count.
372 ****************************************************************************/
373
374 void release_file_oplock(files_struct *fsp)
375 {
376   release_kernel_oplock(fsp);
377
378   if (fsp->oplock_type == LEVEL_II_OPLOCK)
379     level_II_oplocks_open--;
380   else
381     exclusive_oplocks_open--;
382
383   fsp->oplock_type = NO_OPLOCK;
384   fsp->sent_oplock_break = NO_BREAK_SENT;
385
386   flush_write_cache(fsp, OPLOCK_RELEASE_FLUSH);
387 }
388
389 /****************************************************************************
390  Attempt to downgrade an oplock on a file. Doesn't decrement oplock count.
391 ****************************************************************************/
392
393 static void downgrade_file_oplock(files_struct *fsp)
394 {
395   release_kernel_oplock(fsp);
396   fsp->oplock_type = LEVEL_II_OPLOCK;
397   exclusive_oplocks_open--;
398   level_II_oplocks_open++;
399   fsp->sent_oplock_break = NO_BREAK_SENT;
400 }
401
402 /****************************************************************************
403  Remove a file oplock. Copes with level II and exclusive.
404  Locks then unlocks the share mode lock.
405 ****************************************************************************/
406
407 BOOL remove_oplock(files_struct *fsp)
408 {
409   int token;
410   SMB_DEV_T dev = fsp->fd_ptr->dev;
411   SMB_INO_T inode = fsp->fd_ptr->inode;
412   BOOL ret = True;
413
414   /* Remove the oplock flag from the sharemode. */
415   if (lock_share_entry(fsp->conn, dev, inode, &token) == False) {
416     DEBUG(0,("remove_oplock: failed to lock share entry for file %s\n",
417           fsp->fsp_name ));
418     ret = False;
419   }
420
421   if (fsp->sent_oplock_break == EXCLUSIVE_BREAK_SENT) {
422
423     /*
424      * Deal with a reply when a break-to-none was sent.
425      */
426
427     if(remove_share_oplock(token, fsp)==False) {
428       DEBUG(0,("remove_oplock: failed to remove share oplock for file %s fnum %d, \
429 dev = %x, inode = %.0f\n", fsp->fsp_name, fsp->fnum, (unsigned int)dev, (double)inode));
430       ret = False;
431     }
432
433     release_file_oplock(fsp);
434
435   } else {
436
437     /*
438      * Deal with a reply when a break-to-level II was sent.
439      */
440
441     if(downgrade_share_oplock(token, fsp)==False) {
442       DEBUG(0,("remove_oplock: failed to downgrade share oplock for file %s fnum %d, \
443 dev = %x, inode = %.0f\n", fsp->fsp_name, fsp->fnum, (unsigned int)dev, (double)inode));
444       ret = False;
445     }
446
447     downgrade_file_oplock(fsp);
448   }
449
450   unlock_share_entry(fsp->conn, dev, inode, token);
451   return ret;
452 }
453
454 /****************************************************************************
455  Setup the listening set of file descriptors for an oplock break
456  message either from the UDP socket or from the kernel. Returns the maximum
457  fd used.
458 ****************************************************************************/
459
460 int setup_oplock_select_set( fd_set *fds)
461 {
462   int maxfd = oplock_sock;
463
464   if(oplock_sock == -1)
465     return 0;
466
467   FD_SET(oplock_sock,fds);
468
469   if(lp_kernel_oplocks() && (oplock_pipe_read != -1)) {
470     FD_SET(oplock_pipe_read,fds); 
471     maxfd = MAX(maxfd,oplock_pipe_read);
472   }
473
474   return maxfd;
475 }
476
477 /****************************************************************************
478  Process an oplock break message - whether it came from the UDP socket
479  or from the kernel.
480 ****************************************************************************/
481
482 BOOL process_local_message(char *buffer, int buf_size)
483 {
484   int32 msg_len;
485   uint16 from_port;
486   char *msg_start;
487   SMB_DEV_T dev;
488   SMB_INO_T inode;
489   pid_t remotepid;
490   struct timeval tval;
491   struct timeval *ptval = NULL;
492   uint16 break_cmd_type;
493
494   msg_len = IVAL(buffer,OPBRK_CMD_LEN_OFFSET);
495   from_port = SVAL(buffer,OPBRK_CMD_PORT_OFFSET);
496
497   msg_start = &buffer[OPBRK_CMD_HEADER_LEN];
498
499   DEBUG(5,("process_local_message: Got a message of length %d from port (%d)\n", 
500             msg_len, from_port));
501
502   /* 
503    * Pull the info out of the requesting packet.
504    */
505
506   break_cmd_type = SVAL(msg_start,OPBRK_MESSAGE_CMD_OFFSET);
507
508   switch(break_cmd_type)
509   {
510 #if defined(HAVE_KERNEL_OPLOCKS)
511     case KERNEL_OPLOCK_BREAK_CMD:
512       /* Ensure that the msg length is correct. */
513       if(msg_len != KERNEL_OPLOCK_BREAK_MSG_LEN)
514       {
515         DEBUG(0,("process_local_message: incorrect length for KERNEL_OPLOCK_BREAK_CMD (was %d, \
516 should be %d).\n", msg_len, KERNEL_OPLOCK_BREAK_MSG_LEN));
517         return False;
518       }
519       {
520         memcpy((char *)&inode, msg_start+KERNEL_OPLOCK_BREAK_INODE_OFFSET, sizeof(inode));
521         memcpy((char *)&dev, msg_start+KERNEL_OPLOCK_BREAK_DEV_OFFSET, sizeof(dev));
522
523         ptval = NULL;
524
525         DEBUG(5,("process_local_message: kernel oplock break request for \
526 file dev = %x, inode = %.0f\n", (unsigned int)dev, (double)inode));
527       }
528       break;
529 #endif /* HAVE_KERNEL_OPLOCKS */
530
531     case OPLOCK_BREAK_CMD:
532     case LEVEL_II_OPLOCK_BREAK_CMD:
533
534       /* Ensure that the msg length is correct. */
535       if(msg_len != OPLOCK_BREAK_MSG_LEN)
536       {
537         DEBUG(0,("process_local_message: incorrect length for OPLOCK_BREAK_CMD (was %d, should be %d).\n",
538               (int)msg_len, (int)OPLOCK_BREAK_MSG_LEN));
539         return False;
540       }
541       {
542         long usec;
543         time_t sec;
544
545         memcpy((char *)&inode, msg_start+OPLOCK_BREAK_INODE_OFFSET,sizeof(inode));
546         memcpy((char *)&dev, msg_start+OPLOCK_BREAK_DEV_OFFSET,sizeof(dev));
547         memcpy((char *)&sec, msg_start+OPLOCK_BREAK_SEC_OFFSET,sizeof(sec));
548         tval.tv_sec = sec;
549         memcpy((char *)&usec, msg_start+OPLOCK_BREAK_USEC_OFFSET, sizeof(usec));
550         tval.tv_usec = usec;
551
552         ptval = &tval;
553
554         memcpy((char *)&remotepid, msg_start+OPLOCK_BREAK_PID_OFFSET,sizeof(remotepid));
555
556         DEBUG(5,("process_local_message: (%s) oplock break request from \
557 pid %d, port %d, dev = %x, inode = %.0f\n",
558              (break_cmd_type == OPLOCK_BREAK_CMD) ? "exclusive" : "level II",
559              (int)remotepid, from_port, (unsigned int)dev, (double)inode));
560       }
561       break;
562
563     /* 
564      * Keep this as a debug case - eventually we can remove it.
565      */
566     case 0x8001:
567       DEBUG(0,("process_local_message: Received unsolicited break \
568 reply - dumping info.\n"));
569
570       if(msg_len != OPLOCK_BREAK_MSG_LEN)
571       {
572         DEBUG(0,("process_local_message: ubr: incorrect length for reply \
573 (was %d, should be %d).\n", (int)msg_len, (int)OPLOCK_BREAK_MSG_LEN));
574         return False;
575       }
576
577       {
578         memcpy((char *)&inode, msg_start+OPLOCK_BREAK_INODE_OFFSET,sizeof(inode));
579         memcpy((char *)&remotepid, msg_start+OPLOCK_BREAK_PID_OFFSET,sizeof(remotepid));
580         memcpy((char *)&dev, msg_start+OPLOCK_BREAK_DEV_OFFSET,sizeof(dev));
581
582         DEBUG(0,("process_local_message: unsolicited oplock break reply from \
583 pid %d, port %d, dev = %x, inode = %.0f\n", (int)remotepid, from_port, (unsigned int)dev, (double)inode));
584
585        }
586        return False;
587
588     default:
589       DEBUG(0,("process_local_message: unknown UDP message command code (%x) - ignoring.\n",
590                 (unsigned int)SVAL(msg_start,0)));
591       return False;
592   }
593
594   /*
595    * Now actually process the break request.
596    */
597
598   if((exclusive_oplocks_open + level_II_oplocks_open) != 0)
599   {
600     if (oplock_break(dev, inode, ptval, False) == False)
601     {
602       DEBUG(0,("process_local_message: oplock break failed.\n"));
603       return False;
604     }
605   }
606   else
607   {
608     /*
609      * If we have no record of any currently open oplocks,
610      * it's not an error, as a close command may have
611      * just been issued on the file that was oplocked.
612      * Just log a message and return success in this case.
613      */
614     DEBUG(3,("process_local_message: oplock break requested with no outstanding \
615 oplocks. Returning success.\n"));
616   }
617
618   /* 
619    * Do the appropriate reply - none in the kernel or level II case.
620    */
621
622   if(SVAL(msg_start,OPBRK_MESSAGE_CMD_OFFSET) == OPLOCK_BREAK_CMD)
623   {
624     struct sockaddr_in toaddr;
625
626     /* Send the message back after OR'ing in the 'REPLY' bit. */
627     SSVAL(msg_start,OPBRK_MESSAGE_CMD_OFFSET,OPLOCK_BREAK_CMD | CMD_REPLY);
628
629     memset((char *)&toaddr,'\0',sizeof(toaddr));
630     toaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
631     toaddr.sin_port = htons(from_port);
632     toaddr.sin_family = AF_INET;
633
634     if(sendto( oplock_sock, msg_start, OPLOCK_BREAK_MSG_LEN, 0,
635             (struct sockaddr *)&toaddr, sizeof(toaddr)) < 0) 
636     {
637       DEBUG(0,("process_local_message: sendto process %d failed. Errno was %s\n",
638                 (int)remotepid, strerror(errno)));
639       return False;
640     }
641
642     DEBUG(5,("process_local_message: oplock break reply sent to \
643 pid %d, port %d, for file dev = %x, inode = %.0f\n",
644           (int)remotepid, from_port, (unsigned int)dev, (double)inode));
645   }
646
647   return True;
648 }
649
650 /****************************************************************************
651  Set up an oplock break message.
652 ****************************************************************************/
653
654 static void prepare_break_message(char *outbuf, files_struct *fsp, BOOL level2)
655 {
656   memset(outbuf,'\0',smb_size);
657   set_message(outbuf,8,0,True);
658
659   SCVAL(outbuf,smb_com,SMBlockingX);
660   SSVAL(outbuf,smb_tid,fsp->conn->cnum);
661   SSVAL(outbuf,smb_pid,0xFFFF);
662   SSVAL(outbuf,smb_uid,0);
663   SSVAL(outbuf,smb_mid,0xFFFF);
664   SCVAL(outbuf,smb_vwv0,0xFF);
665   SSVAL(outbuf,smb_vwv2,fsp->fnum);
666   SCVAL(outbuf,smb_vwv3,LOCKING_ANDX_OPLOCK_RELEASE);
667   SCVAL(outbuf,smb_vwv3+1,level2 ? OPLOCKLEVEL_II : OPLOCKLEVEL_NONE);
668 }
669
670 /****************************************************************************
671  Function to do the waiting before sending a local break.
672 ****************************************************************************/
673
674 static void wait_before_sending_break(BOOL local_request)
675 {
676   extern struct timeval smb_last_time;
677
678   if(local_request) {
679     struct timeval cur_tv;
680     long wait_left = (long)lp_oplock_break_wait_time();
681
682     GetTimeOfDay(&cur_tv);
683
684     wait_left -= ((cur_tv.tv_sec - smb_last_time.tv_sec)*1000) +
685                 ((cur_tv.tv_usec - smb_last_time.tv_usec)/1000);
686
687     if(wait_left > 0) {
688       wait_left = MIN(wait_left, 1000);
689       sys_usleep(wait_left * 1000);
690     }
691   }
692 }
693
694 /****************************************************************************
695  Ensure that we have a valid oplock.
696 ****************************************************************************/
697
698 static files_struct *initial_break_processing(SMB_DEV_T dev, SMB_INO_T inode, struct timeval *tval)
699 {
700   files_struct *fsp = NULL;
701
702   if( DEBUGLVL( 3 ) )
703   {
704     dbgtext( "initial_break_processing: called for dev = %x, inode = %.0f tv_sec = %x, tv_usec = %x.\n",
705       (unsigned int)dev, (double)inode, tval ? (int)tval->tv_sec : 0,
706       tval ? (int)tval->tv_usec : 0);
707     dbgtext( "Current oplocks_open (exclusive = %d, levelII = %d)\n",
708               exclusive_oplocks_open, level_II_oplocks_open );
709   }
710
711   /* We need to search the file open table for the
712      entry containing this dev and inode, and ensure
713      we have an oplock on it. */
714   fsp = file_find_dit(dev, inode, tval);
715
716   if(fsp == NULL)
717   {
718     /* The file could have been closed in the meantime - return success. */
719     if( DEBUGLVL( 3 ) )
720     {
721       dbgtext( "initial_break_processing: cannot find open file with " );
722       dbgtext( "dev = %x, inode = %.0f ", (unsigned int)dev, (double)inode);
723       dbgtext( "allowing break to succeed.\n" );
724     }
725     return NULL;
726   }
727
728   /* Ensure we have an oplock on the file */
729
730   /* There is a potential race condition in that an oplock could
731      have been broken due to another udp request, and yet there are
732      still oplock break messages being sent in the udp message
733      queue for this file. So return true if we don't have an oplock,
734      as we may have just freed it.
735    */
736
737   if(fsp->oplock_type == NO_OPLOCK)
738   {
739     if( DEBUGLVL( 3 ) )
740     {
741       dbgtext( "initial_break_processing: file %s ", fsp->fsp_name );
742       dbgtext( "(dev = %x, inode = %.0f) has no oplock.\n", (unsigned int)dev, (double)inode );
743       dbgtext( "Allowing break to succeed regardless.\n" );
744     }
745     return NULL;
746   }
747
748   return fsp;
749 }
750
751 /****************************************************************************
752  Process a level II oplock break directly.
753 ****************************************************************************/
754
755 BOOL oplock_break_level2(files_struct *fsp, BOOL local_request, int token)
756 {
757   extern int Client;
758   extern uint32 global_client_caps;
759   char outbuf[128];
760   BOOL got_lock = False;
761   SMB_DEV_T dev = fsp->fd_ptr->dev;
762   SMB_INO_T inode = fsp->fd_ptr->inode;
763
764   /*
765    * We can have a level II oplock even if the client is not
766    * level II oplock aware. In this case just remove the
767    * flags and don't send the break-to-none message to
768    * the client.
769    */
770
771   if (global_client_caps & CAP_LEVEL_II_OPLOCKS) {
772     /*
773      * If we are sending an oplock break due to an SMB sent
774      * by our own client we ensure that we wait at leat
775      * lp_oplock_break_wait_time() milliseconds before sending
776      * the packet. Sending the packet sooner can break Win9x
777      * and has reported to cause problems on NT. JRA.
778      */
779
780     wait_before_sending_break(local_request);
781
782     /* Prepare the SMBlockingX message. */
783
784     prepare_break_message( outbuf, fsp, False);
785     send_smb(Client, outbuf);
786   }
787
788   /*
789    * Now we must update the shared memory structure to tell
790    * everyone else we no longer have a level II oplock on 
791    * this open file. If local_request is true then token is
792    * the existing lock on the shared memory area.
793    */
794
795   if(!local_request && lock_share_entry(fsp->conn, dev, inode, &token) == False) {
796       DEBUG(0,("oplock_break_level2: unable to lock share entry for file %s\n", fsp->fsp_name ));
797   } else {
798     got_lock = True;
799   }
800
801   if(remove_share_oplock(token, fsp)==False) {
802     DEBUG(0,("oplock_break_level2: unable to remove level II oplock for file %s\n", fsp->fsp_name ));
803   }
804
805   if (!local_request && got_lock)
806     unlock_share_entry(fsp->conn, dev, inode, token);
807
808   fsp->oplock_type = NO_OPLOCK;
809   level_II_oplocks_open--;
810
811   if(level_II_oplocks_open < 0)
812   {
813     DEBUG(0,("oplock_break_level2: level_II_oplocks_open < 0 (%d). PANIC ERROR\n",
814               level_II_oplocks_open));
815     abort();
816   }
817
818   if( DEBUGLVL( 3 ) )
819   {
820     dbgtext( "oplock_break_level2: returning success for " );
821     dbgtext( "dev = %x, inode = %.0f\n", (unsigned int)dev, (double)inode );
822     dbgtext( "Current level II oplocks_open = %d\n", level_II_oplocks_open );
823   }
824
825   return True;
826 }
827
828 /****************************************************************************
829  Process an oplock break directly.
830 ****************************************************************************/
831
832 static BOOL oplock_break(SMB_DEV_T dev, SMB_INO_T inode, struct timeval *tval, BOOL local_request)
833 {
834   extern uint32 global_client_caps;
835   extern struct current_user current_user;
836   extern int Client;
837   char *inbuf = NULL;
838   char *outbuf = NULL;
839   files_struct *fsp = NULL;
840   time_t start_time;
841   BOOL shutdown_server = False;
842   BOOL oplock_timeout = False;
843   connection_struct *saved_conn;
844   int saved_vuid;
845   pstring saved_dir; 
846   int timeout = (OPLOCK_BREAK_TIMEOUT * 1000);
847   pstring file_name;
848   BOOL using_levelII;
849
850   if((fsp = initial_break_processing(dev, inode, tval)) == NULL)
851     return True;
852
853   /*
854    * Deal with a level II oplock going break to none separately.
855    */
856
857   if (LEVEL_II_OPLOCK_TYPE(fsp->oplock_type))
858     return oplock_break_level2(fsp, local_request, -1);
859
860   /* Mark the oplock break as sent - we don't want to send twice! */
861   if (fsp->sent_oplock_break)
862   {
863     if( DEBUGLVL( 0 ) )
864     {
865       dbgtext( "oplock_break: ERROR: oplock_break already sent for " );
866       dbgtext( "file %s ", fsp->fsp_name);
867       dbgtext( "(dev = %x, inode = %.0f)\n", (unsigned int)dev, (double)inode );
868     }
869
870     /* We have to fail the open here as we cannot send another oplock break on
871        this file whilst we are awaiting a response from the client - neither
872        can we allow another open to succeed while we are waiting for the
873        client.
874      */
875     return False;
876   }
877
878   if(global_oplock_break) {
879     DEBUG(0,("ABORT : ABORT : recursion in oplock_break !!!!!\n"));
880     abort();
881   }
882
883   /* Now comes the horrid part. We must send an oplock break to the client,
884      and then process incoming messages until we get a close or oplock release.
885      At this point we know we need a new inbuf/outbuf buffer pair.
886      We cannot use these staticaly as we may recurse into here due to
887      messages crossing on the wire.
888    */
889
890   if((inbuf = (char *)malloc(BUFFER_SIZE + SAFETY_MARGIN))==NULL)
891   {
892     DEBUG(0,("oplock_break: malloc fail for input buffer.\n"));
893     return False;
894   }
895
896   if((outbuf = (char *)malloc(BUFFER_SIZE + SAFETY_MARGIN))==NULL)
897   {
898     DEBUG(0,("oplock_break: malloc fail for output buffer.\n"));
899     free(inbuf);
900     inbuf = NULL;
901     return False;
902   }
903
904   /*
905    * If we are sending an oplock break due to an SMB sent
906    * by our own client we ensure that we wait at leat
907    * lp_oplock_break_wait_time() milliseconds before sending
908    * the packet. Sending the packet sooner can break Win9x
909    * and has reported to cause problems on NT. JRA.
910    */
911
912   wait_before_sending_break(local_request);
913
914   /* Prepare the SMBlockingX message. */
915
916   if ((global_client_caps & CAP_LEVEL_II_OPLOCKS) && !lp_kernel_oplocks() && lp_level2_oplocks(SNUM(fsp->conn))) {
917           using_levelII = True;
918   } else {
919           using_levelII = False;
920   }
921
922   prepare_break_message( outbuf, fsp, using_levelII);
923   /* Remember if we just sent a break to level II on this file. */
924   fsp->sent_oplock_break = using_levelII?
925           LEVEL_II_BREAK_SENT:EXCLUSIVE_BREAK_SENT;
926
927   send_smb(Client, outbuf);
928
929   /* We need this in case a readraw crosses on the wire. */
930   global_oplock_break = True;
931  
932   /* Process incoming messages. */
933
934   /* JRA - If we don't get a break from the client in OPLOCK_BREAK_TIMEOUT
935      seconds we should just die.... */
936
937   start_time = time(NULL);
938
939   /*
940    * Save the information we need to re-become the
941    * user, then unbecome the user whilst we're doing this.
942    */
943   saved_conn = fsp->conn;
944   saved_vuid = current_user.vuid;
945   dos_GetWd(saved_dir);
946   unbecome_user();
947   /* Save the chain fnum. */
948   file_chain_save();
949
950   /*
951    * From Charles Hoch <hoch@exemplary.com>. If the break processing
952    * code closes the file (as it often does), then the fsp pointer here
953    * points to free()'d memory. We *must* revalidate fsp each time
954    * around the loop.
955    */
956
957   pstrcpy(file_name, fsp->fsp_name);
958
959   while((fsp = initial_break_processing(dev, inode, tval)) &&
960         OPEN_FSP(fsp) && EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type))
961   {
962     if(receive_smb(Client,inbuf, timeout) == False)
963     {
964       /*
965        * Die if we got an error.
966        */
967
968       if (smb_read_error == READ_EOF) {
969         DEBUG( 0, ( "oplock_break: end of file from client\n" ) );
970         shutdown_server = True;
971       } else if (smb_read_error == READ_ERROR) {
972         DEBUG( 0, ("oplock_break: receive_smb error (%s)\n", strerror(errno)) );
973         shutdown_server = True;
974       } else if (smb_read_error == READ_TIMEOUT) {
975         DEBUG( 0, ( "oplock_break: receive_smb timed out after %d seconds.\n",
976                      OPLOCK_BREAK_TIMEOUT ) );
977         oplock_timeout = True;
978       }
979
980       DEBUGADD( 0, ( "oplock_break failed for file %s ", file_name ) );
981       DEBUGADD( 0, ( "(dev = %x, inode = %.0f).\n", (unsigned int)dev, (double)inode));
982
983       break;
984     }
985
986     /*
987      * There are certain SMB requests that we shouldn't allow
988      * to recurse. opens, renames and deletes are the obvious
989      * ones. This is handled in the switch_message() function.
990      * If global_oplock_break is set they will push the packet onto
991      * the pending smb queue and return -1 (no reply).
992      * JRA.
993      */
994
995     process_smb(inbuf, outbuf);
996
997     /*
998      * Die if we go over the time limit.
999      */
1000
1001     if((time(NULL) - start_time) > OPLOCK_BREAK_TIMEOUT)
1002     {
1003       if( DEBUGLVL( 0 ) )
1004       {
1005         dbgtext( "oplock_break: no break received from client " );
1006         dbgtext( "within %d seconds.\n", OPLOCK_BREAK_TIMEOUT );
1007         dbgtext( "oplock_break failed for file %s ", fsp->fsp_name );
1008         dbgtext( "(dev = %x, inode = %.0f).\n", (unsigned int)dev, (double)inode );
1009       }
1010       oplock_timeout = True;
1011       break;
1012     }
1013   }
1014
1015   /*
1016    * Go back to being the user who requested the oplock
1017    * break.
1018    */
1019   if(!become_user(saved_conn, saved_vuid))
1020   {
1021     DEBUG( 0, ( "oplock_break: unable to re-become user!" ) );
1022     DEBUGADD( 0, ( "Shutting down server\n" ) );
1023     close_sockets();
1024     close(oplock_sock);
1025     exit_server("unable to re-become user");
1026   }
1027   /* Including the directory. */
1028   dos_ChDir(saved_dir);
1029
1030   /* Restore the chain fnum. */
1031   file_chain_restore();
1032
1033   /* Free the buffers we've been using to recurse. */
1034   free(inbuf);
1035   free(outbuf);
1036
1037   /* We need this in case a readraw crossed on the wire. */
1038   if(global_oplock_break)
1039     global_oplock_break = False;
1040
1041   /*
1042    * If the client timed out then clear the oplock (or go to level II)
1043    * and continue. This seems to be what NT does and is better than dropping
1044    * the connection.
1045    */
1046
1047   if(oplock_timeout && (fsp = initial_break_processing(dev, inode, tval)) &&
1048         OPEN_FSP(fsp) && EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type))
1049   {
1050     DEBUG(0,("oplock_break: client failure in oplock break in file %s\n", fsp->fsp_name));
1051     remove_oplock(fsp);
1052     global_client_failed_oplock_break = True; /* Never grant this client an oplock again. */
1053   }
1054
1055   /*
1056    * If the client had an error we must die.
1057    */
1058
1059   if(shutdown_server)
1060   {
1061     DEBUG( 0, ( "oplock_break: client failure in break - " ) );
1062     DEBUGADD( 0, ( "shutting down this smbd.\n" ) );
1063     close_sockets();
1064     close(oplock_sock);
1065     exit_server("oplock break failure");
1066   }
1067
1068   /* Santity check - remove this later. JRA */
1069   if(exclusive_oplocks_open < 0)
1070   {
1071     DEBUG(0,("oplock_break: exclusive_oplocks_open < 0 (%d). PANIC ERROR\n",
1072               exclusive_oplocks_open));
1073     abort();
1074   }
1075
1076   if( DEBUGLVL( 3 ) )
1077   {
1078     dbgtext( "oplock_break: returning success for " );
1079     dbgtext( "dev = %x, inode = %.0f\n", (unsigned int)dev, (double)inode );
1080     dbgtext( "Current exclusive_oplocks_open = %d\n", exclusive_oplocks_open );
1081   }
1082
1083   return True;
1084 }
1085
1086 /****************************************************************************
1087 Send an oplock break message to another smbd process. If the oplock is held 
1088 by the local smbd then call the oplock break function directly.
1089 ****************************************************************************/
1090
1091 BOOL request_oplock_break(share_mode_entry *share_entry, 
1092                           SMB_DEV_T dev, SMB_INO_T inode)
1093 {
1094   char op_break_msg[OPLOCK_BREAK_MSG_LEN];
1095   struct sockaddr_in addr_out;
1096   pid_t pid = getpid();
1097   time_t start_time;
1098   int time_left;
1099   long usec;
1100   time_t sec;
1101
1102   if(pid == share_entry->pid)
1103   {
1104     /* We are breaking our own oplock, make sure it's us. */
1105     if(share_entry->op_port != global_oplock_port)
1106     {
1107       DEBUG(0,("request_oplock_break: corrupt share mode entry - pid = %d, port = %d \
1108 should be %d\n", (int)pid, share_entry->op_port, global_oplock_port));
1109       return False;
1110     }
1111
1112     DEBUG(5,("request_oplock_break: breaking our own oplock\n"));
1113
1114     /* Call oplock break direct. */
1115     return oplock_break(dev, inode, &share_entry->time, True);
1116   }
1117
1118   /* We need to send a OPLOCK_BREAK_CMD message to the
1119      port in the share mode entry. */
1120
1121   if (LEVEL_II_OPLOCK_TYPE(share_entry->op_type)) {
1122     SSVAL(op_break_msg,OPBRK_MESSAGE_CMD_OFFSET,LEVEL_II_OPLOCK_BREAK_CMD);
1123   } else {
1124     SSVAL(op_break_msg,OPBRK_MESSAGE_CMD_OFFSET,OPLOCK_BREAK_CMD);
1125   }
1126   memcpy(op_break_msg+OPLOCK_BREAK_PID_OFFSET,(char *)&pid,sizeof(pid));
1127   sec = (time_t)share_entry->time.tv_sec;
1128   memcpy(op_break_msg+OPLOCK_BREAK_SEC_OFFSET,(char *)&sec,sizeof(sec));
1129   usec = (long)share_entry->time.tv_usec;
1130   memcpy(op_break_msg+OPLOCK_BREAK_USEC_OFFSET,(char *)&usec,sizeof(usec));
1131   memcpy(op_break_msg+OPLOCK_BREAK_DEV_OFFSET,(char *)&dev,sizeof(dev));
1132   memcpy(op_break_msg+OPLOCK_BREAK_INODE_OFFSET,(char *)&inode,sizeof(inode));
1133
1134   /* set the address and port */
1135   memset((char *)&addr_out,'\0',sizeof(addr_out));
1136   addr_out.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
1137   addr_out.sin_port = htons( share_entry->op_port );
1138   addr_out.sin_family = AF_INET;
1139    
1140   if( DEBUGLVL( 3 ) )
1141   {
1142     dbgtext( "request_oplock_break: sending a oplock break message to " );
1143     dbgtext( "pid %d on port %d ", (int)share_entry->pid, share_entry->op_port );
1144     dbgtext( "for dev = %x, inode = %.0f, tv_sec = %x, tv_usec = %x\n",
1145             (unsigned int)dev, (double)inode, (int)share_entry->time.tv_sec,
1146             (int)share_entry->time.tv_usec );
1147
1148   }
1149
1150   if(sendto(oplock_sock,op_break_msg,OPLOCK_BREAK_MSG_LEN,0,
1151          (struct sockaddr *)&addr_out,sizeof(addr_out)) < 0)
1152   {
1153     if( DEBUGLVL( 0 ) )
1154     {
1155       dbgtext( "request_oplock_break: failed when sending a oplock " );
1156       dbgtext( "break message to pid %d ", (int)share_entry->pid );
1157       dbgtext( "on port %d ", share_entry->op_port );
1158       dbgtext( "for dev = %x, inode = %.0f, tv_sec = %x, tv_usec = %x\n",
1159           (unsigned int)dev, (double)inode, (int)share_entry->time.tv_sec,
1160           (int)share_entry->time.tv_usec );
1161       dbgtext( "Error was %s\n", strerror(errno) );
1162     }
1163     return False;
1164   }
1165
1166   /*
1167    * If we just sent a message to a level II oplock share entry then
1168    * we are done and may return.
1169    */
1170
1171   if (LEVEL_II_OPLOCK_TYPE(share_entry->op_type)) {
1172     DEBUG(3,("request_oplock_break: sent break message to level II entry.\n"));
1173     return True;
1174   }
1175
1176   /*
1177    * Now we must await the oplock broken message coming back
1178    * from the target smbd process. Timeout if it fails to
1179    * return in (OPLOCK_BREAK_TIMEOUT + OPLOCK_BREAK_TIMEOUT_FUDGEFACTOR) seconds.
1180    * While we get messages that aren't ours, loop.
1181    */
1182
1183   start_time = time(NULL);
1184   time_left = OPLOCK_BREAK_TIMEOUT+OPLOCK_BREAK_TIMEOUT_FUDGEFACTOR;
1185
1186   while(time_left >= 0)
1187   {
1188     char op_break_reply[OPBRK_CMD_HEADER_LEN+OPLOCK_BREAK_MSG_LEN];
1189     int32 reply_msg_len;
1190     uint16 reply_from_port;
1191     char *reply_msg_start;
1192     fd_set fds;
1193
1194     FD_ZERO(&fds);
1195     FD_SET(oplock_sock,&fds);
1196     if(lp_kernel_oplocks() && (oplock_pipe_read != -1))
1197       FD_SET(oplock_pipe_read,&fds);
1198
1199     if(receive_local_message(&fds, op_break_reply, sizeof(op_break_reply),
1200                time_left ? time_left * 1000 : 1) == False)
1201     {
1202       if(smb_read_error == READ_TIMEOUT)
1203       {
1204         if( DEBUGLVL( 0 ) )
1205         {
1206           dbgtext( "request_oplock_break: no response received to oplock " );
1207           dbgtext( "break request to pid %d ", (int)share_entry->pid );
1208           dbgtext( "on port %d ", share_entry->op_port );
1209           dbgtext( "for dev = %x, inode = %.0f\n", (unsigned int)dev, (double)inode );
1210           dbgtext( "for dev = %x, inode = %.0f, tv_sec = %x, tv_usec = %x\n",
1211              (unsigned int)dev, (double)inode, (int)share_entry->time.tv_sec,
1212              (int)share_entry->time.tv_usec );
1213         }
1214
1215         /*
1216          * This is a hack to make handling of failing clients more robust.
1217          * If a oplock break response message is not received in the timeout
1218          * period we may assume that the smbd servicing that client holding
1219          * the oplock has died and the client changes were lost anyway, so
1220          * we should continue to try and open the file.
1221          */
1222         break;
1223       }
1224       else
1225         if( DEBUGLVL( 0 ) )
1226         {
1227           dbgtext( "request_oplock_break: error in response received " );
1228           dbgtext( "to oplock break request to pid %d ", (int)share_entry->pid );
1229           dbgtext( "on port %d ", share_entry->op_port );
1230           dbgtext( "for dev = %x, inode = %.0f, tv_sec = %x, tv_usec = %x\n",
1231                (unsigned int)dev, (double)inode, (int)share_entry->time.tv_sec,
1232                (int)share_entry->time.tv_usec );
1233           dbgtext( "Error was (%s).\n", strerror(errno) );
1234         }
1235       return False;
1236     }
1237
1238     reply_msg_len = IVAL(op_break_reply,OPBRK_CMD_LEN_OFFSET);
1239     reply_from_port = SVAL(op_break_reply,OPBRK_CMD_PORT_OFFSET);
1240
1241     reply_msg_start = &op_break_reply[OPBRK_CMD_HEADER_LEN];
1242
1243
1244 #if defined(HAVE_KERNEL_OPLOCKS)
1245     if((reply_msg_len != OPLOCK_BREAK_MSG_LEN) && (reply_msg_len != KERNEL_OPLOCK_BREAK_MSG_LEN))
1246 #else
1247     if(reply_msg_len != OPLOCK_BREAK_MSG_LEN)
1248 #endif
1249     {
1250       /* Ignore it. */
1251       DEBUG( 0, ( "request_oplock_break: invalid message length (%d) received.", reply_msg_len ) );
1252       DEBUGADD( 0, ( "  Ignoring.\n" ) );
1253       continue;
1254     }
1255
1256     /*
1257      * Test to see if this is the reply we are awaiting.
1258      */
1259
1260     if((SVAL(reply_msg_start,OPBRK_MESSAGE_CMD_OFFSET) & CMD_REPLY) &&
1261        ((SVAL(reply_msg_start,OPBRK_MESSAGE_CMD_OFFSET) & ~CMD_REPLY) == OPLOCK_BREAK_CMD) &&
1262        (reply_from_port == share_entry->op_port) && 
1263        (memcmp(&reply_msg_start[OPLOCK_BREAK_PID_OFFSET], 
1264                &op_break_msg[OPLOCK_BREAK_PID_OFFSET],
1265                OPLOCK_BREAK_MSG_LEN - OPLOCK_BREAK_PID_OFFSET) == 0))
1266     {
1267       /*
1268        * This is the reply we've been waiting for.
1269        */
1270       break;
1271     }
1272     else
1273     {
1274       /*
1275        * This is another message - a break request.
1276        * Note that both kernel oplock break requests
1277        * and UDP inter-smbd oplock break requests will
1278        * be processed here.
1279        *
1280        * Process it to prevent potential deadlock.
1281        * Note that the code in switch_message() prevents
1282        * us from recursing into here as any SMB requests
1283        * we might process that would cause another oplock
1284        * break request to be made will be queued.
1285        * JRA.
1286        */
1287
1288       process_local_message(op_break_reply, sizeof(op_break_reply));
1289     }
1290
1291     time_left -= (time(NULL) - start_time);
1292   }
1293
1294   DEBUG(3,("request_oplock_break: broke oplock.\n"));
1295
1296   return True;
1297 }
1298
1299 /****************************************************************************
1300   Attempt to break an oplock on a file (if oplocked).
1301   Returns True if the file was closed as a result of
1302   the oplock break, False otherwise.
1303   Used as a last ditch attempt to free a space in the 
1304   file table when we have run out.
1305 ****************************************************************************/
1306
1307 BOOL attempt_close_oplocked_file(files_struct *fsp)
1308 {
1309
1310   DEBUG(5,("attempt_close_oplocked_file: checking file %s.\n", fsp->fsp_name));
1311
1312   if (fsp->open && EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type) && !fsp->sent_oplock_break && (fsp->fd_ptr != NULL)) {
1313
1314     /* Try and break the oplock. */
1315     file_fd_struct *fd_ptr = fsp->fd_ptr;
1316     if(oplock_break( fd_ptr->dev, fd_ptr->inode, &fsp->open_time, True)) {
1317       if(!fsp->open) /* Did the oplock break close the file ? */
1318         return True;
1319     }
1320   }
1321
1322   return False;
1323 }
1324
1325 /****************************************************************************
1326  Init function to check if kernel level oplocks are available.
1327 ****************************************************************************/
1328
1329 void check_kernel_oplocks(void)
1330 {
1331   static BOOL done;
1332
1333   /*
1334    * We only do this check once on startup.
1335    */
1336
1337   if(done)
1338     return;
1339
1340   done = True;
1341   lp_set_kernel_oplocks(False);
1342
1343 #if defined(HAVE_KERNEL_OPLOCKS)
1344   {
1345     int fd;
1346     int pfd[2];
1347     pstring tmpname;
1348
1349     set_process_capability(KERNEL_OPLOCK_CAPABILITY,True);
1350     set_inherited_process_capability(KERNEL_OPLOCK_CAPABILITY,True);
1351
1352         slprintf(tmpname,sizeof(tmpname)-1, "%s/koplock.%d", lp_lockdir(), (int)getpid());
1353
1354     if(pipe(pfd) != 0) {
1355       DEBUG(0,("check_kernel_oplocks: Unable to create pipe. Error was %s\n",
1356             strerror(errno) ));
1357       return;
1358     }
1359
1360     if((fd = sys_open(tmpname, O_RDWR|O_CREAT|O_EXCL|O_TRUNC, 0600)) < 0) {
1361       DEBUG(0,("check_kernel_oplocks: Unable to open temp test file %s. Error was %s\n",
1362             tmpname, strerror(errno) ));
1363       unlink( tmpname );
1364       close(pfd[0]);
1365       close(pfd[1]);
1366       return;
1367     }
1368
1369     unlink( tmpname );
1370
1371     if(fcntl(fd, F_OPLKREG, pfd[1]) == -1) {
1372       DEBUG(0,("check_kernel_oplocks: Kernel oplocks are not available on this machine. \
1373 Disabling kernel oplock support.\n" ));
1374       close(pfd[0]);
1375       close(pfd[1]);
1376       close(fd);
1377       return;
1378     }
1379
1380     if(fcntl(fd, F_OPLKACK, OP_REVOKE) < 0 ) {
1381       DEBUG(0,("check_kernel_oplocks: Error when removing kernel oplock. Error was %s. \
1382 Disabling kernel oplock support.\n", strerror(errno) ));
1383       close(pfd[0]);
1384       close(pfd[1]);
1385       close(fd);
1386       return;
1387     }
1388
1389     close(pfd[0]);
1390     close(pfd[1]);
1391     close(fd);
1392
1393     lp_set_kernel_oplocks(True);
1394
1395     DEBUG(0,("check_kernel_oplocks: Kernel oplocks available and set to %s.\n",
1396           lp_kernel_oplocks() ? "True" : "False" ));
1397
1398   }
1399 #endif /* HAVE_KERNEL_OPLOCKS */
1400 }