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