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