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