99fe7a69fab6a8254217420dc0f5041f33960f52
[kamenim/samba.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 #if defined(HAVE_KERNEL_OPLOCKS)
30 static int oplock_pipe_read = -1;
31 static int oplock_pipe_write = -1;
32 #endif /* HAVE_KERNEL_OPLOCKS */
33
34 /* Current number of oplocks we have outstanding. */
35 int32 global_oplocks_open = 0;
36 BOOL global_oplock_break = False;
37
38 extern int smb_read_error;
39
40 static BOOL oplock_break(SMB_DEV_T dev, SMB_INO_T inode, struct timeval *tval);
41
42 /****************************************************************************
43  Setup the kernel level oplock backchannel for this process.
44 ****************************************************************************/
45
46 BOOL setup_kernel_oplock_pipe(void)
47 {
48 #if defined(HAVE_KERNEL_OPLOCKS)
49   if(lp_kernel_oplocks()) {
50     int pfd[2];
51
52     if(pipe(pfd) != 0) {
53       DEBUG(0,("setup_kernel_oplock_pipe: Unable to create pipe. Error was %s\n",
54             strerror(errno) ));
55       return False;
56     }
57
58     oplock_pipe_read = pfd[0];
59     oplock_pipe_write = pfd[1];
60   }
61 #endif /* HAVE_KERNEL_OPLOCKS */
62   return True;
63 }
64
65 /****************************************************************************
66   open the oplock IPC socket communication
67 ****************************************************************************/
68 BOOL open_oplock_ipc(void)
69 {
70   struct sockaddr_in sock_name;
71   int len = sizeof(sock_name);
72
73   DEBUG(3,("open_oplock_ipc: opening loopback UDP socket.\n"));
74
75   /* Open a lookback UDP socket on a random port. */
76   oplock_sock = open_socket_in(SOCK_DGRAM, 0, 0, htonl(INADDR_LOOPBACK));
77   if (oplock_sock == -1)
78   {
79     DEBUG(0,("open_oplock_ipc: Failed to get local UDP socket for \
80 address %lx. Error was %s\n", (long)htonl(INADDR_LOOPBACK), strerror(errno)));
81     global_oplock_port = 0;
82     return(False);
83   }
84
85   /* Find out the transient UDP port we have been allocated. */
86   if(getsockname(oplock_sock, (struct sockaddr *)&sock_name, &len)<0)
87   {
88     DEBUG(0,("open_oplock_ipc: Failed to get local UDP port. Error was %s\n",
89             strerror(errno)));
90     close(oplock_sock);
91     oplock_sock = -1;
92     global_oplock_port = 0;
93     return False;
94   }
95   global_oplock_port = ntohs(sock_name.sin_port);
96
97   if(!setup_kernel_oplock_pipe())
98     return False;
99
100   DEBUG(3,("open_oplock ipc: pid = %d, global_oplock_port = %u\n", 
101             (int)getpid(), global_oplock_port));
102
103   return True;
104 }
105
106 /****************************************************************************
107  Read an oplock break message from the either the oplock UDP fd
108  or the kernel oplock pipe fd (if kernel oplocks are supported).
109
110  If timeout is zero then *fds contains the file descriptors that
111  are ready to be read and acted upon. If timeout is non-zero then
112  *fds contains the file descriptors to be selected on for read.
113  The timeout is in milliseconds
114
115 ****************************************************************************/
116
117 BOOL receive_local_message(fd_set *fds, char *buffer, int buffer_len, int timeout)
118 {
119   struct sockaddr_in from;
120   int fromlen = sizeof(from);
121   int32 msg_len = 0;
122
123   smb_read_error = 0;
124
125   if(timeout != 0) {
126     struct timeval to;
127     int selrtn;
128     int maxfd = oplock_sock;
129
130 #if defined(HAVE_KERNEL_OPLOCKS)
131     if(lp_kernel_oplocks())
132       maxfd = MAX(maxfd, oplock_pipe_read);
133 #endif /* HAVE_KERNEL_OPLOCKS */
134
135     to.tv_sec = timeout / 1000;
136     to.tv_usec = (timeout % 1000) * 1000;
137
138     selrtn = sys_select(maxfd+1,fds,NULL, &to);
139
140     /* Check if error */
141     if(selrtn == -1) {
142       /* something is wrong. Maybe the socket is dead? */
143       smb_read_error = READ_ERROR;
144       return False;
145     }
146
147     /* Did we timeout ? */
148     if (selrtn == 0) {
149       smb_read_error = READ_TIMEOUT;
150       return False;
151     }
152   }
153
154 #if defined(HAVE_KERNEL_OPLOCKS)
155   if(FD_ISSET(oplock_pipe_read,fds)) {
156     /*
157      * Deal with the kernel <--> smbd
158      * oplock break protocol.
159      */
160
161     oplock_stat_t os;
162     SMB_DEV_T dev;
163     SMB_INO_T inode;
164     char dummy;
165
166     /*
167      * Read one byte of zero to clear the
168      * kernel break notify message.
169      */
170
171     if(read(oplock_pipe_read, &dummy, 1) != 1) {
172       DEBUG(0,("receive_local_message: read of kernel notification failed. \
173 Error was %s.\n", strerror(errno) ));
174       smb_read_error = READ_ERROR;
175       return False;
176     }
177
178     /*
179      * Do a query to get the
180      * device and inode of the file that has the break
181      * request outstanding.
182      */
183
184     if(fcntl(oplock_pipe_read, F_OPLKSTAT, &os) < 0) {
185       DEBUG(0,("receive_local_message: fcntl of kernel notification failed. \
186 Error was %s.\n", strerror(errno) ));
187       if(errno == EAGAIN) {
188         /*
189          * Duplicate kernel break message - ignore.
190          */
191         memset(buffer, '\0', KERNEL_OPLOCK_BREAK_MSG_LEN);
192         return True;
193       }
194       smb_read_error = READ_ERROR;
195       return False;
196     }
197
198     dev = (SMB_DEV_T)os.os_dev;
199     inode = (SMB_DEV_T)os.os_ino;
200
201     DEBUG(5,("receive_local_message: kernel oplock break request received for \
202 dev = %x, inode = %.0f\n", (unsigned int)dev, (double)inode ));
203
204     /*
205      * Create a kernel oplock break message.
206      */
207
208     /* Setup the message header */
209     SIVAL(buffer,OPBRK_CMD_LEN_OFFSET,KERNEL_OPLOCK_BREAK_MSG_LEN);
210     SSVAL(buffer,OPBRK_CMD_PORT_OFFSET,0);
211
212     buffer += OPBRK_CMD_HEADER_LEN;
213
214     SSVAL(buffer,OPBRK_MESSAGE_CMD_OFFSET,KERNEL_OPLOCK_BREAK_CMD);
215     SIVAL(buffer,KERNEL_OPLOCK_BREAK_DEV_OFFSET,dev);
216
217 #ifdef LARGE_SMB_INO_T
218     SIVAL(buffer,KERNEL_OPLOCK_BREAK_INODE_OFFSET,inode & 0xFFFFFFFF);
219     SIVAL(buffer,KERNEL_OPLOCK_BREAK_INODE_OFFSET+4, (inode >> 32 ) & 0xFFFFFFFF );
220 #else /* LARGE_SMB_INO_T */
221     SIVAL(buffer,KERNEL_OPLOCK_BREAK_INODE_OFFSET,inode);
222 #endif /* LARGE_SMB_INO_T */
223
224     return True;
225   }
226 #endif /* HAVE_KERNEL_OPLOCKS */
227
228   /*
229    * From here down we deal with the smbd <--> smbd
230    * oplock break protocol only.
231    */
232
233   /*
234    * Read a loopback udp message.
235    */
236   msg_len = recvfrom(oplock_sock, &buffer[OPBRK_CMD_HEADER_LEN],
237                      buffer_len - OPBRK_CMD_HEADER_LEN, 0,
238                      (struct sockaddr *)&from, &fromlen);
239
240   if(msg_len < 0) {
241     DEBUG(0,("receive_local_message. Error in recvfrom. (%s).\n",strerror(errno)));
242     return False;
243   }
244
245   /* Validate message length. */
246   if(msg_len > (buffer_len - OPBRK_CMD_HEADER_LEN)) {
247     DEBUG(0,("receive_local_message: invalid msg_len (%d) max can be %d\n",
248               msg_len,
249               buffer_len  - OPBRK_CMD_HEADER_LEN));
250     return False;
251   }
252
253   /* Validate message from address (must be localhost). */
254   if(from.sin_addr.s_addr != htonl(INADDR_LOOPBACK)) {
255     DEBUG(0,("receive_local_message: invalid 'from' address \
256 (was %lx should be 127.0.0.1\n", (long)from.sin_addr.s_addr));
257    return False;
258   }
259
260   /* Setup the message header */
261   SIVAL(buffer,OPBRK_CMD_LEN_OFFSET,msg_len);
262   SSVAL(buffer,OPBRK_CMD_PORT_OFFSET,ntohs(from.sin_port));
263
264   return True;
265 }
266
267 /****************************************************************************
268  Attempt to set an oplock on a file. Always succeeds if kernel oplocks are
269  disabled (just sets flags). Returns True if oplock set.
270 ****************************************************************************/
271
272 BOOL set_file_oplock(files_struct *fsp)
273 {
274 #if defined(HAVE_KERNEL_OPLOCKS)
275   if(lp_kernel_oplocks()) {
276
277     if(fcntl(fsp->fd_ptr->fd, F_OPLKREG, oplock_pipe_write) < 0 ) {
278       if(errno != EAGAIN) {
279         DEBUG(0,("set_file_oplock: Unable to get kernel oplock on file %s, dev = %x, \
280 inode = %.0f. Error was %s\n", 
281               fsp->fsp_name, (unsigned int)fsp->fd_ptr->dev, (double)fsp->fd_ptr->inode,
282                strerror(errno) ));
283       } else {
284         DEBUG(5,("set_file_oplock: Refused oplock on file %s, fd = %d, dev = %x, \
285 inode = %.0f. Another process had the file open.\n",
286               fsp->fsp_name, fsp->fd_ptr->fd, (unsigned int)fsp->fd_ptr->dev, (double)fsp->fd_ptr->inode ));
287       }
288       return False;
289     }
290
291     DEBUG(10,("set_file_oplock: got kernel oplock on file %s, dev = %x, inode = %.0f\n",
292           fsp->fsp_name, (unsigned int)fsp->fd_ptr->dev, (double)fsp->fd_ptr->inode));
293
294   }
295 #endif /* HAVE_KERNEL_OPLOCKS */
296
297   DEBUG(5,("set_file_oplock: granted 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   fsp->granted_oplock = True;
301   fsp->sent_oplock_break = False;
302   global_oplocks_open++;
303
304   return True;
305 }
306
307 /****************************************************************************
308  Attempt to release an oplock on a file. Always succeeds if kernel oplocks are
309  disabled (just clears flags).
310 ****************************************************************************/
311
312 static void release_file_oplock(files_struct *fsp)
313 {
314 #if defined(HAVE_KERNEL_OPLOCKS)
315
316   if(lp_kernel_oplocks())
317   {
318     if( DEBUGLVL( 10 ))
319     {
320       /*
321        * Check and print out the current kernel
322        * oplock state of this file.
323        */
324       int state = fcntl(fsp->fd_ptr->fd, F_OPLKACK, -1);
325       dbgtext("release_file_oplock: file %s, dev = %x, inode = %.0f has kernel \
326 oplock state of %x.\n", fsp->fsp_name, (unsigned int)fsp->fd_ptr->dev,
327                         (double)fsp->fd_ptr->inode, state );
328     }
329
330     /*
331      * Remote the kernel oplock on this file.
332      */
333
334     if(fcntl(fsp->fd_ptr->fd, F_OPLKACK, OP_REVOKE) < 0)
335     {
336       if( DEBUGLVL( 0 ))
337       {
338         dbgtext("release_file_oplock: Error when removing kernel oplock on file " );
339         dbgtext("%s, dev = %x, inode = %.0f. Error was %s\n",
340                  fsp->fsp_name, (unsigned int)fsp->fd_ptr->dev, 
341                  (double)fsp->fd_ptr->inode, strerror(errno) );
342       }
343     }
344   }
345 #endif /* HAVE_KERNEL_OPLOCKS */
346
347   fsp->granted_oplock = False;
348   fsp->sent_oplock_break = False;
349   global_oplocks_open--;
350 }
351
352 /****************************************************************************
353  Setup the listening set of file descriptors for an oplock break
354  message either from the UDP socket or from the kernel. Returns the maximum
355  fd used.
356 ****************************************************************************/
357
358 int setup_oplock_select_set( fd_set *fds)
359 {
360   int maxfd = oplock_sock;
361   FD_SET(oplock_sock,fds);
362
363 #if defined(HAVE_KERNEL_OPLOCKS)
364   if(lp_kernel_oplocks()) {
365     FD_SET(oplock_pipe_read,fds); 
366     maxfd = MAX(maxfd,oplock_pipe_read);
367   }
368 #endif /* HAVE_KERNEL_OPLOCKS */
369
370   return maxfd;
371 }
372
373 /****************************************************************************
374  Process an oplock break message - whether it came from the UDP socket
375  or from the kernel.
376 ****************************************************************************/
377
378 BOOL process_local_message(char *buffer, int buf_size)
379 {
380   int32 msg_len;
381   uint16 from_port;
382   char *msg_start;
383   SMB_DEV_T dev;
384   SMB_INO_T inode;
385   uint32 remotepid;
386   struct timeval tval;
387   struct timeval *ptval = NULL;
388
389   msg_len = IVAL(buffer,OPBRK_CMD_LEN_OFFSET);
390   from_port = SVAL(buffer,OPBRK_CMD_PORT_OFFSET);
391
392   msg_start = &buffer[OPBRK_CMD_HEADER_LEN];
393
394   DEBUG(5,("process_local_message: Got a message of length %d from port (%d)\n", 
395             msg_len, from_port));
396
397   /* 
398    * Pull the info out of the requesting packet.
399    */
400
401   switch(SVAL(msg_start,OPBRK_MESSAGE_CMD_OFFSET))
402   {
403 #if defined(HAVE_KERNEL_OPLOCKS)
404     case KERNEL_OPLOCK_BREAK_CMD:
405       /* Ensure that the msg length is correct. */
406       if(msg_len != KERNEL_OPLOCK_BREAK_MSG_LEN)
407       {
408         DEBUG(0,("process_local_message: incorrect length for KERNEL_OPLOCK_BREAK_CMD (was %d, \
409 should be %d).\n", msg_len, KERNEL_OPLOCK_BREAK_MSG_LEN));
410         return False;
411       }
412       {
413         /*
414          * Warning - beware of SMB_INO_T <> 4 bytes. !!
415          */
416 #ifdef LARGE_SMB_INO_T
417         SMB_INO_T inode_low = IVAL(msg_start, KERNEL_OPLOCK_BREAK_INODE_OFFSET);
418         SMB_INO_T inode_high = IVAL(msg_start, KERNEL_OPLOCK_BREAK_INODE_OFFSET + 4);
419         inode = inode_low | (inode_high << 32);
420 #else /* LARGE_SMB_INO_T */
421         inode = IVAL(msg_start, KERNEL_OPLOCK_BREAK_INODE_OFFSET);
422 #endif /* LARGE_SMB_INO_T */
423
424         dev = IVAL(msg_start,KERNEL_OPLOCK_BREAK_DEV_OFFSET);
425
426         ptval = NULL;
427
428         DEBUG(5,("process_local_message: kernel oplock break request for \
429 file dev = %x, inode = %.0f\n", (unsigned int)dev, (double)inode));
430       }
431       break;
432 #endif /* HAVE_KERNEL_OPLOCKS */
433
434     case OPLOCK_BREAK_CMD:
435       /* Ensure that the msg length is correct. */
436       if(msg_len != OPLOCK_BREAK_MSG_LEN)
437       {
438         DEBUG(0,("process_local_message: incorrect length for OPLOCK_BREAK_CMD (was %d, \
439 should be %d).\n", msg_len, OPLOCK_BREAK_MSG_LEN));
440         return False;
441       }
442       {
443         /*
444          * Warning - beware of SMB_INO_T <> 4 bytes. !!
445          */
446 #ifdef LARGE_SMB_INO_T
447         SMB_INO_T inode_low = IVAL(msg_start, OPLOCK_BREAK_INODE_OFFSET);
448         SMB_INO_T inode_high = IVAL(msg_start, OPLOCK_BREAK_INODE_OFFSET + 4);
449         inode = inode_low | (inode_high << 32);
450 #else /* LARGE_SMB_INO_T */
451         inode = IVAL(msg_start, OPLOCK_BREAK_INODE_OFFSET);
452 #endif /* LARGE_SMB_INO_T */
453
454         dev = IVAL(msg_start,OPLOCK_BREAK_DEV_OFFSET);
455
456         tval.tv_sec = (time_t)IVAL(msg_start, OPLOCK_BREAK_SEC_OFFSET);
457         tval.tv_usec = (long)IVAL(msg_start, OPLOCK_BREAK_USEC_OFFSET);
458
459         ptval = &tval;
460
461         remotepid = IVAL(msg_start,OPLOCK_BREAK_PID_OFFSET);
462
463         DEBUG(5,("process_local_message: oplock break request from \
464 pid %d, port %d, dev = %x, inode = %.0f\n", remotepid, from_port, (unsigned int)dev, (double)inode));
465       }
466       break;
467
468     /* 
469      * Keep this as a debug case - eventually we can remove it.
470      */
471     case 0x8001:
472       DEBUG(0,("process_local_message: Received unsolicited break \
473 reply - dumping info.\n"));
474
475       if(msg_len != OPLOCK_BREAK_MSG_LEN)
476       {
477         DEBUG(0,("process_local_message: ubr: incorrect length for reply \
478 (was %d, should be %d).\n", msg_len, OPLOCK_BREAK_MSG_LEN));
479         return False;
480       }
481
482       {
483         /*
484          * Warning - beware of SMB_INO_T <> 4 bytes. !!
485          */
486 #ifdef LARGE_SMB_INO_T
487         SMB_INO_T inode_low = IVAL(msg_start, OPLOCK_BREAK_INODE_OFFSET);
488         SMB_INO_T inode_high = IVAL(msg_start, OPLOCK_BREAK_INODE_OFFSET + 4);
489         inode = inode_low | (inode_high << 32);
490 #else /* LARGE_SMB_INO_T */
491         inode = IVAL(msg_start, OPLOCK_BREAK_INODE_OFFSET);
492 #endif /* LARGE_SMB_INO_T */
493
494         remotepid = IVAL(msg_start,OPLOCK_BREAK_PID_OFFSET);
495         dev = IVAL(msg_start,OPLOCK_BREAK_DEV_OFFSET);
496
497         DEBUG(0,("process_local_message: unsolicited oplock break reply from \
498 pid %d, port %d, dev = %x, inode = %.0f\n", remotepid, from_port, (unsigned int)dev, (double)inode));
499
500        }
501        return False;
502
503     default:
504       DEBUG(0,("process_local_message: unknown UDP message command code (%x) - ignoring.\n",
505                 (unsigned int)SVAL(msg_start,0)));
506       return False;
507   }
508
509   /*
510    * Now actually process the break request.
511    */
512
513   if(global_oplocks_open != 0)
514   {
515     if(oplock_break(dev, inode, ptval) == False)
516     {
517       DEBUG(0,("process_local_message: oplock break failed.\n"));
518       return False;
519     }
520   }
521   else
522   {
523     /*
524      * If we have no record of any currently open oplocks,
525      * it's not an error, as a close command may have
526      * just been issued on the file that was oplocked.
527      * Just log a message and return success in this case.
528      */
529     DEBUG(3,("process_local_message: oplock break requested with no outstanding \
530 oplocks. Returning success.\n"));
531   }
532
533   /* 
534    * Do the appropriate reply - none in the kernel case.
535    */
536
537   if(SVAL(msg_start,OPBRK_MESSAGE_CMD_OFFSET) == OPLOCK_BREAK_CMD)
538   {
539     struct sockaddr_in toaddr;
540
541     /* Send the message back after OR'ing in the 'REPLY' bit. */
542     SSVAL(msg_start,OPBRK_MESSAGE_CMD_OFFSET,OPLOCK_BREAK_CMD | CMD_REPLY);
543
544     bzero((char *)&toaddr,sizeof(toaddr));
545     toaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
546     toaddr.sin_port = htons(from_port);
547     toaddr.sin_family = AF_INET;
548
549     if(sendto( oplock_sock, msg_start, OPLOCK_BREAK_MSG_LEN, 0,
550             (struct sockaddr *)&toaddr, sizeof(toaddr)) < 0) 
551     {
552       DEBUG(0,("process_local_message: sendto process %d failed. Errno was %s\n",
553                 remotepid, strerror(errno)));
554       return False;
555     }
556
557     DEBUG(5,("process_local_message: oplock break reply sent to \
558 pid %d, port %d, for file dev = %x, inode = %.0f\n",
559           remotepid, from_port, (unsigned int)dev, (double)inode));
560   }
561
562   return True;
563 }
564
565 /****************************************************************************
566  Process an oplock break directly.
567 ****************************************************************************/
568
569 static BOOL oplock_break(SMB_DEV_T dev, SMB_INO_T inode, struct timeval *tval)
570 {
571   extern struct current_user current_user;
572   extern int Client;
573   char *inbuf = NULL;
574   char *outbuf = NULL;
575   files_struct *fsp = NULL;
576   time_t start_time;
577   BOOL shutdown_server = False;
578   connection_struct *saved_conn;
579   int saved_vuid;
580   pstring saved_dir; 
581   int break_counter = OPLOCK_BREAK_RESENDS;
582
583   if( DEBUGLVL( 3 ) )
584   {
585     dbgtext( "oplock_break: called for dev = %x, inode = %.0f.\n", (unsigned int)dev, (double)inode );
586     dbgtext( "Current global_oplocks_open = %d\n", global_oplocks_open );
587   }
588
589   /* We need to search the file open table for the
590      entry containing this dev and inode, and ensure
591      we have an oplock on it. */
592   fsp = file_find_dit(dev, inode, tval);
593
594   if(fsp == NULL)
595   {
596     /* The file could have been closed in the meantime - return success. */
597     if( DEBUGLVL( 0 ) )
598     {
599       dbgtext( "oplock_break: cannot find open file with " );
600       dbgtext( "dev = %x, inode = %.0f ", (unsigned int)dev, (double)inode);
601       dbgtext( "allowing break to succeed.\n" );
602     }
603     return True;
604   }
605
606   /* Ensure we have an oplock on the file */
607
608   /* There is a potential race condition in that an oplock could
609      have been broken due to another udp request, and yet there are
610      still oplock break messages being sent in the udp message
611      queue for this file. So return true if we don't have an oplock,
612      as we may have just freed it.
613    */
614
615   if(!fsp->granted_oplock)
616   {
617     if( DEBUGLVL( 0 ) )
618     {
619       dbgtext( "oplock_break: file %s ", fsp->fsp_name );
620       dbgtext( "(dev = %x, inode = %.0f) has no oplock.\n", (unsigned int)dev, (double)inode );
621       dbgtext( "Allowing break to succeed regardless.\n" );
622     }
623     return True;
624   }
625
626   /* mark the oplock break as sent - we don't want to send twice! */
627   if (fsp->sent_oplock_break)
628   {
629     if( DEBUGLVL( 0 ) )
630     {
631       dbgtext( "oplock_break: ERROR: oplock_break already sent for " );
632       dbgtext( "file %s ", fsp->fsp_name);
633       dbgtext( "(dev = %x, inode = %.0f)\n", (unsigned int)dev, (double)inode );
634     }
635
636     /* We have to fail the open here as we cannot send another oplock break on
637        this file whilst we are awaiting a response from the client - neither
638        can we allow another open to succeed while we are waiting for the
639        client.
640      */
641     return False;
642   }
643
644   /* Now comes the horrid part. We must send an oplock break to the client,
645      and then process incoming messages until we get a close or oplock release.
646      At this point we know we need a new inbuf/outbuf buffer pair.
647      We cannot use these staticaly as we may recurse into here due to
648      messages crossing on the wire.
649    */
650
651   if((inbuf = (char *)malloc(BUFFER_SIZE + SAFETY_MARGIN))==NULL)
652   {
653     DEBUG(0,("oplock_break: malloc fail for input buffer.\n"));
654     return False;
655   }
656
657   if((outbuf = (char *)malloc(BUFFER_SIZE + SAFETY_MARGIN))==NULL)
658   {
659     DEBUG(0,("oplock_break: malloc fail for output buffer.\n"));
660     free(inbuf);
661     inbuf = NULL;
662     return False;
663   }
664
665   /* Prepare the SMBlockingX message. */
666   bzero(outbuf,smb_size);
667   set_message(outbuf,8,0,True);
668
669   SCVAL(outbuf,smb_com,SMBlockingX);
670   SSVAL(outbuf,smb_tid,fsp->conn->cnum);
671   SSVAL(outbuf,smb_pid,0xFFFF);
672   SSVAL(outbuf,smb_uid,0);
673   SSVAL(outbuf,smb_mid,0xFFFF);
674   SCVAL(outbuf,smb_vwv0,0xFF);
675   SSVAL(outbuf,smb_vwv2,fsp->fnum);
676   SCVAL(outbuf,smb_vwv3,LOCKING_ANDX_OPLOCK_RELEASE);
677   /* Change this when we have level II oplocks. */
678   SCVAL(outbuf,smb_vwv3+1,OPLOCKLEVEL_NONE);
679  
680   send_smb(Client, outbuf);
681
682   /* Remember we just sent an oplock break on this file. */
683   fsp->sent_oplock_break = True;
684
685   /* We need this in case a readraw crosses on the wire. */
686   global_oplock_break = True;
687  
688   /* Process incoming messages. */
689
690   /* JRA - If we don't get a break from the client in OPLOCK_BREAK_TIMEOUT
691      seconds we should just die.... */
692
693   start_time = time(NULL);
694
695   /*
696    * Save the information we need to re-become the
697    * user, then unbecome the user whilst we're doing this.
698    */
699   saved_conn = fsp->conn;
700   saved_vuid = current_user.vuid;
701   dos_GetWd(saved_dir);
702   unbecome_user();
703   /* Save the chain fnum. */
704   file_chain_save();
705
706   while(OPEN_FSP(fsp) && fsp->granted_oplock)
707   {
708     if(receive_smb(Client,inbuf,
709                    (OPLOCK_BREAK_TIMEOUT/OPLOCK_BREAK_RESENDS) * 1000) == False)
710     {
711
712             /* Isaac suggestd that if a MS client doesn't respond to a
713                oplock break request then we might try resending
714                it. Certainly it's no worse than just dropping the
715                socket! */
716             if (smb_read_error == READ_TIMEOUT && break_counter--) {
717                     DEBUG(2, ( "oplock_break resend\n" ) );
718                     send_smb(Client, outbuf);
719                     continue;
720             }
721
722       /*
723        * Die if we got an error.
724        */
725
726       if (smb_read_error == READ_EOF)
727         DEBUG( 0, ( "oplock_break: end of file from client\n" ) );
728  
729       if (smb_read_error == READ_ERROR)
730         DEBUG( 0, ("oplock_break: receive_smb error (%s)\n", strerror(errno)) );
731
732       if (smb_read_error == READ_TIMEOUT)
733         DEBUG( 0, ( "oplock_break: receive_smb timed out after %d seconds.\n",
734                      OPLOCK_BREAK_TIMEOUT ) );
735
736       DEBUGADD( 0, ( "oplock_break failed for file %s ", fsp->fsp_name ) );
737       DEBUGADD( 0, ( "(dev = %x, inode = %.0f).\n", (unsigned int)dev, (double)inode));
738
739       shutdown_server = True;
740       break;
741     }
742
743     /*
744      * There are certain SMB requests that we shouldn't allow
745      * to recurse. opens, renames and deletes are the obvious
746      * ones. This is handled in the switch_message() function.
747      * If global_oplock_break is set they will push the packet onto
748      * the pending smb queue and return -1 (no reply).
749      * JRA.
750      */
751
752     process_smb(inbuf, outbuf);
753
754     /*
755      * Die if we go over the time limit.
756      */
757
758     if((time(NULL) - start_time) > OPLOCK_BREAK_TIMEOUT)
759     {
760       if( DEBUGLVL( 0 ) )
761         {
762         dbgtext( "oplock_break: no break received from client " );
763         dbgtext( "within %d seconds.\n", OPLOCK_BREAK_TIMEOUT );
764         dbgtext( "oplock_break failed for file %s ", fsp->fsp_name );
765         dbgtext( "(dev = %x, inode = %.0f).\n", (unsigned int)dev, (double)inode );
766         }
767       shutdown_server = True;
768       break;
769     }
770   }
771
772   /*
773    * Go back to being the user who requested the oplock
774    * break.
775    */
776   if(!become_user(saved_conn, saved_vuid))
777   {
778     DEBUG( 0, ( "oplock_break: unable to re-become user!" ) );
779     DEBUGADD( 0, ( "Shutting down server\n" ) );
780     close_sockets();
781     close(oplock_sock);
782     exit_server("unable to re-become user");
783   }
784   /* Including the directory. */
785   dos_ChDir(saved_dir);
786
787   /* Restore the chain fnum. */
788   file_chain_restore();
789
790   /* Free the buffers we've been using to recurse. */
791   free(inbuf);
792   free(outbuf);
793
794   /* We need this in case a readraw crossed on the wire. */
795   if(global_oplock_break)
796     global_oplock_break = False;
797
798   /*
799    * If the client did not respond we must die.
800    */
801
802   if(shutdown_server)
803   {
804     DEBUG( 0, ( "oplock_break: client failure in break - " ) );
805     DEBUGADD( 0, ( "shutting down this smbd.\n" ) );
806     close_sockets();
807     close(oplock_sock);
808     exit_server("oplock break failure");
809   }
810
811   if(OPEN_FSP(fsp))
812   {
813     /* The lockingX reply will have removed the oplock flag 
814        from the sharemode. */
815     release_file_oplock(fsp);
816   }
817
818   /* Santity check - remove this later. JRA */
819   if(global_oplocks_open < 0)
820   {
821     DEBUG(0,("oplock_break: global_oplocks_open < 0 (%d). PANIC ERROR\n",
822               global_oplocks_open));
823     exit_server("oplock_break: global_oplocks_open < 0");
824   }
825
826
827   if( DEBUGLVL( 3 ) )
828   {
829     dbgtext( "oplock_break: returning success for " );
830     dbgtext( "dev = %x, inode = %.0f\n", (unsigned int)dev, (double)inode );
831     dbgtext( "Current global_oplocks_open = %d\n", global_oplocks_open );
832   }
833
834   return True;
835 }
836
837 /****************************************************************************
838 Send an oplock break message to another smbd process. If the oplock is held 
839 by the local smbd then call the oplock break function directly.
840 ****************************************************************************/
841
842 BOOL request_oplock_break(share_mode_entry *share_entry, 
843                           SMB_DEV_T dev, SMB_INO_T inode)
844 {
845   char op_break_msg[OPLOCK_BREAK_MSG_LEN];
846   struct sockaddr_in addr_out;
847   int pid = getpid();
848   time_t start_time;
849   int time_left;
850
851   if(pid == share_entry->pid)
852   {
853     /* We are breaking our own oplock, make sure it's us. */
854     if(share_entry->op_port != global_oplock_port)
855     {
856       DEBUG(0,("request_oplock_break: corrupt share mode entry - pid = %d, port = %d \
857 should be %d\n", pid, share_entry->op_port, global_oplock_port));
858       return False;
859     }
860
861     DEBUG(5,("request_oplock_break: breaking our own oplock\n"));
862
863     /* Call oplock break direct. */
864     return oplock_break(dev, inode, &share_entry->time);
865   }
866
867   /* We need to send a OPLOCK_BREAK_CMD message to the
868      port in the share mode entry. */
869
870   SSVAL(op_break_msg,OPBRK_MESSAGE_CMD_OFFSET,OPLOCK_BREAK_CMD);
871   SIVAL(op_break_msg,OPLOCK_BREAK_PID_OFFSET,pid);
872   SIVAL(op_break_msg,OPLOCK_BREAK_SEC_OFFSET,(uint32)share_entry->time.tv_sec);
873   SIVAL(op_break_msg,OPLOCK_BREAK_USEC_OFFSET,(uint32)share_entry->time.tv_usec);
874   SIVAL(op_break_msg,OPLOCK_BREAK_DEV_OFFSET,dev);
875   /*
876    * WARNING - beware of SMB_INO_T <> 4 bytes.
877    */
878 #ifdef LARGE_SMB_INO_T
879   SIVAL(op_break_msg,OPLOCK_BREAK_INODE_OFFSET,(inode & 0xFFFFFFFFL));
880   SIVAL(op_break_msg,OPLOCK_BREAK_INODE_OFFSET+4,((inode >> 32) & 0xFFFFFFFFL));
881 #else /* LARGE_SMB_INO_T */
882   SIVAL(op_break_msg,OPLOCK_BREAK_INODE_OFFSET,inode);
883 #endif /* LARGE_SMB_INO_T */
884
885   /* set the address and port */
886   bzero((char *)&addr_out,sizeof(addr_out));
887   addr_out.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
888   addr_out.sin_port = htons( share_entry->op_port );
889   addr_out.sin_family = AF_INET;
890    
891   if( DEBUGLVL( 3 ) )
892   {
893     dbgtext( "request_oplock_break: sending a oplock break message to " );
894     dbgtext( "pid %d on port %d ", share_entry->pid, share_entry->op_port );
895     dbgtext( "for dev = %x, inode = %.0f\n", (unsigned int)dev, (double)inode );
896   }
897
898   if(sendto(oplock_sock,op_break_msg,OPLOCK_BREAK_MSG_LEN,0,
899          (struct sockaddr *)&addr_out,sizeof(addr_out)) < 0)
900   {
901     if( DEBUGLVL( 0 ) )
902     {
903       dbgtext( "request_oplock_break: failed when sending a oplock " );
904       dbgtext( "break message to pid %d ", share_entry->pid );
905       dbgtext( "on port %d ", share_entry->op_port );
906       dbgtext( "for dev = %x, inode = %.0f\n", (unsigned int)dev, (double)inode );
907       dbgtext( "Error was %s\n", strerror(errno) );
908     }
909     return False;
910   }
911
912   /*
913    * Now we must await the oplock broken message coming back
914    * from the target smbd process. Timeout if it fails to
915    * return in (OPLOCK_BREAK_TIMEOUT + OPLOCK_BREAK_TIMEOUT_FUDGEFACTOR) seconds.
916    * While we get messages that aren't ours, loop.
917    */
918
919   start_time = time(NULL);
920   time_left = OPLOCK_BREAK_TIMEOUT+OPLOCK_BREAK_TIMEOUT_FUDGEFACTOR;
921
922   while(time_left >= 0)
923   {
924     char op_break_reply[OPBRK_CMD_HEADER_LEN+OPLOCK_BREAK_MSG_LEN];
925     int32 reply_msg_len;
926     uint16 reply_from_port;
927     char *reply_msg_start;
928     fd_set fds;
929
930     FD_ZERO(&fds);
931     FD_SET(oplock_sock,&fds);
932 #if defined(HAVE_KERNEL_OPLOCKS)
933     if(lp_kernel_oplocks())
934       FD_SET(oplock_pipe_read,&fds);
935 #endif /* HAVE_KERNEL_OPLOCKS */
936
937     if(receive_local_message(&fds, op_break_reply, sizeof(op_break_reply),
938                time_left ? time_left * 1000 : 1) == False)
939     {
940       if(smb_read_error == READ_TIMEOUT)
941       {
942         if( DEBUGLVL( 0 ) )
943         {
944           dbgtext( "request_oplock_break: no response received to oplock " );
945           dbgtext( "break request to pid %d ", share_entry->pid );
946           dbgtext( "on port %d ", share_entry->op_port );
947           dbgtext( "for dev = %x, inode = %.0f\n", (unsigned int)dev, (double)inode );
948         }
949
950         /*
951          * This is a hack to make handling of failing clients more robust.
952          * If a oplock break response message is not received in the timeout
953          * period we may assume that the smbd servicing that client holding
954          * the oplock has died and the client changes were lost anyway, so
955          * we should continue to try and open the file.
956          */
957         break;
958       }
959       else
960         if( DEBUGLVL( 0 ) )
961         {
962           dbgtext( "request_oplock_break: error in response received " );
963           dbgtext( "to oplock break request to pid %d ", share_entry->pid );
964           dbgtext( "on port %d ", share_entry->op_port );
965           dbgtext( "for dev = %x, inode = %.0f\n", (unsigned int)dev, (double)inode );
966           dbgtext( "Error was (%s).\n", strerror(errno) );
967         }
968       return False;
969     }
970
971     reply_msg_len = IVAL(op_break_reply,OPBRK_CMD_LEN_OFFSET);
972     reply_from_port = SVAL(op_break_reply,OPBRK_CMD_PORT_OFFSET);
973
974     reply_msg_start = &op_break_reply[OPBRK_CMD_HEADER_LEN];
975
976
977 #if defined(HAVE_KERNEL_OPLOCKS)
978     if((reply_msg_len != OPLOCK_BREAK_MSG_LEN) && (reply_msg_len != KERNEL_OPLOCK_BREAK_MSG_LEN))
979 #else
980     if(reply_msg_len != OPLOCK_BREAK_MSG_LEN)
981 #endif
982     {
983       /* Ignore it. */
984       DEBUG( 0, ( "request_oplock_break: invalid message length (%d) received.", reply_msg_len ) );
985       DEBUGADD( 0, ( "  Ignoring.\n" ) );
986       continue;
987     }
988
989     /*
990      * Test to see if this is the reply we are awaiting.
991      */
992
993     if((SVAL(reply_msg_start,OPBRK_MESSAGE_CMD_OFFSET) & CMD_REPLY) &&
994        ((SVAL(reply_msg_start,OPBRK_MESSAGE_CMD_OFFSET) & ~CMD_REPLY) == OPLOCK_BREAK_CMD) &&
995        (reply_from_port == share_entry->op_port) && 
996        (memcmp(&reply_msg_start[OPLOCK_BREAK_PID_OFFSET], 
997                &op_break_msg[OPLOCK_BREAK_PID_OFFSET],
998                OPLOCK_BREAK_MSG_LEN - OPLOCK_BREAK_PID_OFFSET) == 0))
999     {
1000       /*
1001        * This is the reply we've been waiting for.
1002        */
1003       break;
1004     }
1005     else
1006     {
1007       /*
1008        * This is another message - a break request.
1009        * Note that both kernel oplock break requests
1010        * and UDP inter-smbd oplock break requests will
1011        * be processed here.
1012        *
1013        * Process it to prevent potential deadlock.
1014        * Note that the code in switch_message() prevents
1015        * us from recursing into here as any SMB requests
1016        * we might process that would cause another oplock
1017        * break request to be made will be queued.
1018        * JRA.
1019        */
1020
1021       process_local_message(op_break_reply, sizeof(op_break_reply));
1022     }
1023
1024     time_left -= (time(NULL) - start_time);
1025   }
1026
1027   DEBUG(3,("request_oplock_break: broke oplock.\n"));
1028
1029   return True;
1030 }
1031
1032 /****************************************************************************
1033   Attempt to break an oplock on a file (if oplocked).
1034   Returns True if the file was closed as a result of
1035   the oplock break, False otherwise.
1036   Used as a last ditch attempt to free a space in the 
1037   file table when we have run out.
1038 ****************************************************************************/
1039 BOOL attempt_close_oplocked_file(files_struct *fsp)
1040 {
1041
1042   DEBUG(5,("attempt_close_oplocked_file: checking file %s.\n", fsp->fsp_name));
1043
1044   if (fsp->open && fsp->granted_oplock && !fsp->sent_oplock_break && (fsp->fd_ptr != NULL)) {
1045
1046     /* Try and break the oplock. */
1047     file_fd_struct *fd_ptr = fsp->fd_ptr;
1048     if(oplock_break( fd_ptr->dev, fd_ptr->inode, &fsp->open_time)) {
1049       if(!fsp->open) /* Did the oplock break close the file ? */
1050         return True;
1051     }
1052   }
1053
1054   return False;
1055 }
1056
1057 /****************************************************************************
1058  Init function to check if kernel level oplocks are available.
1059 ****************************************************************************/
1060
1061 void check_kernel_oplocks(void)
1062 {
1063   static BOOL done;
1064
1065   /*
1066    * We only do this check once on startup.
1067    */
1068
1069   if(done)
1070     return;
1071
1072   done = True;
1073   lp_set_kernel_oplocks(False);
1074
1075 #if defined(HAVE_KERNEL_OPLOCKS)
1076   {
1077     int fd;
1078     int pfd[2];
1079     pstring tmpname;
1080
1081     set_process_capability(KERNEL_OPLOCK_CAPABILITY,True);
1082     set_inherited_process_capability(KERNEL_OPLOCK_CAPABILITY,True);
1083
1084         slprintf(tmpname,sizeof(tmpname)-1, "%s/koplock.%d", lp_lockdir(), (int)getpid());
1085
1086     if(pipe(pfd) != 0) {
1087       DEBUG(0,("check_kernel_oplocks: Unable to create pipe. Error was %s\n",
1088             strerror(errno) ));
1089       return;
1090     }
1091
1092     if((fd = sys_open(tmpname, O_RDWR|O_CREAT|O_EXCL|O_TRUNC, 0600)) < 0) {
1093       DEBUG(0,("check_kernel_oplocks: Unable to open temp test file %s. Error was %s\n",
1094             tmpname, strerror(errno) ));
1095       unlink( tmpname );
1096       close(pfd[0]);
1097       close(pfd[1]);
1098       return;
1099     }
1100
1101     unlink( tmpname );
1102
1103     if(fcntl(fd, F_OPLKREG, pfd[1]) == -1) {
1104       DEBUG(0,("check_kernel_oplocks: Kernel oplocks are not available on this machine. \
1105 Disabling kernel oplock support.\n" ));
1106       close(pfd[0]);
1107       close(pfd[1]);
1108       close(fd);
1109       return;
1110     }
1111
1112     if(fcntl(fd, F_OPLKACK, OP_REVOKE) < 0 ) {
1113       DEBUG(0,("check_kernel_oplocks: Error when removing kernel oplock. Error was %s. \
1114 Disabling kernel oplock support.\n", strerror(errno) ));
1115       close(pfd[0]);
1116       close(pfd[1]);
1117       close(fd);
1118       return;
1119     }
1120
1121     close(pfd[0]);
1122     close(pfd[1]);
1123     close(fd);
1124
1125     lp_set_kernel_oplocks(True);
1126
1127     DEBUG(0,("check_kernel_oplocks: Kernel oplocks available and set to %s.\n",
1128           lp_kernel_oplocks() ? "True" : "False" ));
1129
1130   }
1131 #endif /* HAVE_KERNEL_OPLOCKS */
1132 }