r23508: Fix sync_file() to return NTSTATUS and return this
[tprouty/samba.git] / source / smbd / reply.c
1 /* 
2    Unix SMB/CIFS implementation.
3    Main SMB reply routines
4    Copyright (C) Andrew Tridgell 1992-1998
5    Copyright (C) Andrew Bartlett      2001
6    Copyright (C) Jeremy Allison 1992-2007.
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 2 of the License, or
11    (at your option) any later version.
12    
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17    
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 */
22 /*
23    This file handles most of the reply_ calls that the server
24    makes to handle specific protocols
25 */
26
27 #include "includes.h"
28
29 /* look in server.c for some explanation of these variables */
30 extern enum protocol_types Protocol;
31 extern int max_send;
32 extern int max_recv;
33 unsigned int smb_echo_count = 0;
34 extern uint32 global_client_caps;
35
36 extern struct current_user current_user;
37 extern BOOL global_encrypted_passwords_negotiated;
38
39 /****************************************************************************
40  Ensure we check the path in *exactly* the same way as W2K for a findfirst/findnext
41  path or anything including wildcards.
42  We're assuming here that '/' is not the second byte in any multibyte char
43  set (a safe assumption). '\\' *may* be the second byte in a multibyte char
44  set.
45 ****************************************************************************/
46
47 /* Custom version for processing POSIX paths. */
48 #define IS_PATH_SEP(c,posix_only) ((c) == '/' || (!(posix_only) && (c) == '\\'))
49
50 NTSTATUS check_path_syntax_internal(pstring destname,
51                                     const pstring srcname,
52                                     BOOL posix_path,
53                                     BOOL *p_last_component_contains_wcard)
54 {
55         char *d = destname;
56         const char *s = srcname;
57         NTSTATUS ret = NT_STATUS_OK;
58         BOOL start_of_name_component = True;
59
60         *p_last_component_contains_wcard = False;
61
62         while (*s) {
63                 if (IS_PATH_SEP(*s,posix_path)) {
64                         /*
65                          * Safe to assume is not the second part of a mb char
66                          * as this is handled below.
67                          */
68                         /* Eat multiple '/' or '\\' */
69                         while (IS_PATH_SEP(*s,posix_path)) {
70                                 s++;
71                         }
72                         if ((d != destname) && (*s != '\0')) {
73                                 /* We only care about non-leading or trailing '/' or '\\' */
74                                 *d++ = '/';
75                         }
76
77                         start_of_name_component = True;
78                         /* New component. */
79                         *p_last_component_contains_wcard = False;
80                         continue;
81                 }
82
83                 if (start_of_name_component) {
84                         if ((s[0] == '.') && (s[1] == '.') && (IS_PATH_SEP(s[2],posix_path) || s[2] == '\0')) {
85                                 /* Uh oh - "/../" or "\\..\\"  or "/..\0" or "\\..\0" ! */
86
87                                 /*
88                                  * No mb char starts with '.' so we're safe checking the directory separator here.
89                                  */
90
91                                 /* If  we just added a '/' - delete it */
92                                 if ((d > destname) && (*(d-1) == '/')) {
93                                         *(d-1) = '\0';
94                                         d--;
95                                 }
96
97                                 /* Are we at the start ? Can't go back further if so. */
98                                 if (d <= destname) {
99                                         ret = NT_STATUS_OBJECT_PATH_SYNTAX_BAD;
100                                         break;
101                                 }
102                                 /* Go back one level... */
103                                 /* We know this is safe as '/' cannot be part of a mb sequence. */
104                                 /* NOTE - if this assumption is invalid we are not in good shape... */
105                                 /* Decrement d first as d points to the *next* char to write into. */
106                                 for (d--; d > destname; d--) {
107                                         if (*d == '/')
108                                                 break;
109                                 }
110                                 s += 2; /* Else go past the .. */
111                                 /* We're still at the start of a name component, just the previous one. */
112                                 continue;
113
114                         } else if ((s[0] == '.') && ((s[1] == '\0') || IS_PATH_SEP(s[1],posix_path))) {
115                                 if (posix_path) {
116                                         /* Eat the '.' */
117                                         s++;
118                                         continue;
119                                 }
120                         }
121
122                 }
123
124                 if (!(*s & 0x80)) {
125                         if (!posix_path) {
126                                 if (*s <= 0x1f) {
127                                         return NT_STATUS_OBJECT_NAME_INVALID;
128                                 }
129                                 switch (*s) {
130                                         case '*':
131                                         case '?':
132                                         case '<':
133                                         case '>':
134                                         case '"':
135                                                 *p_last_component_contains_wcard = True;
136                                                 break;
137                                         default:
138                                                 break;
139                                 }
140                         }
141                         *d++ = *s++;
142                 } else {
143                         size_t siz;
144                         /* Get the size of the next MB character. */
145                         next_codepoint(s,&siz);
146                         switch(siz) {
147                                 case 5:
148                                         *d++ = *s++;
149                                         /*fall through*/
150                                 case 4:
151                                         *d++ = *s++;
152                                         /*fall through*/
153                                 case 3:
154                                         *d++ = *s++;
155                                         /*fall through*/
156                                 case 2:
157                                         *d++ = *s++;
158                                         /*fall through*/
159                                 case 1:
160                                         *d++ = *s++;
161                                         break;
162                                 default:
163                                         DEBUG(0,("check_path_syntax_internal: character length assumptions invalid !\n"));
164                                         *d = '\0';
165                                         return NT_STATUS_INVALID_PARAMETER;
166                         }
167                 }
168                 start_of_name_component = False;
169         }
170
171         *d = '\0';
172         return ret;
173 }
174
175 /****************************************************************************
176  Ensure we check the path in *exactly* the same way as W2K for regular pathnames.
177  No wildcards allowed.
178 ****************************************************************************/
179
180 NTSTATUS check_path_syntax(pstring destname, const pstring srcname)
181 {
182         BOOL ignore;
183         return check_path_syntax_internal(destname, srcname, False, &ignore);
184 }
185
186 /****************************************************************************
187  Ensure we check the path in *exactly* the same way as W2K for regular pathnames.
188  Wildcards allowed - p_contains_wcard returns true if the last component contained
189  a wildcard.
190 ****************************************************************************/
191
192 NTSTATUS check_path_syntax_wcard(pstring destname, const pstring srcname, BOOL *p_contains_wcard)
193 {
194         return check_path_syntax_internal(destname, srcname, False, p_contains_wcard);
195 }
196
197 /****************************************************************************
198  Check the path for a POSIX client.
199  We're assuming here that '/' is not the second byte in any multibyte char
200  set (a safe assumption).
201 ****************************************************************************/
202
203 NTSTATUS check_path_syntax_posix(pstring destname, const pstring srcname)
204 {
205         BOOL ignore;
206         return check_path_syntax_internal(destname, srcname, True, &ignore);
207 }
208
209 /****************************************************************************
210  Pull a string and check the path allowing a wilcard - provide for error return.
211 ****************************************************************************/
212
213 size_t srvstr_get_path_wcard(char *inbuf, char *dest, const char *src, size_t dest_len, size_t src_len, int flags,
214                                 NTSTATUS *err, BOOL *contains_wcard)
215 {
216         pstring tmppath;
217         char *tmppath_ptr = tmppath;
218         size_t ret;
219 #ifdef DEVELOPER
220         SMB_ASSERT(dest_len == sizeof(pstring));
221 #endif
222
223         if (src_len == 0) {
224                 ret = srvstr_pull_buf( inbuf, tmppath_ptr, src, dest_len, flags);
225         } else {
226                 ret = srvstr_pull( inbuf, tmppath_ptr, src, dest_len, src_len, flags);
227         }
228
229         *contains_wcard = False;
230
231         if (SVAL(inbuf,smb_flg2) & FLAGS2_DFS_PATHNAMES) {
232                 /* 
233                  * For a DFS path the function parse_dfs_path()
234                  * will do the path processing, just make a copy.
235                  */
236                 pstrcpy(dest, tmppath);
237                 *err = NT_STATUS_OK;
238                 return ret;
239         }
240
241         if (lp_posix_pathnames()) {
242                 *err = check_path_syntax_posix(dest, tmppath);
243         } else {
244                 *err = check_path_syntax_wcard(dest, tmppath, contains_wcard);
245         }
246
247         return ret;
248 }
249
250 /****************************************************************************
251  Pull a string and check the path - provide for error return.
252 ****************************************************************************/
253
254 size_t srvstr_get_path(char *inbuf, char *dest, const char *src, size_t dest_len, size_t src_len, int flags, NTSTATUS *err)
255 {
256         pstring tmppath;
257         char *tmppath_ptr = tmppath;
258         size_t ret;
259 #ifdef DEVELOPER
260         SMB_ASSERT(dest_len == sizeof(pstring));
261 #endif
262
263         if (src_len == 0) {
264                 ret = srvstr_pull_buf( inbuf, tmppath_ptr, src, dest_len, flags);
265         } else {
266                 ret = srvstr_pull( inbuf, tmppath_ptr, src, dest_len, src_len, flags);
267         }
268
269         if (SVAL(inbuf,smb_flg2) & FLAGS2_DFS_PATHNAMES) {
270                 /* 
271                  * For a DFS path the function parse_dfs_path()
272                  * will do the path processing, just make a copy.
273                  */
274                 pstrcpy(dest, tmppath);
275                 *err = NT_STATUS_OK;
276                 return ret;
277         }
278
279         if (lp_posix_pathnames()) {
280                 *err = check_path_syntax_posix(dest, tmppath);
281         } else {
282                 *err = check_path_syntax(dest, tmppath);
283         }
284
285         return ret;
286 }
287
288 /****************************************************************************
289  Reply to a special message.
290 ****************************************************************************/
291
292 int reply_special(char *inbuf,char *outbuf)
293 {
294         int outsize = 4;
295         int msg_type = CVAL(inbuf,0);
296         int msg_flags = CVAL(inbuf,1);
297         fstring name1,name2;
298         char name_type = 0;
299         
300         static BOOL already_got_session = False;
301
302         *name1 = *name2 = 0;
303         
304         memset(outbuf,'\0',smb_size);
305
306         smb_setlen(inbuf,outbuf,0);
307         
308         switch (msg_type) {
309         case 0x81: /* session request */
310                 
311                 if (already_got_session) {
312                         exit_server_cleanly("multiple session request not permitted");
313                 }
314                 
315                 SCVAL(outbuf,0,0x82);
316                 SCVAL(outbuf,3,0);
317                 if (name_len(inbuf+4) > 50 || 
318                     name_len(inbuf+4 + name_len(inbuf + 4)) > 50) {
319                         DEBUG(0,("Invalid name length in session request\n"));
320                         return(0);
321                 }
322                 name_extract(inbuf,4,name1);
323                 name_type = name_extract(inbuf,4 + name_len(inbuf + 4),name2);
324                 DEBUG(2,("netbios connect: name1=%s name2=%s\n",
325                          name1,name2));      
326
327                 set_local_machine_name(name1, True);
328                 set_remote_machine_name(name2, True);
329
330                 DEBUG(2,("netbios connect: local=%s remote=%s, name type = %x\n",
331                          get_local_machine_name(), get_remote_machine_name(),
332                          name_type));
333
334                 if (name_type == 'R') {
335                         /* We are being asked for a pathworks session --- 
336                            no thanks! */
337                         SCVAL(outbuf, 0,0x83);
338                         break;
339                 }
340
341                 /* only add the client's machine name to the list
342                    of possibly valid usernames if we are operating
343                    in share mode security */
344                 if (lp_security() == SEC_SHARE) {
345                         add_session_user(get_remote_machine_name());
346                 }
347
348                 reload_services(True);
349                 reopen_logs();
350
351                 already_got_session = True;
352                 break;
353                 
354         case 0x89: /* session keepalive request 
355                       (some old clients produce this?) */
356                 SCVAL(outbuf,0,SMBkeepalive);
357                 SCVAL(outbuf,3,0);
358                 break;
359                 
360         case 0x82: /* positive session response */
361         case 0x83: /* negative session response */
362         case 0x84: /* retarget session response */
363                 DEBUG(0,("Unexpected session response\n"));
364                 break;
365                 
366         case SMBkeepalive: /* session keepalive */
367         default:
368                 return(0);
369         }
370         
371         DEBUG(5,("init msg_type=0x%x msg_flags=0x%x\n",
372                     msg_type, msg_flags));
373         
374         return(outsize);
375 }
376
377 /****************************************************************************
378  Reply to a tcon.
379  conn POINTER CAN BE NULL HERE !
380 ****************************************************************************/
381
382 int reply_tcon(connection_struct *conn,
383                char *inbuf,char *outbuf, int dum_size, int dum_buffsize)
384 {
385         const char *service;
386         pstring service_buf;
387         pstring password;
388         pstring dev;
389         int outsize = 0;
390         uint16 vuid = SVAL(inbuf,smb_uid);
391         int pwlen=0;
392         NTSTATUS nt_status;
393         char *p;
394         DATA_BLOB password_blob;
395         
396         START_PROFILE(SMBtcon);
397
398         *service_buf = *password = *dev = 0;
399
400         p = smb_buf(inbuf)+1;
401         p += srvstr_pull_buf(inbuf, service_buf, p, sizeof(service_buf), STR_TERMINATE) + 1;
402         pwlen = srvstr_pull_buf(inbuf, password, p, sizeof(password), STR_TERMINATE) + 1;
403         p += pwlen;
404         p += srvstr_pull_buf(inbuf, dev, p, sizeof(dev), STR_TERMINATE) + 1;
405
406         p = strrchr_m(service_buf,'\\');
407         if (p) {
408                 service = p+1;
409         } else {
410                 service = service_buf;
411         }
412
413         password_blob = data_blob(password, pwlen+1);
414
415         conn = make_connection(service,password_blob,dev,vuid,&nt_status);
416
417         data_blob_clear_free(&password_blob);
418   
419         if (!conn) {
420                 END_PROFILE(SMBtcon);
421                 return ERROR_NT(nt_status);
422         }
423   
424         outsize = set_message(inbuf,outbuf,2,0,True);
425         SSVAL(outbuf,smb_vwv0,max_recv);
426         SSVAL(outbuf,smb_vwv1,conn->cnum);
427         SSVAL(outbuf,smb_tid,conn->cnum);
428   
429         DEBUG(3,("tcon service=%s cnum=%d\n", 
430                  service, conn->cnum));
431   
432         END_PROFILE(SMBtcon);
433         return(outsize);
434 }
435
436 /****************************************************************************
437  Reply to a tcon and X.
438  conn POINTER CAN BE NULL HERE !
439 ****************************************************************************/
440
441 int reply_tcon_and_X(connection_struct *conn, char *inbuf,char *outbuf,int length,int bufsize)
442 {
443         fstring service;
444         DATA_BLOB password;
445
446         /* what the cleint thinks the device is */
447         fstring client_devicetype;
448         /* what the server tells the client the share represents */
449         const char *server_devicetype;
450         NTSTATUS nt_status;
451         uint16 vuid = SVAL(inbuf,smb_uid);
452         int passlen = SVAL(inbuf,smb_vwv3);
453         pstring path;
454         char *p, *q;
455         uint16 tcon_flags = SVAL(inbuf,smb_vwv2);
456         
457         START_PROFILE(SMBtconX);        
458
459         *service = *client_devicetype = 0;
460
461         /* we might have to close an old one */
462         if ((SVAL(inbuf,smb_vwv2) & 0x1) && conn) {
463                 close_cnum(conn,vuid);
464         }
465
466         if (passlen > MAX_PASS_LEN) {
467                 return ERROR_DOS(ERRDOS,ERRbuftoosmall);
468         }
469  
470         if (global_encrypted_passwords_negotiated) {
471                 password = data_blob(smb_buf(inbuf),passlen);
472                 if (lp_security() == SEC_SHARE) {
473                         /*
474                          * Security = share always has a pad byte
475                          * after the password.
476                          */
477                         p = smb_buf(inbuf) + passlen + 1;
478                 } else {
479                         p = smb_buf(inbuf) + passlen;
480                 }
481         } else {
482                 password = data_blob(smb_buf(inbuf),passlen+1);
483                 /* Ensure correct termination */
484                 password.data[passlen]=0;
485                 p = smb_buf(inbuf) + passlen + 1;
486         }
487
488         p += srvstr_pull_buf(inbuf, path, p, sizeof(path), STR_TERMINATE);
489
490         /*
491          * the service name can be either: \\server\share
492          * or share directly like on the DELL PowerVault 705
493          */
494         if (*path=='\\') {      
495                 q = strchr_m(path+2,'\\');
496                 if (!q) {
497                         END_PROFILE(SMBtconX);
498                         return(ERROR_DOS(ERRDOS,ERRnosuchshare));
499                 }
500                 fstrcpy(service,q+1);
501         }
502         else
503                 fstrcpy(service,path);
504                 
505         p += srvstr_pull(inbuf, client_devicetype, p, sizeof(client_devicetype), 6, STR_ASCII);
506
507         DEBUG(4,("Client requested device type [%s] for share [%s]\n", client_devicetype, service));
508
509         conn = make_connection(service,password,client_devicetype,vuid,&nt_status);
510         
511         data_blob_clear_free(&password);
512
513         if (!conn) {
514                 END_PROFILE(SMBtconX);
515                 return ERROR_NT(nt_status);
516         }
517
518         if ( IS_IPC(conn) )
519                 server_devicetype = "IPC";
520         else if ( IS_PRINT(conn) )
521                 server_devicetype = "LPT1:";
522         else 
523                 server_devicetype = "A:";
524
525         if (Protocol < PROTOCOL_NT1) {
526                 set_message(inbuf,outbuf,2,0,True);
527                 p = smb_buf(outbuf);
528                 p += srvstr_push(outbuf, p, server_devicetype, -1, 
529                                  STR_TERMINATE|STR_ASCII);
530                 set_message_end(inbuf,outbuf,p);
531         } else {
532                 /* NT sets the fstype of IPC$ to the null string */
533                 const char *fstype = IS_IPC(conn) ? "" : lp_fstype(SNUM(conn));
534                 
535                 if (tcon_flags & TCONX_FLAG_EXTENDED_RESPONSE) {
536                         /* Return permissions. */
537                         uint32 perm1 = 0;
538                         uint32 perm2 = 0;
539
540                         set_message(inbuf,outbuf,7,0,True);
541
542                         if (IS_IPC(conn)) {
543                                 perm1 = FILE_ALL_ACCESS;
544                                 perm2 = FILE_ALL_ACCESS;
545                         } else {
546                                 perm1 = CAN_WRITE(conn) ?
547                                                 SHARE_ALL_ACCESS :
548                                                 SHARE_READ_ONLY;
549                         }
550
551                         SIVAL(outbuf, smb_vwv3, perm1);
552                         SIVAL(outbuf, smb_vwv5, perm2);
553                 } else {
554                         set_message(inbuf,outbuf,3,0,True);
555                 }
556
557                 p = smb_buf(outbuf);
558                 p += srvstr_push(outbuf, p, server_devicetype, -1, 
559                                  STR_TERMINATE|STR_ASCII);
560                 p += srvstr_push(outbuf, p, fstype, -1, 
561                                  STR_TERMINATE);
562                 
563                 set_message_end(inbuf,outbuf,p);
564                 
565                 /* what does setting this bit do? It is set by NT4 and
566                    may affect the ability to autorun mounted cdroms */
567                 SSVAL(outbuf, smb_vwv2, SMB_SUPPORT_SEARCH_BITS|
568                                 (lp_csc_policy(SNUM(conn)) << 2));
569                 
570                 init_dfsroot(conn, inbuf, outbuf);
571         }
572
573   
574         DEBUG(3,("tconX service=%s \n",
575                  service));
576   
577         /* set the incoming and outgoing tid to the just created one */
578         SSVAL(inbuf,smb_tid,conn->cnum);
579         SSVAL(outbuf,smb_tid,conn->cnum);
580
581         END_PROFILE(SMBtconX);
582         return chain_reply(inbuf,outbuf,length,bufsize);
583 }
584
585 /****************************************************************************
586  Reply to an unknown type.
587 ****************************************************************************/
588
589 int reply_unknown(char *inbuf,char *outbuf)
590 {
591         int type;
592         type = CVAL(inbuf,smb_com);
593   
594         DEBUG(0,("unknown command type (%s): type=%d (0x%X)\n",
595                  smb_fn_name(type), type, type));
596   
597         return(ERROR_DOS(ERRSRV,ERRunknownsmb));
598 }
599
600 /****************************************************************************
601  Reply to an ioctl.
602  conn POINTER CAN BE NULL HERE !
603 ****************************************************************************/
604
605 int reply_ioctl(connection_struct *conn,
606                 char *inbuf,char *outbuf, int dum_size, int dum_buffsize)
607 {
608         uint16 device     = SVAL(inbuf,smb_vwv1);
609         uint16 function   = SVAL(inbuf,smb_vwv2);
610         uint32 ioctl_code = (device << 16) + function;
611         int replysize, outsize;
612         char *p;
613         START_PROFILE(SMBioctl);
614
615         DEBUG(4, ("Received IOCTL (code 0x%x)\n", ioctl_code));
616
617         switch (ioctl_code) {
618             case IOCTL_QUERY_JOB_INFO:
619                 replysize = 32;
620                 break;
621             default:
622                 END_PROFILE(SMBioctl);
623                 return(ERROR_DOS(ERRSRV,ERRnosupport));
624         }
625
626         outsize = set_message(inbuf,outbuf,8,replysize+1,True);
627         SSVAL(outbuf,smb_vwv1,replysize); /* Total data bytes returned */
628         SSVAL(outbuf,smb_vwv5,replysize); /* Data bytes this buffer */
629         SSVAL(outbuf,smb_vwv6,52);        /* Offset to data */
630         p = smb_buf(outbuf) + 1;          /* Allow for alignment */
631
632         switch (ioctl_code) {
633                 case IOCTL_QUERY_JOB_INFO:                  
634                 {
635                         files_struct *fsp = file_fsp(inbuf,smb_vwv0);
636                         if (!fsp) {
637                                 END_PROFILE(SMBioctl);
638                                 return(UNIXERROR(ERRDOS,ERRbadfid));
639                         }
640                         SSVAL(p,0,fsp->rap_print_jobid);             /* Job number */
641                         srvstr_push(outbuf, p+2, global_myname(), 15, STR_TERMINATE|STR_ASCII);
642                         if (conn) {
643                                 srvstr_push(outbuf, p+18, lp_servicename(SNUM(conn)), 13, STR_TERMINATE|STR_ASCII);
644                         }
645                         break;
646                 }
647         }
648
649         END_PROFILE(SMBioctl);
650         return outsize;
651 }
652
653 /****************************************************************************
654  Strange checkpath NTSTATUS mapping.
655 ****************************************************************************/
656
657 static NTSTATUS map_checkpath_error(const char *inbuf, NTSTATUS status)
658 {
659         /* Strange DOS error code semantics only for checkpath... */
660         if (!(SVAL(inbuf,smb_flg2) & FLAGS2_32_BIT_ERROR_CODES)) {
661                 if (NT_STATUS_EQUAL(NT_STATUS_OBJECT_NAME_INVALID,status)) {
662                         /* We need to map to ERRbadpath */
663                         return NT_STATUS_OBJECT_PATH_NOT_FOUND;
664                 }
665         }
666         return status;
667 }
668         
669 /****************************************************************************
670  Reply to a checkpath.
671 ****************************************************************************/
672
673 int reply_checkpath(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize)
674 {
675         int outsize = 0;
676         pstring name;
677         SMB_STRUCT_STAT sbuf;
678         NTSTATUS status;
679
680         START_PROFILE(SMBcheckpath);
681
682         srvstr_get_path(inbuf, name, smb_buf(inbuf) + 1, sizeof(name), 0, STR_TERMINATE, &status);
683         if (!NT_STATUS_IS_OK(status)) {
684                 END_PROFILE(SMBcheckpath);
685                 status = map_checkpath_error(inbuf, status);
686                 return ERROR_NT(status);
687         }
688
689         status = resolve_dfspath(conn, SVAL(inbuf,smb_flg2) & FLAGS2_DFS_PATHNAMES, name);
690         if (!NT_STATUS_IS_OK(status)) {
691                 if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) {
692                         END_PROFILE(SMBcheckpath);
693                         return ERROR_BOTH(NT_STATUS_PATH_NOT_COVERED, ERRSRV, ERRbadpath);
694                 }
695                 goto path_err;
696         }
697
698         DEBUG(3,("reply_checkpath %s mode=%d\n", name, (int)SVAL(inbuf,smb_vwv0)));
699
700         status = unix_convert(conn, name, False, NULL, &sbuf);
701         if (!NT_STATUS_IS_OK(status)) {
702                 goto path_err;
703         }
704
705         status = check_name(conn, name);
706         if (!NT_STATUS_IS_OK(status)) {
707                 DEBUG(3,("reply_checkpath: check_name of %s failed (%s)\n",name,nt_errstr(status)));
708                 goto path_err;
709         }
710
711         if (!VALID_STAT(sbuf) && (SMB_VFS_STAT(conn,name,&sbuf) != 0)) {
712                 DEBUG(3,("reply_checkpath: stat of %s failed (%s)\n",name,strerror(errno)));
713                 status = map_nt_error_from_unix(errno);
714                 goto path_err;
715         }
716
717         if (!S_ISDIR(sbuf.st_mode)) {
718                 END_PROFILE(SMBcheckpath);
719                 return ERROR_BOTH(NT_STATUS_NOT_A_DIRECTORY,ERRDOS,ERRbadpath);
720         }
721
722         outsize = set_message(inbuf,outbuf,0,0,False);
723
724         END_PROFILE(SMBcheckpath);
725         return outsize;
726
727   path_err:
728
729         END_PROFILE(SMBcheckpath);
730
731         /* We special case this - as when a Windows machine
732                 is parsing a path is steps through the components
733                 one at a time - if a component fails it expects
734                 ERRbadpath, not ERRbadfile.
735         */
736         status = map_checkpath_error(inbuf, status);
737         if(NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
738                 /*
739                  * Windows returns different error codes if
740                  * the parent directory is valid but not the
741                  * last component - it returns NT_STATUS_OBJECT_NAME_NOT_FOUND
742                  * for that case and NT_STATUS_OBJECT_PATH_NOT_FOUND
743                  * if the path is invalid.
744                  */
745                 return ERROR_BOTH(NT_STATUS_OBJECT_NAME_NOT_FOUND,ERRDOS,ERRbadpath);
746         }
747
748         return ERROR_NT(status);
749 }
750
751 /****************************************************************************
752  Reply to a getatr.
753 ****************************************************************************/
754
755 int reply_getatr(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize)
756 {
757         pstring fname;
758         int outsize = 0;
759         SMB_STRUCT_STAT sbuf;
760         int mode=0;
761         SMB_OFF_T size=0;
762         time_t mtime=0;
763         char *p;
764         NTSTATUS status;
765
766         START_PROFILE(SMBgetatr);
767
768         p = smb_buf(inbuf) + 1;
769         p += srvstr_get_path(inbuf, fname, p, sizeof(fname), 0, STR_TERMINATE, &status);
770         if (!NT_STATUS_IS_OK(status)) {
771                 END_PROFILE(SMBgetatr);
772                 return ERROR_NT(status);
773         }
774
775         status = resolve_dfspath(conn, SVAL(inbuf,smb_flg2) & FLAGS2_DFS_PATHNAMES, fname);
776         if (!NT_STATUS_IS_OK(status)) {
777                 END_PROFILE(SMBgetatr);
778                 if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) {
779                         return ERROR_BOTH(NT_STATUS_PATH_NOT_COVERED, ERRSRV, ERRbadpath);
780                 }
781                 return ERROR_NT(status);
782         }
783   
784         /* dos smetimes asks for a stat of "" - it returns a "hidden directory"
785                 under WfWg - weird! */
786         if (*fname == '\0') {
787                 mode = aHIDDEN | aDIR;
788                 if (!CAN_WRITE(conn)) {
789                         mode |= aRONLY;
790                 }
791                 size = 0;
792                 mtime = 0;
793         } else {
794                 status = unix_convert(conn, fname, False, NULL,&sbuf);
795                 if (!NT_STATUS_IS_OK(status)) {
796                         END_PROFILE(SMBgetatr);
797                         return ERROR_NT(status);
798                 }
799                 status = check_name(conn, fname);
800                 if (!NT_STATUS_IS_OK(status)) {
801                         DEBUG(3,("reply_getatr: check_name of %s failed (%s)\n",fname,nt_errstr(status)));
802                         END_PROFILE(SMBgetatr);
803                         return ERROR_NT(status);
804                 }
805                 if (!VALID_STAT(sbuf) && (SMB_VFS_STAT(conn,fname,&sbuf) != 0)) {
806                         DEBUG(3,("reply_getatr: stat of %s failed (%s)\n",fname,strerror(errno)));
807                         return UNIXERROR(ERRDOS,ERRbadfile);
808                 }
809
810                 mode = dos_mode(conn,fname,&sbuf);
811                 size = sbuf.st_size;
812                 mtime = sbuf.st_mtime;
813                 if (mode & aDIR) {
814                         size = 0;
815                 }
816         }
817   
818         outsize = set_message(inbuf,outbuf,10,0,True);
819
820         SSVAL(outbuf,smb_vwv0,mode);
821         if(lp_dos_filetime_resolution(SNUM(conn)) ) {
822                 srv_put_dos_date3(outbuf,smb_vwv1,mtime & ~1);
823         } else {
824                 srv_put_dos_date3(outbuf,smb_vwv1,mtime);
825         }
826         SIVAL(outbuf,smb_vwv3,(uint32)size);
827
828         if (Protocol >= PROTOCOL_NT1) {
829                 SSVAL(outbuf,smb_flg2,SVAL(outbuf, smb_flg2) | FLAGS2_IS_LONG_NAME);
830         }
831   
832         DEBUG(3,("reply_getatr: name=%s mode=%d size=%u\n", fname, mode, (unsigned int)size ) );
833   
834         END_PROFILE(SMBgetatr);
835         return(outsize);
836 }
837
838 /****************************************************************************
839  Reply to a setatr.
840 ****************************************************************************/
841
842 int reply_setatr(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize)
843 {
844         pstring fname;
845         int outsize = 0;
846         int mode;
847         time_t mtime;
848         SMB_STRUCT_STAT sbuf;
849         char *p;
850         NTSTATUS status;
851
852         START_PROFILE(SMBsetatr);
853
854         p = smb_buf(inbuf) + 1;
855         p += srvstr_get_path(inbuf, fname, p, sizeof(fname), 0, STR_TERMINATE, &status);
856         if (!NT_STATUS_IS_OK(status)) {
857                 END_PROFILE(SMBsetatr);
858                 return ERROR_NT(status);
859         }
860
861         status = resolve_dfspath(conn, SVAL(inbuf,smb_flg2) & FLAGS2_DFS_PATHNAMES, fname);
862         if (!NT_STATUS_IS_OK(status)) {
863                 END_PROFILE(SMBsetatr);
864                 if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) {
865                         return ERROR_BOTH(NT_STATUS_PATH_NOT_COVERED, ERRSRV, ERRbadpath);
866                 }
867                 return ERROR_NT(status);
868         }
869   
870         status = unix_convert(conn, fname, False, NULL, &sbuf);
871         if (!NT_STATUS_IS_OK(status)) {
872                 END_PROFILE(SMBsetatr);
873                 return ERROR_NT(status);
874         }
875
876         status = check_name(conn, fname);
877         if (!NT_STATUS_IS_OK(status)) {
878                 END_PROFILE(SMBsetatr);
879                 return ERROR_NT(status);
880         }
881
882         if (fname[0] == '.' && fname[1] == '\0') {
883                 /*
884                  * Not sure here is the right place to catch this
885                  * condition. Might be moved to somewhere else later -- vl
886                  */
887                 END_PROFILE(SMBsetatr);
888                 return ERROR_NT(NT_STATUS_ACCESS_DENIED);
889         }
890
891         mode = SVAL(inbuf,smb_vwv0);
892         mtime = srv_make_unix_date3(inbuf+smb_vwv1);
893   
894         if (mode != FILE_ATTRIBUTE_NORMAL) {
895                 if (VALID_STAT_OF_DIR(sbuf))
896                         mode |= aDIR;
897                 else
898                         mode &= ~aDIR;
899
900                 if (file_set_dosmode(conn,fname,mode,&sbuf,False) != 0) {
901                         END_PROFILE(SMBsetatr);
902                         return UNIXERROR(ERRDOS, ERRnoaccess);
903                 }
904         }
905
906         if (!set_filetime(conn,fname,convert_time_t_to_timespec(mtime))) {
907                 END_PROFILE(SMBsetatr);
908                 return UNIXERROR(ERRDOS, ERRnoaccess);
909         }
910  
911         outsize = set_message(inbuf,outbuf,0,0,False);
912   
913         DEBUG( 3, ( "setatr name=%s mode=%d\n", fname, mode ) );
914   
915         END_PROFILE(SMBsetatr);
916         return(outsize);
917 }
918
919 /****************************************************************************
920  Reply to a dskattr.
921 ****************************************************************************/
922
923 int reply_dskattr(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize)
924 {
925         int outsize = 0;
926         SMB_BIG_UINT dfree,dsize,bsize;
927         START_PROFILE(SMBdskattr);
928
929         if (get_dfree_info(conn,".",True,&bsize,&dfree,&dsize) == (SMB_BIG_UINT)-1) {
930                 END_PROFILE(SMBdskattr);
931                 return(UNIXERROR(ERRHRD,ERRgeneral));
932         }
933   
934         outsize = set_message(inbuf,outbuf,5,0,True);
935         
936         if (Protocol <= PROTOCOL_LANMAN2) {
937                 double total_space, free_space;
938                 /* we need to scale this to a number that DOS6 can handle. We
939                    use floating point so we can handle large drives on systems
940                    that don't have 64 bit integers 
941
942                    we end up displaying a maximum of 2G to DOS systems
943                 */
944                 total_space = dsize * (double)bsize;
945                 free_space = dfree * (double)bsize;
946
947                 dsize = (total_space+63*512) / (64*512);
948                 dfree = (free_space+63*512) / (64*512);
949                 
950                 if (dsize > 0xFFFF) dsize = 0xFFFF;
951                 if (dfree > 0xFFFF) dfree = 0xFFFF;
952
953                 SSVAL(outbuf,smb_vwv0,dsize);
954                 SSVAL(outbuf,smb_vwv1,64); /* this must be 64 for dos systems */
955                 SSVAL(outbuf,smb_vwv2,512); /* and this must be 512 */
956                 SSVAL(outbuf,smb_vwv3,dfree);
957         } else {
958                 SSVAL(outbuf,smb_vwv0,dsize);
959                 SSVAL(outbuf,smb_vwv1,bsize/512);
960                 SSVAL(outbuf,smb_vwv2,512);
961                 SSVAL(outbuf,smb_vwv3,dfree);
962         }
963
964         DEBUG(3,("dskattr dfree=%d\n", (unsigned int)dfree));
965
966         END_PROFILE(SMBdskattr);
967         return(outsize);
968 }
969
970 /****************************************************************************
971  Reply to a search.
972  Can be called from SMBsearch, SMBffirst or SMBfunique.
973 ****************************************************************************/
974
975 int reply_search(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize)
976 {
977         pstring mask;
978         pstring directory;
979         pstring fname;
980         SMB_OFF_T size;
981         uint32 mode;
982         time_t date;
983         uint32 dirtype;
984         int outsize = 0;
985         unsigned int numentries = 0;
986         unsigned int maxentries = 0;
987         BOOL finished = False;
988         char *p;
989         int status_len;
990         pstring path;
991         char status[21];
992         int dptr_num= -1;
993         BOOL check_descend = False;
994         BOOL expect_close = False;
995         NTSTATUS nt_status;
996         BOOL mask_contains_wcard = False;
997         BOOL allow_long_path_components = (SVAL(inbuf,smb_flg2) & FLAGS2_LONG_PATH_COMPONENTS) ? True : False;
998
999         START_PROFILE(SMBsearch);
1000
1001         if (lp_posix_pathnames()) {
1002                 END_PROFILE(SMBsearch);
1003                 return reply_unknown(inbuf, outbuf);
1004         }
1005
1006         *mask = *directory = *fname = 0;
1007
1008         /* If we were called as SMBffirst then we must expect close. */
1009         if(CVAL(inbuf,smb_com) == SMBffirst) {
1010                 expect_close = True;
1011         }
1012   
1013         outsize = set_message(inbuf,outbuf,1,3,True);
1014         maxentries = SVAL(inbuf,smb_vwv0); 
1015         dirtype = SVAL(inbuf,smb_vwv1);
1016         p = smb_buf(inbuf) + 1;
1017         p += srvstr_get_path_wcard(inbuf, path, p, sizeof(path), 0, STR_TERMINATE, &nt_status, &mask_contains_wcard);
1018         if (!NT_STATUS_IS_OK(nt_status)) {
1019                 END_PROFILE(SMBsearch);
1020                 return ERROR_NT(nt_status);
1021         }
1022
1023         nt_status = resolve_dfspath_wcard(conn, SVAL(inbuf,smb_flg2) & FLAGS2_DFS_PATHNAMES, path, &mask_contains_wcard);
1024         if (!NT_STATUS_IS_OK(nt_status)) {
1025                 END_PROFILE(SMBsearch);
1026                 if (NT_STATUS_EQUAL(nt_status,NT_STATUS_PATH_NOT_COVERED)) {
1027                         return ERROR_BOTH(NT_STATUS_PATH_NOT_COVERED, ERRSRV, ERRbadpath);
1028                 }
1029                 return ERROR_NT(nt_status);
1030         }
1031   
1032         p++;
1033         status_len = SVAL(p, 0);
1034         p += 2;
1035   
1036         /* dirtype &= ~aDIR; */
1037
1038         if (status_len == 0) {
1039                 SMB_STRUCT_STAT sbuf;
1040
1041                 pstrcpy(directory,path);
1042                 nt_status = unix_convert(conn, directory, True, NULL, &sbuf);
1043                 if (!NT_STATUS_IS_OK(nt_status)) {
1044                         END_PROFILE(SMBsearch);
1045                         return ERROR_NT(nt_status);
1046                 }
1047
1048                 nt_status = check_name(conn, directory);
1049                 if (!NT_STATUS_IS_OK(nt_status)) {
1050                         END_PROFILE(SMBsearch);
1051                         return ERROR_NT(nt_status);
1052                 }
1053
1054                 p = strrchr_m(directory,'/');
1055                 if (!p) {
1056                         pstrcpy(mask,directory);
1057                         pstrcpy(directory,".");
1058                 } else {
1059                         *p = 0;
1060                         pstrcpy(mask,p+1);
1061                 }
1062
1063                 if (*directory == '\0') {
1064                         pstrcpy(directory,".");
1065                 }
1066                 memset((char *)status,'\0',21);
1067                 SCVAL(status,0,(dirtype & 0x1F));
1068         } else {
1069                 int status_dirtype;
1070
1071                 memcpy(status,p,21);
1072                 status_dirtype = CVAL(status,0) & 0x1F;
1073                 if (status_dirtype != (dirtype & 0x1F)) {
1074                         dirtype = status_dirtype;
1075                 }
1076
1077                 conn->dirptr = dptr_fetch(status+12,&dptr_num);      
1078                 if (!conn->dirptr) {
1079                         goto SearchEmpty;
1080                 }
1081                 string_set(&conn->dirpath,dptr_path(dptr_num));
1082                 pstrcpy(mask, dptr_wcard(dptr_num));
1083                 /*
1084                  * For a 'continue' search we have no string. So
1085                  * check from the initial saved string.
1086                  */
1087                 mask_contains_wcard = ms_has_wild(mask);
1088         }
1089
1090         p = smb_buf(outbuf) + 3;
1091      
1092         if (status_len == 0) {
1093                 nt_status = dptr_create(conn,
1094                                         directory,
1095                                         True,
1096                                         expect_close,
1097                                         SVAL(inbuf,smb_pid),
1098                                         mask,
1099                                         mask_contains_wcard,
1100                                         dirtype,
1101                                         &conn->dirptr);
1102                 if (!NT_STATUS_IS_OK(nt_status)) {
1103                         return ERROR_NT(nt_status);
1104                 }
1105                 dptr_num = dptr_dnum(conn->dirptr);
1106         } else {
1107                 dirtype = dptr_attr(dptr_num);
1108         }
1109
1110         DEBUG(4,("dptr_num is %d\n",dptr_num));
1111
1112         if ((dirtype&0x1F) == aVOLID) {   
1113                 memcpy(p,status,21);
1114                 make_dir_struct(p,"???????????",volume_label(SNUM(conn)),
1115                                 0,aVOLID,0,!allow_long_path_components);
1116                 dptr_fill(p+12,dptr_num);
1117                 if (dptr_zero(p+12) && (status_len==0)) {
1118                         numentries = 1;
1119                 } else {
1120                         numentries = 0;
1121                 }
1122                 p += DIR_STRUCT_SIZE;
1123         } else {
1124                 unsigned int i;
1125                 maxentries = MIN(maxentries, ((BUFFER_SIZE - (p - outbuf))/DIR_STRUCT_SIZE));
1126
1127                 DEBUG(8,("dirpath=<%s> dontdescend=<%s>\n",
1128                         conn->dirpath,lp_dontdescend(SNUM(conn))));
1129                 if (in_list(conn->dirpath, lp_dontdescend(SNUM(conn)),True)) {
1130                         check_descend = True;
1131                 }
1132
1133                 for (i=numentries;(i<maxentries) && !finished;i++) {
1134                         finished = !get_dir_entry(conn,mask,dirtype,fname,&size,&mode,&date,check_descend);
1135                         if (!finished) {
1136                                 memcpy(p,status,21);
1137                                 make_dir_struct(p,mask,fname,size, mode,date,
1138                                                 !allow_long_path_components);
1139                                 if (!dptr_fill(p+12,dptr_num)) {
1140                                         break;
1141                                 }
1142                                 numentries++;
1143                                 p += DIR_STRUCT_SIZE;
1144                         }
1145                 }
1146         }
1147
1148   SearchEmpty:
1149
1150         /* If we were called as SMBffirst with smb_search_id == NULL
1151                 and no entries were found then return error and close dirptr 
1152                 (X/Open spec) */
1153
1154         if (numentries == 0) {
1155                 dptr_close(&dptr_num);
1156         } else if(expect_close && status_len == 0) {
1157                 /* Close the dptr - we know it's gone */
1158                 dptr_close(&dptr_num);
1159         }
1160
1161         /* If we were called as SMBfunique, then we can close the dirptr now ! */
1162         if(dptr_num >= 0 && CVAL(inbuf,smb_com) == SMBfunique) {
1163                 dptr_close(&dptr_num);
1164         }
1165
1166         if ((numentries == 0) && !mask_contains_wcard) {
1167                 return ERROR_BOTH(STATUS_NO_MORE_FILES,ERRDOS,ERRnofiles);
1168         }
1169
1170         SSVAL(outbuf,smb_vwv0,numentries);
1171         SSVAL(outbuf,smb_vwv1,3 + numentries * DIR_STRUCT_SIZE);
1172         SCVAL(smb_buf(outbuf),0,5);
1173         SSVAL(smb_buf(outbuf),1,numentries*DIR_STRUCT_SIZE);
1174
1175         /* The replies here are never long name. */
1176         SSVAL(outbuf,smb_flg2,SVAL(outbuf, smb_flg2) & (~FLAGS2_IS_LONG_NAME));
1177         if (!allow_long_path_components) {
1178                 SSVAL(outbuf,smb_flg2,SVAL(outbuf, smb_flg2) & (~FLAGS2_LONG_PATH_COMPONENTS));
1179         }
1180
1181         /* This SMB *always* returns ASCII names. Remove the unicode bit in flags2. */
1182         SSVAL(outbuf,smb_flg2, (SVAL(outbuf, smb_flg2) & (~FLAGS2_UNICODE_STRINGS)));
1183           
1184         outsize += DIR_STRUCT_SIZE*numentries;
1185         smb_setlen(inbuf,outbuf,outsize - 4);
1186   
1187         if ((! *directory) && dptr_path(dptr_num))
1188                 slprintf(directory, sizeof(directory)-1, "(%s)",dptr_path(dptr_num));
1189
1190         DEBUG( 4, ( "%s mask=%s path=%s dtype=%d nument=%u of %u\n",
1191                 smb_fn_name(CVAL(inbuf,smb_com)), 
1192                 mask, directory, dirtype, numentries, maxentries ) );
1193
1194         END_PROFILE(SMBsearch);
1195         return(outsize);
1196 }
1197
1198 /****************************************************************************
1199  Reply to a fclose (stop directory search).
1200 ****************************************************************************/
1201
1202 int reply_fclose(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize)
1203 {
1204         int outsize = 0;
1205         int status_len;
1206         pstring path;
1207         char status[21];
1208         int dptr_num= -2;
1209         char *p;
1210         NTSTATUS err;
1211         BOOL path_contains_wcard = False;
1212
1213         START_PROFILE(SMBfclose);
1214
1215         if (lp_posix_pathnames()) {
1216                 END_PROFILE(SMBfclose);
1217                 return reply_unknown(inbuf, outbuf);
1218         }
1219
1220         outsize = set_message(inbuf,outbuf,1,0,True);
1221         p = smb_buf(inbuf) + 1;
1222         p += srvstr_get_path_wcard(inbuf, path, p, sizeof(path), 0, STR_TERMINATE, &err, &path_contains_wcard);
1223         if (!NT_STATUS_IS_OK(err)) {
1224                 END_PROFILE(SMBfclose);
1225                 return ERROR_NT(err);
1226         }
1227         p++;
1228         status_len = SVAL(p,0);
1229         p += 2;
1230
1231         if (status_len == 0) {
1232                 END_PROFILE(SMBfclose);
1233                 return ERROR_DOS(ERRSRV,ERRsrverror);
1234         }
1235
1236         memcpy(status,p,21);
1237
1238         if(dptr_fetch(status+12,&dptr_num)) {
1239                 /*  Close the dptr - we know it's gone */
1240                 dptr_close(&dptr_num);
1241         }
1242
1243         SSVAL(outbuf,smb_vwv0,0);
1244
1245         DEBUG(3,("search close\n"));
1246
1247         END_PROFILE(SMBfclose);
1248         return(outsize);
1249 }
1250
1251 /****************************************************************************
1252  Reply to an open.
1253 ****************************************************************************/
1254
1255 int reply_open(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize)
1256 {
1257         pstring fname;
1258         int outsize = 0;
1259         uint32 fattr=0;
1260         SMB_OFF_T size = 0;
1261         time_t mtime=0;
1262         int info;
1263         SMB_STRUCT_STAT sbuf;
1264         files_struct *fsp;
1265         int oplock_request = CORE_OPLOCK_REQUEST(inbuf);
1266         int deny_mode;
1267         uint32 dos_attr = SVAL(inbuf,smb_vwv1);
1268         uint32 access_mask;
1269         uint32 share_mode;
1270         uint32 create_disposition;
1271         uint32 create_options = 0;
1272         NTSTATUS status;
1273         START_PROFILE(SMBopen);
1274  
1275         deny_mode = SVAL(inbuf,smb_vwv0);
1276
1277         srvstr_get_path(inbuf, fname, smb_buf(inbuf)+1, sizeof(fname), 0, STR_TERMINATE, &status);
1278         if (!NT_STATUS_IS_OK(status)) {
1279                 END_PROFILE(SMBopen);
1280                 return ERROR_NT(status);
1281         }
1282
1283         status = resolve_dfspath(conn, SVAL(inbuf,smb_flg2) & FLAGS2_DFS_PATHNAMES, fname);
1284         if (!NT_STATUS_IS_OK(status)) {
1285                 END_PROFILE(SMBopen);
1286                 if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) {
1287                         return ERROR_BOTH(NT_STATUS_PATH_NOT_COVERED, ERRSRV, ERRbadpath);
1288                 }
1289                 return ERROR_NT(status);
1290         }
1291
1292         status = unix_convert(conn, fname, False, NULL, &sbuf);
1293         if (!NT_STATUS_IS_OK(status)) {
1294                 END_PROFILE(SMBopen);
1295                 return ERROR_NT(status);
1296         }
1297     
1298         status = check_name(conn, fname);
1299         if (!NT_STATUS_IS_OK(status)) {
1300                 END_PROFILE(SMBopen);
1301                 return ERROR_NT(status);
1302         }
1303
1304         if (!map_open_params_to_ntcreate(fname, deny_mode, OPENX_FILE_EXISTS_OPEN,
1305                         &access_mask, &share_mode, &create_disposition, &create_options)) {
1306                 END_PROFILE(SMBopen);
1307                 return ERROR_NT(NT_STATUS_DOS(ERRDOS, ERRbadaccess));
1308         }
1309
1310         status = open_file_ntcreate(conn,fname,&sbuf,
1311                         access_mask,
1312                         share_mode,
1313                         create_disposition,
1314                         create_options,
1315                         dos_attr,
1316                         oplock_request,
1317                         &info, &fsp);
1318
1319         if (!NT_STATUS_IS_OK(status)) {
1320                 END_PROFILE(SMBopen);
1321                 if (open_was_deferred(SVAL(inbuf,smb_mid))) {
1322                         /* We have re-scheduled this call. */
1323                         return -1;
1324                 }
1325                 return ERROR_NT(status);
1326         }
1327
1328         size = sbuf.st_size;
1329         fattr = dos_mode(conn,fname,&sbuf);
1330         mtime = sbuf.st_mtime;
1331
1332         if (fattr & aDIR) {
1333                 DEBUG(3,("attempt to open a directory %s\n",fname));
1334                 close_file(fsp,ERROR_CLOSE);
1335                 END_PROFILE(SMBopen);
1336                 return ERROR_DOS(ERRDOS,ERRnoaccess);
1337         }
1338   
1339         outsize = set_message(inbuf,outbuf,7,0,True);
1340         SSVAL(outbuf,smb_vwv0,fsp->fnum);
1341         SSVAL(outbuf,smb_vwv1,fattr);
1342         if(lp_dos_filetime_resolution(SNUM(conn)) ) {
1343                 srv_put_dos_date3(outbuf,smb_vwv2,mtime & ~1);
1344         } else {
1345                 srv_put_dos_date3(outbuf,smb_vwv2,mtime);
1346         }
1347         SIVAL(outbuf,smb_vwv4,(uint32)size);
1348         SSVAL(outbuf,smb_vwv6,deny_mode);
1349
1350         if (oplock_request && lp_fake_oplocks(SNUM(conn))) {
1351                 SCVAL(outbuf,smb_flg,CVAL(outbuf,smb_flg)|CORE_OPLOCK_GRANTED);
1352         }
1353     
1354         if(EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type)) {
1355                 SCVAL(outbuf,smb_flg,CVAL(outbuf,smb_flg)|CORE_OPLOCK_GRANTED);
1356         }
1357         END_PROFILE(SMBopen);
1358         return(outsize);
1359 }
1360
1361 /****************************************************************************
1362  Reply to an open and X.
1363 ****************************************************************************/
1364
1365 int reply_open_and_X(connection_struct *conn, char *inbuf,char *outbuf,int length,int bufsize)
1366 {
1367         pstring fname;
1368         uint16 open_flags = SVAL(inbuf,smb_vwv2);
1369         int deny_mode = SVAL(inbuf,smb_vwv3);
1370         uint32 smb_attr = SVAL(inbuf,smb_vwv5);
1371         /* Breakout the oplock request bits so we can set the
1372                 reply bits separately. */
1373         int ex_oplock_request = EXTENDED_OPLOCK_REQUEST(inbuf);
1374         int core_oplock_request = CORE_OPLOCK_REQUEST(inbuf);
1375         int oplock_request = ex_oplock_request | core_oplock_request;
1376 #if 0
1377         int smb_sattr = SVAL(inbuf,smb_vwv4); 
1378         uint32 smb_time = make_unix_date3(inbuf+smb_vwv6);
1379 #endif
1380         int smb_ofun = SVAL(inbuf,smb_vwv8);
1381         uint32 fattr=0;
1382         int mtime=0;
1383         SMB_STRUCT_STAT sbuf;
1384         int smb_action = 0;
1385         files_struct *fsp;
1386         NTSTATUS status;
1387         SMB_BIG_UINT allocation_size = (SMB_BIG_UINT)IVAL(inbuf,smb_vwv9);
1388         ssize_t retval = -1;
1389         uint32 access_mask;
1390         uint32 share_mode;
1391         uint32 create_disposition;
1392         uint32 create_options = 0;
1393
1394         START_PROFILE(SMBopenX);
1395
1396         /* If it's an IPC, pass off the pipe handler. */
1397         if (IS_IPC(conn)) {
1398                 if (lp_nt_pipe_support()) {
1399                         END_PROFILE(SMBopenX);
1400                         return reply_open_pipe_and_X(conn, inbuf,outbuf,length,bufsize);
1401                 } else {
1402                         END_PROFILE(SMBopenX);
1403                         return ERROR_DOS(ERRSRV,ERRaccess);
1404                 }
1405         }
1406
1407         /* XXXX we need to handle passed times, sattr and flags */
1408         srvstr_get_path(inbuf, fname, smb_buf(inbuf), sizeof(fname), 0, STR_TERMINATE, &status);
1409         if (!NT_STATUS_IS_OK(status)) {
1410                 END_PROFILE(SMBopenX);
1411                 return ERROR_NT(status);
1412         }
1413
1414         status = resolve_dfspath(conn, SVAL(inbuf,smb_flg2) & FLAGS2_DFS_PATHNAMES, fname);
1415         if (!NT_STATUS_IS_OK(status)) {
1416                 END_PROFILE(SMBopenX);
1417                 if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) {
1418                         return ERROR_BOTH(NT_STATUS_PATH_NOT_COVERED, ERRSRV, ERRbadpath);
1419                 }
1420                 return ERROR_NT(status);
1421         }
1422
1423         status = unix_convert(conn, fname, False, NULL, &sbuf);
1424         if (!NT_STATUS_IS_OK(status)) {
1425                 END_PROFILE(SMBopenX);
1426                 return ERROR_NT(status);
1427         }
1428
1429         status = check_name(conn, fname);
1430         if (!NT_STATUS_IS_OK(status)) {
1431                 END_PROFILE(SMBopenX);
1432                 return ERROR_NT(status);
1433         }
1434
1435         if (!map_open_params_to_ntcreate(fname, deny_mode, smb_ofun,
1436                                 &access_mask,
1437                                 &share_mode,
1438                                 &create_disposition,
1439                                 &create_options)) {
1440                 END_PROFILE(SMBopenX);
1441                 return ERROR_NT(NT_STATUS_DOS(ERRDOS, ERRbadaccess));
1442         }
1443
1444         status = open_file_ntcreate(conn,fname,&sbuf,
1445                         access_mask,
1446                         share_mode,
1447                         create_disposition,
1448                         create_options,
1449                         smb_attr,
1450                         oplock_request,
1451                         &smb_action, &fsp);
1452       
1453         if (!NT_STATUS_IS_OK(status)) {
1454                 END_PROFILE(SMBopenX);
1455                 if (open_was_deferred(SVAL(inbuf,smb_mid))) {
1456                         /* We have re-scheduled this call. */
1457                         return -1;
1458                 }
1459                 return ERROR_NT(status);
1460         }
1461
1462         /* Setting the "size" field in vwv9 and vwv10 causes the file to be set to this size,
1463            if the file is truncated or created. */
1464         if (((smb_action == FILE_WAS_CREATED) || (smb_action == FILE_WAS_OVERWRITTEN)) && allocation_size) {
1465                 fsp->initial_allocation_size = smb_roundup(fsp->conn, allocation_size);
1466                 if (vfs_allocate_file_space(fsp, fsp->initial_allocation_size) == -1) {
1467                         close_file(fsp,ERROR_CLOSE);
1468                         END_PROFILE(SMBopenX);
1469                         return ERROR_NT(NT_STATUS_DISK_FULL);
1470                 }
1471                 retval = vfs_set_filelen(fsp, (SMB_OFF_T)allocation_size);
1472                 if (retval < 0) {
1473                         close_file(fsp,ERROR_CLOSE);
1474                         END_PROFILE(SMBopenX);
1475                         return ERROR_NT(NT_STATUS_DISK_FULL);
1476                 }
1477                 sbuf.st_size = get_allocation_size(conn,fsp,&sbuf);
1478         }
1479
1480         fattr = dos_mode(conn,fname,&sbuf);
1481         mtime = sbuf.st_mtime;
1482         if (fattr & aDIR) {
1483                 close_file(fsp,ERROR_CLOSE);
1484                 END_PROFILE(SMBopenX);
1485                 return ERROR_DOS(ERRDOS,ERRnoaccess);
1486         }
1487
1488         /* If the caller set the extended oplock request bit
1489                 and we granted one (by whatever means) - set the
1490                 correct bit for extended oplock reply.
1491         */
1492
1493         if (ex_oplock_request && lp_fake_oplocks(SNUM(conn))) {
1494                 smb_action |= EXTENDED_OPLOCK_GRANTED;
1495         }
1496
1497         if(ex_oplock_request && EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type)) {
1498                 smb_action |= EXTENDED_OPLOCK_GRANTED;
1499         }
1500
1501         /* If the caller set the core oplock request bit
1502                 and we granted one (by whatever means) - set the
1503                 correct bit for core oplock reply.
1504         */
1505
1506         if (core_oplock_request && lp_fake_oplocks(SNUM(conn))) {
1507                 SCVAL(outbuf,smb_flg,CVAL(outbuf,smb_flg)|CORE_OPLOCK_GRANTED);
1508         }
1509
1510         if(core_oplock_request && EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type)) {
1511                 SCVAL(outbuf,smb_flg,CVAL(outbuf,smb_flg)|CORE_OPLOCK_GRANTED);
1512         }
1513
1514         if (open_flags & EXTENDED_RESPONSE_REQUIRED) {
1515                 set_message(inbuf,outbuf,19,0,True);
1516         } else {
1517                 set_message(inbuf,outbuf,15,0,True);
1518         }
1519         SSVAL(outbuf,smb_vwv2,fsp->fnum);
1520         SSVAL(outbuf,smb_vwv3,fattr);
1521         if(lp_dos_filetime_resolution(SNUM(conn)) ) {
1522                 srv_put_dos_date3(outbuf,smb_vwv4,mtime & ~1);
1523         } else {
1524                 srv_put_dos_date3(outbuf,smb_vwv4,mtime);
1525         }
1526         SIVAL(outbuf,smb_vwv6,(uint32)sbuf.st_size);
1527         SSVAL(outbuf,smb_vwv8,GET_OPENX_MODE(deny_mode));
1528         SSVAL(outbuf,smb_vwv11,smb_action);
1529
1530         if (open_flags & EXTENDED_RESPONSE_REQUIRED) {
1531                 SIVAL(outbuf, smb_vwv15, STD_RIGHT_ALL_ACCESS);
1532         }
1533
1534         END_PROFILE(SMBopenX);
1535         return chain_reply(inbuf,outbuf,length,bufsize);
1536 }
1537
1538 /****************************************************************************
1539  Reply to a SMBulogoffX.
1540  conn POINTER CAN BE NULL HERE !
1541 ****************************************************************************/
1542
1543 int reply_ulogoffX(connection_struct *conn, char *inbuf,char *outbuf,int length,int bufsize)
1544 {
1545         uint16 vuid = SVAL(inbuf,smb_uid);
1546         user_struct *vuser = get_valid_user_struct(vuid);
1547         START_PROFILE(SMBulogoffX);
1548
1549         if(vuser == 0)
1550                 DEBUG(3,("ulogoff, vuser id %d does not map to user.\n", vuid));
1551
1552         /* in user level security we are supposed to close any files
1553                 open by this user */
1554         if ((vuser != 0) && (lp_security() != SEC_SHARE))
1555                 file_close_user(vuid);
1556
1557         invalidate_vuid(vuid);
1558
1559         set_message(inbuf,outbuf,2,0,True);
1560
1561         DEBUG( 3, ( "ulogoffX vuid=%d\n", vuid ) );
1562
1563         END_PROFILE(SMBulogoffX);
1564         return chain_reply(inbuf,outbuf,length,bufsize);
1565 }
1566
1567 /****************************************************************************
1568  Reply to a mknew or a create.
1569 ****************************************************************************/
1570
1571 int reply_mknew(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize)
1572 {
1573         pstring fname;
1574         int com;
1575         int outsize = 0;
1576         uint32 fattr = SVAL(inbuf,smb_vwv0);
1577         struct timespec ts[2];
1578         files_struct *fsp;
1579         int oplock_request = CORE_OPLOCK_REQUEST(inbuf);
1580         SMB_STRUCT_STAT sbuf;
1581         NTSTATUS status;
1582         uint32 access_mask = FILE_GENERIC_READ | FILE_GENERIC_WRITE;
1583         uint32 share_mode = FILE_SHARE_READ|FILE_SHARE_WRITE;
1584         uint32 create_disposition;
1585         uint32 create_options = 0;
1586
1587         START_PROFILE(SMBcreate);
1588  
1589         com = SVAL(inbuf,smb_com);
1590
1591         ts[1] = convert_time_t_to_timespec(srv_make_unix_date3(inbuf + smb_vwv1)); /* mtime. */
1592
1593         srvstr_get_path(inbuf, fname, smb_buf(inbuf) + 1, sizeof(fname), 0, STR_TERMINATE, &status);
1594         if (!NT_STATUS_IS_OK(status)) {
1595                 END_PROFILE(SMBcreate);
1596                 return ERROR_NT(status);
1597         }
1598
1599         status = resolve_dfspath(conn, SVAL(inbuf,smb_flg2) & FLAGS2_DFS_PATHNAMES, fname);
1600         if (!NT_STATUS_IS_OK(status)) {
1601                 END_PROFILE(SMBcreate);
1602                 if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) {
1603                         return ERROR_BOTH(NT_STATUS_PATH_NOT_COVERED, ERRSRV, ERRbadpath);
1604                 }
1605                 return ERROR_NT(status);
1606         }
1607
1608         status = unix_convert(conn, fname, False, NULL, &sbuf);
1609         if (!NT_STATUS_IS_OK(status)) {
1610                 END_PROFILE(SMBcreate);
1611                 return ERROR_NT(status);
1612         }
1613
1614         status = check_name(conn, fname);
1615         if (!NT_STATUS_IS_OK(status)) {
1616                 END_PROFILE(SMBcreate);
1617                 return ERROR_NT(status);
1618         }
1619
1620         if (fattr & aVOLID) {
1621                 DEBUG(0,("Attempt to create file (%s) with volid set - please report this\n",fname));
1622         }
1623
1624         if(com == SMBmknew) {
1625                 /* We should fail if file exists. */
1626                 create_disposition = FILE_CREATE;
1627         } else {
1628                 /* Create if file doesn't exist, truncate if it does. */
1629                 create_disposition = FILE_OVERWRITE_IF;
1630         }
1631
1632         /* Open file using ntcreate. */
1633         status = open_file_ntcreate(conn,fname,&sbuf,
1634                                 access_mask,
1635                                 share_mode,
1636                                 create_disposition,
1637                                 create_options,
1638                                 fattr,
1639                                 oplock_request,
1640                                 NULL, &fsp);
1641   
1642         if (!NT_STATUS_IS_OK(status)) {
1643                 END_PROFILE(SMBcreate);
1644                 if (open_was_deferred(SVAL(inbuf,smb_mid))) {
1645                         /* We have re-scheduled this call. */
1646                         return -1;
1647                 }
1648                 return ERROR_NT(status);
1649         }
1650  
1651         ts[0] = get_atimespec(&sbuf); /* atime. */
1652         file_ntimes(conn, fname, ts);
1653
1654         outsize = set_message(inbuf,outbuf,1,0,True);
1655         SSVAL(outbuf,smb_vwv0,fsp->fnum);
1656
1657         if (oplock_request && lp_fake_oplocks(SNUM(conn))) {
1658                 SCVAL(outbuf,smb_flg,CVAL(outbuf,smb_flg)|CORE_OPLOCK_GRANTED);
1659         }
1660  
1661         if(EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type)) {
1662                 SCVAL(outbuf,smb_flg,CVAL(outbuf,smb_flg)|CORE_OPLOCK_GRANTED);
1663         }
1664  
1665         DEBUG( 2, ( "reply_mknew: file %s\n", fname ) );
1666         DEBUG( 3, ( "reply_mknew %s fd=%d dmode=0x%x\n", fname, fsp->fh->fd, (unsigned int)fattr ) );
1667
1668         END_PROFILE(SMBcreate);
1669         return(outsize);
1670 }
1671
1672 /****************************************************************************
1673  Reply to a create temporary file.
1674 ****************************************************************************/
1675
1676 int reply_ctemp(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize)
1677 {
1678         pstring fname;
1679         int outsize = 0;
1680         uint32 fattr = SVAL(inbuf,smb_vwv0);
1681         files_struct *fsp;
1682         int oplock_request = CORE_OPLOCK_REQUEST(inbuf);
1683         int tmpfd;
1684         SMB_STRUCT_STAT sbuf;
1685         char *p, *s;
1686         NTSTATUS status;
1687         unsigned int namelen;
1688
1689         START_PROFILE(SMBctemp);
1690
1691         srvstr_get_path(inbuf, fname, smb_buf(inbuf)+1, sizeof(fname), 0, STR_TERMINATE, &status);
1692         if (!NT_STATUS_IS_OK(status)) {
1693                 END_PROFILE(SMBctemp);
1694                 return ERROR_NT(status);
1695         }
1696         if (*fname) {
1697                 pstrcat(fname,"/TMXXXXXX");
1698         } else {
1699                 pstrcat(fname,"TMXXXXXX");
1700         }
1701
1702         status = resolve_dfspath(conn, SVAL(inbuf,smb_flg2) & FLAGS2_DFS_PATHNAMES, fname);
1703         if (!NT_STATUS_IS_OK(status)) {
1704                 END_PROFILE(SMBctemp);
1705                 if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) {
1706                         return ERROR_BOTH(NT_STATUS_PATH_NOT_COVERED, ERRSRV, ERRbadpath);
1707                 }
1708                 return ERROR_NT(status);
1709         }
1710
1711         status = unix_convert(conn, fname, False, NULL, &sbuf);
1712         if (!NT_STATUS_IS_OK(status)) {
1713                 END_PROFILE(SMBctemp);
1714                 return ERROR_NT(status);
1715         }
1716
1717         status = check_name(conn, fname);
1718         if (!NT_STATUS_IS_OK(status)) {
1719                 END_PROFILE(SMBctemp);
1720                 return ERROR_NT(status);
1721         }
1722   
1723         tmpfd = smb_mkstemp(fname);
1724         if (tmpfd == -1) {
1725                 END_PROFILE(SMBctemp);
1726                 return(UNIXERROR(ERRDOS,ERRnoaccess));
1727         }
1728
1729         SMB_VFS_STAT(conn,fname,&sbuf);
1730
1731         /* We should fail if file does not exist. */
1732         status = open_file_ntcreate(conn,fname,&sbuf,
1733                                 FILE_GENERIC_READ | FILE_GENERIC_WRITE,
1734                                 FILE_SHARE_READ|FILE_SHARE_WRITE,
1735                                 FILE_OPEN,
1736                                 0,
1737                                 fattr,
1738                                 oplock_request,
1739                                 NULL, &fsp);
1740
1741         /* close fd from smb_mkstemp() */
1742         close(tmpfd);
1743
1744         if (!NT_STATUS_IS_OK(status)) {
1745                 END_PROFILE(SMBctemp);
1746                 if (open_was_deferred(SVAL(inbuf,smb_mid))) {
1747                         /* We have re-scheduled this call. */
1748                         return -1;
1749                 }
1750                 return ERROR_NT(status);
1751         }
1752
1753         outsize = set_message(inbuf,outbuf,1,0,True);
1754         SSVAL(outbuf,smb_vwv0,fsp->fnum);
1755
1756         /* the returned filename is relative to the directory */
1757         s = strrchr_m(fname, '/');
1758         if (!s) {
1759                 s = fname;
1760         } else {
1761                 s++;
1762         }
1763
1764         p = smb_buf(outbuf);
1765 #if 0
1766         /* Tested vs W2K3 - this doesn't seem to be here - null terminated filename is the only
1767            thing in the byte section. JRA */
1768         SSVALS(p, 0, -1); /* what is this? not in spec */
1769 #endif
1770         namelen = srvstr_push(outbuf, p, s, -1, STR_ASCII|STR_TERMINATE);
1771         p += namelen;
1772         outsize = set_message_end(inbuf,outbuf, p);
1773
1774         if (oplock_request && lp_fake_oplocks(SNUM(conn))) {
1775                 SCVAL(outbuf,smb_flg,CVAL(outbuf,smb_flg)|CORE_OPLOCK_GRANTED);
1776         }
1777   
1778         if (EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type)) {
1779                 SCVAL(outbuf,smb_flg,CVAL(outbuf,smb_flg)|CORE_OPLOCK_GRANTED);
1780         }
1781
1782         DEBUG( 2, ( "reply_ctemp: created temp file %s\n", fname ) );
1783         DEBUG( 3, ( "reply_ctemp %s fd=%d umode=0%o\n", fname, fsp->fh->fd,
1784                         (unsigned int)sbuf.st_mode ) );
1785
1786         END_PROFILE(SMBctemp);
1787         return(outsize);
1788 }
1789
1790 /*******************************************************************
1791  Check if a user is allowed to rename a file.
1792 ********************************************************************/
1793
1794 static NTSTATUS can_rename(connection_struct *conn, char *fname, uint16 dirtype, SMB_STRUCT_STAT *pst, BOOL self_open)
1795 {
1796         files_struct *fsp;
1797         uint32 fmode;
1798         NTSTATUS status;
1799
1800         if (!CAN_WRITE(conn)) {
1801                 return NT_STATUS_MEDIA_WRITE_PROTECTED;
1802         }
1803
1804         fmode = dos_mode(conn,fname,pst);
1805         if ((fmode & ~dirtype) & (aHIDDEN | aSYSTEM)) {
1806                 return NT_STATUS_NO_SUCH_FILE;
1807         }
1808
1809         if (S_ISDIR(pst->st_mode)) {
1810                 return NT_STATUS_OK;
1811         }
1812
1813         status = open_file_ntcreate(conn, fname, pst,
1814                                 DELETE_ACCESS,
1815                                 /* If we're checking our fsp don't deny for delete. */
1816                                 self_open ?
1817                                         FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE :
1818                                         FILE_SHARE_READ|FILE_SHARE_WRITE,
1819                                 FILE_OPEN,
1820                                 0,
1821                                 FILE_ATTRIBUTE_NORMAL,
1822                                 0,
1823                                 NULL, &fsp);
1824
1825         if (!NT_STATUS_IS_OK(status)) {
1826                 return status;
1827         }
1828         close_file(fsp,NORMAL_CLOSE);
1829         return NT_STATUS_OK;
1830 }
1831
1832 /*******************************************************************
1833  * unlink a file with all relevant access checks
1834  *******************************************************************/
1835
1836 static NTSTATUS do_unlink(connection_struct *conn, char *fname,
1837                           uint32 dirtype, BOOL can_defer)
1838 {
1839         SMB_STRUCT_STAT sbuf;
1840         uint32 fattr;
1841         files_struct *fsp;
1842         uint32 dirtype_orig = dirtype;
1843         NTSTATUS status;
1844
1845         DEBUG(10,("do_unlink: %s, dirtype = %d\n", fname, dirtype ));
1846
1847         if (!CAN_WRITE(conn)) {
1848                 return NT_STATUS_MEDIA_WRITE_PROTECTED;
1849         }
1850
1851         if (SMB_VFS_LSTAT(conn,fname,&sbuf) != 0) {
1852                 return map_nt_error_from_unix(errno);
1853         }
1854
1855         fattr = dos_mode(conn,fname,&sbuf);
1856
1857         if (dirtype & FILE_ATTRIBUTE_NORMAL) {
1858                 dirtype = aDIR|aARCH|aRONLY;
1859         }
1860
1861         dirtype &= (aDIR|aARCH|aRONLY|aHIDDEN|aSYSTEM);
1862         if (!dirtype) {
1863                 return NT_STATUS_NO_SUCH_FILE;
1864         }
1865
1866         if (!dir_check_ftype(conn, fattr, dirtype)) {
1867                 if (fattr & aDIR) {
1868                         return NT_STATUS_FILE_IS_A_DIRECTORY;
1869                 }
1870                 return NT_STATUS_NO_SUCH_FILE;
1871         }
1872
1873         if (dirtype_orig & 0x8000) {
1874                 /* These will never be set for POSIX. */
1875                 return NT_STATUS_NO_SUCH_FILE;
1876         }
1877
1878 #if 0
1879         if ((fattr & dirtype) & FILE_ATTRIBUTE_DIRECTORY) {
1880                 return NT_STATUS_FILE_IS_A_DIRECTORY;
1881         }
1882
1883         if ((fattr & ~dirtype) & (FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM)) {
1884                 return NT_STATUS_NO_SUCH_FILE;
1885         }
1886
1887         if (dirtype & 0xFF00) {
1888                 /* These will never be set for POSIX. */
1889                 return NT_STATUS_NO_SUCH_FILE;
1890         }
1891
1892         dirtype &= 0xFF;
1893         if (!dirtype) {
1894                 return NT_STATUS_NO_SUCH_FILE;
1895         }
1896
1897         /* Can't delete a directory. */
1898         if (fattr & aDIR) {
1899                 return NT_STATUS_FILE_IS_A_DIRECTORY;
1900         }
1901 #endif
1902
1903 #if 0 /* JRATEST */
1904         else if (dirtype & aDIR) /* Asked for a directory and it isn't. */
1905                 return NT_STATUS_OBJECT_NAME_INVALID;
1906 #endif /* JRATEST */
1907
1908         /* Fix for bug #3035 from SATOH Fumiyasu <fumiyas@miraclelinux.com>
1909
1910           On a Windows share, a file with read-only dosmode can be opened with
1911           DELETE_ACCESS. But on a Samba share (delete readonly = no), it
1912           fails with NT_STATUS_CANNOT_DELETE error.
1913
1914           This semantic causes a problem that a user can not
1915           rename a file with read-only dosmode on a Samba share
1916           from a Windows command prompt (i.e. cmd.exe, but can rename
1917           from Windows Explorer).
1918         */
1919
1920         if (!lp_delete_readonly(SNUM(conn))) {
1921                 if (fattr & aRONLY) {
1922                         return NT_STATUS_CANNOT_DELETE;
1923                 }
1924         }
1925
1926         /* On open checks the open itself will check the share mode, so
1927            don't do it here as we'll get it wrong. */
1928
1929         status = open_file_ntcreate(conn, fname, &sbuf,
1930                                     DELETE_ACCESS,
1931                                     FILE_SHARE_NONE,
1932                                     FILE_OPEN,
1933                                     0,
1934                                     FILE_ATTRIBUTE_NORMAL,
1935                                     can_defer ? 0 : INTERNAL_OPEN_ONLY,
1936                                     NULL, &fsp);
1937
1938         if (!NT_STATUS_IS_OK(status)) {
1939                 DEBUG(10, ("open_file_ntcreate failed: %s\n",
1940                            nt_errstr(status)));
1941                 return status;
1942         }
1943
1944         /* The set is across all open files on this dev/inode pair. */
1945         if (!set_delete_on_close(fsp, True, &current_user.ut)) {
1946                 close_file(fsp, NORMAL_CLOSE);
1947                 return NT_STATUS_ACCESS_DENIED;
1948         }
1949
1950         return close_file(fsp,NORMAL_CLOSE);
1951 }
1952
1953 /****************************************************************************
1954  The guts of the unlink command, split out so it may be called by the NT SMB
1955  code.
1956 ****************************************************************************/
1957
1958 NTSTATUS unlink_internals(connection_struct *conn, uint32 dirtype,
1959                           char *name, BOOL has_wild, BOOL can_defer)
1960 {
1961         pstring directory;
1962         pstring mask;
1963         char *p;
1964         int count=0;
1965         NTSTATUS status = NT_STATUS_OK;
1966         SMB_STRUCT_STAT sbuf;
1967         
1968         *directory = *mask = 0;
1969         
1970         status = unix_convert(conn, name, has_wild, NULL, &sbuf);
1971         if (!NT_STATUS_IS_OK(status)) {
1972                 return status;
1973         }
1974         
1975         p = strrchr_m(name,'/');
1976         if (!p) {
1977                 pstrcpy(directory,".");
1978                 pstrcpy(mask,name);
1979         } else {
1980                 *p = 0;
1981                 pstrcpy(directory,name);
1982                 pstrcpy(mask,p+1);
1983         }
1984         
1985         /*
1986          * We should only check the mangled cache
1987          * here if unix_convert failed. This means
1988          * that the path in 'mask' doesn't exist
1989          * on the file system and so we need to look
1990          * for a possible mangle. This patch from
1991          * Tine Smukavec <valentin.smukavec@hermes.si>.
1992          */
1993         
1994         if (!VALID_STAT(sbuf) && mangle_is_mangled(mask,conn->params))
1995                 mangle_check_cache( mask, sizeof(pstring)-1, conn->params );
1996         
1997         if (!has_wild) {
1998                 pstrcat(directory,"/");
1999                 pstrcat(directory,mask);
2000                 if (dirtype == 0) {
2001                         dirtype = FILE_ATTRIBUTE_NORMAL;
2002                 }
2003
2004                 status = check_name(conn, directory);
2005                 if (!NT_STATUS_IS_OK(status)) {
2006                         return status;
2007                 }
2008
2009                 status = do_unlink(conn,directory,dirtype,can_defer);
2010                 if (!NT_STATUS_IS_OK(status)) {
2011                         return status;
2012                 }
2013
2014                 count++;
2015         } else {
2016                 struct smb_Dir *dir_hnd = NULL;
2017                 long offset = 0;
2018                 const char *dname;
2019                 
2020                 if ((dirtype & SAMBA_ATTRIBUTES_MASK) == aDIR) {
2021                         return NT_STATUS_OBJECT_NAME_INVALID;
2022                 }
2023
2024                 if (strequal(mask,"????????.???")) {
2025                         pstrcpy(mask,"*");
2026                 }
2027
2028                 status = check_name(conn, directory);
2029                 if (!NT_STATUS_IS_OK(status)) {
2030                         return status;
2031                 }
2032
2033                 dir_hnd = OpenDir(conn, directory, mask, dirtype);
2034                 if (dir_hnd == NULL) {
2035                         return map_nt_error_from_unix(errno);
2036                 }
2037                 
2038                 /* XXXX the CIFS spec says that if bit0 of the flags2 field is set then
2039                    the pattern matches against the long name, otherwise the short name 
2040                    We don't implement this yet XXXX
2041                 */
2042                 
2043                 status = NT_STATUS_NO_SUCH_FILE;
2044
2045                 while ((dname = ReadDirName(dir_hnd, &offset))) {
2046                         SMB_STRUCT_STAT st;
2047                         pstring fname;
2048                         pstrcpy(fname,dname);
2049
2050                         if (!is_visible_file(conn, directory, dname, &st, True)) {
2051                                 continue;
2052                         }
2053
2054                         /* Quick check for "." and ".." */
2055                         if (fname[0] == '.') {
2056                                 if (!fname[1] || (fname[1] == '.' && !fname[2])) {
2057                                         continue;
2058                                 }
2059                         }
2060
2061                         if(!mask_match(fname, mask, conn->case_sensitive)) {
2062                                 continue;
2063                         }
2064                                 
2065                         slprintf(fname,sizeof(fname)-1, "%s/%s",directory,dname);
2066
2067                         status = check_name(conn, fname);
2068                         if (!NT_STATUS_IS_OK(status)) {
2069                                 CloseDir(dir_hnd);
2070                                 return status;
2071                         }
2072
2073                         status = do_unlink(conn, fname, dirtype, can_defer);
2074                         if (!NT_STATUS_IS_OK(status)) {
2075                                 continue;
2076                         }
2077
2078                         count++;
2079                         DEBUG(3,("unlink_internals: succesful unlink [%s]\n",
2080                                  fname));
2081                 }
2082                 CloseDir(dir_hnd);
2083         }
2084         
2085         if (count == 0 && NT_STATUS_IS_OK(status)) {
2086                 status = map_nt_error_from_unix(errno);
2087         }
2088
2089         return status;
2090 }
2091
2092 /****************************************************************************
2093  Reply to a unlink
2094 ****************************************************************************/
2095
2096 int reply_unlink(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, 
2097                  int dum_buffsize)
2098 {
2099         int outsize = 0;
2100         pstring name;
2101         uint32 dirtype;
2102         NTSTATUS status;
2103         BOOL path_contains_wcard = False;
2104
2105         START_PROFILE(SMBunlink);
2106
2107         dirtype = SVAL(inbuf,smb_vwv0);
2108         
2109         srvstr_get_path_wcard(inbuf, name, smb_buf(inbuf) + 1, sizeof(name), 0, STR_TERMINATE, &status, &path_contains_wcard);
2110         if (!NT_STATUS_IS_OK(status)) {
2111                 END_PROFILE(SMBunlink);
2112                 return ERROR_NT(status);
2113         }
2114
2115         status = resolve_dfspath_wcard(conn, SVAL(inbuf,smb_flg2) & FLAGS2_DFS_PATHNAMES, name, &path_contains_wcard);
2116         if (!NT_STATUS_IS_OK(status)) {
2117                 END_PROFILE(SMBunlink);
2118                 if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) {
2119                         return ERROR_BOTH(NT_STATUS_PATH_NOT_COVERED, ERRSRV, ERRbadpath);
2120                 }
2121                 return ERROR_NT(status);
2122         }
2123         
2124         DEBUG(3,("reply_unlink : %s\n",name));
2125         
2126         status = unlink_internals(conn, dirtype, name, path_contains_wcard,
2127                                   True);
2128         if (!NT_STATUS_IS_OK(status)) {
2129                 if (open_was_deferred(SVAL(inbuf,smb_mid))) {
2130                         /* We have re-scheduled this call. */
2131                         return -1;
2132                 }
2133                 return ERROR_NT(status);
2134         }
2135
2136         outsize = set_message(inbuf,outbuf,0,0,False);
2137   
2138         END_PROFILE(SMBunlink);
2139         return outsize;
2140 }
2141
2142 /****************************************************************************
2143  Fail for readbraw.
2144 ****************************************************************************/
2145
2146 static void fail_readraw(void)
2147 {
2148         pstring errstr;
2149         slprintf(errstr, sizeof(errstr)-1, "FAIL ! reply_readbraw: socket write fail (%s)",
2150                 strerror(errno) );
2151         exit_server_cleanly(errstr);
2152 }
2153
2154 /****************************************************************************
2155  Fake (read/write) sendfile. Returns -1 on read or write fail.
2156 ****************************************************************************/
2157
2158 static ssize_t fake_sendfile(files_struct *fsp, SMB_OFF_T startpos, size_t nread, char *buf, size_t bufsize)
2159 {
2160         size_t tosend = nread;
2161
2162         while (tosend > 0) {
2163                 ssize_t ret;
2164                 size_t cur_read;
2165
2166                 if (tosend > bufsize) {
2167                         cur_read = bufsize;
2168                 } else {
2169                         cur_read = tosend;
2170                 }
2171                 ret = read_file(fsp,buf,startpos,cur_read);
2172                 if (ret == -1) {
2173                         return -1;
2174                 }
2175
2176                 /* If we had a short read, fill with zeros. */
2177                 if (ret < cur_read) {
2178                         memset(buf, '\0', cur_read - ret);
2179                 }
2180
2181                 if (write_data(smbd_server_fd(),buf,cur_read) != cur_read) {
2182                         return -1;
2183                 }
2184                 tosend -= cur_read;
2185                 startpos += cur_read;
2186         }
2187
2188         return (ssize_t)nread;
2189 }
2190
2191 /****************************************************************************
2192  Use sendfile in readbraw.
2193 ****************************************************************************/
2194
2195 void send_file_readbraw(connection_struct *conn, files_struct *fsp, SMB_OFF_T startpos, size_t nread,
2196                 ssize_t mincount, char *outbuf, int out_buffsize)
2197 {
2198         ssize_t ret=0;
2199
2200 #if defined(WITH_SENDFILE)
2201         /*
2202          * We can only use sendfile on a non-chained packet 
2203          * but we can use on a non-oplocked file. tridge proved this
2204          * on a train in Germany :-). JRA.
2205          * reply_readbraw has already checked the length.
2206          */
2207
2208         if ( (chain_size == 0) && (nread > 0) &&
2209             (fsp->wcp == NULL) && lp_use_sendfile(SNUM(conn)) ) {
2210                 DATA_BLOB header;
2211
2212                 _smb_setlen(outbuf,nread);
2213                 header.data = (uint8 *)outbuf;
2214                 header.length = 4;
2215                 header.free = NULL;
2216
2217                 if ( SMB_VFS_SENDFILE( smbd_server_fd(), fsp, fsp->fh->fd, &header, startpos, nread) == -1) {
2218                         /* Returning ENOSYS means no data at all was sent. Do this as a normal read. */
2219                         if (errno == ENOSYS) {
2220                                 goto normal_readbraw;
2221                         }
2222
2223                         /*
2224                          * Special hack for broken Linux with no working sendfile. If we
2225                          * return EINTR we sent the header but not the rest of the data.
2226                          * Fake this up by doing read/write calls.
2227                          */
2228                         if (errno == EINTR) {
2229                                 /* Ensure we don't do this again. */
2230                                 set_use_sendfile(SNUM(conn), False);
2231                                 DEBUG(0,("send_file_readbraw: sendfile not available. Faking..\n"));
2232
2233                                 if (fake_sendfile(fsp, startpos, nread, outbuf + 4, out_buffsize - 4) == -1) {
2234                                         DEBUG(0,("send_file_readbraw: fake_sendfile failed for file %s (%s).\n",
2235                                                 fsp->fsp_name, strerror(errno) ));
2236                                         exit_server_cleanly("send_file_readbraw fake_sendfile failed");
2237                                 }
2238                                 return;
2239                         }
2240
2241                         DEBUG(0,("send_file_readbraw: sendfile failed for file %s (%s). Terminating\n",
2242                                 fsp->fsp_name, strerror(errno) ));
2243                         exit_server_cleanly("send_file_readbraw sendfile failed");
2244                 }
2245
2246                 return;
2247         }
2248 #endif
2249
2250 normal_readbraw:
2251
2252         if (nread > 0) {
2253                 ret = read_file(fsp,outbuf+4,startpos,nread);
2254 #if 0 /* mincount appears to be ignored in a W2K server. JRA. */
2255                 if (ret < mincount)
2256                         ret = 0;
2257 #else
2258                 if (ret < nread)
2259                         ret = 0;
2260 #endif
2261         }
2262
2263         _smb_setlen(outbuf,ret);
2264         if (write_data(smbd_server_fd(),outbuf,4+ret) != 4+ret)
2265                 fail_readraw();
2266 }
2267
2268 /****************************************************************************
2269  Reply to a readbraw (core+ protocol).
2270 ****************************************************************************/
2271
2272 int reply_readbraw(connection_struct *conn, char *inbuf, char *outbuf, int dum_size, int out_buffsize)
2273 {
2274         ssize_t maxcount,mincount;
2275         size_t nread = 0;
2276         SMB_OFF_T startpos;
2277         char *header = outbuf;
2278         files_struct *fsp;
2279         START_PROFILE(SMBreadbraw);
2280
2281         if (srv_is_signing_active()) {
2282                 exit_server_cleanly("reply_readbraw: SMB signing is active - raw reads/writes are disallowed.");
2283         }
2284
2285         /*
2286          * Special check if an oplock break has been issued
2287          * and the readraw request croses on the wire, we must
2288          * return a zero length response here.
2289          */
2290
2291         fsp = file_fsp(inbuf,smb_vwv0);
2292
2293         if (!FNUM_OK(fsp,conn) || !fsp->can_read) {
2294                 /*
2295                  * fsp could be NULL here so use the value from the packet. JRA.
2296                  */
2297                 DEBUG(3,("fnum %d not open in readbraw - cache prime?\n",(int)SVAL(inbuf,smb_vwv0)));
2298                 _smb_setlen(header,0);
2299                 if (write_data(smbd_server_fd(),header,4) != 4)
2300                         fail_readraw();
2301                 END_PROFILE(SMBreadbraw);
2302                 return(-1);
2303         }
2304
2305         CHECK_FSP(fsp,conn);
2306
2307         flush_write_cache(fsp, READRAW_FLUSH);
2308
2309         startpos = IVAL_TO_SMB_OFF_T(inbuf,smb_vwv1);
2310         if(CVAL(inbuf,smb_wct) == 10) {
2311                 /*
2312                  * This is a large offset (64 bit) read.
2313                  */
2314 #ifdef LARGE_SMB_OFF_T
2315
2316                 startpos |= (((SMB_OFF_T)IVAL(inbuf,smb_vwv8)) << 32);
2317
2318 #else /* !LARGE_SMB_OFF_T */
2319
2320                 /*
2321                  * Ensure we haven't been sent a >32 bit offset.
2322                  */
2323
2324                 if(IVAL(inbuf,smb_vwv8) != 0) {
2325                         DEBUG(0,("readbraw - large offset (%x << 32) used and we don't support \
2326 64 bit offsets.\n", (unsigned int)IVAL(inbuf,smb_vwv8) ));
2327                         _smb_setlen(header,0);
2328                         if (write_data(smbd_server_fd(),header,4) != 4)
2329                                 fail_readraw();
2330                         END_PROFILE(SMBreadbraw);
2331                         return(-1);
2332                 }
2333
2334 #endif /* LARGE_SMB_OFF_T */
2335
2336                 if(startpos < 0) {
2337                         DEBUG(0,("readbraw - negative 64 bit readraw offset (%.0f) !\n", (double)startpos ));
2338                         _smb_setlen(header,0);
2339                         if (write_data(smbd_server_fd(),header,4) != 4)
2340                                 fail_readraw();
2341                         END_PROFILE(SMBreadbraw);
2342                         return(-1);
2343                 }      
2344         }
2345         maxcount = (SVAL(inbuf,smb_vwv3) & 0xFFFF);
2346         mincount = (SVAL(inbuf,smb_vwv4) & 0xFFFF);
2347
2348         /* ensure we don't overrun the packet size */
2349         maxcount = MIN(65535,maxcount);
2350
2351         if (!is_locked(fsp,(uint32)SVAL(inbuf,smb_pid),(SMB_BIG_UINT)maxcount,(SMB_BIG_UINT)startpos, READ_LOCK)) {
2352                 SMB_STRUCT_STAT st;
2353                 SMB_OFF_T size = 0;
2354   
2355                 if (SMB_VFS_FSTAT(fsp,fsp->fh->fd,&st) == 0) {
2356                         size = st.st_size;
2357                 }
2358
2359                 if (startpos >= size) {
2360                         nread = 0;
2361                 } else {
2362                         nread = MIN(maxcount,(size - startpos));          
2363                 }
2364         }
2365
2366 #if 0 /* mincount appears to be ignored in a W2K server. JRA. */
2367         if (nread < mincount)
2368                 nread = 0;
2369 #endif
2370   
2371         DEBUG( 3, ( "readbraw fnum=%d start=%.0f max=%lu min=%lu nread=%lu\n", fsp->fnum, (double)startpos,
2372                                 (unsigned long)maxcount, (unsigned long)mincount, (unsigned long)nread ) );
2373   
2374         send_file_readbraw(conn, fsp, startpos, nread, mincount, outbuf, out_buffsize);
2375
2376         DEBUG(5,("readbraw finished\n"));
2377         END_PROFILE(SMBreadbraw);
2378         return -1;
2379 }
2380
2381 #undef DBGC_CLASS
2382 #define DBGC_CLASS DBGC_LOCKING
2383
2384 /****************************************************************************
2385  Reply to a lockread (core+ protocol).
2386 ****************************************************************************/
2387
2388 int reply_lockread(connection_struct *conn, char *inbuf,char *outbuf, int length, int dum_buffsiz)
2389 {
2390         ssize_t nread = -1;
2391         char *data;
2392         int outsize = 0;
2393         SMB_OFF_T startpos;
2394         size_t numtoread;
2395         NTSTATUS status;
2396         files_struct *fsp = file_fsp(inbuf,smb_vwv0);
2397         struct byte_range_lock *br_lck = NULL;
2398         START_PROFILE(SMBlockread);
2399
2400         CHECK_FSP(fsp,conn);
2401         if (!CHECK_READ(fsp,inbuf)) {
2402                 return(ERROR_DOS(ERRDOS,ERRbadaccess));
2403         }
2404
2405         release_level_2_oplocks_on_change(fsp);
2406
2407         numtoread = SVAL(inbuf,smb_vwv1);
2408         startpos = IVAL_TO_SMB_OFF_T(inbuf,smb_vwv2);
2409   
2410         outsize = set_message(inbuf,outbuf,5,3,True);
2411         numtoread = MIN(BUFFER_SIZE-outsize,numtoread);
2412         data = smb_buf(outbuf) + 3;
2413         
2414         /*
2415          * NB. Discovered by Menny Hamburger at Mainsoft. This is a core+
2416          * protocol request that predates the read/write lock concept. 
2417          * Thus instead of asking for a read lock here we need to ask
2418          * for a write lock. JRA.
2419          * Note that the requested lock size is unaffected by max_recv.
2420          */
2421         
2422         br_lck = do_lock(smbd_messaging_context(),
2423                         fsp,
2424                         (uint32)SVAL(inbuf,smb_pid), 
2425                         (SMB_BIG_UINT)numtoread,
2426                         (SMB_BIG_UINT)startpos,
2427                         WRITE_LOCK,
2428                         WINDOWS_LOCK,
2429                         False, /* Non-blocking lock. */
2430                         &status,
2431                         NULL);
2432         TALLOC_FREE(br_lck);
2433
2434         if (NT_STATUS_V(status)) {
2435                 END_PROFILE(SMBlockread);
2436                 return ERROR_NT(status);
2437         }
2438
2439         /*
2440          * However the requested READ size IS affected by max_recv. Insanity.... JRA.
2441          */
2442
2443         if (numtoread > max_recv) {
2444                 DEBUG(0,("reply_lockread: requested read size (%u) is greater than maximum allowed (%u). \
2445 Returning short read of maximum allowed for compatibility with Windows 2000.\n",
2446                         (unsigned int)numtoread, (unsigned int)max_recv ));
2447                 numtoread = MIN(numtoread,max_recv);
2448         }
2449         nread = read_file(fsp,data,startpos,numtoread);
2450
2451         if (nread < 0) {
2452                 END_PROFILE(SMBlockread);
2453                 return(UNIXERROR(ERRDOS,ERRnoaccess));
2454         }
2455         
2456         outsize += nread;
2457         SSVAL(outbuf,smb_vwv0,nread);
2458         SSVAL(outbuf,smb_vwv5,nread+3);
2459         SSVAL(smb_buf(outbuf),1,nread);
2460         
2461         DEBUG(3,("lockread fnum=%d num=%d nread=%d\n",
2462                  fsp->fnum, (int)numtoread, (int)nread));
2463
2464         END_PROFILE(SMBlockread);
2465         return(outsize);
2466 }
2467
2468 #undef DBGC_CLASS
2469 #define DBGC_CLASS DBGC_ALL
2470
2471 /****************************************************************************
2472  Reply to a read.
2473 ****************************************************************************/
2474
2475 int reply_read(connection_struct *conn, char *inbuf,char *outbuf, int size, int dum_buffsize)
2476 {
2477         size_t numtoread;
2478         ssize_t nread = 0;
2479         char *data;
2480         SMB_OFF_T startpos;
2481         int outsize = 0;
2482         files_struct *fsp = file_fsp(inbuf,smb_vwv0);
2483         START_PROFILE(SMBread);
2484
2485         CHECK_FSP(fsp,conn);
2486         if (!CHECK_READ(fsp,inbuf)) {
2487                 return(ERROR_DOS(ERRDOS,ERRbadaccess));
2488         }
2489
2490         numtoread = SVAL(inbuf,smb_vwv1);
2491         startpos = IVAL_TO_SMB_OFF_T(inbuf,smb_vwv2);
2492
2493         outsize = set_message(inbuf,outbuf,5,3,True);
2494         numtoread = MIN(BUFFER_SIZE-outsize,numtoread);
2495         /*
2496          * The requested read size cannot be greater than max_recv. JRA.
2497          */
2498         if (numtoread > max_recv) {
2499                 DEBUG(0,("reply_read: requested read size (%u) is greater than maximum allowed (%u). \
2500 Returning short read of maximum allowed for compatibility with Windows 2000.\n",
2501                         (unsigned int)numtoread, (unsigned int)max_recv ));
2502                 numtoread = MIN(numtoread,max_recv);
2503         }
2504
2505         data = smb_buf(outbuf) + 3;
2506   
2507         if (is_locked(fsp,(uint32)SVAL(inbuf,smb_pid),(SMB_BIG_UINT)numtoread,(SMB_BIG_UINT)startpos, READ_LOCK)) {
2508                 END_PROFILE(SMBread);
2509                 return ERROR_DOS(ERRDOS,ERRlock);
2510         }
2511
2512         if (numtoread > 0)
2513                 nread = read_file(fsp,data,startpos,numtoread);
2514
2515         if (nread < 0) {
2516                 END_PROFILE(SMBread);
2517                 return(UNIXERROR(ERRDOS,ERRnoaccess));
2518         }
2519   
2520         outsize += nread;
2521         SSVAL(outbuf,smb_vwv0,nread);
2522         SSVAL(outbuf,smb_vwv5,nread+3);
2523         SCVAL(smb_buf(outbuf),0,1);
2524         SSVAL(smb_buf(outbuf),1,nread);
2525   
2526         DEBUG( 3, ( "read fnum=%d num=%d nread=%d\n",
2527                 fsp->fnum, (int)numtoread, (int)nread ) );
2528
2529         END_PROFILE(SMBread);
2530         return(outsize);
2531 }
2532
2533 /****************************************************************************
2534  Setup readX header.
2535 ****************************************************************************/
2536
2537 static int setup_readX_header(char *inbuf, char *outbuf, size_t smb_maxcnt)
2538 {
2539         int outsize;
2540         char *data = smb_buf(outbuf);
2541
2542         SSVAL(outbuf,smb_vwv2,0xFFFF); /* Remaining - must be -1. */
2543         SSVAL(outbuf,smb_vwv5,smb_maxcnt);
2544         SSVAL(outbuf,smb_vwv6,smb_offset(data,outbuf));
2545         SSVAL(outbuf,smb_vwv7,(smb_maxcnt >> 16));
2546         SSVAL(smb_buf(outbuf),-2,smb_maxcnt);
2547         SCVAL(outbuf,smb_vwv0,0xFF);
2548         outsize = set_message(inbuf, outbuf,12,smb_maxcnt,False);
2549         /* Reset the outgoing length, set_message truncates at 0x1FFFF. */
2550         _smb_setlen_large(outbuf,(smb_size + 12*2 + smb_maxcnt - 4));
2551         return outsize;
2552 }
2553
2554 /****************************************************************************
2555  Reply to a read and X - possibly using sendfile.
2556 ****************************************************************************/
2557
2558 int send_file_readX(connection_struct *conn, char *inbuf,char *outbuf,int length, int len_outbuf,
2559                 files_struct *fsp, SMB_OFF_T startpos, size_t smb_maxcnt)
2560 {
2561         SMB_STRUCT_STAT sbuf;
2562         int outsize = 0;
2563         ssize_t nread = -1;
2564         char *data = smb_buf(outbuf);
2565
2566         if(SMB_VFS_FSTAT(fsp,fsp->fh->fd, &sbuf) == -1) {
2567                 return(UNIXERROR(ERRDOS,ERRnoaccess));
2568         }
2569
2570         if (startpos > sbuf.st_size) {
2571                 smb_maxcnt = 0;
2572         }
2573
2574         if (smb_maxcnt > (sbuf.st_size - startpos)) {
2575                 smb_maxcnt = (sbuf.st_size - startpos);
2576         }
2577
2578         if (smb_maxcnt == 0) {
2579                 goto normal_read;
2580         }
2581
2582 #if defined(WITH_SENDFILE)
2583         /*
2584          * We can only use sendfile on a non-chained packet 
2585          * but we can use on a non-oplocked file. tridge proved this
2586          * on a train in Germany :-). JRA.
2587          */
2588
2589         if ((chain_size == 0) && (CVAL(inbuf,smb_vwv0) == 0xFF) &&
2590             lp_use_sendfile(SNUM(conn)) && (fsp->wcp == NULL) ) {
2591                 DATA_BLOB header;
2592
2593                 /* 
2594                  * Set up the packet header before send. We
2595                  * assume here the sendfile will work (get the
2596                  * correct amount of data).
2597                  */
2598
2599                 setup_readX_header(inbuf,outbuf,smb_maxcnt);
2600                 set_message(inbuf,outbuf,12,smb_maxcnt,False);
2601                 header.data = (uint8 *)outbuf;
2602                 header.length = data - outbuf;
2603                 header.free = NULL;
2604
2605                 if ((nread = SMB_VFS_SENDFILE( smbd_server_fd(), fsp, fsp->fh->fd, &header, startpos, smb_maxcnt)) == -1) {
2606                         /* Returning ENOSYS means no data at all was sent. Do this as a normal read. */
2607                         if (errno == ENOSYS) {
2608                                 goto normal_read;
2609                         }
2610
2611                         /*
2612                          * Special hack for broken Linux with no working sendfile. If we
2613                          * return EINTR we sent the header but not the rest of the data.
2614                          * Fake this up by doing read/write calls.
2615                          */
2616
2617                         if (errno == EINTR) {
2618                                 /* Ensure we don't do this again. */
2619                                 set_use_sendfile(SNUM(conn), False);
2620                                 DEBUG(0,("send_file_readX: sendfile not available. Faking..\n"));
2621
2622                                 if ((nread = fake_sendfile(fsp, startpos, smb_maxcnt, data,
2623                                                         len_outbuf - (data-outbuf))) == -1) {
2624                                         DEBUG(0,("send_file_readX: fake_sendfile failed for file %s (%s).\n",
2625                                                 fsp->fsp_name, strerror(errno) ));
2626                                         exit_server_cleanly("send_file_readX: fake_sendfile failed");
2627                                 }
2628                                 DEBUG( 3, ( "send_file_readX: fake_sendfile fnum=%d max=%d nread=%d\n",
2629                                         fsp->fnum, (int)smb_maxcnt, (int)nread ) );
2630                                 /* Returning -1 here means successful sendfile. */
2631                                 return -1;
2632                         }
2633
2634                         DEBUG(0,("send_file_readX: sendfile failed for file %s (%s). Terminating\n",
2635                                 fsp->fsp_name, strerror(errno) ));
2636                         exit_server_cleanly("send_file_readX sendfile failed");
2637                 }
2638
2639                 DEBUG( 3, ( "send_file_readX: sendfile fnum=%d max=%d nread=%d\n",
2640                         fsp->fnum, (int)smb_maxcnt, (int)nread ) );
2641                 /* Returning -1 here means successful sendfile. */
2642                 return -1;
2643         }
2644
2645 #endif
2646
2647 normal_read:
2648
2649         if ((smb_maxcnt & 0xFF0000) > 0x10000) {
2650                 int sendlen = setup_readX_header(inbuf,outbuf,smb_maxcnt) - smb_maxcnt;
2651                 /* Send out the header. */
2652                 if (write_data(smbd_server_fd(),outbuf,sendlen) != sendlen) {
2653                         DEBUG(0,("send_file_readX: write_data failed for file %s (%s). Terminating\n",
2654                                 fsp->fsp_name, strerror(errno) ));
2655                         exit_server_cleanly("send_file_readX sendfile failed");
2656                 }
2657                 if ((nread = fake_sendfile(fsp, startpos, smb_maxcnt, data,
2658                                         len_outbuf - (data-outbuf))) == -1) {
2659                         DEBUG(0,("send_file_readX: fake_sendfile failed for file %s (%s).\n",
2660                                 fsp->fsp_name, strerror(errno) ));
2661                         exit_server_cleanly("send_file_readX: fake_sendfile failed");
2662                 }
2663                 return -1;
2664         } else {
2665                 nread = read_file(fsp,data,startpos,smb_maxcnt);
2666
2667                 if (nread < 0) {
2668                         return(UNIXERROR(ERRDOS,ERRnoaccess));
2669                 }
2670
2671                 outsize = setup_readX_header(inbuf, outbuf,nread);
2672
2673                 DEBUG( 3, ( "send_file_readX fnum=%d max=%d nread=%d\n",
2674                         fsp->fnum, (int)smb_maxcnt, (int)nread ) );
2675
2676                 /* Returning the number of bytes we want to send back - including header. */
2677                 return outsize;
2678         }
2679 }
2680
2681 /****************************************************************************
2682  Reply to a read and X.
2683 ****************************************************************************/
2684
2685 int reply_read_and_X(connection_struct *conn, char *inbuf,char *outbuf,int length,int bufsize)
2686 {
2687         files_struct *fsp = file_fsp(inbuf,smb_vwv2);
2688         SMB_OFF_T startpos = IVAL_TO_SMB_OFF_T(inbuf,smb_vwv3);
2689         ssize_t nread = -1;
2690         size_t smb_maxcnt = SVAL(inbuf,smb_vwv5);
2691         BOOL big_readX = False;
2692 #if 0
2693         size_t smb_mincnt = SVAL(inbuf,smb_vwv6);
2694 #endif
2695
2696         START_PROFILE(SMBreadX);
2697
2698         /* If it's an IPC, pass off the pipe handler. */
2699         if (IS_IPC(conn)) {
2700                 END_PROFILE(SMBreadX);
2701                 return reply_pipe_read_and_X(inbuf,outbuf,length,bufsize);
2702         }
2703
2704         CHECK_FSP(fsp,conn);
2705         if (!CHECK_READ(fsp,inbuf)) {
2706                 return(ERROR_DOS(ERRDOS,ERRbadaccess));
2707         }
2708
2709         set_message(inbuf,outbuf,12,0,True);
2710
2711         if (global_client_caps & CAP_LARGE_READX) {
2712                 size_t upper_size = SVAL(inbuf,smb_vwv7);
2713                 smb_maxcnt |= (upper_size<<16);
2714                 if (upper_size > 1) {
2715                         /* Can't do this on a chained packet. */
2716                         if ((CVAL(inbuf,smb_vwv0) != 0xFF)) {
2717                                 return ERROR_NT(NT_STATUS_NOT_SUPPORTED);
2718                         }
2719                         /* We currently don't do this on signed or sealed data. */
2720                         if (srv_is_signing_active() || srv_encryption_on()) {
2721                                 return ERROR_NT(NT_STATUS_NOT_SUPPORTED);
2722                         }
2723                         /* Is there room in the reply for this data ? */
2724                         if (smb_maxcnt > (0xFFFFFF - (smb_size -4 + 12*2)))  {
2725                                 return ERROR_NT(NT_STATUS_INVALID_PARAMETER);
2726                         }
2727                         big_readX = True;
2728                 }
2729         }
2730
2731         if(CVAL(inbuf,smb_wct) == 12) {
2732 #ifdef LARGE_SMB_OFF_T
2733                 /*
2734                  * This is a large offset (64 bit) read.
2735                  */
2736                 startpos |= (((SMB_OFF_T)IVAL(inbuf,smb_vwv10)) << 32);
2737
2738 #else /* !LARGE_SMB_OFF_T */
2739
2740                 /*
2741                  * Ensure we haven't been sent a >32 bit offset.
2742                  */
2743
2744                 if(IVAL(inbuf,smb_vwv10) != 0) {
2745                         DEBUG(0,("reply_read_and_X - large offset (%x << 32) used and we don't support \
2746 64 bit offsets.\n", (unsigned int)IVAL(inbuf,smb_vwv10) ));
2747                         END_PROFILE(SMBreadX);
2748                         return ERROR_DOS(ERRDOS,ERRbadaccess);
2749                 }
2750
2751 #endif /* LARGE_SMB_OFF_T */
2752
2753         }
2754
2755         if (is_locked(fsp,(uint32)SVAL(inbuf,smb_pid),(SMB_BIG_UINT)smb_maxcnt,(SMB_BIG_UINT)startpos, READ_LOCK)) {
2756                 END_PROFILE(SMBreadX);
2757                 return ERROR_DOS(ERRDOS,ERRlock);
2758         }
2759
2760         if (!big_readX && schedule_aio_read_and_X(conn, inbuf, outbuf, length, bufsize, fsp, startpos, smb_maxcnt)) {
2761                 END_PROFILE(SMBreadX);
2762                 return -1;
2763         }
2764
2765         nread = send_file_readX(conn, inbuf, outbuf, length, bufsize, fsp, startpos, smb_maxcnt);
2766         /* Only call chain_reply if not an error. */
2767         if (nread != -1 && SVAL(outbuf,smb_rcls) == 0) {
2768                 nread = chain_reply(inbuf,outbuf,length,bufsize);
2769         }
2770
2771         END_PROFILE(SMBreadX);
2772         return nread;
2773 }
2774
2775 /****************************************************************************
2776  Reply to a writebraw (core+ or LANMAN1.0 protocol).
2777 ****************************************************************************/
2778
2779 int reply_writebraw(connection_struct *conn, char *inbuf,char *outbuf, int size, int dum_buffsize)
2780 {
2781         ssize_t nwritten=0;
2782         ssize_t total_written=0;
2783         size_t numtowrite=0;
2784         size_t tcount;
2785         SMB_OFF_T startpos;
2786         char *data=NULL;
2787         BOOL write_through;
2788         files_struct *fsp = file_fsp(inbuf,smb_vwv0);
2789         int outsize = 0;
2790         NTSTATUS status;
2791         START_PROFILE(SMBwritebraw);
2792
2793         if (srv_is_signing_active()) {
2794                 exit_server_cleanly("reply_writebraw: SMB signing is active - raw reads/writes are disallowed.");
2795         }
2796
2797         CHECK_FSP(fsp,conn);
2798         if (!CHECK_WRITE(fsp)) {
2799                 return(ERROR_DOS(ERRDOS,ERRbadaccess));
2800         }
2801   
2802         tcount = IVAL(inbuf,smb_vwv1);
2803         startpos = IVAL_TO_SMB_OFF_T(inbuf,smb_vwv3);
2804         write_through = BITSETW(inbuf+smb_vwv7,0);
2805
2806         /* We have to deal with slightly different formats depending
2807                 on whether we are using the core+ or lanman1.0 protocol */
2808
2809         if(Protocol <= PROTOCOL_COREPLUS) {
2810                 numtowrite = SVAL(smb_buf(inbuf),-2);
2811                 data = smb_buf(inbuf);
2812         } else {
2813                 numtowrite = SVAL(inbuf,smb_vwv10);
2814                 data = smb_base(inbuf) + SVAL(inbuf, smb_vwv11);
2815         }
2816
2817         /* force the error type */
2818         SCVAL(inbuf,smb_com,SMBwritec);
2819         SCVAL(outbuf,smb_com,SMBwritec);
2820
2821         if (is_locked(fsp,(uint32)SVAL(inbuf,smb_pid),(SMB_BIG_UINT)tcount,(SMB_BIG_UINT)startpos, WRITE_LOCK)) {
2822                 END_PROFILE(SMBwritebraw);
2823                 return(ERROR_DOS(ERRDOS,ERRlock));
2824         }
2825
2826         if (numtowrite>0)
2827                 nwritten = write_file(fsp,data,startpos,numtowrite);
2828   
2829         DEBUG(3,("writebraw1 fnum=%d start=%.0f num=%d wrote=%d sync=%d\n",
2830                 fsp->fnum, (double)startpos, (int)numtowrite, (int)nwritten, (int)write_through));
2831
2832         if (nwritten < (ssize_t)numtowrite)  {
2833                 END_PROFILE(SMBwritebraw);
2834                 return(UNIXERROR(ERRHRD,ERRdiskfull));
2835         }
2836
2837         total_written = nwritten;
2838
2839         /* Return a message to the redirector to tell it to send more bytes */
2840         SCVAL(outbuf,smb_com,SMBwritebraw);
2841         SSVALS(outbuf,smb_vwv0,-1);
2842         outsize = set_message(inbuf,outbuf,Protocol>PROTOCOL_COREPLUS?1:0,0,True);
2843         show_msg(outbuf);
2844         if (!send_smb(smbd_server_fd(),outbuf))
2845                 exit_server_cleanly("reply_writebraw: send_smb failed.");
2846   
2847         /* Now read the raw data into the buffer and write it */
2848         if (read_smb_length(smbd_server_fd(),inbuf,SMB_SECONDARY_WAIT) == -1) {
2849                 exit_server_cleanly("secondary writebraw failed");
2850         }
2851   
2852         /* Even though this is not an smb message, smb_len returns the generic length of an smb message */
2853         numtowrite = smb_len(inbuf);
2854
2855         /* Set up outbuf to return the correct return */
2856         outsize = set_message(inbuf,outbuf,1,0,True);
2857         SCVAL(outbuf,smb_com,SMBwritec);
2858
2859         if (numtowrite != 0) {
2860
2861                 if (numtowrite > BUFFER_SIZE) {
2862                         DEBUG(0,("reply_writebraw: Oversize secondary write raw requested (%u). Terminating\n",
2863                                 (unsigned int)numtowrite ));
2864                         exit_server_cleanly("secondary writebraw failed");
2865                 }
2866
2867                 if (tcount > nwritten+numtowrite) {
2868                         DEBUG(3,("Client overestimated the write %d %d %d\n",
2869                                 (int)tcount,(int)nwritten,(int)numtowrite));
2870                 }
2871
2872                 if (read_data( smbd_server_fd(), inbuf+4, numtowrite) != numtowrite ) {
2873                         DEBUG(0,("reply_writebraw: Oversize secondary write raw read failed (%s). Terminating\n",
2874                                 strerror(errno) ));
2875                         exit_server_cleanly("secondary writebraw failed");
2876                 }
2877
2878                 nwritten = write_file(fsp,inbuf+4,startpos+nwritten,numtowrite);
2879                 if (nwritten == -1) {
2880                         END_PROFILE(SMBwritebraw);
2881                         return(UNIXERROR(ERRHRD,ERRdiskfull));
2882                 }
2883
2884                 if (nwritten < (ssize_t)numtowrite) {
2885                         SCVAL(outbuf,smb_rcls,ERRHRD);
2886                         SSVAL(outbuf,smb_err,ERRdiskfull);      
2887                 }
2888
2889                 if (nwritten > 0)
2890                         total_written += nwritten;
2891         }
2892  
2893         SSVAL(outbuf,smb_vwv0,total_written);
2894
2895         status = sync_file(conn, fsp, write_through);
2896         if (!NT_STATUS_IS_OK(status)) {
2897                 DEBUG(5,("reply_writebraw: sync_file for %s returned %s\n",
2898                         fsp->fsp_name, nt_errstr(status) ));
2899                 END_PROFILE(SMBwritebraw);
2900                 return ERROR_NT(status);
2901         }
2902
2903         DEBUG(3,("writebraw2 fnum=%d start=%.0f num=%d wrote=%d\n",
2904                 fsp->fnum, (double)startpos, (int)numtowrite,(int)total_written));
2905
2906         /* we won't return a status if write through is not selected - this follows what WfWg does */
2907         END_PROFILE(SMBwritebraw);
2908         if (!write_through && total_written==tcount) {
2909
2910 #if RABBIT_PELLET_FIX
2911                 /*
2912                  * Fix for "rabbit pellet" mode, trigger an early TCP ack by
2913                  * sending a SMBkeepalive. Thanks to DaveCB at Sun for this. JRA.
2914                  */
2915                 if (!send_keepalive(smbd_server_fd()))
2916                         exit_server_cleanly("reply_writebraw: send of keepalive failed");
2917 #endif
2918                 return(-1);
2919         }
2920
2921         return(outsize);
2922 }
2923
2924 #undef DBGC_CLASS
2925 #define DBGC_CLASS DBGC_LOCKING
2926
2927 /****************************************************************************
2928  Reply to a writeunlock (core+).
2929 ****************************************************************************/
2930
2931 int reply_writeunlock(connection_struct *conn, char *inbuf,char *outbuf, 
2932                       int size, int dum_buffsize)
2933 {
2934         ssize_t nwritten = -1;
2935         size_t numtowrite;
2936         SMB_OFF_T startpos;
2937         char *data;
2938         NTSTATUS status = NT_STATUS_OK;
2939         files_struct *fsp = file_fsp(inbuf,smb_vwv0);
2940         int outsize = 0;
2941         START_PROFILE(SMBwriteunlock);
2942         
2943         CHECK_FSP(fsp,conn);
2944         if (!CHECK_WRITE(fsp)) {
2945                 return(ERROR_DOS(ERRDOS,ERRbadaccess));
2946         }
2947
2948         numtowrite = SVAL(inbuf,smb_vwv1);
2949         startpos = IVAL_TO_SMB_OFF_T(inbuf,smb_vwv2);
2950         data = smb_buf(inbuf) + 3;
2951   
2952         if (numtowrite && is_locked(fsp,(uint32)SVAL(inbuf,smb_pid),(SMB_BIG_UINT)numtowrite,(SMB_BIG_UINT)startpos, WRITE_LOCK)) {
2953                 END_PROFILE(SMBwriteunlock);
2954                 return ERROR_DOS(ERRDOS,ERRlock);
2955         }
2956
2957         /* The special X/Open SMB protocol handling of
2958            zero length writes is *NOT* done for
2959            this call */
2960         if(numtowrite == 0) {
2961                 nwritten = 0;
2962         } else {
2963                 nwritten = write_file(fsp,data,startpos,numtowrite);
2964         }
2965   
2966         status = sync_file(conn, fsp, False /* write through */);
2967         if (!NT_STATUS_IS_OK(status)) {
2968                 END_PROFILE(SMBwriteunlock);
2969                 DEBUG(5,("reply_writeunlock: sync_file for %s returned %s\n",
2970                         fsp->fsp_name, nt_errstr(status) ));
2971                 return ERROR_NT(status);
2972         }
2973
2974         if(((nwritten == 0) && (numtowrite != 0))||(nwritten < 0)) {
2975                 END_PROFILE(SMBwriteunlock);
2976                 return(UNIXERROR(ERRHRD,ERRdiskfull));
2977         }
2978
2979         if (numtowrite) {
2980                 status = do_unlock(smbd_messaging_context(),
2981                                 fsp,
2982                                 (uint32)SVAL(inbuf,smb_pid),
2983                                 (SMB_BIG_UINT)numtowrite, 
2984                                 (SMB_BIG_UINT)startpos,
2985                                 WINDOWS_LOCK);
2986
2987                 if (NT_STATUS_V(status)) {
2988                         END_PROFILE(SMBwriteunlock);
2989                         return ERROR_NT(status);
2990                 }
2991         }
2992         
2993         outsize = set_message(inbuf,outbuf,1,0,True);
2994         
2995         SSVAL(outbuf,smb_vwv0,nwritten);
2996         
2997         DEBUG(3,("writeunlock fnum=%d num=%d wrote=%d\n",
2998                  fsp->fnum, (int)numtowrite, (int)nwritten));
2999         
3000         END_PROFILE(SMBwriteunlock);
3001         return outsize;
3002 }
3003
3004 #undef DBGC_CLASS
3005 #define DBGC_CLASS DBGC_ALL
3006
3007 /****************************************************************************
3008  Reply to a write.
3009 ****************************************************************************/
3010
3011 int reply_write(connection_struct *conn, char *inbuf,char *outbuf,int size,int dum_buffsize)
3012 {
3013         size_t numtowrite;
3014         ssize_t nwritten = -1;
3015         SMB_OFF_T startpos;
3016         char *data;
3017         files_struct *fsp = file_fsp(inbuf,smb_vwv0);
3018         int outsize = 0;
3019         NTSTATUS status;
3020         START_PROFILE(SMBwrite);
3021
3022         /* If it's an IPC, pass off the pipe handler. */
3023         if (IS_IPC(conn)) {
3024                 END_PROFILE(SMBwrite);
3025                 return reply_pipe_write(inbuf,outbuf,size,dum_buffsize);
3026         }
3027
3028         CHECK_FSP(fsp,conn);
3029         if (!CHECK_WRITE(fsp)) {
3030                 END_PROFILE(SMBwrite);
3031                 return(ERROR_DOS(ERRDOS,ERRbadaccess));
3032         }
3033
3034         numtowrite = SVAL(inbuf,smb_vwv1);
3035         startpos = IVAL_TO_SMB_OFF_T(inbuf,smb_vwv2);
3036         data = smb_buf(inbuf) + 3;
3037   
3038         if (is_locked(fsp,(uint32)SVAL(inbuf,smb_pid),(SMB_BIG_UINT)numtowrite,(SMB_BIG_UINT)startpos, WRITE_LOCK)) {
3039                 END_PROFILE(SMBwrite);
3040                 return ERROR_DOS(ERRDOS,ERRlock);
3041         }
3042
3043         /*
3044          * X/Open SMB protocol says that if smb_vwv1 is
3045          * zero then the file size should be extended or
3046          * truncated to the size given in smb_vwv[2-3].
3047          */
3048
3049         if(numtowrite == 0) {
3050                 /*
3051                  * This is actually an allocate call, and set EOF. JRA.
3052                  */
3053                 nwritten = vfs_allocate_file_space(fsp, (SMB_OFF_T)startpos);
3054                 if (nwritten < 0) {
3055                         END_PROFILE(SMBwrite);
3056                         return ERROR_NT(NT_STATUS_DISK_FULL);
3057                 }
3058                 nwritten = vfs_set_filelen(fsp, (SMB_OFF_T)startpos);
3059                 if (nwritten < 0) {
3060                         END_PROFILE(SMBwrite);
3061                         return ERROR_NT(NT_STATUS_DISK_FULL);
3062                 }
3063         } else
3064                 nwritten = write_file(fsp,data,startpos,numtowrite);
3065   
3066         status = sync_file(conn, fsp, False);
3067         if (!NT_STATUS_IS_OK(status)) {
3068                 END_PROFILE(SMBwrite);
3069                 DEBUG(5,("reply_write: sync_file for %s returned %s\n",
3070                         fsp->fsp_name, nt_errstr(status) ));
3071                 return ERROR_NT(status);
3072         }
3073
3074         if(((nwritten == 0) && (numtowrite != 0))||(nwritten < 0)) {
3075                 END_PROFILE(SMBwrite);
3076                 return(UNIXERROR(ERRHRD,ERRdiskfull));
3077         }
3078
3079         outsize = set_message(inbuf,outbuf,1,0,True);
3080   
3081         SSVAL(outbuf,smb_vwv0,nwritten);
3082
3083         if (nwritten < (ssize_t)numtowrite) {
3084                 SCVAL(outbuf,smb_rcls,ERRHRD);
3085                 SSVAL(outbuf,smb_err,ERRdiskfull);      
3086         }
3087   
3088         DEBUG(3,("write fnum=%d num=%d wrote=%d\n", fsp->fnum, (int)numtowrite, (int)nwritten));
3089
3090         END_PROFILE(SMBwrite);
3091         return(outsize);
3092 }
3093
3094 /****************************************************************************
3095  Reply to a write and X.
3096 ****************************************************************************/
3097
3098 int reply_write_and_X(connection_struct *conn, char *inbuf,char *outbuf,int length,int bufsize)
3099 {
3100         files_struct *fsp = file_fsp(inbuf,smb_vwv2);
3101         SMB_OFF_T startpos = IVAL_TO_SMB_OFF_T(inbuf,smb_vwv3);
3102         size_t numtowrite = SVAL(inbuf,smb_vwv10);
3103         BOOL write_through = BITSETW(inbuf+smb_vwv7,0);
3104         ssize_t nwritten = -1;
3105         unsigned int smb_doff = SVAL(inbuf,smb_vwv11);
3106         unsigned int smblen = smb_len(inbuf);
3107         char *data;
3108         BOOL large_writeX = ((CVAL(inbuf,smb_wct) == 14) && (smblen > 0xFFFF));
3109         NTSTATUS status;
3110         START_PROFILE(SMBwriteX);
3111
3112         /* If it's an IPC, pass off the pipe handler. */
3113         if (IS_IPC(conn)) {
3114                 END_PROFILE(SMBwriteX);
3115                 return reply_pipe_write_and_X(inbuf,outbuf,length,bufsize);
3116         }
3117
3118         CHECK_FSP(fsp,conn);
3119         if (!CHECK_WRITE(fsp)) {
3120                 return(ERROR_DOS(ERRDOS,ERRbadaccess));
3121         }
3122
3123         set_message(inbuf,outbuf,6,0,True);
3124   
3125         /* Deal with possible LARGE_WRITEX */
3126         if (large_writeX) {
3127                 numtowrite |= ((((size_t)SVAL(inbuf,smb_vwv9)) & 1 )<<16);
3128         }
3129
3130         if(smb_doff > smblen || (smb_doff + numtowrite > smblen)) {
3131                 END_PROFILE(SMBwriteX);
3132                 return ERROR_DOS(ERRDOS,ERRbadmem);
3133         }
3134
3135         data = smb_base(inbuf) + smb_doff;
3136
3137         if(CVAL(inbuf,smb_wct) == 14) {
3138 #ifdef LARGE_SMB_OFF_T
3139                 /*
3140                  * This is a large offset (64 bit) write.
3141                  */
3142                 startpos |= (((SMB_OFF_T)IVAL(inbuf,smb_vwv12)) << 32);
3143
3144 #else /* !LARGE_SMB_OFF_T */
3145
3146                 /*
3147                  * Ensure we haven't been sent a >32 bit offset.
3148                  */
3149
3150                 if(IVAL(inbuf,smb_vwv12) != 0) {
3151                         DEBUG(0,("reply_write_and_X - large offset (%x << 32) used and we don't support \
3152 64 bit offsets.\n", (unsigned int)IVAL(inbuf,smb_vwv12) ));
3153                         END_PROFILE(SMBwriteX);
3154                         return ERROR_DOS(ERRDOS,ERRbadaccess);
3155                 }
3156
3157 #endif /* LARGE_SMB_OFF_T */
3158         }
3159
3160         if (is_locked(fsp,(uint32)SVAL(inbuf,smb_pid),(SMB_BIG_UINT)numtowrite,(SMB_BIG_UINT)startpos, WRITE_LOCK)) {
3161                 END_PROFILE(SMBwriteX);
3162                 return ERROR_DOS(ERRDOS,ERRlock);
3163         }
3164
3165         /* X/Open SMB protocol says that, unlike SMBwrite
3166         if the length is zero then NO truncation is
3167         done, just a write of zero. To truncate a file,
3168         use SMBwrite. */
3169
3170         if(numtowrite == 0) {
3171                 nwritten = 0;
3172         } else {
3173
3174                 if (schedule_aio_write_and_X(conn, inbuf, outbuf, length, bufsize,
3175                                         fsp,data,startpos,numtowrite)) {
3176                         END_PROFILE(SMBwriteX);
3177                         return -1;
3178                 }
3179
3180                 nwritten = write_file(fsp,data,startpos,numtowrite);
3181         }
3182   
3183         if(((nwritten == 0) && (numtowrite != 0))||(nwritten < 0)) {
3184                 END_PROFILE(SMBwriteX);
3185                 return(UNIXERROR(ERRHRD,ERRdiskfull));
3186         }
3187
3188         SSVAL(outbuf,smb_vwv2,nwritten);
3189         if (large_writeX)
3190                 SSVAL(outbuf,smb_vwv4,(nwritten>>16)&1);
3191
3192         if (nwritten < (ssize_t)numtowrite) {
3193                 SCVAL(outbuf,smb_rcls,ERRHRD);
3194                 SSVAL(outbuf,smb_err,ERRdiskfull);      
3195         }
3196
3197         DEBUG(3,("writeX fnum=%d num=%d wrote=%d\n",
3198                 fsp->fnum, (int)numtowrite, (int)nwritten));
3199
3200         status = sync_file(conn, fsp, write_through);
3201         if (!NT_STATUS_IS_OK(status)) {
3202                 END_PROFILE(SMBwriteX);
3203                 DEBUG(5,("reply_write_and_X: sync_file for %s returned %s\n",
3204                         fsp->fsp_name, nt_errstr(status) ));
3205                 return ERROR_NT(status);
3206         }
3207
3208         END_PROFILE(SMBwriteX);
3209         return chain_reply(inbuf,outbuf,length,bufsize);
3210 }
3211
3212 /****************************************************************************
3213  Reply to a lseek.
3214 ****************************************************************************/
3215
3216 int reply_lseek(connection_struct *conn, char *inbuf,char *outbuf, int size, int dum_buffsize)
3217 {
3218         SMB_OFF_T startpos;
3219         SMB_OFF_T res= -1;
3220         int mode,umode;
3221         int outsize = 0;
3222         files_struct *fsp = file_fsp(inbuf,smb_vwv0);
3223         START_PROFILE(SMBlseek);
3224
3225         CHECK_FSP(fsp,conn);
3226
3227         flush_write_cache(fsp, SEEK_FLUSH);
3228
3229         mode = SVAL(inbuf,smb_vwv1) & 3;
3230         /* NB. This doesn't use IVAL_TO_SMB_OFF_T as startpos can be signed in this case. */
3231         startpos = (SMB_OFF_T)IVALS(inbuf,smb_vwv2);
3232
3233         switch (mode) {
3234                 case 0:
3235                         umode = SEEK_SET;
3236                         res = startpos;
3237                         break;
3238                 case 1:
3239                         umode = SEEK_CUR;
3240                         res = fsp->fh->pos + startpos;
3241                         break;
3242                 case 2:
3243                         umode = SEEK_END;
3244                         break;
3245                 default:
3246                         umode = SEEK_SET;
3247                         res = startpos;
3248                         break;
3249         }
3250
3251         if (umode == SEEK_END) {
3252                 if((res = SMB_VFS_LSEEK(fsp,fsp->fh->fd,startpos,umode)) == -1) {
3253                         if(errno == EINVAL) {
3254                                 SMB_OFF_T current_pos = startpos;
3255                                 SMB_STRUCT_STAT sbuf;
3256
3257                                 if(SMB_VFS_FSTAT(fsp,fsp->fh->fd, &sbuf) == -1) {
3258                                         END_PROFILE(SMBlseek);
3259                                         return(UNIXERROR(ERRDOS,ERRnoaccess));
3260                                 }
3261
3262                                 current_pos += sbuf.st_size;
3263                                 if(current_pos < 0)
3264                                         res = SMB_VFS_LSEEK(fsp,fsp->fh->fd,0,SEEK_SET);
3265                         }
3266                 }
3267
3268                 if(res == -1) {
3269                         END_PROFILE(SMBlseek);
3270                         return(UNIXERROR(ERRDOS,ERRnoaccess));
3271                 }
3272         }
3273
3274         fsp->fh->pos = res;
3275   
3276         outsize = set_message(inbuf,outbuf,2,0,True);
3277         SIVAL(outbuf,smb_vwv0,res);
3278   
3279         DEBUG(3,("lseek fnum=%d ofs=%.0f newpos = %.0f mode=%d\n",
3280                 fsp->fnum, (double)startpos, (double)res, mode));
3281
3282         END_PROFILE(SMBlseek);
3283         return(outsize);
3284 }
3285
3286 /****************************************************************************
3287  Reply to a flush.
3288 ****************************************************************************/
3289
3290 int reply_flush(connection_struct *conn, char *inbuf,char *outbuf, int size, int dum_buffsize)
3291 {
3292         int outsize = set_message(inbuf,outbuf,0,0,False);
3293         uint16 fnum = SVAL(inbuf,smb_vwv0);
3294         files_struct *fsp = file_fsp(inbuf,smb_vwv0);
3295         START_PROFILE(SMBflush);
3296
3297         if (fnum != 0xFFFF)
3298                 CHECK_FSP(fsp,conn);
3299         
3300         if (!fsp) {
3301                 file_sync_all(conn);
3302         } else {
3303                 NTSTATUS status = sync_file(conn, fsp, True);
3304                 if (!NT_STATUS_IS_OK(status)) {
3305                         END_PROFILE(SMBflush);
3306                         DEBUG(5,("reply_flush: sync_file for %s returned %s\n",
3307                                 fsp->fsp_name, nt_errstr(status) ));
3308                         return ERROR_NT(status);
3309                 }
3310         }
3311         
3312         DEBUG(3,("flush\n"));
3313         END_PROFILE(SMBflush);
3314         return(outsize);
3315 }
3316
3317 /****************************************************************************
3318  Reply to a exit.
3319  conn POINTER CAN BE NULL HERE !
3320 ****************************************************************************/
3321
3322 int reply_exit(connection_struct *conn, 
3323                char *inbuf,char *outbuf, int dum_size, int dum_buffsize)
3324 {
3325         int outsize;
3326         START_PROFILE(SMBexit);
3327
3328         file_close_pid(SVAL(inbuf,smb_pid),SVAL(inbuf,smb_uid));
3329
3330         outsize = set_message(inbuf,outbuf,0,0,False);
3331
3332         DEBUG(3,("exit\n"));
3333
3334         END_PROFILE(SMBexit);
3335         return(outsize);
3336 }
3337
3338 /****************************************************************************
3339  Reply to a close - has to deal with closing a directory opened by NT SMB's.
3340 ****************************************************************************/
3341
3342 int reply_close(connection_struct *conn, char *inbuf,char *outbuf, int size,
3343                 int dum_buffsize)
3344 {
3345         NTSTATUS status = NT_STATUS_OK;
3346         int outsize = 0;
3347         files_struct *fsp = NULL;
3348         START_PROFILE(SMBclose);
3349
3350         outsize = set_message(inbuf,outbuf,0,0,False);
3351
3352         /* If it's an IPC, pass off to the pipe handler. */
3353         if (IS_IPC(conn)) {
3354                 END_PROFILE(SMBclose);
3355                 return reply_pipe_close(conn, inbuf,outbuf);
3356         }
3357
3358         fsp = file_fsp(inbuf,smb_vwv0);
3359
3360         /*
3361          * We can only use CHECK_FSP if we know it's not a directory.
3362          */
3363
3364         if(!fsp || (fsp->conn != conn) || (fsp->vuid != current_user.vuid)) {
3365                 END_PROFILE(SMBclose);
3366                 return ERROR_DOS(ERRDOS,ERRbadfid);
3367         }
3368
3369         if(fsp->is_directory) {
3370                 /*
3371                  * Special case - close NT SMB directory handle.
3372                  */
3373                 DEBUG(3,("close directory fnum=%d\n", fsp->fnum));
3374                 status = close_file(fsp,NORMAL_CLOSE);
3375         } else {
3376                 /*
3377                  * Close ordinary file.
3378                  */
3379
3380                 DEBUG(3,("close fd=%d fnum=%d (numopen=%d)\n",
3381                          fsp->fh->fd, fsp->fnum,
3382                          conn->num_files_open));
3383  
3384                 /*
3385                  * Take care of any time sent in the close.
3386                  */
3387
3388                 fsp_set_pending_modtime(fsp,
3389                                 convert_time_t_to_timespec(srv_make_unix_date3(inbuf+smb_vwv1)));
3390
3391                 /*
3392                  * close_file() returns the unix errno if an error
3393                  * was detected on close - normally this is due to
3394                  * a disk full error. If not then it was probably an I/O error.
3395                  */
3396  
3397                 status = close_file(fsp,NORMAL_CLOSE);
3398         }  
3399
3400         if(!NT_STATUS_IS_OK(status)) {
3401                 END_PROFILE(SMBclose);
3402                 return ERROR_NT(status);
3403         }
3404
3405         END_PROFILE(SMBclose);
3406         return(outsize);
3407 }
3408
3409 /****************************************************************************
3410  Reply to a writeclose (Core+ protocol).
3411 ****************************************************************************/
3412
3413 int reply_writeclose(connection_struct *conn,
3414                      char *inbuf,char *outbuf, int size, int dum_buffsize)
3415 {
3416         size_t numtowrite;
3417         ssize_t nwritten = -1;
3418         int outsize = 0;
3419         NTSTATUS close_status = NT_STATUS_OK;
3420         SMB_OFF_T startpos;
3421         char *data;
3422         struct timespec mtime;
3423         files_struct *fsp = file_fsp(inbuf,smb_vwv0);
3424         START_PROFILE(SMBwriteclose);
3425
3426         CHECK_FSP(fsp,conn);
3427         if (!CHECK_WRITE(fsp)) {
3428                 return(ERROR_DOS(ERRDOS,ERRbadaccess));
3429         }
3430
3431         numtowrite = SVAL(inbuf,smb_vwv1);
3432         startpos = IVAL_TO_SMB_OFF_T(inbuf,smb_vwv2);
3433         mtime = convert_time_t_to_timespec(srv_make_unix_date3(inbuf+smb_vwv4));
3434         data = smb_buf(inbuf) + 1;
3435   
3436         if (numtowrite && is_locked(fsp,(uint32)SVAL(inbuf,smb_pid),(SMB_BIG_UINT)numtowrite,(SMB_BIG_UINT)startpos, WRITE_LOCK)) {
3437                 END_PROFILE(SMBwriteclose);
3438                 return ERROR_DOS(ERRDOS,ERRlock);
3439         }
3440   
3441         nwritten = write_file(fsp,data,startpos,numtowrite);
3442
3443         set_filetime(conn, fsp->fsp_name, mtime);
3444   
3445         /*
3446          * More insanity. W2K only closes the file if writelen > 0.
3447          * JRA.
3448          */
3449
3450         if (numtowrite) {
3451                 DEBUG(3,("reply_writeclose: zero length write doesn't close file %s\n",
3452                         fsp->fsp_name ));
3453                 close_status = close_file(fsp,NORMAL_CLOSE);
3454         }
3455
3456         DEBUG(3,("writeclose fnum=%d num=%d wrote=%d (numopen=%d)\n",
3457                  fsp->fnum, (int)numtowrite, (int)nwritten,
3458                  conn->num_files_open));
3459   
3460         if(((nwritten == 0) && (numtowrite != 0))||(nwritten < 0)) {
3461                 END_PROFILE(SMBwriteclose);
3462                 return(UNIXERROR(ERRHRD,ERRdiskfull));
3463         }
3464  
3465         if(!NT_STATUS_IS_OK(close_status)) {
3466                 END_PROFILE(SMBwriteclose);
3467                 return ERROR_NT(close_status);
3468         }
3469  
3470         outsize = set_message(inbuf,outbuf,1,0,True);
3471   
3472         SSVAL(outbuf,smb_vwv0,nwritten);
3473         END_PROFILE(SMBwriteclose);
3474         return(outsize);
3475 }
3476
3477 #undef DBGC_CLASS
3478 #define DBGC_CLASS DBGC_LOCKING
3479
3480 /****************************************************************************
3481  Reply to a lock.
3482 ****************************************************************************/
3483
3484 int reply_lock(connection_struct *conn,
3485                char *inbuf,char *outbuf, int length, int dum_buffsize)
3486 {
3487         int outsize = set_message(inbuf,outbuf,0,0,False);
3488         SMB_BIG_UINT count,offset;
3489         NTSTATUS status;
3490         files_struct *fsp = file_fsp(inbuf,smb_vwv0);
3491         struct byte_range_lock *br_lck = NULL;
3492
3493         START_PROFILE(SMBlock);
3494
3495         CHECK_FSP(fsp,conn);
3496
3497         release_level_2_oplocks_on_change(fsp);
3498
3499         count = (SMB_BIG_UINT)IVAL(inbuf,smb_vwv1);
3500         offset = (SMB_BIG_UINT)IVAL(inbuf,smb_vwv3);
3501
3502         DEBUG(3,("lock fd=%d fnum=%d offset=%.0f count=%.0f\n",
3503                  fsp->fh->fd, fsp->fnum, (double)offset, (double)count));
3504
3505         br_lck = do_lock(smbd_messaging_context(),
3506                         fsp,
3507                         (uint32)SVAL(inbuf,smb_pid),
3508                         count,
3509                         offset,
3510                         WRITE_LOCK,
3511                         WINDOWS_LOCK,
3512                         False, /* Non-blocking lock. */
3513                         &status,
3514                         NULL);
3515
3516         TALLOC_FREE(br_lck);
3517
3518         if (NT_STATUS_V(status)) {
3519                 END_PROFILE(SMBlock);
3520                 return ERROR_NT(status);
3521         }
3522
3523         END_PROFILE(SMBlock);
3524         return(outsize);
3525 }
3526
3527 /****************************************************************************
3528  Reply to a unlock.
3529 ****************************************************************************/
3530
3531 int reply_unlock(connection_struct *conn, char *inbuf,char *outbuf, int size, 
3532                  int dum_buffsize)
3533 {
3534         int outsize = set_message(inbuf,outbuf,0,0,False);
3535         SMB_BIG_UINT count,offset;
3536         NTSTATUS status;
3537         files_struct *fsp = file_fsp(inbuf,smb_vwv0);
3538         START_PROFILE(SMBunlock);
3539
3540         CHECK_FSP(fsp,conn);
3541         
3542         count = (SMB_BIG_UINT)IVAL(inbuf,smb_vwv1);
3543         offset = (SMB_BIG_UINT)IVAL(inbuf,smb_vwv3);
3544         
3545         status = do_unlock(smbd_messaging_context(),
3546                         fsp,
3547                         (uint32)SVAL(inbuf,smb_pid),
3548                         count,
3549                         offset,
3550                         WINDOWS_LOCK);
3551
3552         if (NT_STATUS_V(status)) {
3553                 END_PROFILE(SMBunlock);
3554                 return ERROR_NT(status);
3555         }
3556
3557         DEBUG( 3, ( "unlock fd=%d fnum=%d offset=%.0f count=%.0f\n",
3558                     fsp->fh->fd, fsp->fnum, (double)offset, (double)count ) );
3559         
3560         END_PROFILE(SMBunlock);
3561         return(outsize);
3562 }
3563
3564 #undef DBGC_CLASS
3565 #define DBGC_CLASS DBGC_ALL
3566
3567 /****************************************************************************
3568  Reply to a tdis.
3569  conn POINTER CAN BE NULL HERE !
3570 ****************************************************************************/
3571
3572 int reply_tdis(connection_struct *conn, 
3573                char *inbuf,char *outbuf, int dum_size, int dum_buffsize)
3574 {
3575         int outsize = set_message(inbuf,outbuf,0,0,False);
3576         uint16 vuid;
3577         START_PROFILE(SMBtdis);
3578
3579         vuid = SVAL(inbuf,smb_uid);
3580
3581         if (!conn) {
3582                 DEBUG(4,("Invalid connection in tdis\n"));
3583                 END_PROFILE(SMBtdis);
3584                 return ERROR_DOS(ERRSRV,ERRinvnid);
3585         }
3586
3587         conn->used = False;
3588
3589         close_cnum(conn,vuid);
3590   
3591         END_PROFILE(SMBtdis);
3592         return outsize;
3593 }
3594
3595 /****************************************************************************
3596  Reply to a echo.
3597  conn POINTER CAN BE NULL HERE !
3598 ****************************************************************************/
3599
3600 int reply_echo(connection_struct *conn,
3601                char *inbuf,char *outbuf, int dum_size, int dum_buffsize)
3602 {
3603         int smb_reverb = SVAL(inbuf,smb_vwv0);
3604         int seq_num;
3605         unsigned int data_len = smb_buflen(inbuf);
3606         int outsize = set_message(inbuf,outbuf,1,data_len,True);
3607         START_PROFILE(SMBecho);
3608
3609         if (data_len > BUFFER_SIZE) {
3610                 DEBUG(0,("reply_echo: data_len too large.\n"));
3611                 END_PROFILE(SMBecho);
3612                 return -1;
3613         }
3614
3615         /* copy any incoming data back out */
3616         if (data_len > 0)
3617                 memcpy(smb_buf(outbuf),smb_buf(inbuf),data_len);
3618
3619         if (smb_reverb > 100) {
3620                 DEBUG(0,("large reverb (%d)?? Setting to 100\n",smb_reverb));
3621                 smb_reverb = 100;
3622         }
3623
3624         for (seq_num =1 ; seq_num <= smb_reverb ; seq_num++) {
3625                 SSVAL(outbuf,smb_vwv0,seq_num);
3626
3627                 smb_setlen(inbuf,outbuf,outsize - 4);
3628
3629                 show_msg(outbuf);
3630                 if (!send_smb(smbd_server_fd(),outbuf))
3631                         exit_server_cleanly("reply_echo: send_smb failed.");
3632         }
3633
3634         DEBUG(3,("echo %d times\n", smb_reverb));
3635
3636         smb_echo_count++;
3637
3638         END_PROFILE(SMBecho);
3639         return -1;
3640 }
3641
3642 /****************************************************************************
3643  Reply to a printopen.
3644 ****************************************************************************/
3645
3646 int reply_printopen(connection_struct *conn, 
3647                     char *inbuf,char *outbuf, int dum_size, int dum_buffsize)
3648 {
3649         int outsize = 0;
3650         files_struct *fsp;
3651         NTSTATUS status;
3652         
3653         START_PROFILE(SMBsplopen);
3654         
3655         if (!CAN_PRINT(conn)) {
3656                 END_PROFILE(SMBsplopen);
3657                 return ERROR_DOS(ERRDOS,ERRnoaccess);
3658         }
3659
3660         /* Open for exclusive use, write only. */
3661         status = print_fsp_open(conn, NULL, &fsp);
3662
3663         if (!NT_STATUS_IS_OK(status)) {
3664                 END_PROFILE(SMBsplopen);
3665                 return(ERROR_NT(status));
3666         }
3667
3668         outsize = set_message(inbuf,outbuf,1,0,True);
3669         SSVAL(outbuf,smb_vwv0,fsp->fnum);
3670   
3671         DEBUG(3,("openprint fd=%d fnum=%d\n",
3672                  fsp->fh->fd, fsp->fnum));
3673
3674         END_PROFILE(SMBsplopen);
3675         return(outsize);
3676 }
3677
3678 /****************************************************************************
3679  Reply to a printclose.
3680 ****************************************************************************/
3681
3682 int reply_printclose(connection_struct *conn,
3683                      char *inbuf,char *outbuf, int dum_size, int dum_buffsize)
3684 {
3685         int outsize = set_message(inbuf,outbuf,0,0,False);
3686         files_struct *fsp = file_fsp(inbuf,smb_vwv0);
3687         NTSTATUS status;
3688         START_PROFILE(SMBsplclose);
3689
3690         CHECK_FSP(fsp,conn);
3691
3692         if (!CAN_PRINT(conn)) {
3693                 END_PROFILE(SMBsplclose);
3694                 return ERROR_NT(NT_STATUS_DOS(ERRSRV, ERRerror));
3695         }
3696   
3697         DEBUG(3,("printclose fd=%d fnum=%d\n",
3698                  fsp->fh->fd,fsp->fnum));
3699   
3700         status = close_file(fsp,NORMAL_CLOSE);
3701
3702         if(!NT_STATUS_IS_OK(status)) {
3703                 END_PROFILE(SMBsplclose);
3704                 return ERROR_NT(status);
3705         }
3706
3707         END_PROFILE(SMBsplclose);
3708         return(outsize);
3709 }
3710
3711 /****************************************************************************
3712  Reply to a printqueue.
3713 ****************************************************************************/
3714
3715 int reply_printqueue(connection_struct *conn,
3716                      char *inbuf,char *outbuf, int dum_size, int dum_buffsize)
3717 {
3718         int outsize = set_message(inbuf,outbuf,2,3,True);
3719         int max_count = SVAL(inbuf,smb_vwv0);
3720         int start_index = SVAL(inbuf,smb_vwv1);
3721         START_PROFILE(SMBsplretq);
3722
3723         /* we used to allow the client to get the cnum wrong, but that
3724            is really quite gross and only worked when there was only
3725            one printer - I think we should now only accept it if they
3726            get it right (tridge) */
3727         if (!CAN_PRINT(conn)) {
3728                 END_PROFILE(SMBsplretq);
3729                 return ERROR_DOS(ERRDOS,ERRnoaccess);
3730         }
3731
3732         SSVAL(outbuf,smb_vwv0,0);
3733         SSVAL(outbuf,smb_vwv1,0);
3734         SCVAL(smb_buf(outbuf),0,1);
3735         SSVAL(smb_buf(outbuf),1,0);
3736   
3737         DEBUG(3,("printqueue start_index=%d max_count=%d\n",
3738                  start_index, max_count));
3739
3740         {
3741                 print_queue_struct *queue = NULL;
3742                 print_status_struct status;
3743                 char *p = smb_buf(outbuf) + 3;
3744                 int count = print_queue_status(SNUM(conn), &queue, &status);
3745                 int num_to_get = ABS(max_count);
3746                 int first = (max_count>0?start_index:start_index+max_count+1);
3747                 int i;
3748
3749                 if (first >= count)
3750                         num_to_get = 0;
3751                 else
3752                         num_to_get = MIN(num_to_get,count-first);
3753     
3754
3755                 for (i=first;i<first+num_to_get;i++) {
3756                         srv_put_dos_date2(p,0,queue[i].time);
3757                         SCVAL(p,4,(queue[i].status==LPQ_PRINTING?2:3));
3758                         SSVAL(p,5, queue[i].job);
3759                         SIVAL(p,7,queue[i].size);
3760                         SCVAL(p,11,0);
3761                         srvstr_push(outbuf, p+12, queue[i].fs_user, 16, STR_ASCII);
3762                         p += 28;
3763                 }
3764
3765                 if (count > 0) {
3766                         outsize = set_message(inbuf,outbuf,2,28*count+3,False); 
3767                         SSVAL(outbuf,smb_vwv0,count);
3768                         SSVAL(outbuf,smb_vwv1,(max_count>0?first+count:first-1));
3769                         SCVAL(smb_buf(outbuf),0,1);
3770                         SSVAL(smb_buf(outbuf),1,28*count);
3771                 }
3772
3773                 SAFE_FREE(queue);
3774           
3775                 DEBUG(3,("%d entries returned in queue\n",count));
3776         }
3777   
3778         END_PROFILE(SMBsplretq);
3779         return(outsize);
3780 }
3781
3782 /****************************************************************************
3783  Reply to a printwrite.
3784 ****************************************************************************/
3785
3786 int reply_printwrite(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize)
3787 {
3788         int numtowrite;
3789         int outsize = set_message(inbuf,outbuf,0,0,False);
3790         char *data;
3791         files_struct *fsp = file_fsp(inbuf,smb_vwv0);
3792
3793         START_PROFILE(SMBsplwr);
3794   
3795         if (!CAN_PRINT(conn)) {
3796                 END_PROFILE(SMBsplwr);
3797                 return ERROR_DOS(ERRDOS,ERRnoaccess);
3798         }
3799
3800         CHECK_FSP(fsp,conn);
3801         if (!CHECK_WRITE(fsp)) {
3802                 return(ERROR_DOS(ERRDOS,ERRbadaccess));
3803         }
3804
3805         numtowrite = SVAL(smb_buf(inbuf),1);
3806         data = smb_buf(inbuf) + 3;
3807   
3808         if (write_file(fsp,data,-1,numtowrite) != numtowrite) {
3809                 END_PROFILE(SMBsplwr);
3810                 return(UNIXERROR(ERRHRD,ERRdiskfull));
3811         }
3812
3813         DEBUG( 3, ( "printwrite fnum=%d num=%d\n", fsp->fnum, numtowrite ) );
3814   
3815         END_PROFILE(SMBsplwr);
3816         return(outsize);
3817 }
3818
3819 /****************************************************************************
3820  Reply to a mkdir.
3821 ****************************************************************************/
3822
3823 int reply_mkdir(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize)
3824 {
3825         pstring directory;
3826         int outsize;
3827         NTSTATUS status;
3828         SMB_STRUCT_STAT sbuf;
3829
3830         START_PROFILE(SMBmkdir);
3831  
3832         srvstr_get_path(inbuf, directory, smb_buf(inbuf) + 1, sizeof(directory), 0, STR_TERMINATE, &status);
3833         if (!NT_STATUS_IS_OK(status)) {
3834                 END_PROFILE(SMBmkdir);
3835                 return ERROR_NT(status);
3836         }
3837
3838         status = resolve_dfspath(conn, SVAL(inbuf,smb_flg2) & FLAGS2_DFS_PATHNAMES, directory);
3839         if (!NT_STATUS_IS_OK(status)) {
3840                 END_PROFILE(SMBmkdir);
3841                 if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) {
3842                         return ERROR_BOTH(NT_STATUS_PATH_NOT_COVERED, ERRSRV, ERRbadpath);
3843                 }
3844                 return ERROR_NT(status);
3845         }
3846
3847         status = unix_convert(conn, directory, False, NULL, &sbuf);
3848         if (!NT_STATUS_IS_OK(status)) {
3849                 END_PROFILE(SMBmkdir);
3850                 return ERROR_NT(status);
3851         }
3852
3853         status = check_name(conn, directory);
3854         if (!NT_STATUS_IS_OK(status)) {
3855                 END_PROFILE(SMBmkdir);
3856                 return ERROR_NT(status);
3857         }
3858   
3859         status = create_directory(conn, directory);
3860
3861         DEBUG(5, ("create_directory returned %s\n", nt_errstr(status)));
3862
3863         if (!NT_STATUS_IS_OK(status)) {
3864
3865                 if (!use_nt_status()
3866                     && NT_STATUS_EQUAL(status,
3867                                        NT_STATUS_OBJECT_NAME_COLLISION)) {
3868                         /*
3869                          * Yes, in the DOS error code case we get a
3870                          * ERRDOS:ERRnoaccess here. See BASE-SAMBA3ERROR
3871                          * samba4 torture test.
3872                          */
3873                         status = NT_STATUS_DOS(ERRDOS, ERRnoaccess);
3874                 }
3875
3876                 END_PROFILE(SMBmkdir);
3877                 return ERROR_NT(status);
3878         }
3879
3880         outsize = set_message(inbuf,outbuf,0,0,False);
3881
3882         DEBUG( 3, ( "mkdir %s ret=%d\n", directory, outsize ) );
3883
3884         END_PROFILE(SMBmkdir);
3885         return(outsize);
3886 }
3887
3888 /****************************************************************************
3889  Static function used by reply_rmdir to delete an entire directory
3890  tree recursively. Return True on ok, False on fail.
3891 ****************************************************************************/
3892
3893 static BOOL recursive_rmdir(connection_struct *conn, char *directory)
3894 {
3895         const char *dname = NULL;
3896         BOOL ret = True;
3897         long offset = 0;
3898         struct smb_Dir *dir_hnd = OpenDir(conn, directory, NULL, 0);
3899
3900         if(dir_hnd == NULL)
3901                 return False;
3902
3903         while((dname = ReadDirName(dir_hnd, &offset))) {
3904                 pstring fullname;
3905                 SMB_STRUCT_STAT st;
3906
3907                 if((strcmp(dname, ".") == 0) || (strcmp(dname, "..")==0))
3908                         continue;
3909
3910                 if (!is_visible_file(conn, directory, dname, &st, False))
3911                         continue;
3912
3913                 /* Construct the full name. */
3914                 if(strlen(directory) + strlen(dname) + 1 >= sizeof(fullname)) {
3915                         errno = ENOMEM;
3916                         ret = False;
3917                         break;
3918                 }
3919
3920                 pstrcpy(fullname, directory);
3921                 pstrcat(fullname, "/");
3922                 pstrcat(fullname, dname);
3923
3924                 if(SMB_VFS_LSTAT(conn,fullname, &st) != 0) {
3925                         ret = False;
3926                         break;
3927                 }
3928
3929                 if(st.st_mode & S_IFDIR) {
3930                         if(!recursive_rmdir(conn, fullname)) {
3931                                 ret = False;
3932                                 break;
3933                         }
3934                         if(SMB_VFS_RMDIR(conn,fullname) != 0) {
3935                                 ret = False;
3936                                 break;
3937                         }
3938                 } else if(SMB_VFS_UNLINK(conn,fullname) != 0) {
3939                         ret = False;
3940                         break;
3941                 }
3942         }
3943         CloseDir(dir_hnd);
3944         return ret;
3945 }
3946
3947 /****************************************************************************
3948  The internals of the rmdir code - called elsewhere.
3949 ****************************************************************************/
3950
3951 NTSTATUS rmdir_internals(connection_struct *conn, const char *directory)
3952 {
3953         int ret;
3954         SMB_STRUCT_STAT st;
3955
3956         /* Might be a symlink. */
3957         if(SMB_VFS_LSTAT(conn, directory, &st) != 0) {
3958                 return map_nt_error_from_unix(errno);
3959         }
3960
3961         if (S_ISLNK(st.st_mode)) {
3962                 /* Is what it points to a directory ? */
3963                 if(SMB_VFS_STAT(conn, directory, &st) != 0) {
3964                         return map_nt_error_from_unix(errno);
3965                 }
3966                 if (!(S_ISDIR(st.st_mode))) {
3967                         return NT_STATUS_NOT_A_DIRECTORY;
3968                 }
3969                 ret = SMB_VFS_UNLINK(conn,directory);
3970         } else {
3971                 ret = SMB_VFS_RMDIR(conn,directory);
3972         }
3973         if (ret == 0) {
3974                 notify_fname(conn, NOTIFY_ACTION_REMOVED,
3975                              FILE_NOTIFY_CHANGE_DIR_NAME,
3976                              directory);
3977                 return NT_STATUS_OK;
3978         }
3979
3980         if(((errno == ENOTEMPTY)||(errno == EEXIST)) && lp_veto_files(SNUM(conn))) {
3981                 /* 
3982                  * Check to see if the only thing in this directory are
3983                  * vetoed files/directories. If so then delete them and
3984                  * retry. If we fail to delete any of them (and we *don't*
3985                  * do a recursive delete) then fail the rmdir.
3986                  */
3987                 const char *dname;
3988                 long dirpos = 0;
3989                 struct smb_Dir *dir_hnd = OpenDir(conn, directory, NULL, 0);
3990
3991                 if(dir_hnd == NULL) {
3992                         errno = ENOTEMPTY;
3993                         goto err;
3994                 }
3995
3996                 while ((dname = ReadDirName(dir_hnd,&dirpos))) {
3997                         if((strcmp(dname, ".") == 0) || (strcmp(dname, "..")==0))
3998                                 continue;
3999                         if (!is_visible_file(conn, directory, dname, &st, False))
4000                                 continue;
4001                         if(!IS_VETO_PATH(conn, dname)) {
4002                                 CloseDir(dir_hnd);
4003                                 errno = ENOTEMPTY;
4004                                 goto err;
4005                         }
4006                 }
4007
4008                 /* We only have veto files/directories. Recursive delete. */
4009
4010                 RewindDir(dir_hnd,&dirpos);
4011                 while ((dname = ReadDirName(dir_hnd,&dirpos))) {
4012                         pstring fullname;
4013
4014                         if((strcmp(dname, ".") == 0) || (strcmp(dname, "..")==0))
4015                                 continue;
4016                         if (!is_visible_file(conn, directory, dname, &st, False))
4017                                 continue;
4018
4019                         /* Construct the full name. */
4020                         if(strlen(directory) + strlen(dname) + 1 >= sizeof(fullname)) {
4021                                 errno = ENOMEM;
4022                                 break;
4023                         }
4024
4025                         pstrcpy(fullname, directory);
4026                         pstrcat(fullname, "/");
4027                         pstrcat(fullname, dname);
4028                    
4029                         if(SMB_VFS_LSTAT(conn,fullname, &st) != 0)
4030                                 break;
4031                         if(st.st_mode & S_IFDIR) {
4032                                 if(lp_recursive_veto_delete(SNUM(conn))) {
4033                                         if(!recursive_rmdir(conn, fullname))
4034                                                 break;
4035                                 }
4036                                 if(SMB_VFS_RMDIR(conn,fullname) != 0)
4037                                         break;
4038                         } else if(SMB_VFS_UNLINK(conn,fullname) != 0)
4039                                 break;
4040                 }
4041                 CloseDir(dir_hnd);
4042                 /* Retry the rmdir */
4043                 ret = SMB_VFS_RMDIR(conn,directory);
4044         }
4045
4046   err:
4047
4048         if (ret != 0) {
4049                 DEBUG(3,("rmdir_internals: couldn't remove directory %s : "
4050                          "%s\n", directory,strerror(errno)));
4051                 return map_nt_error_from_unix(errno);
4052         }
4053
4054         notify_fname(conn, NOTIFY_ACTION_REMOVED,
4055                      FILE_NOTIFY_CHANGE_DIR_NAME,
4056                      directory);
4057
4058         return NT_STATUS_OK;
4059 }
4060
4061 /****************************************************************************
4062  Reply to a rmdir.
4063 ****************************************************************************/
4064
4065 int reply_rmdir(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize)
4066 {
4067         pstring directory;
4068         int outsize = 0;
4069         SMB_STRUCT_STAT sbuf;
4070         NTSTATUS status;
4071         START_PROFILE(SMBrmdir);
4072
4073         srvstr_get_path(inbuf, directory, smb_buf(inbuf) + 1, sizeof(directory), 0, STR_TERMINATE, &status);
4074         if (!NT_STATUS_IS_OK(status)) {
4075                 END_PROFILE(SMBrmdir);
4076                 return ERROR_NT(status);
4077         }
4078
4079         status = resolve_dfspath(conn, SVAL(inbuf,smb_flg2) & FLAGS2_DFS_PATHNAMES, directory);
4080         if (!NT_STATUS_IS_OK(status)) {
4081                 END_PROFILE(SMBrmdir);
4082                 if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) {
4083                         return ERROR_BOTH(NT_STATUS_PATH_NOT_COVERED, ERRSRV, ERRbadpath);
4084                 }
4085                 return ERROR_NT(status);
4086         }
4087
4088         status = unix_convert(conn, directory, False, NULL, &sbuf);
4089         if (!NT_STATUS_IS_OK(status)) {
4090                 END_PROFILE(SMBrmdir);
4091                 return ERROR_NT(status);
4092         }
4093   
4094         status = check_name(conn, directory);
4095         if (!NT_STATUS_IS_OK(status)) {
4096                 END_PROFILE(SMBrmdir);
4097                 return ERROR_NT(status);
4098         }
4099
4100         dptr_closepath(directory,SVAL(inbuf,smb_pid));
4101         status = rmdir_internals(conn, directory);
4102         if (!NT_STATUS_IS_OK(status)) {
4103                 END_PROFILE(SMBrmdir);
4104                 return ERROR_NT(status);
4105         }
4106  
4107         outsize = set_message(inbuf,outbuf,0,0,False);
4108   
4109         DEBUG( 3, ( "rmdir %s\n", directory ) );
4110   
4111         END_PROFILE(SMBrmdir);
4112         return(outsize);
4113 }
4114
4115 /*******************************************************************
4116  Resolve wildcards in a filename rename.
4117  Note that name is in UNIX charset and thus potentially can be more
4118  than fstring buffer (255 bytes) especially in default UTF-8 case.
4119  Therefore, we use pstring inside and all calls should ensure that
4120  name2 is at least pstring-long (they do already)
4121 ********************************************************************/
4122
4123 static BOOL resolve_wildcards(const char *name1, char *name2)
4124 {
4125         pstring root1,root2;
4126         pstring ext1,ext2;
4127         char *p,*p2, *pname1, *pname2;
4128         int available_space, actual_space;
4129         
4130         pname1 = strrchr_m(name1,'/');
4131         pname2 = strrchr_m(name2,'/');
4132
4133         if (!pname1 || !pname2)
4134                 return(False);
4135   
4136         pstrcpy(root1,pname1);
4137         pstrcpy(root2,pname2);
4138         p = strrchr_m(root1,'.');
4139         if (p) {
4140                 *p = 0;
4141                 pstrcpy(ext1,p+1);
4142         } else {
4143                 pstrcpy(ext1,"");    
4144         }
4145         p = strrchr_m(root2,'.');
4146         if (p) {
4147                 *p = 0;
4148                 pstrcpy(ext2,p+1);
4149         } else {
4150                 pstrcpy(ext2,"");    
4151         }
4152
4153         p = root1;
4154         p2 = root2;
4155         while (*p2) {
4156                 if (*p2 == '?') {
4157                         *p2 = *p;
4158                         p2++;
4159                 } else if (*p2 == '*') {
4160                         pstrcpy(p2, p);
4161                         break;
4162                 } else {
4163                         p2++;
4164                 }
4165                 if (*p)
4166                         p++;
4167         }
4168
4169         p = ext1;
4170         p2 = ext2;
4171         while (*p2) {
4172                 if (*p2 == '?') {
4173                         *p2 = *p;
4174                         p2++;
4175                 } else if (*p2 == '*') {
4176                         pstrcpy(p2, p);
4177                         break;
4178                 } else {
4179                         p2++;
4180                 }
4181                 if (*p)
4182                         p++;
4183         }
4184
4185         available_space = sizeof(pstring) - PTR_DIFF(pname2, name2);
4186         
4187         if (ext2[0]) {
4188                 actual_space = snprintf(pname2, available_space - 1, "%s.%s", root2, ext2);
4189                 if (actual_space >= available_space - 1) {
4190                         DEBUG(1,("resolve_wildcards: can't fit resolved name into specified buffer (overrun by %d bytes)\n",
4191                                 actual_space - available_space));
4192                 }
4193         } else {
4194                 pstrcpy_base(pname2, root2, name2);
4195         }
4196
4197         return(True);
4198 }
4199
4200 /****************************************************************************
4201  Ensure open files have their names updated. Updated to notify other smbd's
4202  asynchronously.
4203 ****************************************************************************/
4204
4205 static void rename_open_files(connection_struct *conn,
4206                               struct share_mode_lock *lck,
4207                               const char *newname)
4208 {
4209         files_struct *fsp;
4210         BOOL did_rename = False;
4211
4212         for(fsp = file_find_di_first(lck->id); fsp;
4213             fsp = file_find_di_next(fsp)) {
4214                 /* fsp_name is a relative path under the fsp. To change this for other
4215                    sharepaths we need to manipulate relative paths. */
4216                 /* TODO - create the absolute path and manipulate the newname
4217                    relative to the sharepath. */
4218                 if (fsp->conn != conn) {
4219                         continue;
4220                 }
4221                 DEBUG(10,("rename_open_files: renaming file fnum %d (file_id %s) from %s -> %s\n",
4222                           fsp->fnum, file_id_static_string(&fsp->file_id),
4223                         fsp->fsp_name, newname ));
4224                 string_set(&fsp->fsp_name, newname);
4225                 did_rename = True;
4226         }
4227
4228         if (!did_rename) {
4229                 DEBUG(10,("rename_open_files: no open files on file_id %s for %s\n",
4230                           file_id_static_string(&lck->id), newname ));
4231         }
4232
4233         /* Send messages to all smbd's (not ourself) that the name has changed. */
4234         rename_share_filename(smbd_messaging_context(), lck, conn->connectpath,
4235                               newname);
4236 }
4237
4238 /****************************************************************************
4239  We need to check if the source path is a parent directory of the destination
4240  (ie. a rename of /foo/bar/baz -> /foo/bar/baz/bibble/bobble. If so we must
4241  refuse the rename with a sharing violation. Under UNIX the above call can
4242  *succeed* if /foo/bar/baz is a symlink to another area in the share. We
4243  probably need to check that the client is a Windows one before disallowing
4244  this as a UNIX client (one with UNIX extensions) can know the source is a
4245  symlink and make this decision intelligently. Found by an excellent bug
4246  report from <AndyLiebman@aol.com>.
4247 ****************************************************************************/
4248
4249 static BOOL rename_path_prefix_equal(const char *src, const char *dest)
4250 {
4251         const char *psrc = src;
4252         const char *pdst = dest;
4253         size_t slen;
4254
4255         if (psrc[0] == '.' && psrc[1] == '/') {
4256                 psrc += 2;
4257         }
4258         if (pdst[0] == '.' && pdst[1] == '/') {
4259                 pdst += 2;
4260         }
4261         if ((slen = strlen(psrc)) > strlen(pdst)) {
4262                 return False;
4263         }
4264         return ((memcmp(psrc, pdst, slen) == 0) && pdst[slen] == '/');
4265 }
4266
4267 /*
4268  * Do the notify calls from a rename
4269  */
4270
4271 static void notify_rename(connection_struct *conn, BOOL is_dir,
4272                           const char *oldpath, const char *newpath)
4273 {
4274         char *olddir, *newdir;
4275         const char *oldname, *newname;
4276         uint32 mask;
4277
4278         mask = is_dir ? FILE_NOTIFY_CHANGE_DIR_NAME
4279                 : FILE_NOTIFY_CHANGE_FILE_NAME;
4280
4281         if (!parent_dirname_talloc(NULL, oldpath, &olddir, &oldname)
4282             || !parent_dirname_talloc(NULL, newpath, &newdir, &newname)) {
4283                 TALLOC_FREE(olddir);
4284                 return;
4285         }
4286
4287         if (strcmp(olddir, newdir) == 0) {
4288                 notify_fname(conn, NOTIFY_ACTION_OLD_NAME, mask, oldpath);
4289                 notify_fname(conn, NOTIFY_ACTION_NEW_NAME, mask, newpath);
4290         }
4291         else {
4292                 notify_fname(conn, NOTIFY_ACTION_REMOVED, mask, oldpath);
4293                 notify_fname(conn, NOTIFY_ACTION_ADDED, mask, newpath);
4294         }
4295         TALLOC_FREE(olddir);
4296         TALLOC_FREE(newdir);
4297
4298         /* this is a strange one. w2k3 gives an additional event for
4299            CHANGE_ATTRIBUTES and CHANGE_CREATION on the new file when renaming
4300            files, but not directories */
4301         if (!is_dir) {
4302                 notify_fname(conn, NOTIFY_ACTION_MODIFIED,
4303                              FILE_NOTIFY_CHANGE_ATTRIBUTES
4304                              |FILE_NOTIFY_CHANGE_CREATION,
4305                              newpath);
4306         }
4307 }
4308
4309 /****************************************************************************
4310  Rename an open file - given an fsp.
4311 ****************************************************************************/
4312
4313 NTSTATUS rename_internals_fsp(connection_struct *conn, files_struct *fsp, pstring newname, uint32 attrs, BOOL replace_if_exists)
4314 {
4315         SMB_STRUCT_STAT sbuf, sbuf1;
4316         pstring newname_last_component;
4317         NTSTATUS status = NT_STATUS_OK;
4318         struct share_mode_lock *lck = NULL;
4319         BOOL dst_exists;
4320
4321         ZERO_STRUCT(sbuf);
4322
4323         status = unix_convert(conn, newname, False, newname_last_component, &sbuf);
4324
4325         /* If an error we expect this to be NT_STATUS_OBJECT_PATH_NOT_FOUND */
4326
4327         if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(NT_STATUS_OBJECT_PATH_NOT_FOUND, status)) {
4328                 return status;
4329         }
4330
4331         status = check_name(conn, newname);
4332         if (!NT_STATUS_IS_OK(status)) {
4333                 return status;
4334         }
4335   
4336         /* Ensure newname contains a '/' */
4337         if(strrchr_m(newname,'/') == 0) {
4338                 pstring tmpstr;
4339                 
4340                 pstrcpy(tmpstr, "./");
4341                 pstrcat(tmpstr, newname);
4342                 pstrcpy(newname, tmpstr);
4343         }
4344
4345         /*
4346          * Check for special case with case preserving and not
4347          * case sensitive. If the old last component differs from the original
4348          * last component only by case, then we should allow
4349          * the rename (user is trying to change the case of the
4350          * filename).
4351          */
4352
4353         if((conn->case_sensitive == False) && (conn->case_preserve == True) &&
4354                         strequal(newname, fsp->fsp_name)) {
4355                 char *p;
4356                 pstring newname_modified_last_component;
4357
4358                 /*
4359                  * Get the last component of the modified name.
4360                  * Note that we guarantee that newname contains a '/'
4361                  * character above.
4362                  */
4363                 p = strrchr_m(newname,'/');
4364                 pstrcpy(newname_modified_last_component,p+1);
4365                         
4366                 if(strcsequal(newname_modified_last_component, 
4367                               newname_last_component) == False) {
4368                         /*
4369                          * Replace the modified last component with
4370                          * the original.
4371                          */
4372                         pstrcpy(p+1, newname_last_component);
4373                 }
4374         }
4375
4376         /*
4377          * If the src and dest names are identical - including case,
4378          * don't do the rename, just return success.
4379          */
4380
4381         if (strcsequal(fsp->fsp_name, newname)) {
4382                 DEBUG(3,("rename_internals_fsp: identical names in rename %s - returning success\n",
4383                         newname));
4384                 return NT_STATUS_OK;
4385         }
4386
4387         /*
4388          * Have vfs_object_exist also fill sbuf1
4389          */
4390         dst_exists = vfs_object_exist(conn, newname, &sbuf1);
4391
4392         if(!replace_if_exists && dst_exists) {
4393                 DEBUG(3,("rename_internals_fsp: dest exists doing rename %s -> %s\n",
4394                         fsp->fsp_name,newname));
4395                 return NT_STATUS_OBJECT_NAME_COLLISION;
4396         }
4397
4398         if (file_find_di_first(file_id_sbuf(&sbuf1)) != NULL) {
4399                 DEBUG(3, ("rename_internals_fsp: Target file open\n"));
4400                 return NT_STATUS_ACCESS_DENIED;
4401         }
4402
4403         /* Ensure we have a valid stat struct for the source. */
4404         if (fsp->fh->fd != -1) {
4405                 if (SMB_VFS_FSTAT(fsp,fsp->fh->fd,&sbuf) == -1) {
4406                         return map_nt_error_from_unix(errno);
4407                 }
4408         } else {
4409                 if (SMB_VFS_STAT(conn,fsp->fsp_name,&sbuf) == -1) {
4410                         return map_nt_error_from_unix(errno);
4411                 }
4412         }
4413
4414         status = can_rename(conn,fsp->fsp_name,attrs,&sbuf,True);
4415
4416         if (!NT_STATUS_IS_OK(status)) {
4417                 DEBUG(3,("rename_internals_fsp: Error %s rename %s -> %s\n",
4418                         nt_errstr(status), fsp->fsp_name,newname));
4419                 if (NT_STATUS_EQUAL(status,NT_STATUS_SHARING_VIOLATION))
4420                         status = NT_STATUS_ACCESS_DENIED;
4421                 return status;
4422         }
4423
4424         if (rename_path_prefix_equal(fsp->fsp_name, newname)) {
4425                 return NT_STATUS_ACCESS_DENIED;
4426         }
4427
4428         lck = get_share_mode_lock(NULL, fsp->file_id, NULL, NULL);
4429
4430         /*
4431          * We have the file open ourselves, so not being able to get the
4432          * corresponding share mode lock is a fatal error.
4433          */
4434
4435         SMB_ASSERT(lck != NULL);
4436
4437         if(SMB_VFS_RENAME(conn,fsp->fsp_name, newname) == 0) {
4438                 uint32 create_options = fsp->fh->private_options;
4439
4440                 DEBUG(3,("rename_internals_fsp: succeeded doing rename on %s -> %s\n",
4441                         fsp->fsp_name,newname));
4442
4443                 rename_open_files(conn, lck, newname);
4444
4445                 notify_rename(conn, fsp->is_directory, fsp->fsp_name, newname);
4446
4447                 /*
4448                  * A rename acts as a new file create w.r.t. allowing an initial delete
4449                  * on close, probably because in Windows there is a new handle to the
4450                  * new file. If initial delete on close was requested but not
4451                  * originally set, we need to set it here. This is probably not 100% correct,
4452                  * but will work for the CIFSFS client which in non-posix mode
4453                  * depends on these semantics. JRA.
4454                  */
4455
4456                 set_allow_initial_delete_on_close(lck, fsp, True);
4457
4458                 if (create_options & FILE_DELETE_ON_CLOSE) {
4459                         status = can_set_delete_on_close(fsp, True, 0);
4460
4461                         if (NT_STATUS_IS_OK(status)) {
4462                                 /* Note that here we set the *inital* delete on close flag,
4463                                  * not the regular one. The magic gets handled in close. */
4464                                 fsp->initial_delete_on_close = True;
4465                         }
4466                 }
4467                 TALLOC_FREE(lck);
4468                 return NT_STATUS_OK;    
4469         }
4470
4471         TALLOC_FREE(lck);
4472
4473         if (errno == ENOTDIR || errno == EISDIR) {
4474                 status = NT_STATUS_OBJECT_NAME_COLLISION;
4475         } else {
4476                 status = map_nt_error_from_unix(errno);
4477         }
4478                 
4479         DEBUG(3,("rename_internals_fsp: Error %s rename %s -> %s\n",
4480                 nt_errstr(status), fsp->fsp_name,newname));
4481
4482         return status;
4483 }
4484
4485 /****************************************************************************
4486  The guts of the rename command, split out so it may be called by the NT SMB
4487  code. 
4488 ****************************************************************************/
4489
4490 NTSTATUS rename_internals(connection_struct *conn,
4491                                 pstring name,
4492                                 pstring newname,
4493                                 uint32 attrs,
4494                                 BOOL replace_if_exists,
4495                                 BOOL src_has_wild,
4496                                 BOOL dest_has_wild)
4497 {
4498         pstring directory;
4499         pstring mask;
4500         pstring last_component_src;
4501         pstring last_component_dest;
4502         char *p;
4503         int count=0;
4504         NTSTATUS status = NT_STATUS_OK;
4505         SMB_STRUCT_STAT sbuf1, sbuf2;
4506         struct share_mode_lock *lck = NULL;
4507         struct smb_Dir *dir_hnd = NULL;
4508         const char *dname;
4509         long offset = 0;
4510         pstring destname;
4511
4512         *directory = *mask = 0;
4513
4514         ZERO_STRUCT(sbuf1);
4515         ZERO_STRUCT(sbuf2);
4516
4517         status = unix_convert(conn, name, src_has_wild, last_component_src, &sbuf1);
4518         if (!NT_STATUS_IS_OK(status)) {
4519                 return status;
4520         }
4521
4522         status = unix_convert(conn, newname, dest_has_wild, last_component_dest, &sbuf2);
4523         if (!NT_STATUS_IS_OK(status)) {
4524                 return status;
4525         }
4526
4527         /*
4528          * Split the old name into directory and last component
4529          * strings. Note that unix_convert may have stripped off a 
4530          * leading ./ from both name and newname if the rename is 
4531          * at the root of the share. We need to make sure either both
4532          * name and newname contain a / character or neither of them do
4533          * as this is checked in resolve_wildcards().
4534          */
4535
4536         p = strrchr_m(name,'/');
4537         if (!p) {
4538                 pstrcpy(directory,".");
4539                 pstrcpy(mask,name);
4540         } else {
4541                 *p = 0;
4542                 pstrcpy(directory,name);
4543                 pstrcpy(mask,p+1);
4544                 *p = '/'; /* Replace needed for exceptional test below. */
4545         }
4546
4547         /*
4548          * We should only check the mangled cache
4549          * here if unix_convert failed. This means
4550          * that the path in 'mask' doesn't exist
4551          * on the file system and so we need to look
4552          * for a possible mangle. This patch from
4553          * Tine Smukavec <valentin.smukavec@hermes.si>.
4554          */
4555
4556         if (!VALID_STAT(sbuf1) && mangle_is_mangled(mask, conn->params)) {
4557                 mangle_check_cache( mask, sizeof(pstring)-1, conn->params );
4558         }
4559
4560         if (!src_has_wild) {
4561                 /*
4562                  * No wildcards - just process the one file.
4563                  */
4564                 BOOL is_short_name = mangle_is_8_3(name, True, conn->params);
4565
4566                 /* Add a terminating '/' to the directory name. */
4567                 pstrcat(directory,"/");
4568                 pstrcat(directory,mask);
4569                 
4570                 /* Ensure newname contains a '/' also */
4571                 if(strrchr_m(newname,'/') == 0) {
4572                         pstring tmpstr;
4573                         
4574                         pstrcpy(tmpstr, "./");
4575                         pstrcat(tmpstr, newname);
4576                         pstrcpy(newname, tmpstr);
4577                 }
4578                 
4579                 DEBUG(3, ("rename_internals: case_sensitive = %d, "
4580                           "case_preserve = %d, short case preserve = %d, "
4581                           "directory = %s, newname = %s, "
4582                           "last_component_dest = %s, is_8_3 = %d\n", 
4583                           conn->case_sensitive, conn->case_preserve,
4584                           conn->short_case_preserve, directory, 
4585                           newname, last_component_dest, is_short_name));
4586
4587                 /* Ensure the source name is valid for us to access. */
4588                 status = check_name(conn, directory);
4589                 if (!NT_STATUS_IS_OK(status)) {
4590                         return status;
4591                 }
4592
4593                 /* The dest name still may have wildcards. */
4594                 if (dest_has_wild) {
4595                         if (!resolve_wildcards(directory,newname)) {
4596                                 DEBUG(6, ("rename_internals: resolve_wildcards %s %s failed\n", 
4597                                           directory,newname));
4598                                 return NT_STATUS_NO_MEMORY;
4599                         }
4600                 }
4601                                 
4602                 /*
4603                  * Check for special case with case preserving and not
4604                  * case sensitive, if directory and newname are identical,
4605                  * and the old last component differs from the original
4606                  * last component only by case, then we should allow
4607                  * the rename (user is trying to change the case of the
4608                  * filename).
4609                  */
4610                 if((conn->case_sensitive == False) && 
4611                    (((conn->case_preserve == True) && 
4612                      (is_short_name == False)) || 
4613                     ((conn->short_case_preserve == True) && 
4614                      (is_short_name == True))) &&
4615                    strcsequal(directory, newname)) {
4616                         pstring modified_last_component;
4617
4618                         /*
4619                          * Get the last component of the modified name.
4620                          * Note that we guarantee that newname contains a '/'
4621                          * character above.
4622                          */
4623                         p = strrchr_m(newname,'/');
4624                         pstrcpy(modified_last_component,p+1);
4625                         
4626                         if(strcsequal(modified_last_component, 
4627                                       last_component_dest) == False) {
4628                                 /*
4629                                  * Replace the modified last component with
4630                                  * the original.
4631                                  */
4632                                 pstrcpy(p+1, last_component_dest);
4633                         }
4634                 }
4635         
4636                 /* Ensure the dest name is valid for us to access. */
4637                 status = check_name(conn, newname);
4638                 if (!NT_STATUS_IS_OK(status)) {
4639                         return status;
4640                 }
4641
4642                 /*
4643                  * The source object must exist, and it may not have a
4644                  * conflicting share mode.
4645                  */
4646                 status = can_rename(conn,directory,attrs,&sbuf1,False);
4647
4648                 if (!NT_STATUS_IS_OK(status)) {
4649                         DEBUG(3,("rename_internals: Error %s rename %s -> "
4650                                  "%s\n", nt_errstr(status), directory,
4651                                  newname));
4652                         return status;
4653                 }
4654
4655                 /*
4656                  * If the src and dest names are identical - including case,
4657                  * don't do the rename, just return success.
4658                  */
4659
4660                 if (strcsequal(directory, newname)) {
4661                         DEBUG(3, ("rename_internals: identical names in "
4662                                   "rename %s - returning success\n",
4663                                   directory));
4664                         return NT_STATUS_OK;
4665                 }
4666
4667                 if(!replace_if_exists && vfs_object_exist(conn,newname,NULL)) {
4668                         DEBUG(3,("rename_internals: dest exists doing "
4669                                  "rename %s -> %s\n", directory, newname));
4670                         return NT_STATUS_OBJECT_NAME_COLLISION;
4671                 }
4672
4673                 if (rename_path_prefix_equal(directory, newname)) {
4674                         return NT_STATUS_SHARING_VIOLATION;
4675                 }
4676
4677                 lck = get_share_mode_lock(NULL, file_id_sbuf(&sbuf1),
4678                                           NULL, NULL);
4679
4680                 if(SMB_VFS_RENAME(conn,directory, newname) == 0) {
4681                         DEBUG(3,("rename_internals: succeeded doing rename "
4682                                  "on %s -> %s\n", directory, newname));
4683                         if (lck != NULL) {
4684                                 /*
4685                                  * Only in this case there are open files at
4686                                  * all.
4687                                  */
4688                                 rename_open_files(conn, lck, newname);
4689                         }
4690                         TALLOC_FREE(lck);
4691                         notify_rename(conn, S_ISDIR(sbuf1.st_mode),
4692                                       directory, newname);
4693                         return NT_STATUS_OK;    
4694                 }
4695
4696                 TALLOC_FREE(lck);
4697                 if (errno == ENOTDIR || errno == EISDIR) {
4698                         status = NT_STATUS_OBJECT_NAME_COLLISION;
4699                 } else {
4700                         status = map_nt_error_from_unix(errno);
4701                 }
4702                 
4703                 DEBUG(3,("rename_internals: Error %s rename %s -> %s\n",
4704                         nt_errstr(status), directory,newname));
4705
4706                 return status;
4707         }
4708
4709         /*
4710          * Wildcards - process each file that matches.
4711          */
4712         if (strequal(mask,"????????.???")) {
4713                 pstrcpy(mask,"*");
4714         }
4715                         
4716         status = check_name(conn, directory);
4717         if (!NT_STATUS_IS_OK(status)) {
4718                 return status;
4719         }
4720         
4721         dir_hnd = OpenDir(conn, directory, mask, attrs);
4722         if (dir_hnd == NULL) {
4723                 return map_nt_error_from_unix(errno);
4724         }
4725                 
4726         status = NT_STATUS_NO_SUCH_FILE;
4727         /*
4728          * Was status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
4729          * - gentest fix. JRA
4730          */
4731                         
4732         while ((dname = ReadDirName(dir_hnd, &offset))) {
4733                 pstring fname;
4734                 BOOL sysdir_entry = False;
4735
4736                 pstrcpy(fname,dname);
4737                                 
4738                 /* Quick check for "." and ".." */
4739                 if (fname[0] == '.') {
4740                         if (!fname[1] || (fname[1] == '.' && !fname[2])) {
4741                                 if (attrs & aDIR) {
4742                                         sysdir_entry = True;
4743                                 } else {
4744                                         continue;
4745                                 }
4746                         }
4747                 }
4748
4749                 if (!is_visible_file(conn, directory, dname, &sbuf1, False)) {
4750                         continue;
4751                 }
4752
4753                 if(!mask_match(fname, mask, conn->case_sensitive)) {
4754                         continue;
4755                 }
4756                                 
4757                 if (sysdir_entry) {
4758                         status = NT_STATUS_OBJECT_NAME_INVALID;
4759                         break;
4760                 }
4761
4762                 status = NT_STATUS_ACCESS_DENIED;
4763                 slprintf(fname, sizeof(fname)-1, "%s/%s", directory, dname);
4764
4765                 /* Ensure the source name is valid for us to access. */
4766                 status = check_name(conn, fname);
4767                 if (!NT_STATUS_IS_OK(status)) {
4768                         return status;
4769                 }
4770
4771                 /*
4772                  * can_rename does an open_file_ntcreate which needs a valid
4773                  * stat in case the file exists
4774                  */
4775
4776                 ZERO_STRUCT(sbuf1);
4777                 SMB_VFS_STAT(conn, fname, &sbuf1);
4778
4779                 status = can_rename(conn,fname,attrs,&sbuf1,False);
4780
4781                 if (!NT_STATUS_IS_OK(status)) {
4782                         DEBUG(6, ("rename %s refused: %s\n", fname,
4783                                   nt_errstr(status)));
4784                         continue;
4785                 }
4786                 pstrcpy(destname,newname);
4787                         
4788                 if (!resolve_wildcards(fname,destname)) {
4789                         DEBUG(6, ("resolve_wildcards %s %s failed\n", 
4790                                   fname, destname));
4791                         continue;
4792                 }
4793                                 
4794                 /* Ensure the dest name is valid for us to access. */
4795                 status = check_name(conn, destname);
4796                 if (!NT_STATUS_IS_OK(status)) {
4797                         return status;
4798                 }
4799
4800                 if (strcsequal(fname,destname)) {
4801                         DEBUG(3,("rename_internals: identical names "
4802                                  "in wildcard rename %s - success\n",
4803                                  fname));
4804                         count++;
4805                         status = NT_STATUS_OK;
4806                         continue;
4807                 }
4808
4809                 if (!replace_if_exists && vfs_file_exist(conn,destname, NULL)) {
4810                         DEBUG(6,("file_exist %s\n", destname));
4811                         status = NT_STATUS_OBJECT_NAME_COLLISION;
4812                         continue;
4813                 }
4814                                 
4815                 if (rename_path_prefix_equal(fname, destname)) {
4816                         return NT_STATUS_SHARING_VIOLATION;
4817                 }
4818
4819                 lck = get_share_mode_lock(NULL, file_id_sbuf(&sbuf1), NULL,
4820                                           NULL);
4821
4822                 if (!SMB_VFS_RENAME(conn,fname,destname)) {
4823                         if (lck != NULL) {
4824                                 /*
4825                                  * Only in this case there are open files at
4826                                  * all.
4827                                  */
4828                                 rename_open_files(conn, lck, newname);
4829                         }
4830                         count++;
4831                         status = NT_STATUS_OK;
4832                 }
4833                 TALLOC_FREE(lck);
4834                 DEBUG(3,("rename_internals: doing rename on %s -> "
4835                          "%s\n",fname,destname));
4836         }
4837         CloseDir(dir_hnd);
4838
4839         if (count == 0 && NT_STATUS_IS_OK(status)) {
4840                 status = map_nt_error_from_unix(errno);
4841         }
4842         
4843         return status;
4844 }
4845
4846 /****************************************************************************
4847  Reply to a mv.
4848 ****************************************************************************/
4849
4850 int reply_mv(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, 
4851              int dum_buffsize)
4852 {
4853         int outsize = 0;
4854         pstring name;
4855         pstring newname;
4856         char *p;
4857         uint32 attrs = SVAL(inbuf,smb_vwv0);
4858         NTSTATUS status;
4859         BOOL src_has_wcard = False;
4860         BOOL dest_has_wcard = False;
4861
4862         START_PROFILE(SMBmv);
4863
4864         p = smb_buf(inbuf) + 1;
4865         p += srvstr_get_path_wcard(inbuf, name, p, sizeof(name), 0, STR_TERMINATE, &status, &src_has_wcard);
4866         if (!NT_STATUS_IS_OK(status)) {
4867                 END_PROFILE(SMBmv);
4868                 return ERROR_NT(status);
4869         }
4870         p++;
4871         p += srvstr_get_path_wcard(inbuf, newname, p, sizeof(newname), 0, STR_TERMINATE, &status, &dest_has_wcard);
4872         if (!NT_STATUS_IS_OK(status)) {
4873                 END_PROFILE(SMBmv);
4874                 return ERROR_NT(status);
4875         }
4876         
4877         status = resolve_dfspath_wcard(conn, SVAL(inbuf,smb_flg2) & FLAGS2_DFS_PATHNAMES, name, &src_has_wcard);
4878         if (!NT_STATUS_IS_OK(status)) {
4879                 END_PROFILE(SMBmv);
4880                 if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) {
4881                         return ERROR_BOTH(NT_STATUS_PATH_NOT_COVERED, ERRSRV, ERRbadpath);
4882                 }
4883                 return ERROR_NT(status);
4884         }
4885
4886         status = resolve_dfspath_wcard(conn, SVAL(inbuf,smb_flg2) & FLAGS2_DFS_PATHNAMES, newname, &dest_has_wcard);
4887         if (!NT_STATUS_IS_OK(status)) {
4888                 END_PROFILE(SMBmv);
4889                 if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) {
4890                         return ERROR_BOTH(NT_STATUS_PATH_NOT_COVERED, ERRSRV, ERRbadpath);
4891                 }
4892                 return ERROR_NT(status);
4893         }
4894         
4895         DEBUG(3,("reply_mv : %s -> %s\n",name,newname));
4896         
4897         status = rename_internals(conn, name, newname, attrs, False, src_has_wcard, dest_has_wcard);
4898         if (!NT_STATUS_IS_OK(status)) {
4899                 END_PROFILE(SMBmv);
4900                 if (open_was_deferred(SVAL(inbuf,smb_mid))) {
4901                         /* We have re-scheduled this call. */
4902                         return -1;
4903                 }
4904                 return ERROR_NT(status);
4905         }
4906
4907         outsize = set_message(inbuf,outbuf,0,0,False);
4908   
4909         END_PROFILE(SMBmv);
4910         return(outsize);
4911 }
4912
4913 /*******************************************************************
4914  Copy a file as part of a reply_copy.
4915 ******************************************************************/
4916
4917 /*
4918  * TODO: check error codes on all callers
4919  */
4920
4921 NTSTATUS copy_file(connection_struct *conn,
4922                         char *src,
4923                         char *dest1,
4924                         int ofun,
4925                         int count,
4926                         BOOL target_is_directory)
4927 {
4928         SMB_STRUCT_STAT src_sbuf, sbuf2;
4929         SMB_OFF_T ret=-1;
4930         files_struct *fsp1,*fsp2;
4931         pstring dest;
4932         uint32 dosattrs;
4933         uint32 new_create_disposition;
4934         NTSTATUS status;
4935  
4936         pstrcpy(dest,dest1);
4937         if (target_is_directory) {
4938                 char *p = strrchr_m(src,'/');
4939                 if (p) {
4940                         p++;
4941                 } else {
4942                         p = src;
4943                 }
4944                 pstrcat(dest,"/");
4945                 pstrcat(dest,p);
4946         }
4947
4948         if (!vfs_file_exist(conn,src,&src_sbuf)) {
4949                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
4950         }
4951
4952         if (!target_is_directory && count) {
4953                 new_create_disposition = FILE_OPEN;
4954         } else {
4955                 if (!map_open_params_to_ntcreate(dest1,0,ofun,
4956                                 NULL, NULL, &new_create_disposition, NULL)) {
4957                         return NT_STATUS_INVALID_PARAMETER;
4958                 }
4959         }
4960
4961         status = open_file_ntcreate(conn,src,&src_sbuf,
4962                         FILE_GENERIC_READ,
4963                         FILE_SHARE_READ|FILE_SHARE_WRITE,
4964                         FILE_OPEN,
4965                         0,
4966                         FILE_ATTRIBUTE_NORMAL,
4967                         INTERNAL_OPEN_ONLY,
4968                         NULL, &fsp1);
4969
4970         if (!NT_STATUS_IS_OK(status)) {
4971                 return status;
4972         }
4973
4974         dosattrs = dos_mode(conn, src, &src_sbuf);
4975         if (SMB_VFS_STAT(conn,dest,&sbuf2) == -1) {
4976                 ZERO_STRUCTP(&sbuf2);
4977         }
4978
4979         status = open_file_ntcreate(conn,dest,&sbuf2,
4980                         FILE_GENERIC_WRITE,
4981                         FILE_SHARE_READ|FILE_SHARE_WRITE,
4982                         new_create_disposition,
4983                         0,
4984                         dosattrs,
4985                         INTERNAL_OPEN_ONLY,
4986                         NULL, &fsp2);
4987
4988         if (!NT_STATUS_IS_OK(status)) {
4989                 close_file(fsp1,ERROR_CLOSE);
4990                 return status;
4991         }
4992
4993         if ((ofun&3) == 1) {
4994                 if(SMB_VFS_LSEEK(fsp2,fsp2->fh->fd,0,SEEK_END) == -1) {
4995                         DEBUG(0,("copy_file: error - vfs lseek returned error %s\n", strerror(errno) ));
4996                         /*
4997                          * Stop the copy from occurring.
4998                          */
4999                         ret = -1;
5000                         src_sbuf.st_size = 0;
5001                 }
5002         }
5003   
5004         if (src_sbuf.st_size) {
5005                 ret = vfs_transfer_file(fsp1, fsp2, src_sbuf.st_size);
5006         }
5007
5008         close_file(fsp1,NORMAL_CLOSE);
5009
5010         /* Ensure the modtime is set correctly on the destination file. */
5011         fsp_set_pending_modtime( fsp2, get_mtimespec(&src_sbuf));
5012
5013         /*
5014          * As we are opening fsp1 read-only we only expect
5015          * an error on close on fsp2 if we are out of space.
5016          * Thus we don't look at the error return from the
5017          * close of fsp1.
5018          */
5019         status = close_file(fsp2,NORMAL_CLOSE);
5020
5021         if (!NT_STATUS_IS_OK(status)) {
5022                 return status;
5023         }
5024
5025         if (ret != (SMB_OFF_T)src_sbuf.st_size) {
5026                 return NT_STATUS_DISK_FULL;
5027         }
5028
5029         return NT_STATUS_OK;
5030 }
5031
5032 /****************************************************************************
5033  Reply to a file copy.
5034 ****************************************************************************/
5035
5036 int reply_copy(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize)
5037 {
5038         int outsize = 0;
5039         pstring name;
5040         pstring directory;
5041         pstring mask,newname;
5042         char *p;
5043         int count=0;
5044         int error = ERRnoaccess;
5045         int err = 0;
5046         int tid2 = SVAL(inbuf,smb_vwv0);
5047         int ofun = SVAL(inbuf,smb_vwv1);
5048         int flags = SVAL(inbuf,smb_vwv2);
5049         BOOL target_is_directory=False;
5050         BOOL source_has_wild = False;
5051         BOOL dest_has_wild = False;
5052         SMB_STRUCT_STAT sbuf1, sbuf2;
5053         NTSTATUS status;
5054         START_PROFILE(SMBcopy);
5055
5056         *directory = *mask = 0;
5057
5058         p = smb_buf(inbuf);
5059         p += srvstr_get_path_wcard(inbuf, name, p, sizeof(name), 0, STR_TERMINATE, &status, &source_has_wild);
5060         if (!NT_STATUS_IS_OK(status)) {
5061                 END_PROFILE(SMBcopy);
5062                 return ERROR_NT(status);
5063         }
5064         p += srvstr_get_path_wcard(inbuf, newname, p, sizeof(newname), 0, STR_TERMINATE, &status, &dest_has_wild);
5065         if (!NT_STATUS_IS_OK(status)) {
5066                 END_PROFILE(SMBcopy);
5067                 return ERROR_NT(status);
5068         }
5069    
5070         DEBUG(3,("reply_copy : %s -> %s\n",name,newname));
5071    
5072         if (tid2 != conn->cnum) {
5073                 /* can't currently handle inter share copies XXXX */
5074                 DEBUG(3,("Rejecting inter-share copy\n"));
5075                 END_PROFILE(SMBcopy);
5076                 return ERROR_DOS(ERRSRV,ERRinvdevice);
5077         }
5078
5079         status = resolve_dfspath_wcard(conn, SVAL(inbuf,smb_flg2) & FLAGS2_DFS_PATHNAMES, name, &source_has_wild);
5080         if (!NT_STATUS_IS_OK(status)) {
5081                 END_PROFILE(SMBcopy);
5082                 if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) {
5083                         return ERROR_BOTH(NT_STATUS_PATH_NOT_COVERED, ERRSRV, ERRbadpath);
5084                 }
5085                 return ERROR_NT(status);
5086         }
5087
5088         status = resolve_dfspath_wcard(conn, SVAL(inbuf,smb_flg2) & FLAGS2_DFS_PATHNAMES, newname, &dest_has_wild);
5089         if (!NT_STATUS_IS_OK(status)) {
5090                 END_PROFILE(SMBcopy);
5091                 if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) {
5092                         return ERROR_BOTH(NT_STATUS_PATH_NOT_COVERED, ERRSRV, ERRbadpath);
5093                 }
5094                 return ERROR_NT(status);
5095         }
5096
5097         status = unix_convert(conn, name, source_has_wild, NULL, &sbuf1);
5098         if (!NT_STATUS_IS_OK(status)) {
5099                 END_PROFILE(SMBcopy);
5100                 return ERROR_NT(status);
5101         }
5102
5103         status = unix_convert(conn, newname, dest_has_wild, NULL, &sbuf2);
5104         if (!NT_STATUS_IS_OK(status)) {
5105                 END_PROFILE(SMBcopy);
5106                 return ERROR_NT(status);
5107         }
5108
5109         target_is_directory = VALID_STAT_OF_DIR(sbuf2);
5110
5111         if ((flags&1) && target_is_directory) {
5112                 END_PROFILE(SMBcopy);
5113                 return ERROR_DOS(ERRDOS,ERRbadfile);
5114         }
5115
5116         if ((flags&2) && !target_is_directory) {
5117                 END_PROFILE(SMBcopy);
5118                 return ERROR_DOS(ERRDOS,ERRbadpath);
5119         }
5120
5121         if ((flags&(1<<5)) && VALID_STAT_OF_DIR(sbuf1)) {
5122                 /* wants a tree copy! XXXX */
5123                 DEBUG(3,("Rejecting tree copy\n"));
5124                 END_PROFILE(SMBcopy);
5125                 return ERROR_DOS(ERRSRV,ERRerror);
5126         }
5127
5128         p = strrchr_m(name,'/');
5129         if (!p) {
5130                 pstrcpy(directory,"./");
5131                 pstrcpy(mask,name);
5132         } else {
5133                 *p = 0;
5134                 pstrcpy(directory,name);
5135                 pstrcpy(mask,p+1);
5136         }
5137
5138         /*
5139          * We should only check the mangled cache
5140          * here if unix_convert failed. This means
5141          * that the path in 'mask' doesn't exist
5142          * on the file system and so we need to look
5143          * for a possible mangle. This patch from
5144          * Tine Smukavec <valentin.smukavec@hermes.si>.
5145          */
5146
5147         if (!VALID_STAT(sbuf1) && mangle_is_mangled(mask, conn->params)) {
5148                 mangle_check_cache( mask, sizeof(pstring)-1, conn->params );
5149         }
5150
5151         if (!source_has_wild) {
5152                 pstrcat(directory,"/");
5153                 pstrcat(directory,mask);
5154                 if (dest_has_wild) {
5155                         if (!resolve_wildcards(directory,newname)) {
5156                                 END_PROFILE(SMBcopy);
5157                                 return ERROR_NT(NT_STATUS_NO_MEMORY);
5158                         }
5159                 }
5160
5161                 status = check_name(conn, directory);
5162                 if (!NT_STATUS_IS_OK(status)) {
5163                         return ERROR_NT(status);
5164                 }
5165                 
5166                 status = check_name(conn, newname);
5167                 if (!NT_STATUS_IS_OK(status)) {
5168                         return ERROR_NT(status);
5169                 }
5170                 
5171                 status = copy_file(conn,directory,newname,ofun,
5172                                         count,target_is_directory);
5173
5174                 if(!NT_STATUS_IS_OK(status)) {
5175                         END_PROFILE(SMBcopy);
5176                         return ERROR_NT(status);
5177                 } else {
5178                         count++;
5179                 }
5180         } else {
5181                 struct smb_Dir *dir_hnd = NULL;
5182                 const char *dname;
5183                 long offset = 0;
5184                 pstring destname;
5185
5186                 if (strequal(mask,"????????.???"))
5187                         pstrcpy(mask,"*");
5188
5189                 status = check_name(conn, directory);
5190                 if (!NT_STATUS_IS_OK(status)) {
5191                         return ERROR_NT(status);
5192                 }
5193                 
5194                 dir_hnd = OpenDir(conn, directory, mask, 0);
5195                 if (dir_hnd == NULL) {
5196                         status = map_nt_error_from_unix(errno);
5197                         return ERROR_NT(status);
5198                 }
5199
5200                 error = ERRbadfile;
5201
5202                 while ((dname = ReadDirName(dir_hnd, &offset))) {
5203                         pstring fname;
5204                         pstrcpy(fname,dname);
5205     
5206                         if (!is_visible_file(conn, directory, dname, &sbuf1, False)) {
5207                                 continue;
5208                         }
5209
5210                         if(!mask_match(fname, mask, conn->case_sensitive)) {
5211                                 continue;
5212                         }
5213
5214                         error = ERRnoaccess;
5215                         slprintf(fname,sizeof(fname)-1, "%s/%s",directory,dname);
5216                         pstrcpy(destname,newname);
5217                         if (!resolve_wildcards(fname,destname)) {
5218                                 continue;
5219                         }
5220
5221                         status = check_name(conn, fname);
5222                         if (!NT_STATUS_IS_OK(status)) {
5223                                 return ERROR_NT(status);
5224                         }
5225                 
5226                         status = check_name(conn, destname);
5227                         if (!NT_STATUS_IS_OK(status)) {
5228                                 return ERROR_NT(status);
5229                         }
5230                 
5231                         DEBUG(3,("reply_copy : doing copy on %s -> %s\n",fname, destname));
5232
5233                         status = copy_file(conn,fname,destname,ofun,
5234                                         count,target_is_directory);
5235                         if (NT_STATUS_IS_OK(status)) {
5236                                 count++;
5237                         }
5238                 }
5239                 CloseDir(dir_hnd);
5240         }
5241   
5242         if (count == 0) {
5243                 if(err) {
5244                         /* Error on close... */
5245                         errno = err;
5246                         END_PROFILE(SMBcopy);
5247                         return(UNIXERROR(ERRHRD,ERRgeneral));
5248                 }
5249
5250                 END_PROFILE(SMBcopy);
5251                 return ERROR_DOS(ERRDOS,error);
5252         }
5253   
5254         outsize = set_message(inbuf,outbuf,1,0,True);
5255         SSVAL(outbuf,smb_vwv0,count);
5256
5257         END_PROFILE(SMBcopy);
5258         return(outsize);
5259 }
5260
5261 /****************************************************************************
5262  Reply to a setdir.
5263 ****************************************************************************/
5264
5265 int reply_setdir(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize)
5266 {
5267         int snum;
5268         int outsize = 0;
5269         pstring newdir;
5270         NTSTATUS status;
5271
5272         START_PROFILE(pathworks_setdir);
5273   
5274         snum = SNUM(conn);
5275         if (!CAN_SETDIR(snum)) {
5276                 END_PROFILE(pathworks_setdir);
5277                 return ERROR_DOS(ERRDOS,ERRnoaccess);
5278         }
5279
5280         srvstr_get_path(inbuf, newdir, smb_buf(inbuf) + 1, sizeof(newdir), 0, STR_TERMINATE, &status);
5281         if (!NT_STATUS_IS_OK(status)) {
5282                 END_PROFILE(pathworks_setdir);
5283                 return ERROR_NT(status);
5284         }
5285   
5286         status = resolve_dfspath(conn, SVAL(inbuf,smb_flg2) & FLAGS2_DFS_PATHNAMES, newdir);
5287         if (!NT_STATUS_IS_OK(status)) {
5288                 END_PROFILE(pathworks_setdir);
5289                 if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) {
5290                         return ERROR_BOTH(NT_STATUS_PATH_NOT_COVERED, ERRSRV, ERRbadpath);
5291                 }
5292                 return ERROR_NT(status);
5293         }
5294
5295         if (strlen(newdir) != 0) {
5296                 if (!vfs_directory_exist(conn,newdir,NULL)) {
5297                         END_PROFILE(pathworks_setdir);
5298                         return ERROR_DOS(ERRDOS,ERRbadpath);
5299                 }
5300                 set_conn_connectpath(conn,newdir);
5301         }
5302   
5303         outsize = set_message(inbuf,outbuf,0,0,False);
5304         SCVAL(outbuf,smb_reh,CVAL(inbuf,smb_reh));
5305   
5306         DEBUG(3,("setdir %s\n", newdir));
5307
5308         END_PROFILE(pathworks_setdir);
5309         return(outsize);
5310 }
5311
5312 #undef DBGC_CLASS
5313 #define DBGC_CLASS DBGC_LOCKING
5314
5315 /****************************************************************************
5316  Get a lock pid, dealing with large count requests.
5317 ****************************************************************************/
5318
5319 uint32 get_lock_pid( char *data, int data_offset, BOOL large_file_format)
5320 {
5321         if(!large_file_format)
5322                 return (uint32)SVAL(data,SMB_LPID_OFFSET(data_offset));
5323         else
5324                 return (uint32)SVAL(data,SMB_LARGE_LPID_OFFSET(data_offset));
5325 }
5326
5327 /****************************************************************************
5328  Get a lock count, dealing with large count requests.
5329 ****************************************************************************/
5330
5331 SMB_BIG_UINT get_lock_count( char *data, int data_offset, BOOL large_file_format)
5332 {
5333         SMB_BIG_UINT count = 0;
5334
5335         if(!large_file_format) {
5336                 count = (SMB_BIG_UINT)IVAL(data,SMB_LKLEN_OFFSET(data_offset));
5337         } else {
5338
5339 #if defined(HAVE_LONGLONG)
5340                 count = (((SMB_BIG_UINT) IVAL(data,SMB_LARGE_LKLEN_OFFSET_HIGH(data_offset))) << 32) |
5341                         ((SMB_BIG_UINT) IVAL(data,SMB_LARGE_LKLEN_OFFSET_LOW(data_offset)));
5342 #else /* HAVE_LONGLONG */
5343
5344                 /*
5345                  * NT4.x seems to be broken in that it sends large file (64 bit)
5346                  * lockingX calls even if the CAP_LARGE_FILES was *not*
5347                  * negotiated. For boxes without large unsigned ints truncate the
5348                  * lock count by dropping the top 32 bits.
5349                  */
5350
5351                 if(IVAL(data,SMB_LARGE_LKLEN_OFFSET_HIGH(data_offset)) != 0) {
5352                         DEBUG(3,("get_lock_count: truncating lock count (high)0x%x (low)0x%x to just low count.\n",
5353                                 (unsigned int)IVAL(data,SMB_LARGE_LKLEN_OFFSET_HIGH(data_offset)),
5354                                 (unsigned int)IVAL(data,SMB_LARGE_LKLEN_OFFSET_LOW(data_offset)) ));
5355                                 SIVAL(data,SMB_LARGE_LKLEN_OFFSET_HIGH(data_offset),0);
5356                 }
5357
5358                 count = (SMB_BIG_UINT)IVAL(data,SMB_LARGE_LKLEN_OFFSET_LOW(data_offset));
5359 #endif /* HAVE_LONGLONG */
5360         }
5361
5362         return count;
5363 }
5364
5365 #if !defined(HAVE_LONGLONG)
5366 /****************************************************************************
5367  Pathetically try and map a 64 bit lock offset into 31 bits. I hate Windows :-).
5368 ****************************************************************************/
5369
5370 static uint32 map_lock_offset(uint32 high, uint32 low)
5371 {
5372         unsigned int i;
5373         uint32 mask = 0;
5374         uint32 highcopy = high;
5375  
5376         /*
5377          * Try and find out how many significant bits there are in high.
5378          */
5379  
5380         for(i = 0; highcopy; i++)
5381                 highcopy >>= 1;
5382  
5383         /*
5384          * We use 31 bits not 32 here as POSIX
5385          * lock offsets may not be negative.
5386          */
5387  
5388         mask = (~0) << (31 - i);
5389  
5390         if(low & mask)
5391                 return 0; /* Fail. */
5392  
5393         high <<= (31 - i);
5394  
5395         return (high|low);
5396 }
5397 #endif /* !defined(HAVE_LONGLONG) */
5398
5399 /****************************************************************************
5400  Get a lock offset, dealing with large offset requests.
5401 ****************************************************************************/
5402
5403 SMB_BIG_UINT get_lock_offset( char *data, int data_offset, BOOL large_file_format, BOOL *err)
5404 {
5405         SMB_BIG_UINT offset = 0;
5406
5407         *err = False;
5408
5409         if(!large_file_format) {
5410                 offset = (SMB_BIG_UINT)IVAL(data,SMB_LKOFF_OFFSET(data_offset));
5411         } else {
5412
5413 #if defined(HAVE_LONGLONG)
5414                 offset = (((SMB_BIG_UINT) IVAL(data,SMB_LARGE_LKOFF_OFFSET_HIGH(data_offset))) << 32) |
5415                                 ((SMB_BIG_UINT) IVAL(data,SMB_LARGE_LKOFF_OFFSET_LOW(data_offset)));
5416 #else /* HAVE_LONGLONG */
5417
5418                 /*
5419                  * NT4.x seems to be broken in that it sends large file (64 bit)
5420                  * lockingX calls even if the CAP_LARGE_FILES was *not*
5421                  * negotiated. For boxes without large unsigned ints mangle the
5422                  * lock offset by mapping the top 32 bits onto the lower 32.
5423                  */
5424       
5425                 if(IVAL(data,SMB_LARGE_LKOFF_OFFSET_HIGH(data_offset)) != 0) {
5426                         uint32 low = IVAL(data,SMB_LARGE_LKOFF_OFFSET_LOW(data_offset));
5427                         uint32 high = IVAL(data,SMB_LARGE_LKOFF_OFFSET_HIGH(data_offset));
5428                         uint32 new_low = 0;
5429
5430                         if((new_low = map_lock_offset(high, low)) == 0) {
5431                                 *err = True;
5432                                 return (SMB_BIG_UINT)-1;
5433                         }
5434
5435                         DEBUG(3,("get_lock_offset: truncating lock offset (high)0x%x (low)0x%x to offset 0x%x.\n",
5436                                 (unsigned int)high, (unsigned int)low, (unsigned int)new_low ));
5437                         SIVAL(data,SMB_LARGE_LKOFF_OFFSET_HIGH(data_offset),0);
5438                         SIVAL(data,SMB_LARGE_LKOFF_OFFSET_LOW(data_offset),new_low);
5439                 }
5440
5441                 offset = (SMB_BIG_UINT)IVAL(data,SMB_LARGE_LKOFF_OFFSET_LOW(data_offset));
5442 #endif /* HAVE_LONGLONG */
5443         }
5444
5445         return offset;
5446 }
5447
5448 /****************************************************************************
5449  Reply to a lockingX request.
5450 ****************************************************************************/
5451
5452 int reply_lockingX(connection_struct *conn, char *inbuf, char *outbuf,
5453                    int length, int bufsize)
5454 {
5455         files_struct *fsp = file_fsp(inbuf,smb_vwv2);
5456         unsigned char locktype = CVAL(inbuf,smb_vwv3);
5457         unsigned char oplocklevel = CVAL(inbuf,smb_vwv3+1);
5458         uint16 num_ulocks = SVAL(inbuf,smb_vwv6);
5459         uint16 num_locks = SVAL(inbuf,smb_vwv7);
5460         SMB_BIG_UINT count = 0, offset = 0;
5461         uint32 lock_pid;
5462         int32 lock_timeout = IVAL(inbuf,smb_vwv4);
5463         int i;
5464         char *data;
5465         BOOL large_file_format =
5466                 (locktype & LOCKING_ANDX_LARGE_FILES)?True:False;
5467         BOOL err;
5468         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
5469
5470         START_PROFILE(SMBlockingX);
5471         
5472         CHECK_FSP(fsp,conn);
5473         
5474         data = smb_buf(inbuf);
5475
5476         if (locktype & LOCKING_ANDX_CHANGE_LOCKTYPE) {
5477                 /* we don't support these - and CANCEL_LOCK makes w2k
5478                    and XP reboot so I don't really want to be
5479                    compatible! (tridge) */
5480                 return ERROR_NT(NT_STATUS_DOS(ERRDOS, ERRnoatomiclocks));
5481         }
5482         
5483         /* Check if this is an oplock break on a file
5484            we have granted an oplock on.
5485         */
5486         if ((locktype & LOCKING_ANDX_OPLOCK_RELEASE)) {
5487                 /* Client can insist on breaking to none. */
5488                 BOOL break_to_none = (oplocklevel == 0);
5489                 BOOL result;
5490
5491                 DEBUG(5,("reply_lockingX: oplock break reply (%u) from client "
5492                          "for fnum = %d\n", (unsigned int)oplocklevel,
5493                          fsp->fnum ));
5494
5495                 /*
5496                  * Make sure we have granted an exclusive or batch oplock on
5497                  * this file.
5498                  */
5499                 
5500                 if (fsp->oplock_type == 0) {
5501
5502                         /* The Samba4 nbench simulator doesn't understand
5503                            the difference between break to level2 and break
5504                            to none from level2 - it sends oplock break
5505                            replies in both cases. Don't keep logging an error
5506                            message here - just ignore it. JRA. */
5507
5508                         DEBUG(5,("reply_lockingX: Error : oplock break from "
5509                                  "client for fnum = %d (oplock=%d) and no "
5510                                  "oplock granted on this file (%s).\n",
5511                                  fsp->fnum, fsp->oplock_type, fsp->fsp_name));
5512
5513                         /* if this is a pure oplock break request then don't
5514                          * send a reply */
5515                         if (num_locks == 0 && num_ulocks == 0) {
5516                                 END_PROFILE(SMBlockingX);
5517                                 return -1;
5518                         } else {
5519                                 END_PROFILE(SMBlockingX);
5520                                 return ERROR_DOS(ERRDOS,ERRlock);
5521                         }
5522                 }
5523
5524                 if ((fsp->sent_oplock_break == BREAK_TO_NONE_SENT) ||
5525                     (break_to_none)) {
5526                         result = remove_oplock(fsp);
5527                 } else {
5528                         result = downgrade_oplock(fsp);
5529                 }
5530                 
5531                 if (!result) {
5532                         DEBUG(0, ("reply_lockingX: error in removing "
5533                                   "oplock on file %s\n", fsp->fsp_name));
5534                         /* Hmmm. Is this panic justified? */
5535                         smb_panic("internal tdb error");
5536                 }
5537
5538                 reply_to_oplock_break_requests(fsp);
5539
5540                 /* if this is a pure oplock break request then don't send a
5541                  * reply */
5542                 if (num_locks == 0 && num_ulocks == 0) {
5543                         /* Sanity check - ensure a pure oplock break is not a
5544                            chained request. */
5545                         if(CVAL(inbuf,smb_vwv0) != 0xff)
5546                                 DEBUG(0,("reply_lockingX: Error : pure oplock "
5547                                          "break is a chained %d request !\n",
5548                                          (unsigned int)CVAL(inbuf,smb_vwv0) ));
5549                         END_PROFILE(SMBlockingX);
5550                         return -1;
5551                 }
5552         }
5553
5554         /*
5555          * We do this check *after* we have checked this is not a oplock break
5556          * response message. JRA.
5557          */
5558         
5559         release_level_2_oplocks_on_change(fsp);
5560         
5561         /* Data now points at the beginning of the list
5562            of smb_unlkrng structs */
5563         for(i = 0; i < (int)num_ulocks; i++) {
5564                 lock_pid = get_lock_pid( data, i, large_file_format);
5565                 count = get_lock_count( data, i, large_file_format);
5566                 offset = get_lock_offset( data, i, large_file_format, &err);
5567                 
5568                 /*
5569                  * There is no error code marked "stupid client bug".... :-).
5570                  */
5571                 if(err) {
5572                         END_PROFILE(SMBlockingX);
5573                         return ERROR_DOS(ERRDOS,ERRnoaccess);
5574                 }
5575
5576                 DEBUG(10,("reply_lockingX: unlock start=%.0f, len=%.0f for "
5577                           "pid %u, file %s\n", (double)offset, (double)count,
5578                           (unsigned int)lock_pid, fsp->fsp_name ));
5579                 
5580                 status = do_unlock(smbd_messaging_context(),
5581                                 fsp,
5582                                 lock_pid,
5583                                 count,
5584                                 offset,
5585                                 WINDOWS_LOCK);
5586
5587                 if (NT_STATUS_V(status)) {
5588                         END_PROFILE(SMBlockingX);
5589                         return ERROR_NT(status);
5590                 }
5591         }
5592
5593         /* Setup the timeout in seconds. */
5594
5595         if (!lp_blocking_locks(SNUM(conn))) {
5596                 lock_timeout = 0;
5597         }
5598         
5599         /* Now do any requested locks */
5600         data += ((large_file_format ? 20 : 10)*num_ulocks);
5601         
5602         /* Data now points at the beginning of the list
5603            of smb_lkrng structs */
5604         
5605         for(i = 0; i < (int)num_locks; i++) {
5606                 enum brl_type lock_type = ((locktype & LOCKING_ANDX_SHARED_LOCK) ?
5607                                 READ_LOCK:WRITE_LOCK);
5608                 lock_pid = get_lock_pid( data, i, large_file_format);
5609                 count = get_lock_count( data, i, large_file_format);
5610                 offset = get_lock_offset( data, i, large_file_format, &err);
5611                 
5612                 /*
5613                  * There is no error code marked "stupid client bug".... :-).
5614                  */
5615                 if(err) {
5616                         END_PROFILE(SMBlockingX);
5617                         return ERROR_DOS(ERRDOS,ERRnoaccess);
5618                 }
5619                 
5620                 DEBUG(10,("reply_lockingX: lock start=%.0f, len=%.0f for pid "
5621                           "%u, file %s timeout = %d\n", (double)offset,
5622                           (double)count, (unsigned int)lock_pid,
5623                           fsp->fsp_name, (int)lock_timeout ));
5624                 
5625                 if (locktype & LOCKING_ANDX_CANCEL_LOCK) {
5626                         if (lp_blocking_locks(SNUM(conn))) {
5627
5628                                 /* Schedule a message to ourselves to
5629                                    remove the blocking lock record and
5630                                    return the right error. */
5631
5632                                 if (!blocking_lock_cancel(fsp,
5633                                                 lock_pid,
5634                                                 offset,
5635                                                 count,
5636                                                 WINDOWS_LOCK,
5637                                                 locktype,
5638                                                 NT_STATUS_FILE_LOCK_CONFLICT)) {
5639                                         END_PROFILE(SMBlockingX);
5640                                         return ERROR_NT(NT_STATUS_DOS(ERRDOS, ERRcancelviolation));
5641                                 }
5642                         }
5643                         /* Remove a matching pending lock. */
5644                         status = do_lock_cancel(fsp,
5645                                                 lock_pid,
5646                                                 count,
5647                                                 offset,
5648                                                 WINDOWS_LOCK);
5649                 } else {
5650                         BOOL blocking_lock = lock_timeout ? True : False;
5651                         BOOL defer_lock = False;
5652                         struct byte_range_lock *br_lck;
5653                         uint32 block_smbpid;
5654
5655                         br_lck = do_lock(smbd_messaging_context(),
5656                                         fsp,
5657                                         lock_pid,
5658                                         count,
5659                                         offset, 
5660                                         lock_type,
5661                                         WINDOWS_LOCK,
5662                                         blocking_lock,
5663                                         &status,
5664                                         &block_smbpid);
5665
5666                         if (br_lck && blocking_lock && ERROR_WAS_LOCK_DENIED(status)) {
5667                                 /* Windows internal resolution for blocking locks seems
5668                                    to be about 200ms... Don't wait for less than that. JRA. */
5669                                 if (lock_timeout != -1 && lock_timeout < lp_lock_spin_time()) {
5670                                         lock_timeout = lp_lock_spin_time();
5671                                 }
5672                                 defer_lock = True;
5673                         }
5674
5675                         /* This heuristic seems to match W2K3 very well. If a
5676                            lock sent with timeout of zero would fail with NT_STATUS_FILE_LOCK_CONFLICT
5677                            it pretends we asked for a timeout of between 150 - 300 milliseconds as
5678                            far as I can tell. Replacement for do_lock_spin(). JRA. */
5679
5680                         if (br_lck && lp_blocking_locks(SNUM(conn)) && !blocking_lock &&
5681                                         NT_STATUS_EQUAL((status), NT_STATUS_FILE_LOCK_CONFLICT)) {
5682                                 defer_lock = True;
5683                                 lock_timeout = lp_lock_spin_time();
5684                         }
5685
5686                         if (br_lck && defer_lock) {
5687                                 /*
5688                                  * A blocking lock was requested. Package up
5689                                  * this smb into a queued request and push it
5690                                  * onto the blocking lock queue.
5691                                  */
5692                                 if(push_blocking_lock_request(br_lck,
5693                                                         inbuf, length,
5694                                                         fsp,
5695                                                         lock_timeout,
5696                                                         i,
5697                                                         lock_pid,
5698                                                         lock_type,
5699                                                         WINDOWS_LOCK,
5700                                                         offset,
5701                                                         count,
5702                                                         block_smbpid)) {
5703                                         TALLOC_FREE(br_lck);
5704                                         END_PROFILE(SMBlockingX);
5705                                         return -1;
5706                                 }
5707                         }
5708
5709                         TALLOC_FREE(br_lck);
5710                 }
5711
5712                 if (NT_STATUS_V(status)) {
5713                         END_PROFILE(SMBlockingX);
5714                         return ERROR_NT(status);
5715                 }
5716         }
5717         
5718         /* If any of the above locks failed, then we must unlock
5719            all of the previous locks (X/Open spec). */
5720
5721         if (!(locktype & LOCKING_ANDX_CANCEL_LOCK) &&
5722                         (i != num_locks) &&
5723                         (num_locks != 0)) {
5724                 /*
5725                  * Ensure we don't do a remove on the lock that just failed,
5726                  * as under POSIX rules, if we have a lock already there, we
5727                  * will delete it (and we shouldn't) .....
5728                  */
5729                 for(i--; i >= 0; i--) {
5730                         lock_pid = get_lock_pid( data, i, large_file_format);
5731                         count = get_lock_count( data, i, large_file_format);
5732                         offset = get_lock_offset( data, i, large_file_format,
5733                                                   &err);
5734                         
5735                         /*
5736                          * There is no error code marked "stupid client
5737                          * bug".... :-).
5738                          */
5739                         if(err) {
5740                                 END_PROFILE(SMBlockingX);
5741                                 return ERROR_DOS(ERRDOS,ERRnoaccess);
5742                         }
5743                         
5744                         do_unlock(smbd_messaging_context(),
5745                                 fsp,
5746                                 lock_pid,
5747                                 count,
5748                                 offset,
5749                                 WINDOWS_LOCK);
5750                 }
5751                 END_PROFILE(SMBlockingX);
5752                 return ERROR_NT(status);
5753         }
5754
5755         set_message(inbuf,outbuf,2,0,True);
5756         
5757         DEBUG(3, ("lockingX fnum=%d type=%d num_locks=%d num_ulocks=%d\n",
5758                   fsp->fnum, (unsigned int)locktype, num_locks, num_ulocks));
5759         
5760         END_PROFILE(SMBlockingX);
5761         return chain_reply(inbuf,outbuf,length,bufsize);
5762 }
5763
5764 #undef DBGC_CLASS
5765 #define DBGC_CLASS DBGC_ALL
5766
5767 /****************************************************************************
5768  Reply to a SMBreadbmpx (read block multiplex) request.
5769 ****************************************************************************/
5770
5771 int reply_readbmpx(connection_struct *conn, char *inbuf,char *outbuf,int length,int bufsize)
5772 {
5773         ssize_t nread = -1;
5774         ssize_t total_read;
5775         char *data;
5776         SMB_OFF_T startpos;
5777         int outsize;
5778         size_t maxcount;
5779         int max_per_packet;
5780         size_t tcount;
5781         int pad;
5782         files_struct *fsp = file_fsp(inbuf,smb_vwv0);
5783         START_PROFILE(SMBreadBmpx);
5784
5785         /* this function doesn't seem to work - disable by default */
5786         if (!lp_readbmpx()) {
5787                 END_PROFILE(SMBreadBmpx);
5788                 return ERROR_DOS(ERRSRV,ERRuseSTD);
5789         }
5790
5791         outsize = set_message(inbuf,outbuf,8,0,True);
5792
5793         CHECK_FSP(fsp,conn);
5794         if (!CHECK_READ(fsp,inbuf)) {
5795                 return(ERROR_DOS(ERRDOS,ERRbadaccess));
5796         }
5797
5798         startpos = IVAL_TO_SMB_OFF_T(inbuf,smb_vwv1);
5799         maxcount = SVAL(inbuf,smb_vwv3);
5800
5801         data = smb_buf(outbuf);
5802         pad = ((long)data)%4;
5803         if (pad)
5804                 pad = 4 - pad;
5805         data += pad;
5806
5807         max_per_packet = bufsize-(outsize+pad);
5808         tcount = maxcount;
5809         total_read = 0;
5810
5811         if (is_locked(fsp,(uint32)SVAL(inbuf,smb_pid),(SMB_BIG_UINT)maxcount,(SMB_BIG_UINT)startpos, READ_LOCK)) {
5812                 END_PROFILE(SMBreadBmpx);
5813                 return ERROR_DOS(ERRDOS,ERRlock);
5814         }
5815
5816         do {
5817                 size_t N = MIN(max_per_packet,tcount-total_read);
5818   
5819                 nread = read_file(fsp,data,startpos,N);
5820
5821                 if (nread <= 0)
5822                         nread = 0;
5823
5824                 if (nread < (ssize_t)N)
5825                         tcount = total_read + nread;
5826
5827                 set_message(inbuf,outbuf,8,nread+pad,False);
5828                 SIVAL(outbuf,smb_vwv0,startpos);
5829                 SSVAL(outbuf,smb_vwv2,tcount);
5830                 SSVAL(outbuf,smb_vwv6,nread);
5831                 SSVAL(outbuf,smb_vwv7,smb_offset(data,outbuf));
5832
5833                 show_msg(outbuf);
5834                 if (!send_smb(smbd_server_fd(),outbuf))
5835                         exit_server_cleanly("reply_readbmpx: send_smb failed.");
5836
5837                 total_read += nread;
5838                 startpos += nread;
5839         } while (total_read < (ssize_t)tcount);
5840
5841         END_PROFILE(SMBreadBmpx);
5842         return(-1);
5843 }
5844
5845 /****************************************************************************
5846  Reply to a SMBsetattrE.
5847 ****************************************************************************/
5848
5849 int reply_setattrE(connection_struct *conn, char *inbuf,char *outbuf, int size, int dum_buffsize)
5850 {
5851         struct timespec ts[2];
5852         int outsize = 0;
5853         files_struct *fsp = file_fsp(inbuf,smb_vwv0);
5854         START_PROFILE(SMBsetattrE);
5855
5856         outsize = set_message(inbuf,outbuf,0,0,False);
5857
5858         if(!fsp || (fsp->conn != conn)) {
5859                 END_PROFILE(SMBsetattrE);
5860                 return ERROR_DOS(ERRDOS,ERRbadfid);
5861         }
5862
5863         /*
5864          * Convert the DOS times into unix times. Ignore create
5865          * time as UNIX can't set this.
5866          */
5867
5868         ts[0] = convert_time_t_to_timespec(srv_make_unix_date2(inbuf+smb_vwv3)); /* atime. */
5869         ts[1] = convert_time_t_to_timespec(srv_make_unix_date2(inbuf+smb_vwv5)); /* mtime. */
5870   
5871         /* 
5872          * Patch from Ray Frush <frush@engr.colostate.edu>
5873          * Sometimes times are sent as zero - ignore them.
5874          */
5875
5876         if (null_timespec(ts[0]) && null_timespec(ts[1])) {
5877                 /* Ignore request */
5878                 if( DEBUGLVL( 3 ) ) {
5879                         dbgtext( "reply_setattrE fnum=%d ", fsp->fnum);
5880                         dbgtext( "ignoring zero request - not setting timestamps of 0\n" );
5881                 }
5882                 END_PROFILE(SMBsetattrE);
5883                 return(outsize);
5884         } else if (!null_timespec(ts[0]) && null_timespec(ts[1])) {
5885                 /* set modify time = to access time if modify time was unset */
5886                 ts[1] = ts[0];
5887         }
5888
5889         /* Set the date on this file */
5890         /* Should we set pending modtime here ? JRA */
5891         if(file_ntimes(conn, fsp->fsp_name, ts)) {
5892                 END_PROFILE(SMBsetattrE);
5893                 return ERROR_DOS(ERRDOS,ERRnoaccess);
5894         }
5895   
5896         DEBUG( 3, ( "reply_setattrE fnum=%d actime=%u modtime=%u\n",
5897                 fsp->fnum,
5898                 (unsigned int)ts[0].tv_sec,
5899                 (unsigned int)ts[1].tv_sec));
5900
5901         END_PROFILE(SMBsetattrE);
5902         return(outsize);
5903 }
5904
5905
5906 /* Back from the dead for OS/2..... JRA. */
5907
5908 /****************************************************************************
5909  Reply to a SMBwritebmpx (write block multiplex primary) request.
5910 ****************************************************************************/
5911
5912 int reply_writebmpx(connection_struct *conn, char *inbuf,char *outbuf, int size, int dum_buffsize)
5913 {
5914         size_t numtowrite;
5915         ssize_t nwritten = -1;
5916         int outsize = 0;
5917         SMB_OFF_T startpos;
5918         size_t tcount;
5919         BOOL write_through;
5920         int smb_doff;
5921         char *data;
5922         files_struct *fsp = file_fsp(inbuf,smb_vwv0);
5923         NTSTATUS status;
5924         START_PROFILE(SMBwriteBmpx);
5925
5926         CHECK_FSP(fsp,conn);
5927         if (!CHECK_WRITE(fsp)) {
5928                 return(ERROR_DOS(ERRDOS,ERRbadaccess));
5929         }
5930         if (HAS_CACHED_ERROR(fsp)) {
5931                 return(CACHED_ERROR(fsp));
5932         }
5933
5934         tcount = SVAL(inbuf,smb_vwv1);
5935         startpos = IVAL_TO_SMB_OFF_T(inbuf,smb_vwv3);
5936         write_through = BITSETW(inbuf+smb_vwv7,0);
5937         numtowrite = SVAL(inbuf,smb_vwv10);
5938         smb_doff = SVAL(inbuf,smb_vwv11);
5939
5940         data = smb_base(inbuf) + smb_doff;
5941
5942         /* If this fails we need to send an SMBwriteC response,
5943                 not an SMBwritebmpx - set this up now so we don't forget */
5944         SCVAL(outbuf,smb_com,SMBwritec);
5945
5946         if (is_locked(fsp,(uint32)SVAL(inbuf,smb_pid),(SMB_BIG_UINT)tcount,(SMB_BIG_UINT)startpos,WRITE_LOCK)) {
5947                 END_PROFILE(SMBwriteBmpx);
5948                 return(ERROR_DOS(ERRDOS,ERRlock));
5949         }
5950
5951         nwritten = write_file(fsp,data,startpos,numtowrite);
5952
5953         status = sync_file(conn, fsp, write_through);
5954         if (!NT_STATUS_IS_OK(status)) {
5955                 END_PROFILE(SMBwriteBmpx);
5956                 DEBUG(5,("reply_writebmpx: sync_file for %s returned %s\n",
5957                         fsp->fsp_name, nt_errstr(status) ));
5958                 return ERROR_NT(status);
5959         }
5960   
5961         if(nwritten < (ssize_t)numtowrite) {
5962                 END_PROFILE(SMBwriteBmpx);
5963                 return(UNIXERROR(ERRHRD,ERRdiskfull));
5964         }
5965
5966         /* If the maximum to be written to this file
5967                 is greater than what we just wrote then set
5968                 up a secondary struct to be attached to this
5969                 fd, we will use this to cache error messages etc. */
5970
5971         if((ssize_t)tcount > nwritten) {
5972                 write_bmpx_struct *wbms;
5973                 if(fsp->wbmpx_ptr != NULL)
5974                         wbms = fsp->wbmpx_ptr; /* Use an existing struct */
5975                 else
5976                         wbms = SMB_MALLOC_P(write_bmpx_struct);
5977                 if(!wbms) {
5978                         DEBUG(0,("Out of memory in reply_readmpx\n"));
5979                         END_PROFILE(SMBwriteBmpx);
5980                         return(ERROR_DOS(ERRSRV,ERRnoresource));
5981                 }
5982                 wbms->wr_mode = write_through;
5983                 wbms->wr_discard = False; /* No errors yet */
5984                 wbms->wr_total_written = nwritten;
5985                 wbms->wr_errclass = 0;
5986                 wbms->wr_error = 0;
5987                 fsp->wbmpx_ptr = wbms;
5988         }
5989
5990         /* We are returning successfully, set the message type back to
5991                 SMBwritebmpx */
5992         SCVAL(outbuf,smb_com,SMBwriteBmpx);
5993   
5994         outsize = set_message(inbuf,outbuf,1,0,True);
5995   
5996         SSVALS(outbuf,smb_vwv0,-1); /* We don't support smb_remaining */
5997   
5998         DEBUG( 3, ( "writebmpx fnum=%d num=%d wrote=%d\n",
5999                         fsp->fnum, (int)numtowrite, (int)nwritten ) );
6000
6001         if (write_through && tcount==nwritten) {
6002                 /* We need to send both a primary and a secondary response */
6003                 smb_setlen(inbuf,outbuf,outsize - 4);
6004                 show_msg(outbuf);
6005                 if (!send_smb(smbd_server_fd(),outbuf))
6006                         exit_server_cleanly("reply_writebmpx: send_smb failed.");
6007
6008                 /* Now the secondary */
6009                 outsize = set_message(inbuf,outbuf,1,0,True);
6010                 SCVAL(outbuf,smb_com,SMBwritec);
6011                 SSVAL(outbuf,smb_vwv0,nwritten);
6012         }
6013
6014         END_PROFILE(SMBwriteBmpx);
6015         return(outsize);
6016 }
6017
6018 /****************************************************************************
6019  Reply to a SMBwritebs (write block multiplex secondary) request.
6020 ****************************************************************************/
6021
6022 int reply_writebs(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize)
6023 {
6024         size_t numtowrite;
6025         ssize_t nwritten = -1;
6026         int outsize = 0;
6027         SMB_OFF_T startpos;
6028         size_t tcount;
6029         BOOL write_through;
6030         int smb_doff;
6031         char *data;
6032         write_bmpx_struct *wbms;
6033         BOOL send_response = False; 
6034         files_struct *fsp = file_fsp(inbuf,smb_vwv0);
6035         NTSTATUS status;
6036         START_PROFILE(SMBwriteBs);
6037
6038         CHECK_FSP(fsp,conn);
6039         if (!CHECK_WRITE(fsp)) {
6040                 return(ERROR_DOS(ERRDOS,ERRbadaccess));
6041         }
6042
6043         tcount = SVAL(inbuf,smb_vwv1);
6044         startpos = IVAL_TO_SMB_OFF_T(inbuf,smb_vwv2);
6045         numtowrite = SVAL(inbuf,smb_vwv6);
6046         smb_doff = SVAL(inbuf,smb_vwv7);
6047
6048         data = smb_base(inbuf) + smb_doff;
6049
6050         /* We need to send an SMBwriteC response, not an SMBwritebs */
6051         SCVAL(outbuf,smb_com,SMBwritec);
6052
6053         /* This fd should have an auxiliary struct attached,
6054                 check that it does */
6055         wbms = fsp->wbmpx_ptr;
6056         if(!wbms) {
6057                 END_PROFILE(SMBwriteBs);
6058                 return(-1);
6059         }
6060
6061         /* If write through is set we can return errors, else we must cache them */
6062         write_through = wbms->wr_mode;
6063
6064         /* Check for an earlier error */
6065         if(wbms->wr_discard) {
6066                 END_PROFILE(SMBwriteBs);
6067                 return -1; /* Just discard the packet */
6068         }
6069
6070         nwritten = write_file(fsp,data,startpos,numtowrite);
6071
6072         status = sync_file(conn, fsp, write_through);
6073   
6074         if (nwritten < (ssize_t)numtowrite || !NT_STATUS_IS_OK(status)) {
6075                 if(write_through) {
6076                         /* We are returning an error - we can delete the aux struct */
6077                         if (wbms)
6078                                 free((char *)wbms);
6079                         fsp->wbmpx_ptr = NULL;
6080                         END_PROFILE(SMBwriteBs);
6081                         return(ERROR_DOS(ERRHRD,ERRdiskfull));
6082                 }
6083                 wbms->wr_errclass = ERRHRD;
6084                 wbms->wr_error = ERRdiskfull;
6085                 wbms->wr_status = NT_STATUS_DISK_FULL;
6086                 wbms->wr_discard = True;
6087                 END_PROFILE(SMBwriteBs);
6088                 return -1;
6089         }
6090
6091         /* Increment the total written, if this matches tcount
6092                 we can discard the auxiliary struct (hurrah !) and return a writeC */
6093         wbms->wr_total_written += nwritten;
6094         if(wbms->wr_total_written >= tcount) {
6095                 if (write_through) {
6096                         outsize = set_message(inbuf,outbuf,1,0,True);
6097                         SSVAL(outbuf,smb_vwv0,wbms->wr_total_written);    
6098                         send_response = True;
6099                 }
6100
6101                 free((char *)wbms);
6102                 fsp->wbmpx_ptr = NULL;
6103         }
6104
6105         if(send_response) {
6106                 END_PROFILE(SMBwriteBs);
6107                 return(outsize);
6108         }
6109
6110         END_PROFILE(SMBwriteBs);
6111         return(-1);
6112 }
6113
6114 /****************************************************************************
6115  Reply to a SMBgetattrE.
6116 ****************************************************************************/
6117
6118 int reply_getattrE(connection_struct *conn, char *inbuf,char *outbuf, int size, int dum_buffsize)
6119 {
6120         SMB_STRUCT_STAT sbuf;
6121         int outsize = 0;
6122         int mode;
6123         files_struct *fsp = file_fsp(inbuf,smb_vwv0);
6124         START_PROFILE(SMBgetattrE);
6125
6126         outsize = set_message(inbuf,outbuf,11,0,True);
6127
6128         if(!fsp || (fsp->conn != conn)) {
6129                 END_PROFILE(SMBgetattrE);
6130                 return ERROR_DOS(ERRDOS,ERRbadfid);
6131         }
6132
6133         /* Do an fstat on this file */
6134         if(fsp_stat(fsp, &sbuf)) {
6135                 END_PROFILE(SMBgetattrE);
6136                 return(UNIXERROR(ERRDOS,ERRnoaccess));
6137         }
6138   
6139         mode = dos_mode(conn,fsp->fsp_name,&sbuf);
6140   
6141         /*
6142          * Convert the times into dos times. Set create
6143          * date to be last modify date as UNIX doesn't save
6144          * this.
6145          */
6146
6147         srv_put_dos_date2(outbuf,smb_vwv0,get_create_time(&sbuf,lp_fake_dir_create_times(SNUM(conn))));
6148         srv_put_dos_date2(outbuf,smb_vwv2,sbuf.st_atime);
6149         /* Should we check pending modtime here ? JRA */
6150         srv_put_dos_date2(outbuf,smb_vwv4,sbuf.st_mtime);
6151
6152         if (mode & aDIR) {
6153                 SIVAL(outbuf,smb_vwv6,0);
6154                 SIVAL(outbuf,smb_vwv8,0);
6155         } else {
6156                 uint32 allocation_size = get_allocation_size(conn,fsp, &sbuf);
6157                 SIVAL(outbuf,smb_vwv6,(uint32)sbuf.st_size);
6158                 SIVAL(outbuf,smb_vwv8,allocation_size);
6159         }
6160         SSVAL(outbuf,smb_vwv10, mode);
6161   
6162         DEBUG( 3, ( "reply_getattrE fnum=%d\n", fsp->fnum));
6163   
6164         END_PROFILE(SMBgetattrE);
6165         return(outsize);
6166 }