b4ae0f61a9a4aa23d7cdac2b4c8953e0dd166c94
[samba.git] / source3 / smbd / nttrans.c
1 /*
2    Unix SMB/Netbios implementation.
3    Version 1.9.
4    SMB NT transaction handling
5    Copyright (C) Jeremy Allison 1994-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 #include "nterr.h"
24
25 extern int DEBUGLEVEL;
26 extern int Protocol;
27 extern int smb_read_error;
28 extern int global_oplock_break;
29 extern BOOL case_sensitive;
30 extern BOOL case_preserve;
31 extern BOOL short_case_preserve;
32
33 static void remove_pending_change_notify_requests_by_mid(int mid);
34
35 static char *known_nt_pipes[] = {
36   "\\LANMAN",
37   "\\srvsvc",
38   "\\samr",
39   "\\wkssvc",
40   "\\NETLOGON",
41   "\\ntlsa",
42   "\\ntsvcs",
43   "\\lsass",
44   "\\lsarpc",
45   "\\winreg",
46   "\\spoolss",
47   NULL
48 };
49
50 /****************************************************************************
51  Send the required number of replies back.
52  We assume all fields other than the data fields are
53  set correctly for the type of call.
54  HACK ! Always assumes smb_setup field is zero.
55 ****************************************************************************/
56
57 static int send_nt_replies(char *inbuf, char *outbuf, int bufsize, uint32 nt_error, char *params,
58                            int paramsize, char *pdata, int datasize)
59 {
60   extern int max_send;
61   int data_to_send = datasize;
62   int params_to_send = paramsize;
63   int useable_space;
64   char *pp = params;
65   char *pd = pdata;
66   int params_sent_thistime, data_sent_thistime, total_sent_thistime;
67   int alignment_offset = 3;
68   int data_alignment_offset = 0;
69
70   /*
71    * Initially set the wcnt area to be 18 - this is true for all
72    * transNT replies.
73    */
74
75   set_message(outbuf,18,0,True);
76
77   if(nt_error != 0) {
78     /* NT Error. */
79     SSVAL(outbuf,smb_flg2, SVAL(outbuf,smb_flg2) | FLAGS2_32_BIT_ERROR_CODES);
80
81     ERROR(0,nt_error);
82   }
83
84   /* 
85    * If there genuinely are no parameters or data to send just send
86    * the empty packet.
87    */
88
89   if(params_to_send == 0 && data_to_send == 0) {
90     send_smb(smbd_server_fd(),outbuf);
91     return 0;
92   }
93
94   /*
95    * When sending params and data ensure that both are nicely aligned.
96    * Only do this alignment when there is also data to send - else
97    * can cause NT redirector problems.
98    */
99
100   if (((params_to_send % 4) != 0) && (data_to_send != 0))
101     data_alignment_offset = 4 - (params_to_send % 4);
102
103   /* 
104    * Space is bufsize minus Netbios over TCP header minus SMB header.
105    * The alignment_offset is to align the param bytes on a four byte
106    * boundary (2 bytes for data len, one byte pad). 
107    * NT needs this to work correctly.
108    */
109
110   useable_space = bufsize - ((smb_buf(outbuf)+
111                     alignment_offset+data_alignment_offset) -
112                     outbuf);
113
114   /*
115    * useable_space can never be more than max_send minus the
116    * alignment offset.
117    */
118
119   useable_space = MIN(useable_space,
120                       max_send - (alignment_offset+data_alignment_offset));
121
122
123   while (params_to_send || data_to_send) {
124
125     /*
126      * Calculate whether we will totally or partially fill this packet.
127      */
128
129     total_sent_thistime = params_to_send + data_to_send +
130                             alignment_offset + data_alignment_offset;
131
132     /* 
133      * We can never send more than useable_space.
134      */
135
136     total_sent_thistime = MIN(total_sent_thistime, useable_space);
137
138     set_message(outbuf, 18, total_sent_thistime, True);
139
140     /*
141      * Set total params and data to be sent.
142      */
143
144     SIVAL(outbuf,smb_ntr_TotalParameterCount,paramsize);
145     SIVAL(outbuf,smb_ntr_TotalDataCount,datasize);
146
147     /* 
148      * Calculate how many parameters and data we can fit into
149      * this packet. Parameters get precedence.
150      */
151
152     params_sent_thistime = MIN(params_to_send,useable_space);
153     data_sent_thistime = useable_space - params_sent_thistime;
154     data_sent_thistime = MIN(data_sent_thistime,data_to_send);
155
156     SIVAL(outbuf,smb_ntr_ParameterCount,params_sent_thistime);
157
158     if(params_sent_thistime == 0) {
159       SIVAL(outbuf,smb_ntr_ParameterOffset,0);
160       SIVAL(outbuf,smb_ntr_ParameterDisplacement,0);
161     } else {
162       /*
163        * smb_ntr_ParameterOffset is the offset from the start of the SMB header to the
164        * parameter bytes, however the first 4 bytes of outbuf are
165        * the Netbios over TCP header. Thus use smb_base() to subtract
166        * them from the calculation.
167        */
168
169       SIVAL(outbuf,smb_ntr_ParameterOffset,
170             ((smb_buf(outbuf)+alignment_offset) - smb_base(outbuf)));
171       /* 
172        * Absolute displacement of param bytes sent in this packet.
173        */
174
175       SIVAL(outbuf,smb_ntr_ParameterDisplacement,pp - params);
176     }
177
178     /*
179      * Deal with the data portion.
180      */
181
182     SIVAL(outbuf,smb_ntr_DataCount, data_sent_thistime);
183
184     if(data_sent_thistime == 0) {
185       SIVAL(outbuf,smb_ntr_DataOffset,0);
186       SIVAL(outbuf,smb_ntr_DataDisplacement, 0);
187     } else {
188       /*
189        * The offset of the data bytes is the offset of the
190        * parameter bytes plus the number of parameters being sent this time.
191        */
192
193       SIVAL(outbuf,smb_ntr_DataOffset,((smb_buf(outbuf)+alignment_offset) -
194             smb_base(outbuf)) + params_sent_thistime + data_alignment_offset);
195       SIVAL(outbuf,smb_ntr_DataDisplacement, pd - pdata);
196     }
197
198     /* 
199      * Copy the param bytes into the packet.
200      */
201
202     if(params_sent_thistime)
203       memcpy((smb_buf(outbuf)+alignment_offset),pp,params_sent_thistime);
204
205     /*
206      * Copy in the data bytes
207      */
208
209     if(data_sent_thistime)
210       memcpy(smb_buf(outbuf)+alignment_offset+params_sent_thistime+
211              data_alignment_offset,pd,data_sent_thistime);
212     
213     DEBUG(9,("nt_rep: params_sent_thistime = %d, data_sent_thistime = %d, useable_space = %d\n",
214           params_sent_thistime, data_sent_thistime, useable_space));
215     DEBUG(9,("nt_rep: params_to_send = %d, data_to_send = %d, paramsize = %d, datasize = %d\n",
216           params_to_send, data_to_send, paramsize, datasize));
217     
218     /* Send the packet */
219     send_smb(smbd_server_fd(),outbuf);
220     
221     pp += params_sent_thistime;
222     pd += data_sent_thistime;
223     
224     params_to_send -= params_sent_thistime;
225     data_to_send -= data_sent_thistime;
226
227     /*
228      * Sanity check
229      */
230
231     if(params_to_send < 0 || data_to_send < 0) {
232       DEBUG(0,("send_nt_replies failed sanity check pts = %d, dts = %d\n!!!",
233             params_to_send, data_to_send));
234       return -1;
235     }
236   } 
237
238   return 0;
239 }
240
241 /****************************************************************************
242  (Hopefully) temporary call to fix bugs in NT5.0beta2. This OS sends unicode
243  strings in NT calls AND DOESN'T SET THE UNICODE BIT !!!!!!!
244 ****************************************************************************/
245
246 static void get_filename( char *fname, char *inbuf, int data_offset, int data_len, int fname_len)
247 {
248   /*
249    * We need various heuristics here to detect a unicode string... JRA.
250    */
251
252   DEBUG(10,("get_filename: data_offset = %d, data_len = %d, fname_len = %d\n",
253            data_offset, data_len, fname_len ));
254
255   if(data_len - fname_len > 1) {
256     /*
257      * NT 5.0 Beta 2 has kindly sent us a UNICODE string
258      * without bothering to set the unicode bit. How kind.
259      *
260      * Firstly - ensure that the data offset is aligned
261      * on a 2 byte boundary - add one if not.
262      */
263     fname_len = fname_len/2;
264     if(data_offset & 1)
265       data_offset++;
266     pstrcpy(fname, dos_unistrn2((uint16 *)(inbuf+data_offset), fname_len));
267   } else {
268     StrnCpy(fname,inbuf+data_offset,fname_len);
269     fname[fname_len] = '\0';
270   }
271 }
272
273 /****************************************************************************
274  Fix bugs in Win2000 final release. In trans calls this OS sends unicode
275  strings AND DOESN'T SET THE UNICODE BIT !!!!!!!
276 ****************************************************************************/
277
278 static void get_filename_transact( char *fname, char *inbuf, int data_offset, int data_len, int fname_len)
279 {
280   /*
281    * We need various heuristics here to detect a unicode string... JRA.
282    */
283
284   DEBUG(10,("get_filename_transact: data_offset = %d, data_len = %d, fname_len = %d\n",
285            data_offset, data_len, fname_len ));
286
287   /*
288    * Win2K sends a unicode filename plus one extra alingment byte.
289    * WinNT4.x send an ascii string with multiple garbage bytes on
290    * the end here.
291    */
292
293   if((data_len - fname_len == 1) || (inbuf[data_offset] == '\0')) {
294     /*
295      * Ensure that the data offset is aligned
296      * on a 2 byte boundary - add one if not.
297      */
298     fname_len = fname_len/2;
299     if(data_offset & 1)
300       data_offset++;
301     pstrcpy(fname, dos_unistrn2((uint16 *)(inbuf+data_offset), fname_len));
302   } else {
303     StrnCpy(fname,inbuf+data_offset,fname_len);
304     fname[fname_len] = '\0';
305   }
306 }
307
308 /****************************************************************************
309  Save case statics.
310 ****************************************************************************/
311
312 static BOOL saved_case_sensitive;
313 static BOOL saved_case_preserve;
314 static BOOL saved_short_case_preserve;
315
316 /****************************************************************************
317  Save case semantics.
318 ****************************************************************************/
319
320 static void set_posix_case_semantics(uint32 file_attributes)
321 {
322   if(!(file_attributes & FILE_FLAG_POSIX_SEMANTICS))
323     return;
324
325   saved_case_sensitive = case_sensitive;
326   saved_case_preserve = case_preserve;
327   saved_short_case_preserve = short_case_preserve;
328
329   /* Set to POSIX. */
330   case_sensitive = True;
331   case_preserve = True;
332   short_case_preserve = True;
333 }
334
335 /****************************************************************************
336  Restore case semantics.
337 ****************************************************************************/
338
339 static void restore_case_semantics(uint32 file_attributes)
340 {
341   if(!(file_attributes & FILE_FLAG_POSIX_SEMANTICS))
342     return;
343
344   case_sensitive = saved_case_sensitive;
345   case_preserve = saved_case_preserve;
346   short_case_preserve = saved_short_case_preserve;
347 }
348
349 /****************************************************************************
350  Utility function to map create disposition.
351 ****************************************************************************/
352
353 static int map_create_disposition( uint32 create_disposition)
354 {
355   int ret;
356
357   switch( create_disposition ) {
358   case FILE_CREATE:
359     /* create if not exist, fail if exist */
360     ret = (FILE_CREATE_IF_NOT_EXIST|FILE_EXISTS_FAIL);
361     break;
362   case FILE_SUPERSEDE:
363   case FILE_OVERWRITE_IF:
364     /* create if not exist, trunc if exist */
365     ret = (FILE_CREATE_IF_NOT_EXIST|FILE_EXISTS_TRUNCATE);
366     break;
367   case FILE_OPEN:
368     /* fail if not exist, open if exists */
369     ret = (FILE_FAIL_IF_NOT_EXIST|FILE_EXISTS_OPEN);
370     break;
371   case FILE_OPEN_IF:
372     /* create if not exist, open if exists */
373     ret = (FILE_CREATE_IF_NOT_EXIST|FILE_EXISTS_OPEN);
374     break;
375   case FILE_OVERWRITE:
376     /* fail if not exist, truncate if exists */
377     ret = (FILE_FAIL_IF_NOT_EXIST|FILE_EXISTS_TRUNCATE);
378     break;
379   default:
380     DEBUG(0,("map_create_disposition: Incorrect value for create_disposition = %d\n",
381              create_disposition ));
382     return -1;
383   }
384
385   DEBUG(10,("map_create_disposition: Mapped create_disposition %lx to %x\n",
386         (unsigned long)create_disposition, ret ));
387
388   return ret;
389 }
390
391 /****************************************************************************
392  Utility function to map share modes.
393 ****************************************************************************/
394
395 static int map_share_mode( BOOL *pstat_open_only, char *fname,
396                                                         uint32 desired_access, uint32 share_access, uint32 file_attributes)
397 {
398   int smb_open_mode = -1;
399
400   *pstat_open_only = False;
401
402   switch( desired_access & (FILE_READ_DATA|FILE_WRITE_DATA|FILE_APPEND_DATA) ) {
403   case FILE_READ_DATA:
404     smb_open_mode = DOS_OPEN_RDONLY;
405     break;
406   case FILE_WRITE_DATA:
407   case FILE_APPEND_DATA:
408   case FILE_WRITE_DATA|FILE_APPEND_DATA:
409     smb_open_mode = DOS_OPEN_WRONLY;
410     break;
411   case FILE_READ_DATA|FILE_WRITE_DATA:
412   case FILE_READ_DATA|FILE_WRITE_DATA|FILE_APPEND_DATA:
413   case FILE_READ_DATA|FILE_APPEND_DATA:
414     smb_open_mode = DOS_OPEN_RDWR;
415     break;
416   }
417
418   /*
419    * NB. For DELETE_ACCESS we should really check the
420    * directory permissions, as that is what controls
421    * delete, and for WRITE_DAC_ACCESS we should really
422    * check the ownership, as that is what controls the
423    * chmod. Note that this is *NOT* a security hole (this
424    * note is for you, Andrew) as we are not *allowing*
425    * the access at this point, the actual unlink or
426    * chown or chmod call would do this. We are just helping
427    * clients out by telling them if they have a hope
428    * of any of this succeeding. POSIX acls may still
429    * deny the real call. JRA.
430    */
431
432   if (smb_open_mode == -1) {
433         if(desired_access == WRITE_DAC_ACCESS || desired_access == READ_CONTROL_ACCESS)
434                 *pstat_open_only = True;
435
436     if(desired_access & (DELETE_ACCESS|WRITE_DAC_ACCESS|WRITE_OWNER_ACCESS|
437                               FILE_EXECUTE|FILE_READ_ATTRIBUTES|
438                               FILE_READ_EA|FILE_WRITE_EA|SYSTEM_SECURITY_ACCESS|
439                               FILE_WRITE_ATTRIBUTES|READ_CONTROL_ACCESS))
440       smb_open_mode = DOS_OPEN_RDONLY;
441     else {
442       DEBUG(0,("map_share_mode: Incorrect value %lx for desired_access to file %s\n",
443              (unsigned long)desired_access, fname));
444       return -1;
445     }
446   }
447
448   /*
449    * Set the special bit that means allow share delete.
450    * This is held outside the normal share mode bits at 1<<15.
451    * JRA.
452    */
453
454   if(share_access & FILE_SHARE_DELETE)
455     smb_open_mode |= ALLOW_SHARE_DELETE;
456
457   /* Add in the requested share mode. */
458   switch( share_access & (FILE_SHARE_READ|FILE_SHARE_WRITE)) {
459   case FILE_SHARE_READ:
460     smb_open_mode |= SET_DENY_MODE(DENY_WRITE);
461     break;
462   case FILE_SHARE_WRITE:
463     smb_open_mode |= SET_DENY_MODE(DENY_READ);
464     break;
465   case (FILE_SHARE_READ|FILE_SHARE_WRITE):
466     smb_open_mode |= SET_DENY_MODE(DENY_NONE);
467     break;
468   case FILE_SHARE_NONE:
469     smb_open_mode |= SET_DENY_MODE(DENY_ALL);
470     break;
471   }
472
473   /*
474    * Handle an O_SYNC request.
475    */
476
477   if(file_attributes & FILE_FLAG_WRITE_THROUGH)
478     smb_open_mode |= FILE_SYNC_OPENMODE;
479
480   DEBUG(10,("map_share_mode: Mapped desired access %lx, share access %lx, file attributes %lx \
481 to open_mode %x\n", (unsigned long)desired_access, (unsigned long)share_access,
482                     (unsigned long)file_attributes, smb_open_mode ));
483  
484   return smb_open_mode;
485 }
486
487 /*
488  * This is a *disgusting* hack.
489  * This is *so* bad that even I'm embarrassed (and I
490  * have no shame). Here's the deal :
491  * Until we get the correct SPOOLSS code into smbd
492  * then when we're running with NT SMB support then
493  * NT makes this call with a level of zero, and then
494  * immediately follows it with an open request to
495  * the \\SRVSVC pipe. If we allow that open to
496  * succeed then NT barfs when it cannot open the
497  * \\SPOOLSS pipe immediately after and continually
498  * whines saying "Printer name is invalid" forever
499  * after. If we cause *JUST THIS NEXT OPEN* of \\SRVSVC
500  * to fail, then NT downgrades to using the downlevel code
501  * and everything works as well as before. I hate
502  * myself for adding this code.... JRA.
503  *
504  * The HACK_FAIL_TIME define allows only a 2
505  * second window for this to occur, just in
506  * case...
507  */
508
509 static BOOL fail_next_srvsvc = False;
510 static time_t fail_time;
511 #define HACK_FAIL_TIME 2 /* In seconds. */
512
513 void fail_next_srvsvc_open(void)
514 {
515   /* Check client is WinNT proper; Win2K doesn't like Jeremy's hack - matty */
516   if (get_remote_arch() != RA_WINNT)
517     return;
518
519   fail_next_srvsvc = True;
520   fail_time = time(NULL);
521   DEBUG(10,("fail_next_srvsvc_open: setting up timeout close of \\srvsvc pipe for print fix.\n"));
522 }
523
524 /*
525  * HACK alert.... see above - JRA.
526  */
527
528 BOOL should_fail_next_srvsvc_open(const char *pipename)
529 {
530
531   DEBUG(10,("should_fail_next_srvsvc_open: fail = %d, pipe = %s\n",
532     (int)fail_next_srvsvc, pipename));
533
534   if(fail_next_srvsvc && (time(NULL) > fail_time + HACK_FAIL_TIME)) {
535     fail_next_srvsvc = False;
536     fail_time = (time_t)0;
537     DEBUG(10,("should_fail_next_srvsvc_open: End of timeout close of \\srvsvc pipe for print fix.\n"));
538   }
539
540   if(fail_next_srvsvc && strequal(pipename, "srvsvc")) {
541     fail_next_srvsvc = False;
542     DEBUG(10,("should_fail_next_srvsvc_open: Deliberately failing open of \\srvsvc pipe for print fix.\n"));
543     return True;
544   }
545   return False;
546 }
547
548
549 /****************************************************************************
550  Reply to an NT create and X call on a pipe.
551 ****************************************************************************/
552 static int nt_open_pipe(char *fname, connection_struct *conn,
553                         char *inbuf, char *outbuf, int *ppnum)
554 {
555         pipes_struct *p = NULL;
556
557         uint16 vuid = SVAL(inbuf, smb_uid);
558         int i;
559
560         DEBUG(4,("nt_open_pipe: Opening pipe %s.\n", fname));
561     
562         /* See if it is one we want to handle. */
563         for( i = 0; known_nt_pipes[i]; i++ )
564                 if( strequal(fname,known_nt_pipes[i]))
565                         break;
566     
567         if ( known_nt_pipes[i] == NULL )
568                 return(ERROR(ERRSRV,ERRaccess));
569     
570         /* Strip \\ off the name. */
571         fname++;
572     
573         if(should_fail_next_srvsvc_open(fname))
574                 return (ERROR(ERRSRV,ERRaccess));
575
576         DEBUG(3,("nt_open_pipe: Known pipe %s opening.\n", fname));
577
578         p = open_rpc_pipe_p(fname, conn, vuid);
579         if (!p)
580                 return(ERROR(ERRSRV,ERRnofids));
581
582         *ppnum = p->pnum;
583
584         return 0;
585 }
586
587 /****************************************************************************
588  Reply to an NT create and X call.
589 ****************************************************************************/
590
591 int reply_ntcreate_and_X(connection_struct *conn,
592                          char *inbuf,char *outbuf,int length,int bufsize)
593 {  
594         pstring fname;
595         uint32 flags = IVAL(inbuf,smb_ntcreate_Flags);
596         uint32 desired_access = IVAL(inbuf,smb_ntcreate_DesiredAccess);
597         uint32 file_attributes = IVAL(inbuf,smb_ntcreate_FileAttributes);
598         uint32 share_access = IVAL(inbuf,smb_ntcreate_ShareAccess);
599         uint32 create_disposition = IVAL(inbuf,smb_ntcreate_CreateDisposition);
600         uint32 create_options = IVAL(inbuf,smb_ntcreate_CreateOptions);
601         uint32 fname_len = MIN(((uint32)SVAL(inbuf,smb_ntcreate_NameLength)),
602                                ((uint32)sizeof(fname)-1));
603         uint16 root_dir_fid = (uint16)IVAL(inbuf,smb_ntcreate_RootDirectoryFid);
604         int smb_ofun;
605         int smb_open_mode;
606         int smb_attr = (file_attributes & SAMBA_ATTRIBUTES_MASK);
607         /* Breakout the oplock request bits so we can set the
608            reply bits separately. */
609         int oplock_request = 0;
610         mode_t unixmode;
611         int pnum = -1;
612         int fmode=0,rmode=0;
613         SMB_OFF_T file_len = 0;
614         SMB_STRUCT_STAT sbuf;
615         int smb_action = 0;
616         BOOL bad_path = False;
617         files_struct *fsp=NULL;
618         char *p = NULL;
619         BOOL stat_open_only = False;
620
621         /* 
622          * We need to construct the open_and_X ofun value from the
623          * NT values, as that's what our code is structured to accept.
624          */    
625         
626         if((smb_ofun = map_create_disposition( create_disposition )) == -1)
627                 return(ERROR(ERRDOS,ERRbadaccess));
628
629         /*
630          * Get the file name.
631          */
632
633     if(root_dir_fid != 0) {
634       /*
635        * This filename is relative to a directory fid.
636        */
637       files_struct *dir_fsp = file_fsp(inbuf,smb_ntcreate_RootDirectoryFid);
638       size_t dir_name_len;
639
640       if(!dir_fsp)
641         return(ERROR(ERRDOS,ERRbadfid));
642
643       if(!dir_fsp->is_directory) {
644         /* 
645          * Check to see if this is a mac fork of some kind.
646          */
647
648         get_filename(&fname[0], inbuf, smb_buf(inbuf)-inbuf, 
649                    smb_buflen(inbuf),fname_len);
650
651         if( fname[0] == ':') {
652           SSVAL(outbuf, smb_flg2, FLAGS2_32_BIT_ERROR_CODES);
653           return(ERROR(0, 0xc0000000|NT_STATUS_OBJECT_PATH_NOT_FOUND));
654         }
655         return(ERROR(ERRDOS,ERRbadfid));
656       }
657
658       /*
659        * Copy in the base directory name.
660        */
661
662       pstrcpy( fname, dir_fsp->fsp_name );
663       dir_name_len = strlen(fname);
664
665       /*
666        * Ensure it ends in a '\'.
667        */
668
669       if(fname[dir_name_len-1] != '\\' && fname[dir_name_len-1] != '/') {
670         pstrcat(fname, "\\");
671         dir_name_len++;
672       }
673
674       /*
675        * This next calculation can refuse a correct filename if we're dealing
676        * with the Win2k unicode bug, but that would be rare. JRA.
677        */
678
679       if(fname_len + dir_name_len >= sizeof(pstring))
680         return(ERROR(ERRSRV,ERRfilespecs));
681
682       get_filename(&fname[dir_name_len], inbuf, smb_buf(inbuf)-inbuf, 
683                    smb_buflen(inbuf),fname_len);
684
685     } else {
686       
687       get_filename(fname, inbuf, smb_buf(inbuf)-inbuf, 
688                    smb_buflen(inbuf),fname_len);
689     }
690         
691         /* If it's an IPC, use the pipe handler. */
692
693         if (IS_IPC(conn) && lp_nt_pipe_support()) {
694
695                 int ret = nt_open_pipe(fname, conn, inbuf, outbuf, &pnum);
696                 if(ret != 0)
697                         return ret;
698
699                 /*
700                  * Deal with pipe return.
701                  */  
702
703                 set_message(outbuf,34,0,True);
704         
705                 p = outbuf + smb_vwv2;
706                 p++;
707                 SSVAL(p,0,pnum);
708                 p += 2;
709                 SIVAL(p,0,FILE_WAS_OPENED);
710                 p += 4;
711                 p += 32;
712                 SIVAL(p,0,FILE_ATTRIBUTE_NORMAL); /* File Attributes. */
713                 p += 20;
714                 /* File type. */
715                 SSVAL(p,0,FILE_TYPE_MESSAGE_MODE_PIPE);
716                 /* Device state. */
717                 SSVAL(p,2, 0x5FF); /* ? */
718
719                 DEBUG(5,("reply_ntcreate_and_X: open pipe = %s\n", fname));
720
721                 return chain_reply(inbuf,outbuf,length,bufsize);
722         }
723
724         /*
725          * Now contruct the smb_open_mode value from the filename, 
726      * desired access and the share access.
727          */
728         RESOLVE_DFSPATH(fname, conn, inbuf, outbuf);
729
730         if((smb_open_mode = map_share_mode(&stat_open_only, fname, desired_access, 
731                                            share_access, 
732                                            file_attributes)) == -1)
733                 return(ERROR(ERRDOS,ERRbadaccess));
734
735         oplock_request = (flags & REQUEST_OPLOCK) ? EXCLUSIVE_OPLOCK : 0;
736         oplock_request |= (flags & REQUEST_BATCH_OPLOCK) ? BATCH_OPLOCK : 0;
737
738         /*
739          * Ordinary file or directory.
740          */
741                 
742         /*
743          * Check if POSIX semantics are wanted.
744          */
745                 
746         set_posix_case_semantics(file_attributes);
747                 
748         unix_convert(fname,conn,0,&bad_path,NULL);
749                 
750         unixmode = unix_mode(conn,smb_attr | aARCH, fname);
751     
752         /* 
753          * If it's a request for a directory open, deal with it separately.
754          */
755
756         if(create_options & FILE_DIRECTORY_FILE) {
757                 oplock_request = 0;
758                 
759                 fsp = open_directory(conn, fname, smb_ofun, unixmode, &smb_action);
760                         
761                 restore_case_semantics(file_attributes);
762
763                 if(!fsp) {
764                         return(UNIXERROR(ERRDOS,ERRnoaccess));
765                 }
766         } else {
767                 /*
768                  * Ordinary file case.
769                  */
770
771                 /* NB. We have a potential bug here. If we
772                  * cause an oplock break to ourselves, then we
773                  * could end up processing filename related
774                  * SMB requests whilst we await the oplock
775                  * break response. As we may have changed the
776                  * filename case semantics to be POSIX-like,
777                  * this could mean a filename request could
778                  * fail when it should succeed. This is a rare
779                  * condition, but eventually we must arrange
780                  * to restore the correct case semantics
781                  * before issuing an oplock break request to
782                  * our client. JRA.  */
783
784                 fsp = open_file_shared(conn,fname,smb_open_mode,
785                                  smb_ofun,unixmode, oplock_request,&rmode,&smb_action);
786
787                 if (!fsp) { 
788                         /* We cheat here. There are two cases we
789                          * care about. One is a directory rename,
790                          * where the NT client will attempt to
791                          * open the source directory for
792                          * DELETE access. Note that when the
793                          * NT client does this it does *not*
794                          * set the directory bit in the
795                          * request packet. This is translated
796                          * into a read/write open
797                          * request. POSIX states that any open
798                          * for write request on a directory
799                          * will generate an EISDIR error, so
800                          * we can catch this here and open a
801                          * pseudo handle that is flagged as a
802                          * directory. The second is an open
803                          * for a permissions read only, which
804                          * we handle in the open_file_stat case. JRA.
805                          */
806
807                         if(errno == EISDIR) {
808
809                                 /*
810                                  * Fail the open if it was explicitly a non-directory file.
811                                  */
812
813                                 if (create_options & FILE_NON_DIRECTORY_FILE) {
814                                         restore_case_semantics(file_attributes);
815                                         SSVAL(outbuf, smb_flg2, FLAGS2_32_BIT_ERROR_CODES);
816                                         return(ERROR(0, 0xc0000000|NT_STATUS_FILE_IS_A_DIRECTORY));
817                                 }
818         
819                                 oplock_request = 0;
820                                 fsp = open_directory(conn, fname, smb_ofun, unixmode, &smb_action);
821                                 
822                                 if(!fsp) {
823                                         restore_case_semantics(file_attributes);
824                                         return(UNIXERROR(ERRDOS,ERRnoaccess));
825                                 }
826 #ifdef EROFS
827                         } else if (((errno == EACCES) || (errno == EROFS)) && stat_open_only) {
828 #else /* !EROFS */
829                         } else if (errno == EACCES && stat_open_only) {
830 #endif
831                                 /*
832                                  * We couldn't open normally and all we want
833                                  * are the permissions. Try and do a stat open.
834                                  */
835
836                                 oplock_request = 0;
837
838                                 fsp = open_file_stat(conn,fname,smb_open_mode,&sbuf,&smb_action);
839
840                                 if(!fsp) {
841                                         restore_case_semantics(file_attributes);
842                                         return(UNIXERROR(ERRDOS,ERRnoaccess));
843                                 }
844
845                         } else {
846
847                                 if((errno == ENOENT) && bad_path) {
848                                         unix_ERR_class = ERRDOS;
849                                         unix_ERR_code = ERRbadpath;
850                                 }
851                                 
852                                 restore_case_semantics(file_attributes);
853                                 
854                                 return(UNIXERROR(ERRDOS,ERRnoaccess));
855                         }
856                 } 
857         }
858                 
859         if(fsp->is_directory) {
860                 if(conn->vfs_ops.stat(dos_to_unix(fsp->fsp_name, False), &sbuf) != 0) {
861                         close_file(fsp,True);
862                         restore_case_semantics(file_attributes);
863                         return(ERROR(ERRDOS,ERRnoaccess));
864                 }
865         } else {
866                 if (conn->vfs_ops.fstat(fsp->fd,&sbuf) != 0) {
867                         close_file(fsp,False);
868                         restore_case_semantics(file_attributes);
869                         return(ERROR(ERRDOS,ERRnoaccess));
870                 } 
871         }
872                 
873         restore_case_semantics(file_attributes);
874                 
875         file_len = sbuf.st_size;
876         fmode = dos_mode(conn,fname,&sbuf);
877         if(fmode == 0)
878                 fmode = FILE_ATTRIBUTE_NORMAL;
879         if (!fsp->is_directory && (fmode & aDIR)) {
880                 close_file(fsp,False);
881                 return(ERROR(ERRDOS,ERRnoaccess));
882         } 
883         
884         /* 
885          * If the caller set the extended oplock request bit
886          * and we granted one (by whatever means) - set the
887          * correct bit for extended oplock reply.
888          */
889         
890         if (oplock_request && lp_fake_oplocks(SNUM(conn)))
891                 smb_action |= EXTENDED_OPLOCK_GRANTED;
892         
893         if(oplock_request && EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type))
894                 smb_action |= EXTENDED_OPLOCK_GRANTED;
895
896         set_message(outbuf,34,0,True);
897         
898         p = outbuf + smb_vwv2;
899         
900         /*
901          * Currently as we don't support level II oplocks we just report
902          * exclusive & batch here.
903          */
904
905     if (smb_action & EXTENDED_OPLOCK_GRANTED)   
906                 SCVAL(p,0, BATCH_OPLOCK_RETURN);
907         else if (LEVEL_II_OPLOCK_TYPE(fsp->oplock_type))
908         SCVAL(p,0, LEVEL_II_OPLOCK_RETURN);
909         else
910                 SCVAL(p,0,NO_OPLOCK_RETURN);
911         
912         p++;
913         SSVAL(p,0,fsp->fnum);
914         p += 2;
915         SIVAL(p,0,smb_action);
916         p += 4;
917         
918         /* Create time. */  
919         put_long_date(p,get_create_time(&sbuf,lp_fake_dir_create_times(SNUM(conn))));
920         p += 8;
921         put_long_date(p,sbuf.st_atime); /* access time */
922         p += 8;
923         put_long_date(p,sbuf.st_mtime); /* write time */
924         p += 8;
925         put_long_date(p,sbuf.st_mtime); /* change time */
926         p += 8;
927         SIVAL(p,0,fmode); /* File Attributes. */
928         p += 4;
929         SOFF_T(p, 0, file_len);
930         p += 8;
931         SOFF_T(p,0,file_len);
932         p += 12;
933         SCVAL(p,0,fsp->is_directory ? 1 : 0);
934         
935         DEBUG(5,("reply_ntcreate_and_X: fnum = %d, open name = %s\n", fsp->fnum, fsp->fsp_name));
936
937         return chain_reply(inbuf,outbuf,length,bufsize);
938 }
939
940 /****************************************************************************
941  Reply to a NT_TRANSACT_CREATE call (needs to process SD's).
942 ****************************************************************************/
943
944 static int call_nt_transact_create(connection_struct *conn,
945                                         char *inbuf, char *outbuf, int length, 
946                                         int bufsize, char **ppsetup, char **ppparams, 
947                                         char **ppdata)
948 {
949   pstring fname;
950   char *params = *ppparams;
951   int total_parameter_count = (int)IVAL(inbuf, smb_nt_TotalParameterCount);
952   /* Breakout the oplock request bits so we can set the
953      reply bits separately. */
954   int oplock_request = 0;
955   mode_t unixmode;
956   int pnum = -1;
957   int fmode=0,rmode=0;
958   SMB_OFF_T file_len = 0;
959   SMB_STRUCT_STAT sbuf;
960   int smb_action = 0;
961   BOOL bad_path = False;
962   files_struct *fsp = NULL;
963   char *p = NULL;
964   BOOL stat_open_only = False;
965   uint32 flags;
966   uint32 desired_access;
967   uint32 file_attributes;
968   uint32 share_access;
969   uint32 create_disposition;
970   uint32 create_options;
971   uint32 fname_len;
972   uint16 root_dir_fid;
973   int smb_ofun;
974   int smb_open_mode;
975   int smb_attr;
976
977   DEBUG(5,("call_nt_transact_create\n"));
978
979   /*
980    * Ensure minimum number of parameters sent.
981    */
982
983   if(total_parameter_count < 54) {
984     DEBUG(0,("call_nt_transact_create - insufficient parameters (%u)\n", (unsigned int)total_parameter_count));
985     return(ERROR(ERRDOS,ERRbadaccess));
986   }
987
988   flags = IVAL(params,0);
989   desired_access = IVAL(params,8);
990   file_attributes = IVAL(params,20);
991   share_access = IVAL(params,24);
992   create_disposition = IVAL(params,28);
993   create_options = IVAL(params,32);
994   fname_len = MIN(((uint32)IVAL(params,44)),((uint32)sizeof(fname)-1));
995   root_dir_fid = (uint16)IVAL(params,4);
996   smb_attr = (file_attributes & SAMBA_ATTRIBUTES_MASK);
997
998   /* 
999    * We need to construct the open_and_X ofun value from the
1000    * NT values, as that's what our code is structured to accept.
1001    */    
1002
1003   if((smb_ofun = map_create_disposition( create_disposition )) == -1)
1004     return(ERROR(ERRDOS,ERRbadmem));
1005
1006   /*
1007    * Get the file name.
1008    */
1009
1010   if(root_dir_fid != 0) {
1011     /*
1012      * This filename is relative to a directory fid.
1013      */
1014
1015     files_struct *dir_fsp = file_fsp(params,4);
1016     size_t dir_name_len;
1017
1018     if(!dir_fsp)
1019         return(ERROR(ERRDOS,ERRbadfid));
1020
1021     if(!dir_fsp->is_directory) {
1022       /*
1023        * Check to see if this is a mac fork of some kind.
1024        */
1025
1026       get_filename_transact(&fname[0], params, 53,
1027                             total_parameter_count - 53 - fname_len, fname_len);
1028
1029       if( fname[0] == ':') {
1030           SSVAL(outbuf, smb_flg2, FLAGS2_32_BIT_ERROR_CODES);
1031           return(ERROR(0, 0xc0000000|NT_STATUS_OBJECT_PATH_NOT_FOUND));
1032       }
1033
1034       return(ERROR(ERRDOS,ERRbadfid));
1035     }
1036
1037     /*
1038      * Copy in the base directory name.
1039      */
1040
1041     pstrcpy( fname, dir_fsp->fsp_name );
1042     dir_name_len = strlen(fname);
1043
1044     /*
1045      * Ensure it ends in a '\'.
1046      */
1047
1048     if((fname[dir_name_len-1] != '\\') && (fname[dir_name_len-1] != '/')) {
1049       pstrcat(fname, "\\");
1050       dir_name_len++;
1051     }
1052
1053     /*
1054      * This next calculation can refuse a correct filename if we're dealing
1055      * with the Win2k unicode bug, but that would be rare. JRA.
1056      */
1057
1058     if(fname_len + dir_name_len >= sizeof(pstring))
1059       return(ERROR(ERRSRV,ERRfilespecs));
1060
1061     get_filename_transact(&fname[dir_name_len], params, 53,
1062                  total_parameter_count - 53 - fname_len, fname_len);
1063
1064   } else {
1065     get_filename_transact(&fname[0], params, 53,
1066                  total_parameter_count - 53 - fname_len, fname_len);
1067   }
1068
1069   /* If it's an IPC, use the pipe handler. */
1070   if (IS_IPC(conn)) {
1071     int ret = nt_open_pipe(fname, conn, inbuf, outbuf, &pnum);
1072     if(ret != 0)
1073       return ret;
1074     smb_action = FILE_WAS_OPENED;
1075   } else {
1076
1077     /*
1078      * Now contruct the smb_open_mode value from the desired access
1079      * and the share access.
1080      */
1081
1082     if((smb_open_mode = map_share_mode( &stat_open_only, fname, desired_access,
1083                                         share_access, file_attributes)) == -1)
1084       return(ERROR(ERRDOS,ERRbadaccess));
1085
1086     oplock_request = (flags & REQUEST_OPLOCK) ? EXCLUSIVE_OPLOCK : 0;
1087     oplock_request |= (flags & REQUEST_BATCH_OPLOCK) ? BATCH_OPLOCK : 0;
1088
1089     /*
1090      * Check if POSIX semantics are wanted.
1091      */
1092
1093     set_posix_case_semantics(file_attributes);
1094     
1095     RESOLVE_DFSPATH(fname, conn, inbuf, outbuf);
1096
1097     unix_convert(fname,conn,0,&bad_path,NULL);
1098     
1099     unixmode = unix_mode(conn,smb_attr | aARCH, fname);
1100     
1101     /*
1102      * If it's a request for a directory open, deal with it separately.
1103      */
1104
1105     if(create_options & FILE_DIRECTORY_FILE) {
1106
1107       oplock_request = 0;
1108
1109       /*
1110        * We will get a create directory here if the Win32
1111        * app specified a security descriptor in the 
1112        * CreateDirectory() call.
1113        */
1114
1115       fsp = open_directory(conn, fname, smb_ofun, unixmode, &smb_action);
1116
1117       if(!fsp) {
1118         restore_case_semantics(file_attributes);
1119         return(UNIXERROR(ERRDOS,ERRnoaccess));
1120       }
1121
1122       if(conn->vfs_ops.stat(dos_to_unix(fsp->fsp_name, False),
1123                              &sbuf) != 0) {
1124         close_file(fsp,True);
1125         restore_case_semantics(file_attributes);
1126         return(ERROR(ERRDOS,ERRnoaccess));
1127       }
1128
1129     } else {
1130
1131       /*
1132        * Ordinary file case.
1133        */
1134
1135       fsp = open_file_shared(conn,fname,smb_open_mode,smb_ofun,unixmode,
1136                        oplock_request,&rmode,&smb_action);
1137
1138       if (!fsp) { 
1139
1140                 if(errno == EISDIR) {
1141
1142                         /*
1143                          * Fail the open if it was explicitly a non-directory file.
1144                          */
1145
1146                         if (create_options & FILE_NON_DIRECTORY_FILE) {
1147                                 restore_case_semantics(file_attributes);
1148                                 SSVAL(outbuf, smb_flg2, FLAGS2_32_BIT_ERROR_CODES);
1149                                 return(ERROR(0, 0xc0000000|NT_STATUS_FILE_IS_A_DIRECTORY));
1150                         }
1151         
1152                         oplock_request = 0;
1153                         fsp = open_directory(conn, fname, smb_ofun, unixmode, &smb_action);
1154                                 
1155                         if(!fsp) {
1156                                 restore_case_semantics(file_attributes);
1157                                 return(UNIXERROR(ERRDOS,ERRnoaccess));
1158                         }
1159 #ifdef EROFS
1160                 } else if (((errno == EACCES) || (errno == EROFS)) && stat_open_only) {
1161 #else /* !EROFS */
1162                 } else if (errno == EACCES && stat_open_only) {
1163 #endif
1164
1165                         /*
1166                          * We couldn't open normally and all we want
1167                          * are the permissions. Try and do a stat open.
1168                          */
1169
1170                         oplock_request = 0;
1171
1172                         fsp = open_file_stat(conn,fname,smb_open_mode,&sbuf,&smb_action);
1173
1174                         if(!fsp) {
1175                                 restore_case_semantics(file_attributes);
1176                                 return(UNIXERROR(ERRDOS,ERRnoaccess));
1177                         }
1178                 } else {
1179
1180                         if((errno == ENOENT) && bad_path) {
1181                                 unix_ERR_class = ERRDOS;
1182                                 unix_ERR_code = ERRbadpath;
1183                         }
1184
1185                         restore_case_semantics(file_attributes);
1186
1187                         return(UNIXERROR(ERRDOS,ERRnoaccess));
1188                 }
1189       } 
1190   
1191       if(fsp->is_directory) {
1192           if(conn->vfs_ops.stat(dos_to_unix(fsp->fsp_name,False), &sbuf) != 0) {
1193               close_file(fsp,True);
1194               restore_case_semantics(file_attributes);
1195               return(ERROR(ERRDOS,ERRnoaccess));
1196           }
1197       } else {
1198           if (!fsp->stat_open && conn->vfs_ops.fstat(fsp->fd,&sbuf) != 0) {
1199               close_file(fsp,False);
1200               restore_case_semantics(file_attributes);
1201               return(ERROR(ERRDOS,ERRnoaccess));
1202           } 
1203       }
1204  
1205       file_len = sbuf.st_size;
1206       fmode = dos_mode(conn,fname,&sbuf);
1207       if(fmode == 0)
1208         fmode = FILE_ATTRIBUTE_NORMAL;
1209
1210       if (fmode & aDIR) {
1211         close_file(fsp,False);
1212         restore_case_semantics(file_attributes);
1213         return(ERROR(ERRDOS,ERRnoaccess));
1214       } 
1215
1216       /* 
1217        * If the caller set the extended oplock request bit
1218        * and we granted one (by whatever means) - set the
1219        * correct bit for extended oplock reply.
1220        */
1221     
1222       if (oplock_request && lp_fake_oplocks(SNUM(conn)))
1223         smb_action |= EXTENDED_OPLOCK_GRANTED;
1224   
1225       if(oplock_request && EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type))
1226         smb_action |= EXTENDED_OPLOCK_GRANTED;
1227     }
1228   }
1229
1230   restore_case_semantics(file_attributes);
1231
1232   /* Realloc the size of parameters and data we will return */
1233   params = *ppparams = Realloc(*ppparams, 69);
1234   if(params == NULL)
1235     return(ERROR(ERRDOS,ERRnomem));
1236
1237   memset((char *)params,'\0',69);
1238
1239   p = params;
1240   if (smb_action & EXTENDED_OPLOCK_GRANTED)     
1241         SCVAL(p,0, BATCH_OPLOCK_RETURN);
1242   else if (LEVEL_II_OPLOCK_TYPE(fsp->oplock_type))
1243     SCVAL(p,0, LEVEL_II_OPLOCK_RETURN);
1244   else
1245         SCVAL(p,0,NO_OPLOCK_RETURN);
1246         
1247   p += 2;
1248   if (IS_IPC(conn)) {
1249           SSVAL(p,0,pnum);
1250   } else {
1251           SSVAL(p,0,fsp->fnum);
1252   }
1253   p += 2;
1254   SIVAL(p,0,smb_action);
1255   p += 8;
1256
1257   if (IS_IPC(conn)) {
1258     /*
1259      * Deal with pipe return.
1260      */  
1261     p += 32;
1262     SIVAL(p,0,FILE_ATTRIBUTE_NORMAL); /* File Attributes. */
1263     p += 20;
1264     /* File type. */
1265     SSVAL(p,0,FILE_TYPE_MESSAGE_MODE_PIPE);
1266     /* Device state. */
1267     SSVAL(p,2, 0x5FF); /* ? */
1268   } else {
1269     /*
1270      * Deal with file return.
1271      */
1272     /* Create time. */
1273     put_long_date(p,get_create_time(&sbuf,lp_fake_dir_create_times(SNUM(conn))));
1274     p += 8;
1275     put_long_date(p,sbuf.st_atime); /* access time */
1276     p += 8;
1277     put_long_date(p,sbuf.st_mtime); /* write time */
1278     p += 8;
1279     put_long_date(p,sbuf.st_mtime); /* change time */
1280     p += 8;
1281     SIVAL(p,0,fmode); /* File Attributes. */
1282     p += 4;
1283     SOFF_T(p,0,file_len);
1284     p += 8;
1285     SOFF_T(p,0,file_len);
1286   }
1287
1288   DEBUG(5,("call_nt_transact_create: open name = %s\n", fname));
1289
1290   /* Send the required number of replies */
1291   send_nt_replies(inbuf, outbuf, bufsize, 0, params, 69, *ppdata, 0);
1292
1293   return -1;
1294 }
1295
1296 /****************************************************************************
1297  Reply to a NT CANCEL request.
1298 ****************************************************************************/
1299 int reply_ntcancel(connection_struct *conn,
1300                    char *inbuf,char *outbuf,int length,int bufsize)
1301 {
1302         /*
1303          * Go through and cancel any pending change notifies.
1304          */
1305         
1306         int mid = SVAL(inbuf,smb_mid);
1307         remove_pending_change_notify_requests_by_mid(mid);
1308         remove_pending_lock_requests_by_mid(mid);
1309         
1310         DEBUG(3,("reply_ntcancel: cancel called on mid = %d.\n", mid));
1311
1312         return(-1);
1313 }
1314
1315 /****************************************************************************
1316  Reply to an unsolicited SMBNTtranss - just ignore it!
1317 ****************************************************************************/
1318 int reply_nttranss(connection_struct *conn,
1319                    char *inbuf,char *outbuf,int length,int bufsize)
1320 {
1321         DEBUG(4,("Ignoring nttranss of length %d\n",length));
1322         return(-1);
1323 }
1324
1325 /****************************************************************************
1326  Reply to an NT transact rename command.
1327 ****************************************************************************/
1328
1329 static int call_nt_transact_rename(connection_struct *conn,
1330                                    char *inbuf, char *outbuf, int length, 
1331                                    int bufsize,
1332                                    char **ppsetup, char **ppparams, char **ppdata)
1333 {
1334   char *params = *ppparams;
1335   pstring new_name;
1336   files_struct *fsp = file_fsp(params, 0);
1337   BOOL replace_if_exists = (SVAL(params,2) & RENAME_REPLACE_IF_EXISTS) ? True : False;
1338   uint32 fname_len = MIN((((uint32)IVAL(inbuf,smb_nt_TotalParameterCount)-4)),
1339                          ((uint32)sizeof(new_name)-1));
1340   int outsize = 0;
1341
1342   CHECK_FSP(fsp, conn);
1343   StrnCpy(new_name,params+4,fname_len);
1344   new_name[fname_len] = '\0';
1345
1346   outsize = rename_internals(conn, inbuf, outbuf, fsp->fsp_name,
1347                              new_name, replace_if_exists);
1348   if(outsize == 0) {
1349     /*
1350      * Rename was successful.
1351      */
1352     send_nt_replies(inbuf, outbuf, bufsize, 0, NULL, 0, NULL, 0);
1353
1354     DEBUG(3,("nt transact rename from = %s, to = %s succeeded.\n", 
1355           fsp->fsp_name, new_name));
1356
1357     outsize = -1;
1358   }
1359
1360   return(outsize);
1361 }
1362    
1363 /****************************************************************************
1364  This is the structure to keep the information needed to
1365  determine if a directory has changed.
1366 *****************************************************************************/
1367
1368 typedef struct {
1369   time_t modify_time; /* Info from the directory we're monitoring. */ 
1370   time_t status_time; /* Info from the directory we're monitoring. */
1371   time_t total_time; /* Total time of all directory entries - don't care if it wraps. */
1372   unsigned int num_entries; /* Zero or the number of files in the directory. */
1373 } change_hash_data;
1374
1375 /****************************************************************************
1376  This is the structure to queue to implement NT change
1377  notify. It consists of smb_size bytes stored from the
1378  transact command (to keep the mid, tid etc around).
1379  Plus the fid to examine and the time to check next.
1380 *****************************************************************************/
1381
1382 typedef struct {
1383   ubi_slNode msg_next;
1384   files_struct *fsp;
1385   connection_struct *conn;
1386   uint32 flags;
1387   time_t next_check_time;
1388   change_hash_data change_data;
1389   char request_buf[smb_size];
1390 } change_notify_buf;
1391
1392 static ubi_slList change_notify_queue = { NULL, (ubi_slNodePtr)&change_notify_queue, 0};
1393
1394 /****************************************************************************
1395  Setup the common parts of the return packet and send it.
1396 *****************************************************************************/
1397
1398 static void change_notify_reply_packet(char *inbuf, int error_class, uint32 error_code)
1399 {
1400   char outbuf[smb_size+38];
1401
1402   memset(outbuf, '\0', sizeof(outbuf));
1403   construct_reply_common(inbuf, outbuf);
1404
1405   /*
1406    * If we're returning a 'too much in the directory changed' we need to
1407    * set this is an NT error status flags. If we don't then the (probably
1408    * untested) code in the NT redirector has a bug in that it doesn't re-issue
1409    * the change notify.... Ah - I *love* it when I get so deeply into this I
1410    * can even determine how MS failed to test stuff and why.... :-). JRA.
1411    */
1412
1413   if(error_class == 0) /* NT Error. */
1414     SSVAL(outbuf,smb_flg2, SVAL(outbuf,smb_flg2) | FLAGS2_32_BIT_ERROR_CODES);
1415
1416   ERROR(error_class,error_code);
1417
1418   /*
1419    * Seems NT needs a transact command with an error code
1420    * in it. This is a longer packet than a simple error.
1421    */
1422   set_message(outbuf,18,0,False);
1423
1424   send_smb(smbd_server_fd(),outbuf);
1425 }
1426
1427 /****************************************************************************
1428  Create the hash we will use to determine if the contents changed.
1429 *****************************************************************************/
1430
1431 static BOOL create_directory_notify_hash( change_notify_buf *cnbp, change_hash_data *change_data)
1432 {
1433   SMB_STRUCT_STAT st;
1434   files_struct *fsp = cnbp->fsp;
1435
1436   memset((char *)change_data, '\0', sizeof(change_data));
1437
1438   /* 
1439    * Store the current timestamp on the directory we are monitoring.
1440    */
1441
1442   if(dos_stat(fsp->fsp_name, &st) < 0) {
1443     DEBUG(0,("create_directory_notify_hash: Unable to stat name = %s. \
1444 Error was %s\n", fsp->fsp_name, strerror(errno) ));
1445     return False;
1446   }
1447  
1448   change_data->modify_time = st.st_mtime;
1449   change_data->status_time = st.st_ctime;
1450
1451   /*
1452    * If we are to watch for changes that are only stored
1453    * in inodes of files, not in the directory inode, we must
1454    * scan the directory and produce a unique identifier with
1455    * which we can determine if anything changed. We use the
1456    * modify and change times from all the files in the
1457    * directory, added together (ignoring wrapping if it's
1458    * larger than the max time_t value).
1459    */
1460
1461   if(cnbp->flags & (FILE_NOTIFY_CHANGE_SIZE|FILE_NOTIFY_CHANGE_LAST_WRITE)) {
1462     pstring full_name;
1463     char *p;
1464     char *fname;
1465     size_t remaining_len;
1466     size_t fullname_len;
1467     void *dp = OpenDir(cnbp->conn, fsp->fsp_name, True);
1468
1469     if(dp == NULL) {
1470       DEBUG(0,("create_directory_notify_hash: Unable to open directory = %s. \
1471 Error was %s\n", fsp->fsp_name, strerror(errno) ));
1472       return False;
1473     }
1474
1475     change_data->num_entries = 0;
1476
1477     pstrcpy(full_name, fsp->fsp_name);
1478     pstrcat(full_name, "/");
1479
1480     fullname_len = strlen(full_name);
1481     remaining_len = sizeof(full_name) - fullname_len - 1;
1482     p = &full_name[fullname_len];
1483
1484     while ((fname = ReadDirName(dp))) {
1485       if(strequal(fname, ".") || strequal(fname, ".."))
1486         continue;
1487
1488       change_data->num_entries++;
1489       safe_strcpy( p, fname, remaining_len);
1490
1491       memset(&st, '\0', sizeof(st));
1492
1493       /*
1494        * Do the stat - but ignore errors.
1495        */
1496
1497       if(dos_stat(full_name, &st) < 0) {
1498         DEBUG(5,("create_directory_notify_hash: Unable to stat content file = %s. \
1499 Error was %s\n", fsp->fsp_name, strerror(errno) ));
1500       }
1501       change_data->total_time += (st.st_mtime + st.st_ctime);
1502     }
1503
1504     CloseDir(dp);
1505   }
1506
1507   return True;
1508 }
1509
1510 /****************************************************************************
1511  Delete entries by fnum from the change notify pending queue.
1512 *****************************************************************************/
1513
1514 void remove_pending_change_notify_requests_by_fid(files_struct *fsp)
1515 {
1516   change_notify_buf *cnbp = (change_notify_buf *)ubi_slFirst( &change_notify_queue );
1517   change_notify_buf *prev = NULL;
1518
1519   while(cnbp != NULL) {
1520     if(cnbp->fsp->fnum == fsp->fnum) {
1521       free((char *)ubi_slRemNext( &change_notify_queue, prev));
1522       cnbp = (change_notify_buf *)(prev ? ubi_slNext(prev) : ubi_slFirst(&change_notify_queue));
1523       continue;
1524     }
1525
1526     prev = cnbp;
1527     cnbp = (change_notify_buf *)ubi_slNext(cnbp);
1528   }
1529 }
1530
1531 /****************************************************************************
1532  Delete entries by mid from the change notify pending queue. Always send reply.
1533 *****************************************************************************/
1534
1535 static void remove_pending_change_notify_requests_by_mid(int mid)
1536 {
1537   change_notify_buf *cnbp = (change_notify_buf *)ubi_slFirst( &change_notify_queue );
1538   change_notify_buf *prev = NULL;
1539
1540   while(cnbp != NULL) {
1541     if(SVAL(cnbp->request_buf,smb_mid) == mid) {
1542       change_notify_reply_packet(cnbp->request_buf,0,0xC0000000 |NT_STATUS_CANCELLED);
1543       free((char *)ubi_slRemNext( &change_notify_queue, prev));
1544       cnbp = (change_notify_buf *)(prev ? ubi_slNext(prev) : ubi_slFirst(&change_notify_queue));
1545       continue;
1546     }
1547
1548     prev = cnbp;
1549     cnbp = (change_notify_buf *)ubi_slNext(cnbp);
1550   }
1551 }
1552
1553 /****************************************************************************
1554  Delete entries by filename and cnum from the change notify pending queue.
1555  Always send reply.
1556 *****************************************************************************/
1557
1558 void remove_pending_change_notify_requests_by_filename(files_struct *fsp)
1559 {
1560   change_notify_buf *cnbp = (change_notify_buf *)ubi_slFirst( &change_notify_queue );
1561   change_notify_buf *prev = NULL;
1562
1563   while(cnbp != NULL) {
1564     /*
1565      * We know it refers to the same directory if the connection number and
1566      * the filename are identical.
1567      */
1568     if((cnbp->fsp->conn == fsp->conn) && strequal(cnbp->fsp->fsp_name,fsp->fsp_name)) {
1569       change_notify_reply_packet(cnbp->request_buf,0,0xC0000000 |NT_STATUS_CANCELLED);
1570       free((char *)ubi_slRemNext( &change_notify_queue, prev));
1571       cnbp = (change_notify_buf *)(prev ? ubi_slNext(prev) : ubi_slFirst(&change_notify_queue));
1572       continue;
1573     }
1574
1575     prev = cnbp;
1576     cnbp = (change_notify_buf *)ubi_slNext(cnbp);
1577   }
1578 }
1579
1580 /****************************************************************************
1581  Process the change notify queue. Note that this is only called as root.
1582  Returns True if there are still outstanding change notify requests on the
1583  queue.
1584 *****************************************************************************/
1585
1586 BOOL process_pending_change_notify_queue(time_t t)
1587 {
1588   change_notify_buf *cnbp = (change_notify_buf *)ubi_slFirst( &change_notify_queue );
1589   change_notify_buf *prev = NULL;
1590
1591   if(cnbp == NULL)
1592     return False;
1593
1594   if(cnbp->next_check_time >= t)
1595     return True;
1596
1597   /*
1598    * It's time to check. Go through the queue and see if
1599    * the timestamps changed.
1600    */
1601
1602   while((cnbp != NULL) && (cnbp->next_check_time <= t)) {
1603     change_hash_data change_data;
1604     connection_struct *conn = cnbp->conn;
1605     uint16 vuid = (lp_security() == SEC_SHARE) ? UID_FIELD_INVALID : 
1606                   SVAL(cnbp->request_buf,smb_uid);
1607
1608     ZERO_STRUCT(change_data);
1609
1610     /*
1611      * Ensure we don't have any old chain_fsp values
1612      * sitting around....
1613      */
1614     chain_size = 0;
1615     file_chain_reset();
1616
1617     if(!become_user(conn,vuid)) {
1618       DEBUG(0,("process_pending_change_notify_queue: Unable to become user vuid=%d.\n",
1619             vuid ));
1620       /*
1621        * Remove the entry and return an error to the client.
1622        */
1623       change_notify_reply_packet(cnbp->request_buf,ERRSRV,ERRaccess);
1624       free((char *)ubi_slRemNext( &change_notify_queue, prev));
1625       cnbp = (change_notify_buf *)(prev ? ubi_slNext(prev) : ubi_slFirst(&change_notify_queue));
1626       continue;
1627     }
1628
1629     if(!become_service(conn,True)) {
1630             DEBUG(0,("process_pending_change_notify_queue: Unable to become service Error was %s.\n", strerror(errno) ));
1631       /*
1632        * Remove the entry and return an error to the client.
1633        */
1634       change_notify_reply_packet(cnbp->request_buf,ERRSRV,ERRaccess);
1635       free((char *)ubi_slRemNext( &change_notify_queue, prev));
1636       cnbp = (change_notify_buf *)(prev ? ubi_slNext(prev) : ubi_slFirst(&change_notify_queue));
1637       unbecome_user();
1638       continue;
1639     }
1640
1641     if(!create_directory_notify_hash( cnbp, &change_data)) {
1642       DEBUG(0,("process_pending_change_notify_queue: Unable to create change data for \
1643 directory %s\n", cnbp->fsp->fsp_name ));
1644       /*
1645        * Remove the entry and return an error to the client.
1646        */
1647       change_notify_reply_packet(cnbp->request_buf,ERRSRV,ERRaccess);
1648       free((char *)ubi_slRemNext( &change_notify_queue, prev));
1649       cnbp = (change_notify_buf *)(prev ? ubi_slNext(prev) : ubi_slFirst(&change_notify_queue));
1650       unbecome_user();
1651       continue;
1652     }
1653
1654     if(memcmp( (char *)&cnbp->change_data, (char *)&change_data, sizeof(change_data))) {
1655       /*
1656        * Remove the entry and return a change notify to the client.
1657        */
1658       DEBUG(5,("process_pending_change_notify_queue: directory name = %s changed.\n",
1659             cnbp->fsp->fsp_name ));
1660       change_notify_reply_packet(cnbp->request_buf,0,NT_STATUS_NOTIFY_ENUM_DIR);
1661       free((char *)ubi_slRemNext( &change_notify_queue, prev));
1662       cnbp = (change_notify_buf *)(prev ? ubi_slNext(prev) : ubi_slFirst(&change_notify_queue));
1663       unbecome_user();
1664       continue;
1665     }
1666
1667     unbecome_user();
1668
1669     /*
1670      * Move to the next in the list.
1671      */
1672     prev = cnbp;
1673     cnbp = (change_notify_buf *)ubi_slNext(cnbp);
1674   }
1675
1676   return (cnbp != NULL);
1677 }
1678
1679 /****************************************************************************
1680  Return true if there are pending change notifies.
1681 ****************************************************************************/
1682
1683 BOOL change_notifies_pending(void)
1684 {
1685   change_notify_buf *cnbp = (change_notify_buf *)ubi_slFirst( &change_notify_queue );
1686   return (cnbp != NULL);
1687 }
1688
1689 /****************************************************************************
1690  Reply to a notify change - queue the request and 
1691  don't allow a directory to be opened.
1692 ****************************************************************************/
1693
1694 static int call_nt_transact_notify_change(connection_struct *conn,
1695                                           char *inbuf, char *outbuf, int length,
1696                                           int bufsize, 
1697                                           char **ppsetup, 
1698                                           char **ppparams, char **ppdata)
1699 {
1700   char *setup = *ppsetup;
1701   files_struct *fsp;
1702   change_notify_buf *cnbp;
1703
1704   fsp = file_fsp(setup,4);
1705
1706   DEBUG(3,("call_nt_transact_notify_change\n"));
1707
1708   if(!fsp)
1709     return(ERROR(ERRDOS,ERRbadfid));
1710
1711   if((!fsp->is_directory) || (conn != fsp->conn))
1712     return(ERROR(ERRDOS,ERRbadfid));
1713
1714   /*
1715    * Now queue an entry on the notify change stack. We timestamp
1716    * the entry we are adding so that we know when to scan next.
1717    * We only need to save smb_size bytes from this incoming packet
1718    * as we will always by returning a 'read the directory yourself'
1719    * error.
1720    */
1721
1722   if((cnbp = (change_notify_buf *)malloc(sizeof(change_notify_buf))) == NULL) {
1723     DEBUG(0,("call_nt_transact_notify_change: malloc fail !\n" ));
1724     return -1;
1725   }
1726
1727   memset((char *)cnbp, '\0', sizeof(change_notify_buf));
1728
1729   memcpy(cnbp->request_buf, inbuf, smb_size);
1730   cnbp->fsp = fsp;
1731   cnbp->conn = conn;
1732   cnbp->next_check_time = time(NULL) + lp_change_notify_timeout();
1733   cnbp->flags = IVAL(setup, 0);
1734
1735   if(!create_directory_notify_hash( cnbp, &cnbp->change_data )) {
1736     free((char *)cnbp);
1737     return(UNIXERROR(ERRDOS,ERRbadfid));
1738   }
1739
1740   /*
1741    * Adding to the tail enables us to check only
1742    * the head when scanning for change, as this entry
1743    * is forced to have the first timeout expiration.
1744    */
1745
1746   ubi_slAddTail(&change_notify_queue, cnbp);
1747
1748   DEBUG(3,("call_nt_transact_notify_change: notify change called on directory \
1749 name = %s\n", fsp->fsp_name ));
1750
1751   return -1;
1752 }
1753
1754 /****************************************************************************
1755  Map unix perms to NT.
1756 ****************************************************************************/
1757
1758 static SEC_ACCESS map_unix_perms( int *pacl_type, mode_t perm, int r_mask, int w_mask, int x_mask, BOOL is_directory)
1759 {
1760         SEC_ACCESS sa;
1761         uint32 nt_mask = 0;
1762
1763         *pacl_type = SEC_ACE_TYPE_ACCESS_ALLOWED;
1764
1765         if((perm & (r_mask|w_mask|x_mask)) == (r_mask|w_mask|x_mask)) {
1766                 nt_mask = UNIX_ACCESS_RWX;
1767         } else if((perm & (r_mask|w_mask|x_mask)) == 0) {
1768                 nt_mask = UNIX_ACCESS_NONE;
1769         } else {
1770                 nt_mask |= (perm & r_mask) ? UNIX_ACCESS_R : 0;
1771                 if(is_directory)
1772                         nt_mask |= (perm & w_mask) ? UNIX_ACCESS_W : 0;
1773                 else
1774                         nt_mask |= (perm & w_mask) ? UNIX_ACCESS_W : 0;
1775                 nt_mask |= (perm & x_mask) ? UNIX_ACCESS_X : 0;
1776         }
1777         init_sec_access(&sa,nt_mask);
1778         return sa;
1779 }
1780
1781 /****************************************************************************
1782  Function to create owner and group SIDs from a SMB_STRUCT_STAT.
1783 ****************************************************************************/
1784
1785 static void create_file_sids(SMB_STRUCT_STAT *psbuf, DOM_SID *powner_sid, DOM_SID *pgroup_sid)
1786 {
1787   extern DOM_SID global_sam_sid;
1788
1789   sid_copy(powner_sid, &global_sam_sid);
1790   sid_copy(pgroup_sid, &global_sam_sid);
1791   sid_append_rid(powner_sid, pdb_uid_to_user_rid(psbuf->st_uid));
1792   sid_append_rid(pgroup_sid, pdb_gid_to_group_rid(psbuf->st_gid));
1793 }
1794
1795 /****************************************************************************
1796  Reply to query a security descriptor from an fsp. If it succeeds it allocates
1797  the space for the return elements and returns True.
1798 ****************************************************************************/
1799
1800 static size_t get_nt_acl(files_struct *fsp, SEC_DESC **ppdesc)
1801 {
1802   extern DOM_SID global_sid_World;
1803   SMB_STRUCT_STAT sbuf;
1804   SEC_ACE ace_list[6];
1805   DOM_SID owner_sid;
1806   DOM_SID group_sid;
1807   size_t sec_desc_size;
1808   SEC_ACL *psa = NULL;
1809   SEC_ACCESS owner_access;
1810   int owner_acl_type;
1811   SEC_ACCESS group_access;
1812   int grp_acl_type;
1813   SEC_ACCESS other_access;
1814   int other_acl_type;
1815   int num_acls = 0;
1816  
1817   *ppdesc = NULL;
1818
1819   if(!lp_nt_acl_support()) {
1820     sid_copy( &owner_sid, &global_sid_World);
1821     sid_copy( &group_sid, &global_sid_World);
1822   } else {
1823
1824     if(fsp->is_directory || fsp->fd == -1) {
1825       if(dos_stat(fsp->fsp_name, &sbuf) != 0) {
1826         return 0;
1827       }
1828     } else {
1829       if(fsp->conn->vfs_ops.fstat(fsp->fd,&sbuf) != 0) {
1830         return 0;
1831       }
1832     }
1833
1834     /*
1835      * Get the owner, group and world SIDs.
1836      */
1837
1838     create_file_sids(&sbuf, &owner_sid, &group_sid);
1839
1840     /*
1841      * Create the generic 3 element UNIX acl.
1842      */
1843
1844     owner_access = map_unix_perms(&owner_acl_type, sbuf.st_mode,
1845                                                         S_IRUSR, S_IWUSR, S_IXUSR, fsp->is_directory);
1846     group_access = map_unix_perms(&grp_acl_type, sbuf.st_mode,
1847                                                         S_IRGRP, S_IWGRP, S_IXGRP, fsp->is_directory);
1848     other_access = map_unix_perms(&other_acl_type, sbuf.st_mode,
1849                                                         S_IROTH, S_IWOTH, S_IXOTH, fsp->is_directory);
1850
1851     if(owner_access.mask)
1852       init_sec_ace(&ace_list[num_acls++], &owner_sid, owner_acl_type,
1853                    owner_access, 0);
1854
1855     if(group_access.mask)
1856       init_sec_ace(&ace_list[num_acls++], &group_sid, grp_acl_type,
1857                    group_access, 0);
1858
1859     if(other_access.mask)
1860       init_sec_ace(&ace_list[num_acls++], &global_sid_World, other_acl_type,
1861                    other_access, 0);
1862
1863     if(fsp->is_directory) {
1864       /*
1865        * For directory ACLs we also add in the inherited permissions
1866        * ACE entries. These are the permissions a file would get when
1867        * being created in the directory.
1868        */
1869       mode_t mode = unix_mode( fsp->conn, FILE_ATTRIBUTE_ARCHIVE, fsp->fsp_name);
1870
1871       owner_access = map_unix_perms(&owner_acl_type, mode,
1872                             S_IRUSR, S_IWUSR, S_IXUSR, fsp->is_directory);
1873       group_access = map_unix_perms(&grp_acl_type, mode,
1874                             S_IRGRP, S_IWGRP, S_IXGRP, fsp->is_directory);
1875       other_access = map_unix_perms(&other_acl_type, mode,
1876                             S_IROTH, S_IWOTH, S_IXOTH, fsp->is_directory);
1877
1878       if(owner_access.mask)
1879         init_sec_ace(&ace_list[num_acls++], &owner_sid, owner_acl_type,
1880                      owner_access, SEC_ACE_FLAG_OBJECT_INHERIT|SEC_ACE_FLAG_INHERIT_ONLY);
1881
1882       if(group_access.mask)
1883         init_sec_ace(&ace_list[num_acls++], &group_sid, grp_acl_type,
1884                      group_access, SEC_ACE_FLAG_OBJECT_INHERIT|SEC_ACE_FLAG_INHERIT_ONLY);
1885
1886       if(other_access.mask)
1887         init_sec_ace(&ace_list[num_acls++], &global_sid_World, other_acl_type,
1888                      other_access, SEC_ACE_FLAG_OBJECT_INHERIT|SEC_ACE_FLAG_INHERIT_ONLY);
1889     }
1890
1891     if(num_acls)
1892       if((psa = make_sec_acl( 3, num_acls, ace_list)) == NULL) {
1893         DEBUG(0,("get_nt_acl: Unable to malloc space for acl.\n"));
1894         return 0;
1895       }
1896   }
1897
1898   *ppdesc = make_standard_sec_desc( &owner_sid, &group_sid, psa, &sec_desc_size);
1899
1900   if(!*ppdesc) {
1901     DEBUG(0,("get_nt_acl: Unable to malloc space for security descriptor.\n"));
1902     sec_desc_size = 0;
1903   }
1904
1905   free_sec_acl(&psa);
1906
1907   return sec_desc_size;
1908 }
1909
1910 /****************************************************************************
1911  Reply to query a security descriptor - currently this is not implemented (it
1912  is planned to be though). Right now it just returns the same thing NT would
1913  when queried on a FAT filesystem. JRA.
1914 ****************************************************************************/
1915
1916 static int call_nt_transact_query_security_desc(connection_struct *conn,
1917                                                 char *inbuf, char *outbuf, 
1918                                                 int length, int bufsize, 
1919                                                 char **ppsetup, char **ppparams, char **ppdata)
1920 {
1921   uint32 max_data_count = IVAL(inbuf,smb_nt_MaxDataCount);
1922   char *params = *ppparams;
1923   char *data = *ppdata;
1924   prs_struct pd;
1925   SEC_DESC *psd;
1926   size_t sec_desc_size;
1927
1928   files_struct *fsp = file_fsp(params,0);
1929
1930   if(!fsp)
1931     return(ERROR(ERRDOS,ERRbadfid));
1932
1933   DEBUG(3,("call_nt_transact_query_security_desc: file = %s\n", fsp->fsp_name ));
1934
1935   params = *ppparams = Realloc(*ppparams, 4);
1936   if(params == NULL)
1937     return(ERROR(ERRDOS,ERRnomem));
1938
1939   /*
1940    * Get the permissions to return.
1941    */
1942
1943   if((sec_desc_size = get_nt_acl(fsp, &psd)) == 0)
1944     return(UNIXERROR(ERRDOS,ERRnoaccess));
1945
1946   DEBUG(3,("call_nt_transact_query_security_desc: sec_desc_size = %d.\n",(int)sec_desc_size));
1947
1948   SIVAL(params,0,(uint32)sec_desc_size);
1949
1950   if(max_data_count < sec_desc_size) {
1951
1952     free_sec_desc(&psd);
1953
1954     send_nt_replies(inbuf, outbuf, bufsize, 0xC0000000|NT_STATUS_BUFFER_TOO_SMALL,
1955                     params, 4, *ppdata, 0);
1956     return -1;
1957   }
1958
1959   /*
1960    * Allocate the data we will point this at.
1961    */
1962
1963   data = *ppdata = Realloc(*ppdata, sec_desc_size);
1964   if(data == NULL) {
1965     free_sec_desc(&psd);
1966     return(ERROR(ERRDOS,ERRnomem));
1967   }
1968
1969   memset(data, '\0', sec_desc_size);
1970
1971   /*
1972    * Init the parse struct we will marshall into.
1973    */
1974
1975   prs_init(&pd, 0, 4, MARSHALL);
1976
1977   /*
1978    * Setup the prs_struct to point at the memory we just
1979    * allocated.
1980    */
1981         
1982   prs_give_memory( &pd, data, (uint32)sec_desc_size, False);
1983
1984   /*
1985    * Finally, linearize into the outgoing buffer.
1986    */
1987
1988   if(!sec_io_desc( "sd data", &psd, &pd, 1)) {
1989     free_sec_desc(&psd);
1990     DEBUG(0,("call_nt_transact_query_security_desc: Error in marshalling \
1991 security descriptor.\n"));
1992     /*
1993      * Return access denied for want of a better error message..
1994      */ 
1995     return(UNIXERROR(ERRDOS,ERRnoaccess));
1996   }
1997
1998   /*
1999    * Now we can delete the security descriptor.
2000    */
2001
2002   free_sec_desc(&psd);
2003
2004   send_nt_replies(inbuf, outbuf, bufsize, 0, params, 4, data, (int)sec_desc_size);
2005   return -1;
2006 }
2007
2008 /****************************************************************************
2009  Validate a SID.
2010 ****************************************************************************/
2011
2012 static BOOL validate_unix_sid( DOM_SID *psid, uint32 *prid, DOM_SID *sd_sid)
2013 {
2014   extern DOM_SID global_sam_sid;
2015   DOM_SID sid;
2016
2017   if(!sd_sid) {
2018     DEBUG(5,("validate_unix_sid: sid missing.\n"));
2019     return False;
2020   }
2021
2022   sid_copy(psid, sd_sid);
2023   sid_copy(&sid, sd_sid);
2024
2025   if(!sid_split_rid(&sid, prid)) {
2026     DEBUG(5,("validate_unix_sid: cannot get RID from sid.\n"));
2027     return False;
2028   }
2029
2030   if(!sid_equal( &sid, &global_sam_sid)) {
2031     DEBUG(5,("validate_unix_sid: sid is not ours.\n"));
2032     return False;
2033   }
2034
2035   return True;
2036 }
2037
2038 /****************************************************************************
2039  Map NT perms to UNIX.
2040 ****************************************************************************/
2041
2042 #define FILE_SPECIFIC_READ_BITS (FILE_READ_DATA|FILE_READ_EA|FILE_READ_ATTRIBUTES)
2043 #define FILE_SPECIFIC_WRITE_BITS (FILE_WRITE_DATA|FILE_APPEND_DATA|FILE_WRITE_EA|FILE_WRITE_ATTRIBUTES)
2044 #define FILE_SPECIFIC_EXECUTE_BITS (FILE_EXECUTE)
2045
2046 static mode_t map_nt_perms( SEC_ACCESS sec_access, int type)
2047 {
2048   mode_t mode = 0;
2049
2050   switch(type) {
2051   case S_IRUSR:
2052     if(sec_access.mask & GENERIC_ALL_ACCESS)
2053       mode = S_IRUSR|S_IWUSR|S_IXUSR;
2054     else {
2055       mode |= (sec_access.mask & (GENERIC_READ_ACCESS|FILE_SPECIFIC_READ_BITS)) ? S_IRUSR : 0;
2056       mode |= (sec_access.mask & (GENERIC_WRITE_ACCESS|FILE_SPECIFIC_WRITE_BITS)) ? S_IWUSR : 0;
2057       mode |= (sec_access.mask & (GENERIC_EXECUTE_ACCESS|FILE_SPECIFIC_EXECUTE_BITS)) ? S_IXUSR : 0;
2058     }
2059     break;
2060   case S_IRGRP:
2061     if(sec_access.mask & GENERIC_ALL_ACCESS)
2062       mode = S_IRGRP|S_IWGRP|S_IXGRP;
2063     else {
2064       mode |= (sec_access.mask & (GENERIC_READ_ACCESS|FILE_SPECIFIC_READ_BITS)) ? S_IRGRP : 0;
2065       mode |= (sec_access.mask & (GENERIC_WRITE_ACCESS|FILE_SPECIFIC_WRITE_BITS)) ? S_IWGRP : 0;
2066       mode |= (sec_access.mask & (GENERIC_EXECUTE_ACCESS|FILE_SPECIFIC_EXECUTE_BITS)) ? S_IXGRP : 0;
2067     }
2068     break;
2069   case S_IROTH:
2070     if(sec_access.mask & GENERIC_ALL_ACCESS)
2071       mode = S_IROTH|S_IWOTH|S_IXOTH;
2072     else {
2073       mode |= (sec_access.mask & (GENERIC_READ_ACCESS|FILE_SPECIFIC_READ_BITS)) ? S_IROTH : 0;
2074       mode |= (sec_access.mask & (GENERIC_WRITE_ACCESS|FILE_SPECIFIC_WRITE_BITS)) ? S_IWOTH : 0;
2075       mode |= (sec_access.mask & (GENERIC_EXECUTE_ACCESS|FILE_SPECIFIC_EXECUTE_BITS)) ? S_IXOTH : 0;
2076     }
2077     break;
2078   }
2079
2080   return mode;
2081 }
2082
2083 /****************************************************************************
2084  Unpack a SEC_DESC into a owner, group and set of UNIX permissions.
2085 ****************************************************************************/
2086
2087 static BOOL unpack_nt_permissions(SMB_STRUCT_STAT *psbuf, uid_t *puser, gid_t *pgrp, mode_t *pmode,
2088                                   uint32 security_info_sent, SEC_DESC *psd, BOOL is_directory)
2089 {
2090   extern DOM_SID global_sid_World;
2091   DOM_SID owner_sid;
2092   DOM_SID grp_sid;
2093   DOM_SID file_owner_sid;
2094   DOM_SID file_grp_sid;
2095   uint32 owner_rid;
2096   uint32 grp_rid;
2097   SEC_ACL *dacl = psd->dacl;
2098   BOOL all_aces_are_inherit_only = (is_directory ? True : False);
2099   int i;
2100
2101   *pmode = 0;
2102   *puser = (uid_t)-1;
2103   *pgrp = (gid_t)-1;
2104
2105   if(security_info_sent == 0) {
2106     DEBUG(0,("unpack_nt_permissions: no security info sent !\n"));
2107     return False;
2108   }
2109
2110   /*
2111    * Windows 2000 sends the owner and group SIDs as the logged in
2112    * user, not the connected user. But it still sends the file
2113    * owner SIDs on an ACL set. So we need to check for the file
2114    * owner and group SIDs as well as the owner SIDs. JRA.
2115    */
2116  
2117   create_file_sids(psbuf, &file_owner_sid, &file_grp_sid);
2118
2119   /*
2120    * Validate the owner and group SID's.
2121    */
2122
2123   memset(&owner_sid, '\0', sizeof(owner_sid));
2124   memset(&grp_sid, '\0', sizeof(grp_sid));
2125
2126   DEBUG(5,("unpack_nt_permissions: validating owner_sid.\n"));
2127
2128   /*
2129    * Don't immediately fail if the owner sid cannot be validated.
2130    * This may be a group chown only set.
2131    */
2132
2133   if(!validate_unix_sid( &owner_sid, &owner_rid, psd->owner_sid))
2134     DEBUG(3,("unpack_nt_permissions: unable to validate owner sid.\n"));
2135   else if(security_info_sent & OWNER_SECURITY_INFORMATION)
2136     *puser = pdb_user_rid_to_uid(owner_rid);
2137
2138   /*
2139    * Don't immediately fail if the group sid cannot be validated.
2140    * This may be an owner chown only set.
2141    */
2142
2143   if(!validate_unix_sid( &grp_sid, &grp_rid, psd->grp_sid))
2144     DEBUG(3,("unpack_nt_permissions: unable to validate group sid.\n"));
2145   else if(security_info_sent & GROUP_SECURITY_INFORMATION)
2146     *pgrp = pdb_user_rid_to_gid(grp_rid);
2147
2148   /*
2149    * If no DACL then this is a chown only security descriptor.
2150    */
2151
2152   if(!(security_info_sent & DACL_SECURITY_INFORMATION) || !dacl) {
2153     *pmode = 0;
2154     return True;
2155   }
2156
2157   /*
2158    * Now go through the DACL and ensure that
2159    * any owner/group sids match.
2160    */
2161
2162   for(i = 0; i < dacl->num_aces; i++) {
2163     DOM_SID ace_sid;
2164     SEC_ACE *psa = &dacl->ace_list[i];
2165
2166     if((psa->type != SEC_ACE_TYPE_ACCESS_ALLOWED) &&
2167        (psa->type != SEC_ACE_TYPE_ACCESS_DENIED)) {
2168       DEBUG(3,("unpack_nt_permissions: unable to set anything but an ALLOW or DENY ACE.\n"));
2169       return False;
2170     }
2171
2172     /*
2173      * Ignore or remove bits we don't care about on a directory ACE.
2174      */
2175
2176     if(is_directory) {
2177       if(psa->flags & SEC_ACE_FLAG_INHERIT_ONLY) {
2178         DEBUG(3,("unpack_nt_permissions: ignoring inherit only ACE.\n"));
2179         continue;
2180       }
2181
2182       /*
2183        * At least one of the ACE entries wasn't inherit only.
2184        * Flag this so we know the returned mode is valid.
2185        */
2186
2187       all_aces_are_inherit_only = False;
2188     }
2189
2190     /*
2191      * Windows 2000 sets these flags even on *file* ACE's. This is wrong
2192      * but we can ignore them for now. Revisit this when we go to POSIX
2193      * ACLs on directories.
2194      */
2195
2196     psa->flags &= ~(SEC_ACE_FLAG_OBJECT_INHERIT|SEC_ACE_FLAG_CONTAINER_INHERIT);
2197
2198     if(psa->flags != 0) {
2199       DEBUG(1,("unpack_nt_permissions: unable to set ACE flags (%x).\n", 
2200             (unsigned int)psa->flags));
2201       return False;
2202     }
2203
2204     /*
2205      * The security mask may be UNIX_ACCESS_NONE which should map into
2206      * no permissions (we overload the WRITE_OWNER bit for this) or it
2207      * should be one of the ALL/EXECUTE/READ/WRITE bits. Arrange for this
2208      * to be so. Any other bits override the UNIX_ACCESS_NONE bit.
2209      */
2210
2211     psa->info.mask &= (GENERIC_ALL_ACCESS|GENERIC_EXECUTE_ACCESS|GENERIC_WRITE_ACCESS|
2212                      GENERIC_READ_ACCESS|UNIX_ACCESS_NONE|FILE_ALL_ATTRIBUTES);
2213
2214     if(psa->info.mask != UNIX_ACCESS_NONE)
2215       psa->info.mask &= ~UNIX_ACCESS_NONE;
2216
2217     sid_copy(&ace_sid, &psa->sid);
2218
2219     if(sid_equal(&ace_sid, &file_owner_sid)) {
2220       /*
2221        * Map the desired permissions into owner perms.
2222        */
2223
2224       if(psa->type == SEC_ACE_TYPE_ACCESS_ALLOWED)
2225         *pmode |= map_nt_perms( psa->info, S_IRUSR);
2226       else
2227         *pmode &= ~(map_nt_perms( psa->info, S_IRUSR));
2228
2229     } else if( sid_equal(&ace_sid, &file_grp_sid)) {
2230       /*
2231        * Map the desired permissions into group perms.
2232        */
2233
2234       if(psa->type == SEC_ACE_TYPE_ACCESS_ALLOWED)
2235         *pmode |= map_nt_perms( psa->info, S_IRGRP);
2236       else
2237         *pmode &= ~(map_nt_perms( psa->info, S_IRGRP));
2238
2239     } else if( sid_equal(&ace_sid, &global_sid_World)) {
2240       /*
2241        * Map the desired permissions into other perms.
2242        */
2243
2244       if(psa->type == SEC_ACE_TYPE_ACCESS_ALLOWED)
2245         *pmode |= map_nt_perms( psa->info, S_IROTH);
2246       else
2247         *pmode &= ~(map_nt_perms( psa->info, S_IROTH));
2248
2249     } else {
2250       DEBUG(0,("unpack_nt_permissions: unknown SID used in ACL.\n"));
2251       return False;
2252     }
2253   }
2254
2255   if (is_directory && all_aces_are_inherit_only) {
2256     /*
2257      * Windows 2000 is doing one of these weird 'inherit acl'
2258      * traverses to conserve NTFS ACL resources. Just pretend
2259      * there was no DACL sent. JRA.
2260      */
2261
2262     DEBUG(10,("unpack_nt_permissions: Win2k inherit acl traverse. Ignoring DACL.\n"));
2263     free_sec_acl(&psd->dacl);
2264   }
2265
2266   return True;
2267 }
2268
2269 /****************************************************************************
2270  Reply to set a security descriptor. Map to UNIX perms.
2271 ****************************************************************************/
2272
2273 static int call_nt_transact_set_security_desc(connection_struct *conn,
2274                                                                         char *inbuf, char *outbuf, int length,
2275                                                                         int bufsize, char **ppsetup, 
2276                                                                         char **ppparams, char **ppdata)
2277 {
2278   uint32 total_parameter_count = IVAL(inbuf, smb_nts_TotalParameterCount);
2279   char *params= *ppparams;
2280   char *data = *ppdata;
2281   prs_struct pd;
2282   SEC_DESC *psd = NULL;
2283   uint32 total_data_count = (uint32)IVAL(inbuf, smb_nts_TotalDataCount);
2284   uid_t user = (uid_t)-1;
2285   gid_t grp = (gid_t)-1;
2286   mode_t perms = 0;
2287   SMB_STRUCT_STAT sbuf;
2288   files_struct *fsp = NULL;
2289   uint32 security_info_sent = 0;
2290   BOOL got_dacl = False;
2291
2292   if(!lp_nt_acl_support())
2293     return(UNIXERROR(ERRDOS,ERRnoaccess));
2294
2295   if(total_parameter_count < 8)
2296     return(ERROR(ERRDOS,ERRbadfunc));
2297
2298   if((fsp = file_fsp(params,0)) == NULL)
2299     return(ERROR(ERRDOS,ERRbadfid));
2300
2301   security_info_sent = IVAL(params,4);
2302
2303   DEBUG(3,("call_nt_transact_set_security_desc: file = %s, sent 0x%x\n", fsp->fsp_name,
2304        (unsigned int)security_info_sent ));
2305
2306   /*
2307    * Init the parse struct we will unmarshall from.
2308    */
2309
2310   prs_init(&pd, 0, 4, UNMARSHALL);
2311
2312   /*
2313    * Setup the prs_struct to point at the memory we just
2314    * allocated.
2315    */
2316         
2317   prs_give_memory( &pd, data, total_data_count, False);
2318
2319   /*
2320    * Finally, unmarshall from the data buffer.
2321    */
2322
2323   if(!sec_io_desc( "sd data", &psd, &pd, 1)) {
2324     free_sec_desc(&psd);
2325     DEBUG(0,("call_nt_transact_set_security_desc: Error in unmarshalling \
2326 security descriptor.\n"));
2327     /*
2328      * Return access denied for want of a better error message..
2329      */ 
2330     return(UNIXERROR(ERRDOS,ERRnoaccess));
2331   }
2332
2333   /*
2334    * Get the current state of the file.
2335    */
2336
2337   if(fsp->is_directory) {
2338     if(dos_stat(fsp->fsp_name, &sbuf) != 0) {
2339       free_sec_desc(&psd);
2340       return(UNIXERROR(ERRDOS,ERRnoaccess));
2341     }
2342   } else {
2343
2344     int ret;
2345
2346     if(fsp->fd == -1)
2347       ret = conn->vfs_ops.stat(dos_to_unix(fsp->fsp_name,False), &sbuf);
2348     else
2349       ret = conn->vfs_ops.fstat(fsp->fd,&sbuf);
2350
2351     if(ret != 0) {
2352       free_sec_desc(&psd);
2353       return(UNIXERROR(ERRDOS,ERRnoaccess));
2354     }
2355   }
2356
2357   /*
2358    * Unpack the user/group/world id's and permissions.
2359    */
2360
2361   if(!unpack_nt_permissions( &sbuf, &user, &grp, &perms, security_info_sent, psd, fsp->is_directory)) {
2362     free_sec_desc(&psd);
2363     return(UNIXERROR(ERRDOS,ERRnoaccess));
2364   }
2365
2366   if (psd->dacl != NULL)
2367     got_dacl = True;
2368
2369   free_sec_desc(&psd);
2370
2371   /*
2372    * Do we need to chown ?
2373    */
2374
2375   if((user != (uid_t)-1 || grp != (uid_t)-1) && (sbuf.st_uid != user || sbuf.st_gid != grp)) {
2376
2377     DEBUG(3,("call_nt_transact_set_security_desc: chown %s. uid = %u, gid = %u.\n",
2378           fsp->fsp_name, (unsigned int)user, (unsigned int)grp ));
2379
2380     if(dos_chown( fsp->fsp_name, user, grp) == -1) {
2381       DEBUG(3,("call_nt_transact_set_security_desc: chown %s, %u, %u failed. Error = %s.\n",
2382             fsp->fsp_name, (unsigned int)user, (unsigned int)grp, strerror(errno) ));
2383       return(UNIXERROR(ERRDOS,ERRnoaccess));
2384     }
2385
2386     /*
2387      * Recheck the current state of the file, which may have changed.
2388      * (suid/sgid bits, for instance)
2389      */
2390
2391     if(fsp->is_directory) {
2392       if(dos_stat(fsp->fsp_name, &sbuf) != 0) {
2393         return(UNIXERROR(ERRDOS,ERRnoaccess));
2394       }
2395     } else {
2396
2397       int ret;
2398     
2399       if(fsp->fd == -1)
2400         ret = conn->vfs_ops.stat(dos_to_unix(fsp->fsp_name,False), &sbuf);
2401       else
2402         ret = conn->vfs_ops.fstat(fsp->fd,&sbuf);
2403   
2404       if(ret != 0)
2405         return(UNIXERROR(ERRDOS,ERRnoaccess));
2406     }
2407   }
2408
2409   /*
2410    * Only change security if we got a DACL.
2411    */
2412
2413   if((security_info_sent & DACL_SECURITY_INFORMATION) && got_dacl) {
2414
2415     /*
2416      * Check to see if we need to change anything.
2417      * Enforce limits on modified bits *only*. Don't enforce masks
2418          * on bits not changed by the user.
2419      */
2420
2421     if(fsp->is_directory) {
2422
2423       perms &= (lp_dir_security_mask(SNUM(conn)) | sbuf.st_mode);
2424       perms |= (lp_force_dir_security_mode(SNUM(conn)) & ( perms ^ sbuf.st_mode ));
2425
2426     } else {
2427
2428       perms &= (lp_security_mask(SNUM(conn)) | sbuf.st_mode); 
2429       perms |= (lp_force_security_mode(SNUM(conn)) & ( perms ^ sbuf.st_mode ));
2430
2431     }
2432
2433     /*
2434      * Preserve special bits.
2435      */
2436
2437     perms |= (sbuf.st_mode & ~0777);
2438
2439     /*
2440      * Do we need to chmod ?
2441      */
2442
2443     if(sbuf.st_mode != perms) {
2444
2445       DEBUG(3,("call_nt_transact_set_security_desc: chmod %s. perms = 0%o.\n",
2446             fsp->fsp_name, (unsigned int)perms ));
2447
2448       if(conn->vfs_ops.chmod(dos_to_unix(fsp->fsp_name, False), perms) == -1) {
2449         DEBUG(3,("call_nt_transact_set_security_desc: chmod %s, 0%o failed. Error = %s.\n",
2450               fsp->fsp_name, (unsigned int)perms, strerror(errno) ));
2451         return(UNIXERROR(ERRDOS,ERRnoaccess));
2452       }
2453     }
2454   }
2455
2456   send_nt_replies(inbuf, outbuf, bufsize, 0, NULL, 0, NULL, 0);
2457   return -1;
2458 }
2459    
2460 /****************************************************************************
2461  Reply to IOCTL - not implemented - no plans.
2462 ****************************************************************************/
2463 static int call_nt_transact_ioctl(connection_struct *conn,
2464                                   char *inbuf, char *outbuf, int length,
2465                                   int bufsize, 
2466                                   char **ppsetup, char **ppparams, char **ppdata)
2467 {
2468   static BOOL logged_message = False;
2469
2470   if(!logged_message) {
2471     DEBUG(0,("call_nt_transact_ioctl: Currently not implemented.\n"));
2472     logged_message = True; /* Only print this once... */
2473   }
2474   return(ERROR(ERRSRV,ERRnosupport));
2475 }
2476    
2477 /****************************************************************************
2478  Reply to a SMBNTtrans.
2479 ****************************************************************************/
2480 int reply_nttrans(connection_struct *conn,
2481                   char *inbuf,char *outbuf,int length,int bufsize)
2482 {
2483   int  outsize = 0;
2484 #if 0 /* Not used. */
2485   uint16 max_setup_count = CVAL(inbuf, smb_nt_MaxSetupCount);
2486   uint32 max_parameter_count = IVAL(inbuf, smb_nt_MaxParameterCount);
2487   uint32 max_data_count = IVAL(inbuf,smb_nt_MaxDataCount);
2488 #endif /* Not used. */
2489   uint32 total_parameter_count = IVAL(inbuf, smb_nt_TotalParameterCount);
2490   uint32 total_data_count = IVAL(inbuf, smb_nt_TotalDataCount);
2491   uint32 parameter_count = IVAL(inbuf,smb_nt_ParameterCount);
2492   uint32 parameter_offset = IVAL(inbuf,smb_nt_ParameterOffset);
2493   uint32 data_count = IVAL(inbuf,smb_nt_DataCount);
2494   uint32 data_offset = IVAL(inbuf,smb_nt_DataOffset);
2495   uint16 setup_count = 2*CVAL(inbuf,smb_nt_SetupCount); /* setup count is in *words* */
2496   uint16 function_code = SVAL( inbuf, smb_nt_Function);
2497   char *params = NULL, *data = NULL, *setup = NULL;
2498   uint32 num_params_sofar, num_data_sofar;
2499
2500   if(global_oplock_break && (function_code == NT_TRANSACT_CREATE)) {
2501     /*
2502      * Queue this open message as we are the process of an oplock break.
2503      */
2504
2505     DEBUG(2,("reply_nttrans: queueing message NT_TRANSACT_CREATE \
2506 due to being in oplock break state.\n" ));
2507
2508     push_oplock_pending_smb_message( inbuf, length);
2509     return -1;
2510   }
2511
2512   outsize = set_message(outbuf,0,0,True);
2513
2514   /* 
2515    * All nttrans messages we handle have smb_wct == 19 + setup_count.
2516    * Ensure this is so as a sanity check.
2517    */
2518
2519   if(CVAL(inbuf, smb_wct) != 19 + (setup_count/2)) {
2520     DEBUG(2,("Invalid smb_wct %d in nttrans call (should be %d)\n",
2521           CVAL(inbuf, smb_wct), 19 + (setup_count/2)));
2522     return(ERROR(ERRSRV,ERRerror));
2523   }
2524     
2525   /* Allocate the space for the setup, the maximum needed parameters and data */
2526
2527   if(setup_count > 0)
2528     setup = (char *)malloc(setup_count);
2529   if (total_parameter_count > 0)
2530     params = (char *)malloc(total_parameter_count);
2531   if (total_data_count > 0)
2532     data = (char *)malloc(total_data_count);
2533  
2534   if ((total_parameter_count && !params)  || (total_data_count && !data) ||
2535       (setup_count && !setup)) {
2536     DEBUG(0,("reply_nttrans : Out of memory\n"));
2537     return(ERROR(ERRDOS,ERRnomem));
2538   }
2539
2540   /* Copy the param and data bytes sent with this request into
2541      the params buffer */
2542   num_params_sofar = parameter_count;
2543   num_data_sofar = data_count;
2544
2545   if (parameter_count > total_parameter_count || data_count > total_data_count)
2546     exit_server("reply_nttrans: invalid sizes in packet.\n");
2547
2548   if(setup) {
2549     memcpy( setup, &inbuf[smb_nt_SetupStart], setup_count);
2550     DEBUG(10,("reply_nttrans: setup_count = %d\n", setup_count));
2551     dump_data(10, setup, setup_count);
2552   }
2553   if(params) {
2554     memcpy( params, smb_base(inbuf) + parameter_offset, parameter_count);
2555     DEBUG(10,("reply_nttrans: parameter_count = %d\n", parameter_count));
2556     dump_data(10, params, parameter_count);
2557   }
2558   if(data) {
2559     memcpy( data, smb_base(inbuf) + data_offset, data_count);
2560     DEBUG(10,("reply_nttrans: data_count = %d\n",data_count));
2561     dump_data(10, data, data_count);
2562   }
2563
2564   if(num_data_sofar < total_data_count || num_params_sofar < total_parameter_count) {
2565     /* We need to send an interim response then receive the rest
2566        of the parameter/data bytes */
2567     outsize = set_message(outbuf,0,0,True);
2568     send_smb(smbd_server_fd(),outbuf);
2569
2570     while( num_data_sofar < total_data_count || num_params_sofar < total_parameter_count) {
2571       BOOL ret;
2572
2573       ret = receive_next_smb(inbuf,bufsize,SMB_SECONDARY_WAIT);
2574
2575       if((ret && (CVAL(inbuf, smb_com) != SMBnttranss)) || !ret) {
2576         outsize = set_message(outbuf,0,0,True);
2577         if(ret) {
2578                 DEBUG(0,("reply_nttrans: Invalid secondary nttrans packet\n"));
2579         } else {
2580                 DEBUG(0,("reply_nttrans: %s in getting secondary nttrans response.\n",
2581                          (smb_read_error == READ_ERROR) ? "error" : "timeout" ));
2582         }
2583         if(params)
2584           free(params);
2585         if(data)
2586           free(data);
2587         if(setup)
2588           free(setup);
2589         return(ERROR(ERRSRV,ERRerror));
2590       }
2591       
2592       /* Revise total_params and total_data in case they have changed downwards */
2593       total_parameter_count = IVAL(inbuf, smb_nts_TotalParameterCount);
2594       total_data_count = IVAL(inbuf, smb_nts_TotalDataCount);
2595       num_params_sofar += (parameter_count = IVAL(inbuf,smb_nts_ParameterCount));
2596       num_data_sofar += ( data_count = IVAL(inbuf, smb_nts_DataCount));
2597       if (num_params_sofar > total_parameter_count || num_data_sofar > total_data_count)
2598         exit_server("reply_nttrans2: data overflow in secondary nttrans packet\n");
2599
2600       memcpy( &params[ IVAL(inbuf, smb_nts_ParameterDisplacement)], 
2601               smb_base(inbuf) + IVAL(inbuf, smb_nts_ParameterOffset), parameter_count);
2602       memcpy( &data[IVAL(inbuf, smb_nts_DataDisplacement)],
2603               smb_base(inbuf)+ IVAL(inbuf, smb_nts_DataOffset), data_count);
2604     }
2605   }
2606
2607   if (Protocol >= PROTOCOL_NT1) {
2608     uint16 flg2 = SVAL(outbuf,smb_flg2);
2609     SSVAL(outbuf,smb_flg2,flg2 | 0x40); /* IS_LONG_NAME */
2610   }
2611
2612   /* Now we must call the relevant NT_TRANS function */
2613   switch(function_code) {
2614     case NT_TRANSACT_CREATE:
2615       outsize = call_nt_transact_create(conn, inbuf, outbuf, length, bufsize, 
2616                                         &setup, &params, &data);
2617       break;
2618     case NT_TRANSACT_IOCTL:
2619       outsize = call_nt_transact_ioctl(conn, 
2620                                        inbuf, outbuf, length, bufsize, 
2621                                        &setup, &params, &data);
2622       break;
2623     case NT_TRANSACT_SET_SECURITY_DESC:
2624       outsize = call_nt_transact_set_security_desc(conn, inbuf, outbuf, 
2625                                                    length, bufsize, 
2626                                                    &setup, &params, &data);
2627       break;
2628     case NT_TRANSACT_NOTIFY_CHANGE:
2629       outsize = call_nt_transact_notify_change(conn, inbuf, outbuf, 
2630                                                length, bufsize, 
2631                                                &setup, &params, &data);
2632       break;
2633     case NT_TRANSACT_RENAME:
2634       outsize = call_nt_transact_rename(conn, inbuf, outbuf, length, 
2635                                         bufsize, 
2636                                         &setup, &params, &data);
2637       break;
2638
2639     case NT_TRANSACT_QUERY_SECURITY_DESC:
2640       outsize = call_nt_transact_query_security_desc(conn, inbuf, outbuf, 
2641                                                      length, bufsize, 
2642                                                      &setup, &params, &data);
2643       break;
2644   default:
2645           /* Error in request */
2646           DEBUG(0,("reply_nttrans: Unknown request %d in nttrans call\n", function_code));
2647           if(setup)
2648                   free(setup);
2649           if(params)
2650                   free(params);
2651           if(data)
2652                   free(data);
2653           return (ERROR(ERRSRV,ERRerror));
2654   }
2655
2656   /* As we do not know how many data packets will need to be
2657      returned here the various call_nt_transact_xxxx calls
2658      must send their own. Thus a call_nt_transact_xxxx routine only
2659      returns a value other than -1 when it wants to send
2660      an error packet. 
2661   */
2662
2663   if(setup)
2664     free(setup);
2665   if(params)
2666     free(params);
2667   if(data)
2668     free(data);
2669   return outsize; /* If a correct response was needed the call_nt_transact_xxxx 
2670                      calls have already sent it. If outsize != -1 then it is
2671                      returning an error packet. */
2672 }