r22922: Move "normal_read:" label out of ifdef guard. Fix the build.
[abartlet/samba.git/.git] / source3 / 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)
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                                 FILE_SHARE_READ|FILE_SHARE_WRITE,
1816                                 FILE_OPEN,
1817                                 0,
1818                                 FILE_ATTRIBUTE_NORMAL,
1819                                 0,
1820                                 NULL, &fsp);
1821
1822         if (!NT_STATUS_IS_OK(status)) {
1823                 return status;
1824         }
1825         close_file(fsp,NORMAL_CLOSE);
1826         return NT_STATUS_OK;
1827 }
1828
1829 /*******************************************************************
1830  Check if a user is allowed to delete a file.
1831 ********************************************************************/
1832
1833 static NTSTATUS can_delete(connection_struct *conn, char *fname,
1834                            uint32 dirtype, BOOL can_defer)
1835 {
1836         SMB_STRUCT_STAT sbuf;
1837         uint32 fattr;
1838         files_struct *fsp;
1839         uint32 dirtype_orig = dirtype;
1840         NTSTATUS status;
1841
1842         DEBUG(10,("can_delete: %s, dirtype = %d\n", fname, dirtype ));
1843
1844         if (!CAN_WRITE(conn)) {
1845                 return NT_STATUS_MEDIA_WRITE_PROTECTED;
1846         }
1847
1848         if (SMB_VFS_LSTAT(conn,fname,&sbuf) != 0) {
1849                 return map_nt_error_from_unix(errno);
1850         }
1851
1852         fattr = dos_mode(conn,fname,&sbuf);
1853
1854         if (dirtype & FILE_ATTRIBUTE_NORMAL) {
1855                 dirtype = aDIR|aARCH|aRONLY;
1856         }
1857
1858         dirtype &= (aDIR|aARCH|aRONLY|aHIDDEN|aSYSTEM);
1859         if (!dirtype) {
1860                 return NT_STATUS_NO_SUCH_FILE;
1861         }
1862
1863         if (!dir_check_ftype(conn, fattr, dirtype)) {
1864                 if (fattr & aDIR) {
1865                         return NT_STATUS_FILE_IS_A_DIRECTORY;
1866                 }
1867                 return NT_STATUS_NO_SUCH_FILE;
1868         }
1869
1870         if (dirtype_orig & 0x8000) {
1871                 /* These will never be set for POSIX. */
1872                 return NT_STATUS_NO_SUCH_FILE;
1873         }
1874
1875 #if 0
1876         if ((fattr & dirtype) & FILE_ATTRIBUTE_DIRECTORY) {
1877                 return NT_STATUS_FILE_IS_A_DIRECTORY;
1878         }
1879
1880         if ((fattr & ~dirtype) & (FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM)) {
1881                 return NT_STATUS_NO_SUCH_FILE;
1882         }
1883
1884         if (dirtype & 0xFF00) {
1885                 /* These will never be set for POSIX. */
1886                 return NT_STATUS_NO_SUCH_FILE;
1887         }
1888
1889         dirtype &= 0xFF;
1890         if (!dirtype) {
1891                 return NT_STATUS_NO_SUCH_FILE;
1892         }
1893
1894         /* Can't delete a directory. */
1895         if (fattr & aDIR) {
1896                 return NT_STATUS_FILE_IS_A_DIRECTORY;
1897         }
1898 #endif
1899
1900 #if 0 /* JRATEST */
1901         else if (dirtype & aDIR) /* Asked for a directory and it isn't. */
1902                 return NT_STATUS_OBJECT_NAME_INVALID;
1903 #endif /* JRATEST */
1904
1905         /* Fix for bug #3035 from SATOH Fumiyasu <fumiyas@miraclelinux.com>
1906
1907           On a Windows share, a file with read-only dosmode can be opened with
1908           DELETE_ACCESS. But on a Samba share (delete readonly = no), it
1909           fails with NT_STATUS_CANNOT_DELETE error.
1910
1911           This semantic causes a problem that a user can not
1912           rename a file with read-only dosmode on a Samba share
1913           from a Windows command prompt (i.e. cmd.exe, but can rename
1914           from Windows Explorer).
1915         */
1916
1917         if (!lp_delete_readonly(SNUM(conn))) {
1918                 if (fattr & aRONLY) {
1919                         return NT_STATUS_CANNOT_DELETE;
1920                 }
1921         }
1922
1923         /* On open checks the open itself will check the share mode, so
1924            don't do it here as we'll get it wrong. */
1925
1926         status = open_file_ntcreate(conn, fname, &sbuf,
1927                                     DELETE_ACCESS,
1928                                     FILE_SHARE_NONE,
1929                                     FILE_OPEN,
1930                                     0,
1931                                     FILE_ATTRIBUTE_NORMAL,
1932                                     can_defer ? 0 : INTERNAL_OPEN_ONLY,
1933                                     NULL, &fsp);
1934
1935         if (NT_STATUS_IS_OK(status)) {
1936                 close_file(fsp,NORMAL_CLOSE);
1937         }
1938         return status;
1939 }
1940
1941 /****************************************************************************
1942  The guts of the unlink command, split out so it may be called by the NT SMB
1943  code.
1944 ****************************************************************************/
1945
1946 NTSTATUS unlink_internals(connection_struct *conn, uint32 dirtype,
1947                           char *name, BOOL has_wild, BOOL can_defer)
1948 {
1949         pstring directory;
1950         pstring mask;
1951         char *p;
1952         int count=0;
1953         NTSTATUS status = NT_STATUS_OK;
1954         SMB_STRUCT_STAT sbuf;
1955         
1956         *directory = *mask = 0;
1957         
1958         status = unix_convert(conn, name, has_wild, NULL, &sbuf);
1959         if (!NT_STATUS_IS_OK(status)) {
1960                 return status;
1961         }
1962         
1963         p = strrchr_m(name,'/');
1964         if (!p) {
1965                 pstrcpy(directory,".");
1966                 pstrcpy(mask,name);
1967         } else {
1968                 *p = 0;
1969                 pstrcpy(directory,name);
1970                 pstrcpy(mask,p+1);
1971         }
1972         
1973         /*
1974          * We should only check the mangled cache
1975          * here if unix_convert failed. This means
1976          * that the path in 'mask' doesn't exist
1977          * on the file system and so we need to look
1978          * for a possible mangle. This patch from
1979          * Tine Smukavec <valentin.smukavec@hermes.si>.
1980          */
1981         
1982         if (!VALID_STAT(sbuf) && mangle_is_mangled(mask,conn->params))
1983                 mangle_check_cache( mask, sizeof(pstring)-1, conn->params );
1984         
1985         if (!has_wild) {
1986                 pstrcat(directory,"/");
1987                 pstrcat(directory,mask);
1988                 if (dirtype == 0) {
1989                         dirtype = FILE_ATTRIBUTE_NORMAL;
1990                 }
1991
1992                 status = check_name(conn, directory);
1993                 if (!NT_STATUS_IS_OK(status)) {
1994                         return status;
1995                 }
1996
1997                 status = can_delete(conn,directory,dirtype,can_defer);
1998                 if (!NT_STATUS_IS_OK(status)) {
1999                         return status;
2000                 }
2001
2002                 if (SMB_VFS_UNLINK(conn,directory) == 0) {
2003                         count++;
2004                         notify_fname(conn, NOTIFY_ACTION_REMOVED,
2005                                      FILE_NOTIFY_CHANGE_FILE_NAME,
2006                                      directory);
2007                 }
2008         } else {
2009                 struct smb_Dir *dir_hnd = NULL;
2010                 long offset = 0;
2011                 const char *dname;
2012                 
2013                 if ((dirtype & SAMBA_ATTRIBUTES_MASK) == aDIR) {
2014                         return NT_STATUS_OBJECT_NAME_INVALID;
2015                 }
2016
2017                 if (strequal(mask,"????????.???")) {
2018                         pstrcpy(mask,"*");
2019                 }
2020
2021                 status = check_name(conn, directory);
2022                 if (!NT_STATUS_IS_OK(status)) {
2023                         return status;
2024                 }
2025
2026                 dir_hnd = OpenDir(conn, directory, mask, dirtype);
2027                 if (dir_hnd == NULL) {
2028                         return map_nt_error_from_unix(errno);
2029                 }
2030                 
2031                 /* XXXX the CIFS spec says that if bit0 of the flags2 field is set then
2032                    the pattern matches against the long name, otherwise the short name 
2033                    We don't implement this yet XXXX
2034                 */
2035                 
2036                 status = NT_STATUS_NO_SUCH_FILE;
2037
2038                 while ((dname = ReadDirName(dir_hnd, &offset))) {
2039                         SMB_STRUCT_STAT st;
2040                         pstring fname;
2041                         pstrcpy(fname,dname);
2042
2043                         if (!is_visible_file(conn, directory, dname, &st, True)) {
2044                                 continue;
2045                         }
2046
2047                         /* Quick check for "." and ".." */
2048                         if (fname[0] == '.') {
2049                                 if (!fname[1] || (fname[1] == '.' && !fname[2])) {
2050                                         continue;
2051                                 }
2052                         }
2053
2054                         if(!mask_match(fname, mask, conn->case_sensitive)) {
2055                                 continue;
2056                         }
2057                                 
2058                         slprintf(fname,sizeof(fname)-1, "%s/%s",directory,dname);
2059
2060                         status = check_name(conn, fname);
2061                         if (!NT_STATUS_IS_OK(status)) {
2062                                 CloseDir(dir_hnd);
2063                                 return status;
2064                         }
2065
2066                         status = can_delete(conn, fname, dirtype, can_defer);
2067                         if (!NT_STATUS_IS_OK(status)) {
2068                                 continue;
2069                         }
2070                         if (SMB_VFS_UNLINK(conn,fname) == 0) {
2071                                 count++;
2072                                 DEBUG(3,("unlink_internals: succesful unlink "
2073                                          "[%s]\n",fname));
2074                                 notify_fname(conn, NOTIFY_ACTION_REMOVED,
2075                                              FILE_NOTIFY_CHANGE_FILE_NAME,
2076                                              fname);
2077                         }
2078                                 
2079                 }
2080                 CloseDir(dir_hnd);
2081         }
2082         
2083         if (count == 0 && NT_STATUS_IS_OK(status)) {
2084                 status = map_nt_error_from_unix(errno);
2085         }
2086
2087         return status;
2088 }
2089
2090 /****************************************************************************
2091  Reply to a unlink
2092 ****************************************************************************/
2093
2094 int reply_unlink(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, 
2095                  int dum_buffsize)
2096 {
2097         int outsize = 0;
2098         pstring name;
2099         uint32 dirtype;
2100         NTSTATUS status;
2101         BOOL path_contains_wcard = False;
2102
2103         START_PROFILE(SMBunlink);
2104
2105         dirtype = SVAL(inbuf,smb_vwv0);
2106         
2107         srvstr_get_path_wcard(inbuf, name, smb_buf(inbuf) + 1, sizeof(name), 0, STR_TERMINATE, &status, &path_contains_wcard);
2108         if (!NT_STATUS_IS_OK(status)) {
2109                 END_PROFILE(SMBunlink);
2110                 return ERROR_NT(status);
2111         }
2112
2113         status = resolve_dfspath_wcard(conn, SVAL(inbuf,smb_flg2) & FLAGS2_DFS_PATHNAMES, name, &path_contains_wcard);
2114         if (!NT_STATUS_IS_OK(status)) {
2115                 END_PROFILE(SMBunlink);
2116                 if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) {
2117                         return ERROR_BOTH(NT_STATUS_PATH_NOT_COVERED, ERRSRV, ERRbadpath);
2118                 }
2119                 return ERROR_NT(status);
2120         }
2121         
2122         DEBUG(3,("reply_unlink : %s\n",name));
2123         
2124         status = unlink_internals(conn, dirtype, name, path_contains_wcard,
2125                                   True);
2126         if (!NT_STATUS_IS_OK(status)) {
2127                 if (open_was_deferred(SVAL(inbuf,smb_mid))) {
2128                         /* We have re-scheduled this call. */
2129                         return -1;
2130                 }
2131                 return ERROR_NT(status);
2132         }
2133
2134         outsize = set_message(inbuf,outbuf,0,0,False);
2135   
2136         END_PROFILE(SMBunlink);
2137         return outsize;
2138 }
2139
2140 /****************************************************************************
2141  Fail for readbraw.
2142 ****************************************************************************/
2143
2144 static void fail_readraw(void)
2145 {
2146         pstring errstr;
2147         slprintf(errstr, sizeof(errstr)-1, "FAIL ! reply_readbraw: socket write fail (%s)",
2148                 strerror(errno) );
2149         exit_server_cleanly(errstr);
2150 }
2151
2152 /****************************************************************************
2153  Fake (read/write) sendfile. Returns -1 on read or write fail.
2154 ****************************************************************************/
2155
2156 static ssize_t fake_sendfile(files_struct *fsp, SMB_OFF_T startpos, size_t nread, char *buf, size_t bufsize)
2157 {
2158         size_t tosend = nread;
2159
2160         while (tosend > 0) {
2161                 ssize_t ret;
2162                 size_t cur_read;
2163
2164                 if (tosend > bufsize) {
2165                         cur_read = bufsize;
2166                 } else {
2167                         cur_read = tosend;
2168                 }
2169                 ret = read_file(fsp,buf,startpos,cur_read);
2170                 if (ret == -1) {
2171                         return -1;
2172                 }
2173
2174                 /* If we had a short read, fill with zeros. */
2175                 if (ret < cur_read) {
2176                         memset(buf, '\0', cur_read - ret);
2177                 }
2178
2179                 if (write_data(smbd_server_fd(),buf,cur_read) != cur_read) {
2180                         return -1;
2181                 }
2182                 tosend -= cur_read;
2183                 startpos += cur_read;
2184         }
2185
2186         return (ssize_t)nread;
2187 }
2188
2189 /****************************************************************************
2190  Use sendfile in readbraw.
2191 ****************************************************************************/
2192
2193 void send_file_readbraw(connection_struct *conn, files_struct *fsp, SMB_OFF_T startpos, size_t nread,
2194                 ssize_t mincount, char *outbuf, int out_buffsize)
2195 {
2196         ssize_t ret=0;
2197
2198 #if defined(WITH_SENDFILE)
2199         /*
2200          * We can only use sendfile on a non-chained packet 
2201          * but we can use on a non-oplocked file. tridge proved this
2202          * on a train in Germany :-). JRA.
2203          * reply_readbraw has already checked the length.
2204          */
2205
2206         if ( (chain_size == 0) && (nread > 0) &&
2207             (fsp->wcp == NULL) && lp_use_sendfile(SNUM(conn)) ) {
2208                 DATA_BLOB header;
2209
2210                 _smb_setlen(outbuf,nread);
2211                 header.data = (uint8 *)outbuf;
2212                 header.length = 4;
2213                 header.free = NULL;
2214
2215                 if ( SMB_VFS_SENDFILE( smbd_server_fd(), fsp, fsp->fh->fd, &header, startpos, nread) == -1) {
2216                         /* Returning ENOSYS means no data at all was sent. Do this as a normal read. */
2217                         if (errno == ENOSYS) {
2218                                 goto normal_readbraw;
2219                         }
2220
2221                         /*
2222                          * Special hack for broken Linux with no working sendfile. If we
2223                          * return EINTR we sent the header but not the rest of the data.
2224                          * Fake this up by doing read/write calls.
2225                          */
2226                         if (errno == EINTR) {
2227                                 /* Ensure we don't do this again. */
2228                                 set_use_sendfile(SNUM(conn), False);
2229                                 DEBUG(0,("send_file_readbraw: sendfile not available. Faking..\n"));
2230
2231                                 if (fake_sendfile(fsp, startpos, nread, outbuf + 4, out_buffsize - 4) == -1) {
2232                                         DEBUG(0,("send_file_readbraw: fake_sendfile failed for file %s (%s).\n",
2233                                                 fsp->fsp_name, strerror(errno) ));
2234                                         exit_server_cleanly("send_file_readbraw fake_sendfile failed");
2235                                 }
2236                                 return;
2237                         }
2238
2239                         DEBUG(0,("send_file_readbraw: sendfile failed for file %s (%s). Terminating\n",
2240                                 fsp->fsp_name, strerror(errno) ));
2241                         exit_server_cleanly("send_file_readbraw sendfile failed");
2242                 }
2243
2244                 return;
2245         }
2246
2247   normal_readbraw:
2248
2249 #endif
2250
2251         if (nread > 0) {
2252                 ret = read_file(fsp,outbuf+4,startpos,nread);
2253 #if 0 /* mincount appears to be ignored in a W2K server. JRA. */
2254                 if (ret < mincount)
2255                         ret = 0;
2256 #else
2257                 if (ret < nread)
2258                         ret = 0;
2259 #endif
2260         }
2261
2262         _smb_setlen(outbuf,ret);
2263         if (write_data(smbd_server_fd(),outbuf,4+ret) != 4+ret)
2264                 fail_readraw();
2265 }
2266
2267 /****************************************************************************
2268  Reply to a readbraw (core+ protocol).
2269 ****************************************************************************/
2270
2271 int reply_readbraw(connection_struct *conn, char *inbuf, char *outbuf, int dum_size, int out_buffsize)
2272 {
2273         ssize_t maxcount,mincount;
2274         size_t nread = 0;
2275         SMB_OFF_T startpos;
2276         char *header = outbuf;
2277         files_struct *fsp;
2278         START_PROFILE(SMBreadbraw);
2279
2280         if (srv_is_signing_active()) {
2281                 exit_server_cleanly("reply_readbraw: SMB signing is active - raw reads/writes are disallowed.");
2282         }
2283
2284         /*
2285          * Special check if an oplock break has been issued
2286          * and the readraw request croses on the wire, we must
2287          * return a zero length response here.
2288          */
2289
2290         fsp = file_fsp(inbuf,smb_vwv0);
2291
2292         if (!FNUM_OK(fsp,conn) || !fsp->can_read) {
2293                 /*
2294                  * fsp could be NULL here so use the value from the packet. JRA.
2295                  */
2296                 DEBUG(3,("fnum %d not open in readbraw - cache prime?\n",(int)SVAL(inbuf,smb_vwv0)));
2297                 _smb_setlen(header,0);
2298                 if (write_data(smbd_server_fd(),header,4) != 4)
2299                         fail_readraw();
2300                 END_PROFILE(SMBreadbraw);
2301                 return(-1);
2302         }
2303
2304         CHECK_FSP(fsp,conn);
2305
2306         flush_write_cache(fsp, READRAW_FLUSH);
2307
2308         startpos = IVAL_TO_SMB_OFF_T(inbuf,smb_vwv1);
2309         if(CVAL(inbuf,smb_wct) == 10) {
2310                 /*
2311                  * This is a large offset (64 bit) read.
2312                  */
2313 #ifdef LARGE_SMB_OFF_T
2314
2315                 startpos |= (((SMB_OFF_T)IVAL(inbuf,smb_vwv8)) << 32);
2316
2317 #else /* !LARGE_SMB_OFF_T */
2318
2319                 /*
2320                  * Ensure we haven't been sent a >32 bit offset.
2321                  */
2322
2323                 if(IVAL(inbuf,smb_vwv8) != 0) {
2324                         DEBUG(0,("readbraw - large offset (%x << 32) used and we don't support \
2325 64 bit offsets.\n", (unsigned int)IVAL(inbuf,smb_vwv8) ));
2326                         _smb_setlen(header,0);
2327                         if (write_data(smbd_server_fd(),header,4) != 4)
2328                                 fail_readraw();
2329                         END_PROFILE(SMBreadbraw);
2330                         return(-1);
2331                 }
2332
2333 #endif /* LARGE_SMB_OFF_T */
2334
2335                 if(startpos < 0) {
2336                         DEBUG(0,("readbraw - negative 64 bit readraw offset (%.0f) !\n", (double)startpos ));
2337                         _smb_setlen(header,0);
2338                         if (write_data(smbd_server_fd(),header,4) != 4)
2339                                 fail_readraw();
2340                         END_PROFILE(SMBreadbraw);
2341                         return(-1);
2342                 }      
2343         }
2344         maxcount = (SVAL(inbuf,smb_vwv3) & 0xFFFF);
2345         mincount = (SVAL(inbuf,smb_vwv4) & 0xFFFF);
2346
2347         /* ensure we don't overrun the packet size */
2348         maxcount = MIN(65535,maxcount);
2349
2350         if (!is_locked(fsp,(uint32)SVAL(inbuf,smb_pid),(SMB_BIG_UINT)maxcount,(SMB_BIG_UINT)startpos, READ_LOCK)) {
2351                 SMB_STRUCT_STAT st;
2352                 SMB_OFF_T size = 0;
2353   
2354                 if (SMB_VFS_FSTAT(fsp,fsp->fh->fd,&st) == 0) {
2355                         size = st.st_size;
2356                 }
2357
2358                 if (startpos >= size) {
2359                         nread = 0;
2360                 } else {
2361                         nread = MIN(maxcount,(size - startpos));          
2362                 }
2363         }
2364
2365 #if 0 /* mincount appears to be ignored in a W2K server. JRA. */
2366         if (nread < mincount)
2367                 nread = 0;
2368 #endif
2369   
2370         DEBUG( 3, ( "readbraw fnum=%d start=%.0f max=%lu min=%lu nread=%lu\n", fsp->fnum, (double)startpos,
2371                                 (unsigned long)maxcount, (unsigned long)mincount, (unsigned long)nread ) );
2372   
2373         send_file_readbraw(conn, fsp, startpos, nread, mincount, outbuf, out_buffsize);
2374
2375         DEBUG(5,("readbraw finished\n"));
2376         END_PROFILE(SMBreadbraw);
2377         return -1;
2378 }
2379
2380 #undef DBGC_CLASS
2381 #define DBGC_CLASS DBGC_LOCKING
2382
2383 /****************************************************************************
2384  Reply to a lockread (core+ protocol).
2385 ****************************************************************************/
2386
2387 int reply_lockread(connection_struct *conn, char *inbuf,char *outbuf, int length, int dum_buffsiz)
2388 {
2389         ssize_t nread = -1;
2390         char *data;
2391         int outsize = 0;
2392         SMB_OFF_T startpos;
2393         size_t numtoread;
2394         NTSTATUS status;
2395         files_struct *fsp = file_fsp(inbuf,smb_vwv0);
2396         struct byte_range_lock *br_lck = NULL;
2397         START_PROFILE(SMBlockread);
2398
2399         CHECK_FSP(fsp,conn);
2400         if (!CHECK_READ(fsp,inbuf)) {
2401                 return(ERROR_DOS(ERRDOS,ERRbadaccess));
2402         }
2403
2404         release_level_2_oplocks_on_change(fsp);
2405
2406         numtoread = SVAL(inbuf,smb_vwv1);
2407         startpos = IVAL_TO_SMB_OFF_T(inbuf,smb_vwv2);
2408   
2409         outsize = set_message(inbuf,outbuf,5,3,True);
2410         numtoread = MIN(BUFFER_SIZE-outsize,numtoread);
2411         data = smb_buf(outbuf) + 3;
2412         
2413         /*
2414          * NB. Discovered by Menny Hamburger at Mainsoft. This is a core+
2415          * protocol request that predates the read/write lock concept. 
2416          * Thus instead of asking for a read lock here we need to ask
2417          * for a write lock. JRA.
2418          * Note that the requested lock size is unaffected by max_recv.
2419          */
2420         
2421         br_lck = do_lock(smbd_messaging_context(),
2422                         fsp,
2423                         (uint32)SVAL(inbuf,smb_pid), 
2424                         (SMB_BIG_UINT)numtoread,
2425                         (SMB_BIG_UINT)startpos,
2426                         WRITE_LOCK,
2427                         WINDOWS_LOCK,
2428                         False, /* Non-blocking lock. */
2429                         &status);
2430         TALLOC_FREE(br_lck);
2431
2432         if (NT_STATUS_V(status)) {
2433                 END_PROFILE(SMBlockread);
2434                 return ERROR_NT(status);
2435         }
2436
2437         /*
2438          * However the requested READ size IS affected by max_recv. Insanity.... JRA.
2439          */
2440
2441         if (numtoread > max_recv) {
2442                 DEBUG(0,("reply_lockread: requested read size (%u) is greater than maximum allowed (%u). \
2443 Returning short read of maximum allowed for compatibility with Windows 2000.\n",
2444                         (unsigned int)numtoread, (unsigned int)max_recv ));
2445                 numtoread = MIN(numtoread,max_recv);
2446         }
2447         nread = read_file(fsp,data,startpos,numtoread);
2448
2449         if (nread < 0) {
2450                 END_PROFILE(SMBlockread);
2451                 return(UNIXERROR(ERRDOS,ERRnoaccess));
2452         }
2453         
2454         outsize += nread;
2455         SSVAL(outbuf,smb_vwv0,nread);
2456         SSVAL(outbuf,smb_vwv5,nread+3);
2457         SSVAL(smb_buf(outbuf),1,nread);
2458         
2459         DEBUG(3,("lockread fnum=%d num=%d nread=%d\n",
2460                  fsp->fnum, (int)numtoread, (int)nread));
2461
2462         END_PROFILE(SMBlockread);
2463         return(outsize);
2464 }
2465
2466 #undef DBGC_CLASS
2467 #define DBGC_CLASS DBGC_ALL
2468
2469 /****************************************************************************
2470  Reply to a read.
2471 ****************************************************************************/
2472
2473 int reply_read(connection_struct *conn, char *inbuf,char *outbuf, int size, int dum_buffsize)
2474 {
2475         size_t numtoread;
2476         ssize_t nread = 0;
2477         char *data;
2478         SMB_OFF_T startpos;
2479         int outsize = 0;
2480         files_struct *fsp = file_fsp(inbuf,smb_vwv0);
2481         START_PROFILE(SMBread);
2482
2483         CHECK_FSP(fsp,conn);
2484         if (!CHECK_READ(fsp,inbuf)) {
2485                 return(ERROR_DOS(ERRDOS,ERRbadaccess));
2486         }
2487
2488         numtoread = SVAL(inbuf,smb_vwv1);
2489         startpos = IVAL_TO_SMB_OFF_T(inbuf,smb_vwv2);
2490
2491         outsize = set_message(inbuf,outbuf,5,3,True);
2492         numtoread = MIN(BUFFER_SIZE-outsize,numtoread);
2493         /*
2494          * The requested read size cannot be greater than max_recv. JRA.
2495          */
2496         if (numtoread > max_recv) {
2497                 DEBUG(0,("reply_read: requested read size (%u) is greater than maximum allowed (%u). \
2498 Returning short read of maximum allowed for compatibility with Windows 2000.\n",
2499                         (unsigned int)numtoread, (unsigned int)max_recv ));
2500                 numtoread = MIN(numtoread,max_recv);
2501         }
2502
2503         data = smb_buf(outbuf) + 3;
2504   
2505         if (is_locked(fsp,(uint32)SVAL(inbuf,smb_pid),(SMB_BIG_UINT)numtoread,(SMB_BIG_UINT)startpos, READ_LOCK)) {
2506                 END_PROFILE(SMBread);
2507                 return ERROR_DOS(ERRDOS,ERRlock);
2508         }
2509
2510         if (numtoread > 0)
2511                 nread = read_file(fsp,data,startpos,numtoread);
2512
2513         if (nread < 0) {
2514                 END_PROFILE(SMBread);
2515                 return(UNIXERROR(ERRDOS,ERRnoaccess));
2516         }
2517   
2518         outsize += nread;
2519         SSVAL(outbuf,smb_vwv0,nread);
2520         SSVAL(outbuf,smb_vwv5,nread+3);
2521         SCVAL(smb_buf(outbuf),0,1);
2522         SSVAL(smb_buf(outbuf),1,nread);
2523   
2524         DEBUG( 3, ( "read fnum=%d num=%d nread=%d\n",
2525                 fsp->fnum, (int)numtoread, (int)nread ) );
2526
2527         END_PROFILE(SMBread);
2528         return(outsize);
2529 }
2530
2531 /****************************************************************************
2532  Setup readX header.
2533 ****************************************************************************/
2534
2535 static int setup_readX_header(char *inbuf, char *outbuf, size_t smb_maxcnt)
2536 {
2537         int outsize;
2538         char *data = smb_buf(outbuf);
2539
2540         SSVAL(outbuf,smb_vwv2,0xFFFF); /* Remaining - must be -1. */
2541         SSVAL(outbuf,smb_vwv5,smb_maxcnt);
2542         SSVAL(outbuf,smb_vwv6,smb_offset(data,outbuf));
2543         SSVAL(outbuf,smb_vwv7,(smb_maxcnt >> 16));
2544         SSVAL(smb_buf(outbuf),-2,smb_maxcnt);
2545         SCVAL(outbuf,smb_vwv0,0xFF);
2546         outsize = set_message(inbuf, outbuf,12,smb_maxcnt,False);
2547         /* Reset the outgoing length, set_message truncates at 0x1FFFF. */
2548         _smb_setlen_large(outbuf,(smb_size + 12*2 + smb_maxcnt - 4));
2549         return outsize;
2550 }
2551
2552 /****************************************************************************
2553  Reply to a read and X - possibly using sendfile.
2554 ****************************************************************************/
2555
2556 int send_file_readX(connection_struct *conn, char *inbuf,char *outbuf,int length, int len_outbuf,
2557                 files_struct *fsp, SMB_OFF_T startpos, size_t smb_maxcnt)
2558 {
2559         SMB_STRUCT_STAT sbuf;
2560         int outsize = 0;
2561         ssize_t nread = -1;
2562         char *data = smb_buf(outbuf);
2563
2564         if(SMB_VFS_FSTAT(fsp,fsp->fh->fd, &sbuf) == -1) {
2565                 return(UNIXERROR(ERRDOS,ERRnoaccess));
2566         }
2567
2568         if (startpos > sbuf.st_size) {
2569                 smb_maxcnt = 0;
2570         }
2571
2572         if (smb_maxcnt > (sbuf.st_size - startpos)) {
2573                 smb_maxcnt = (sbuf.st_size - startpos);
2574         }
2575
2576         if (smb_maxcnt == 0) {
2577                 goto normal_read;
2578         }
2579
2580 #if defined(WITH_SENDFILE)
2581         /*
2582          * We can only use sendfile on a non-chained packet 
2583          * but we can use on a non-oplocked file. tridge proved this
2584          * on a train in Germany :-). JRA.
2585          */
2586
2587         if ((chain_size == 0) && (CVAL(inbuf,smb_vwv0) == 0xFF) &&
2588             lp_use_sendfile(SNUM(conn)) && (fsp->wcp == NULL) ) {
2589                 DATA_BLOB header;
2590
2591                 /* 
2592                  * Set up the packet header before send. We
2593                  * assume here the sendfile will work (get the
2594                  * correct amount of data).
2595                  */
2596
2597                 setup_readX_header(inbuf,outbuf,smb_maxcnt);
2598                 set_message(inbuf,outbuf,12,smb_maxcnt,False);
2599                 header.data = (uint8 *)outbuf;
2600                 header.length = data - outbuf;
2601                 header.free = NULL;
2602
2603                 if ((nread = SMB_VFS_SENDFILE( smbd_server_fd(), fsp, fsp->fh->fd, &header, startpos, smb_maxcnt)) == -1) {
2604                         /* Returning ENOSYS means no data at all was sent. Do this as a normal read. */
2605                         if (errno == ENOSYS) {
2606                                 goto normal_read;
2607                         }
2608
2609                         /*
2610                          * Special hack for broken Linux with no working sendfile. If we
2611                          * return EINTR we sent the header but not the rest of the data.
2612                          * Fake this up by doing read/write calls.
2613                          */
2614
2615                         if (errno == EINTR) {
2616                                 /* Ensure we don't do this again. */
2617                                 set_use_sendfile(SNUM(conn), False);
2618                                 DEBUG(0,("send_file_readX: sendfile not available. Faking..\n"));
2619
2620                                 if ((nread = fake_sendfile(fsp, startpos, smb_maxcnt, data,
2621                                                         len_outbuf - (data-outbuf))) == -1) {
2622                                         DEBUG(0,("send_file_readX: fake_sendfile failed for file %s (%s).\n",
2623                                                 fsp->fsp_name, strerror(errno) ));
2624                                         exit_server_cleanly("send_file_readX: fake_sendfile failed");
2625                                 }
2626                                 DEBUG( 3, ( "send_file_readX: fake_sendfile fnum=%d max=%d nread=%d\n",
2627                                         fsp->fnum, (int)smb_maxcnt, (int)nread ) );
2628                                 /* Returning -1 here means successful sendfile. */
2629                                 return -1;
2630                         }
2631
2632                         DEBUG(0,("send_file_readX: sendfile failed for file %s (%s). Terminating\n",
2633                                 fsp->fsp_name, strerror(errno) ));
2634                         exit_server_cleanly("send_file_readX sendfile failed");
2635                 }
2636
2637                 DEBUG( 3, ( "send_file_readX: sendfile fnum=%d max=%d nread=%d\n",
2638                         fsp->fnum, (int)smb_maxcnt, (int)nread ) );
2639                 /* Returning -1 here means successful sendfile. */
2640                 return -1;
2641         }
2642
2643 #endif
2644
2645   normal_read:
2646
2647         if ((smb_maxcnt && 0xFF0000) > 0x10000) {
2648                 int sendlen = setup_readX_header(inbuf,outbuf,smb_maxcnt) - smb_maxcnt;
2649                 /* Send out the header. */
2650                 if (write_data(smbd_server_fd(),outbuf,sendlen) != sendlen) {
2651                         DEBUG(0,("send_file_readX: write_data failed for file %s (%s). Terminating\n",
2652                                 fsp->fsp_name, strerror(errno) ));
2653                         exit_server_cleanly("send_file_readX sendfile failed");
2654                 }
2655                 if ((nread = fake_sendfile(fsp, startpos, smb_maxcnt, data,
2656                                         len_outbuf - (data-outbuf))) == -1) {
2657                         DEBUG(0,("send_file_readX: fake_sendfile failed for file %s (%s).\n",
2658                                 fsp->fsp_name, strerror(errno) ));
2659                         exit_server_cleanly("send_file_readX: fake_sendfile failed");
2660                 }
2661                 return -1;
2662         } else {
2663                 nread = read_file(fsp,data,startpos,smb_maxcnt);
2664
2665                 if (nread < 0) {
2666                         return(UNIXERROR(ERRDOS,ERRnoaccess));
2667                 }
2668
2669                 outsize = set_message(inbuf, outbuf,12,nread,False);
2670                 SSVAL(outbuf,smb_vwv2,0xFFFF); /* Remaining - must be -1. */
2671                 SSVAL(outbuf,smb_vwv5,nread);
2672                 SSVAL(outbuf,smb_vwv6,smb_offset(data,outbuf));
2673                 SSVAL(outbuf,smb_vwv7,((nread >> 16) & 1));
2674                 SSVAL(smb_buf(outbuf),-2,nread);
2675
2676                 DEBUG( 3, ( "send_file_readX fnum=%d max=%d nread=%d\n",
2677                         fsp->fnum, (int)smb_maxcnt, (int)nread ) );
2678
2679                 /* Returning the number of bytes we want to send back - including header. */
2680                 return outsize;
2681         }
2682 }
2683
2684 /****************************************************************************
2685  Reply to a read and X.
2686 ****************************************************************************/
2687
2688 int reply_read_and_X(connection_struct *conn, char *inbuf,char *outbuf,int length,int bufsize)
2689 {
2690         files_struct *fsp = file_fsp(inbuf,smb_vwv2);
2691         SMB_OFF_T startpos = IVAL_TO_SMB_OFF_T(inbuf,smb_vwv3);
2692         ssize_t nread = -1;
2693         size_t smb_maxcnt = SVAL(inbuf,smb_vwv5);
2694         BOOL big_readX = False;
2695 #if 0
2696         size_t smb_mincnt = SVAL(inbuf,smb_vwv6);
2697 #endif
2698
2699         START_PROFILE(SMBreadX);
2700
2701         /* If it's an IPC, pass off the pipe handler. */
2702         if (IS_IPC(conn)) {
2703                 END_PROFILE(SMBreadX);
2704                 return reply_pipe_read_and_X(inbuf,outbuf,length,bufsize);
2705         }
2706
2707         CHECK_FSP(fsp,conn);
2708         if (!CHECK_READ(fsp,inbuf)) {
2709                 return(ERROR_DOS(ERRDOS,ERRbadaccess));
2710         }
2711
2712         set_message(inbuf,outbuf,12,0,True);
2713
2714         if (global_client_caps & CAP_LARGE_READX) {
2715                 size_t upper_size = SVAL(inbuf,smb_vwv7);
2716                 smb_maxcnt |= (upper_size<<16);
2717                 if (upper_size > 1) {
2718                         /* Can't do this on a chained packet. */
2719                         if ((CVAL(inbuf,smb_vwv0) != 0xFF)) {
2720                                 return ERROR_NT(NT_STATUS_NOT_SUPPORTED);
2721                         }
2722                         /* We currently don't do this on signed or sealed data. */
2723                         if (srv_is_signing_active() || srv_encryption_on()) {
2724                                 return ERROR_NT(NT_STATUS_NOT_SUPPORTED);
2725                         }
2726                         big_readX = True;
2727                 }
2728         }
2729
2730         if(CVAL(inbuf,smb_wct) == 12) {
2731 #ifdef LARGE_SMB_OFF_T
2732                 /*
2733                  * This is a large offset (64 bit) read.
2734                  */
2735                 startpos |= (((SMB_OFF_T)IVAL(inbuf,smb_vwv10)) << 32);
2736
2737 #else /* !LARGE_SMB_OFF_T */
2738
2739                 /*
2740                  * Ensure we haven't been sent a >32 bit offset.
2741                  */
2742
2743                 if(IVAL(inbuf,smb_vwv10) != 0) {
2744                         DEBUG(0,("reply_read_and_X - large offset (%x << 32) used and we don't support \
2745 64 bit offsets.\n", (unsigned int)IVAL(inbuf,smb_vwv10) ));
2746                         END_PROFILE(SMBreadX);
2747                         return ERROR_DOS(ERRDOS,ERRbadaccess);
2748                 }
2749
2750 #endif /* LARGE_SMB_OFF_T */
2751
2752         }
2753
2754         if (is_locked(fsp,(uint32)SVAL(inbuf,smb_pid),(SMB_BIG_UINT)smb_maxcnt,(SMB_BIG_UINT)startpos, READ_LOCK)) {
2755                 END_PROFILE(SMBreadX);
2756                 return ERROR_DOS(ERRDOS,ERRlock);
2757         }
2758
2759         if (!big_readX && schedule_aio_read_and_X(conn, inbuf, outbuf, length, bufsize, fsp, startpos, smb_maxcnt)) {
2760                 END_PROFILE(SMBreadX);
2761                 return -1;
2762         }
2763
2764         nread = send_file_readX(conn, inbuf, outbuf, length, bufsize, fsp, startpos, smb_maxcnt);
2765         /* Only call chain_reply if not an error. */
2766         if (nread != -1 && SVAL(outbuf,smb_rcls) == 0) {
2767                 nread = chain_reply(inbuf,outbuf,length,bufsize);
2768         }
2769
2770         END_PROFILE(SMBreadX);
2771         return nread;
2772 }
2773
2774 /****************************************************************************
2775  Reply to a writebraw (core+ or LANMAN1.0 protocol).
2776 ****************************************************************************/
2777
2778 int reply_writebraw(connection_struct *conn, char *inbuf,char *outbuf, int size, int dum_buffsize)
2779 {
2780         ssize_t nwritten=0;
2781         ssize_t total_written=0;
2782         size_t numtowrite=0;
2783         size_t tcount;
2784         SMB_OFF_T startpos;
2785         char *data=NULL;
2786         BOOL write_through;
2787         files_struct *fsp = file_fsp(inbuf,smb_vwv0);
2788         int outsize = 0;
2789         START_PROFILE(SMBwritebraw);
2790
2791         if (srv_is_signing_active()) {
2792                 exit_server_cleanly("reply_writebraw: SMB signing is active - raw reads/writes are disallowed.");
2793         }
2794
2795         CHECK_FSP(fsp,conn);
2796         if (!CHECK_WRITE(fsp)) {
2797                 return(ERROR_DOS(ERRDOS,ERRbadaccess));
2798         }
2799   
2800         tcount = IVAL(inbuf,smb_vwv1);
2801         startpos = IVAL_TO_SMB_OFF_T(inbuf,smb_vwv3);
2802         write_through = BITSETW(inbuf+smb_vwv7,0);
2803
2804         /* We have to deal with slightly different formats depending
2805                 on whether we are using the core+ or lanman1.0 protocol */
2806
2807         if(Protocol <= PROTOCOL_COREPLUS) {
2808                 numtowrite = SVAL(smb_buf(inbuf),-2);
2809                 data = smb_buf(inbuf);
2810         } else {
2811                 numtowrite = SVAL(inbuf,smb_vwv10);
2812                 data = smb_base(inbuf) + SVAL(inbuf, smb_vwv11);
2813         }
2814
2815         /* force the error type */
2816         SCVAL(inbuf,smb_com,SMBwritec);
2817         SCVAL(outbuf,smb_com,SMBwritec);
2818
2819         if (is_locked(fsp,(uint32)SVAL(inbuf,smb_pid),(SMB_BIG_UINT)tcount,(SMB_BIG_UINT)startpos, WRITE_LOCK)) {
2820                 END_PROFILE(SMBwritebraw);
2821                 return(ERROR_DOS(ERRDOS,ERRlock));
2822         }
2823
2824         if (numtowrite>0)
2825                 nwritten = write_file(fsp,data,startpos,numtowrite);
2826   
2827         DEBUG(3,("writebraw1 fnum=%d start=%.0f num=%d wrote=%d sync=%d\n",
2828                 fsp->fnum, (double)startpos, (int)numtowrite, (int)nwritten, (int)write_through));
2829
2830         if (nwritten < (ssize_t)numtowrite)  {
2831                 END_PROFILE(SMBwritebraw);
2832                 return(UNIXERROR(ERRHRD,ERRdiskfull));
2833         }
2834
2835         total_written = nwritten;
2836
2837         /* Return a message to the redirector to tell it to send more bytes */
2838         SCVAL(outbuf,smb_com,SMBwritebraw);
2839         SSVALS(outbuf,smb_vwv0,-1);
2840         outsize = set_message(inbuf,outbuf,Protocol>PROTOCOL_COREPLUS?1:0,0,True);
2841         show_msg(outbuf);
2842         if (!send_smb(smbd_server_fd(),outbuf))
2843                 exit_server_cleanly("reply_writebraw: send_smb failed.");
2844   
2845         /* Now read the raw data into the buffer and write it */
2846         if (read_smb_length(smbd_server_fd(),inbuf,SMB_SECONDARY_WAIT) == -1) {
2847                 exit_server_cleanly("secondary writebraw failed");
2848         }
2849   
2850         /* Even though this is not an smb message, smb_len returns the generic length of an smb message */
2851         numtowrite = smb_len(inbuf);
2852
2853         /* Set up outbuf to return the correct return */
2854         outsize = set_message(inbuf,outbuf,1,0,True);
2855         SCVAL(outbuf,smb_com,SMBwritec);
2856
2857         if (numtowrite != 0) {
2858
2859                 if (numtowrite > BUFFER_SIZE) {
2860                         DEBUG(0,("reply_writebraw: Oversize secondary write raw requested (%u). Terminating\n",
2861                                 (unsigned int)numtowrite ));
2862                         exit_server_cleanly("secondary writebraw failed");
2863                 }
2864
2865                 if (tcount > nwritten+numtowrite) {
2866                         DEBUG(3,("Client overestimated the write %d %d %d\n",
2867                                 (int)tcount,(int)nwritten,(int)numtowrite));
2868                 }
2869
2870                 if (read_data( smbd_server_fd(), inbuf+4, numtowrite) != numtowrite ) {
2871                         DEBUG(0,("reply_writebraw: Oversize secondary write raw read failed (%s). Terminating\n",
2872                                 strerror(errno) ));
2873                         exit_server_cleanly("secondary writebraw failed");
2874                 }
2875
2876                 nwritten = write_file(fsp,inbuf+4,startpos+nwritten,numtowrite);
2877                 if (nwritten == -1) {
2878                         END_PROFILE(SMBwritebraw);
2879                         return(UNIXERROR(ERRHRD,ERRdiskfull));
2880                 }
2881
2882                 if (nwritten < (ssize_t)numtowrite) {
2883                         SCVAL(outbuf,smb_rcls,ERRHRD);
2884                         SSVAL(outbuf,smb_err,ERRdiskfull);      
2885                 }
2886
2887                 if (nwritten > 0)
2888                         total_written += nwritten;
2889         }
2890  
2891         SSVAL(outbuf,smb_vwv0,total_written);
2892
2893         sync_file(conn, fsp, write_through);
2894
2895         DEBUG(3,("writebraw2 fnum=%d start=%.0f num=%d wrote=%d\n",
2896                 fsp->fnum, (double)startpos, (int)numtowrite,(int)total_written));
2897
2898         /* we won't return a status if write through is not selected - this follows what WfWg does */
2899         END_PROFILE(SMBwritebraw);
2900         if (!write_through && total_written==tcount) {
2901
2902 #if RABBIT_PELLET_FIX
2903                 /*
2904                  * Fix for "rabbit pellet" mode, trigger an early TCP ack by
2905                  * sending a SMBkeepalive. Thanks to DaveCB at Sun for this. JRA.
2906                  */
2907                 if (!send_keepalive(smbd_server_fd()))
2908                         exit_server_cleanly("reply_writebraw: send of keepalive failed");
2909 #endif
2910                 return(-1);
2911         }
2912
2913         return(outsize);
2914 }
2915
2916 #undef DBGC_CLASS
2917 #define DBGC_CLASS DBGC_LOCKING
2918
2919 /****************************************************************************
2920  Reply to a writeunlock (core+).
2921 ****************************************************************************/
2922
2923 int reply_writeunlock(connection_struct *conn, char *inbuf,char *outbuf, 
2924                       int size, int dum_buffsize)
2925 {
2926         ssize_t nwritten = -1;
2927         size_t numtowrite;
2928         SMB_OFF_T startpos;
2929         char *data;
2930         NTSTATUS status = NT_STATUS_OK;
2931         files_struct *fsp = file_fsp(inbuf,smb_vwv0);
2932         int outsize = 0;
2933         START_PROFILE(SMBwriteunlock);
2934         
2935         CHECK_FSP(fsp,conn);
2936         if (!CHECK_WRITE(fsp)) {
2937                 return(ERROR_DOS(ERRDOS,ERRbadaccess));
2938         }
2939
2940         numtowrite = SVAL(inbuf,smb_vwv1);
2941         startpos = IVAL_TO_SMB_OFF_T(inbuf,smb_vwv2);
2942         data = smb_buf(inbuf) + 3;
2943   
2944         if (numtowrite && is_locked(fsp,(uint32)SVAL(inbuf,smb_pid),(SMB_BIG_UINT)numtowrite,(SMB_BIG_UINT)startpos, WRITE_LOCK)) {
2945                 END_PROFILE(SMBwriteunlock);
2946                 return ERROR_DOS(ERRDOS,ERRlock);
2947         }
2948
2949         /* The special X/Open SMB protocol handling of
2950            zero length writes is *NOT* done for
2951            this call */
2952         if(numtowrite == 0) {
2953                 nwritten = 0;
2954         } else {
2955                 nwritten = write_file(fsp,data,startpos,numtowrite);
2956         }
2957   
2958         sync_file(conn, fsp, False /* write through */);
2959
2960         if(((nwritten == 0) && (numtowrite != 0))||(nwritten < 0)) {
2961                 END_PROFILE(SMBwriteunlock);
2962                 return(UNIXERROR(ERRHRD,ERRdiskfull));
2963         }
2964
2965         if (numtowrite) {
2966                 status = do_unlock(smbd_messaging_context(),
2967                                 fsp,
2968                                 (uint32)SVAL(inbuf,smb_pid),
2969                                 (SMB_BIG_UINT)numtowrite, 
2970                                 (SMB_BIG_UINT)startpos,
2971                                 WINDOWS_LOCK);
2972
2973                 if (NT_STATUS_V(status)) {
2974                         END_PROFILE(SMBwriteunlock);
2975                         return ERROR_NT(status);
2976                 }
2977         }
2978         
2979         outsize = set_message(inbuf,outbuf,1,0,True);
2980         
2981         SSVAL(outbuf,smb_vwv0,nwritten);
2982         
2983         DEBUG(3,("writeunlock fnum=%d num=%d wrote=%d\n",
2984                  fsp->fnum, (int)numtowrite, (int)nwritten));
2985         
2986         END_PROFILE(SMBwriteunlock);
2987         return outsize;
2988 }
2989
2990 #undef DBGC_CLASS
2991 #define DBGC_CLASS DBGC_ALL
2992
2993 /****************************************************************************
2994  Reply to a write.
2995 ****************************************************************************/
2996
2997 int reply_write(connection_struct *conn, char *inbuf,char *outbuf,int size,int dum_buffsize)
2998 {
2999         size_t numtowrite;
3000         ssize_t nwritten = -1;
3001         SMB_OFF_T startpos;
3002         char *data;
3003         files_struct *fsp = file_fsp(inbuf,smb_vwv0);
3004         int outsize = 0;
3005         START_PROFILE(SMBwrite);
3006
3007         /* If it's an IPC, pass off the pipe handler. */
3008         if (IS_IPC(conn)) {
3009                 END_PROFILE(SMBwrite);
3010                 return reply_pipe_write(inbuf,outbuf,size,dum_buffsize);
3011         }
3012
3013         CHECK_FSP(fsp,conn);
3014         if (!CHECK_WRITE(fsp)) {
3015                 return(ERROR_DOS(ERRDOS,ERRbadaccess));
3016         }
3017
3018         numtowrite = SVAL(inbuf,smb_vwv1);
3019         startpos = IVAL_TO_SMB_OFF_T(inbuf,smb_vwv2);
3020         data = smb_buf(inbuf) + 3;
3021   
3022         if (is_locked(fsp,(uint32)SVAL(inbuf,smb_pid),(SMB_BIG_UINT)numtowrite,(SMB_BIG_UINT)startpos, WRITE_LOCK)) {
3023                 END_PROFILE(SMBwrite);
3024                 return ERROR_DOS(ERRDOS,ERRlock);
3025         }
3026
3027         /*
3028          * X/Open SMB protocol says that if smb_vwv1 is
3029          * zero then the file size should be extended or
3030          * truncated to the size given in smb_vwv[2-3].
3031          */
3032
3033         if(numtowrite == 0) {
3034                 /*
3035                  * This is actually an allocate call, and set EOF. JRA.
3036                  */
3037                 nwritten = vfs_allocate_file_space(fsp, (SMB_OFF_T)startpos);
3038                 if (nwritten < 0) {
3039                         END_PROFILE(SMBwrite);
3040                         return ERROR_NT(NT_STATUS_DISK_FULL);
3041                 }
3042                 nwritten = vfs_set_filelen(fsp, (SMB_OFF_T)startpos);
3043                 if (nwritten < 0) {
3044                         END_PROFILE(SMBwrite);
3045                         return ERROR_NT(NT_STATUS_DISK_FULL);
3046                 }
3047         } else
3048                 nwritten = write_file(fsp,data,startpos,numtowrite);
3049   
3050         sync_file(conn, fsp, False);
3051
3052         if(((nwritten == 0) && (numtowrite != 0))||(nwritten < 0)) {
3053                 END_PROFILE(SMBwrite);
3054                 return(UNIXERROR(ERRHRD,ERRdiskfull));
3055         }
3056
3057         outsize = set_message(inbuf,outbuf,1,0,True);
3058   
3059         SSVAL(outbuf,smb_vwv0,nwritten);
3060
3061         if (nwritten < (ssize_t)numtowrite) {
3062                 SCVAL(outbuf,smb_rcls,ERRHRD);
3063                 SSVAL(outbuf,smb_err,ERRdiskfull);      
3064         }
3065   
3066         DEBUG(3,("write fnum=%d num=%d wrote=%d\n", fsp->fnum, (int)numtowrite, (int)nwritten));
3067
3068         END_PROFILE(SMBwrite);
3069         return(outsize);
3070 }
3071
3072 /****************************************************************************
3073  Reply to a write and X.
3074 ****************************************************************************/
3075
3076 int reply_write_and_X(connection_struct *conn, char *inbuf,char *outbuf,int length,int bufsize)
3077 {
3078         files_struct *fsp = file_fsp(inbuf,smb_vwv2);
3079         SMB_OFF_T startpos = IVAL_TO_SMB_OFF_T(inbuf,smb_vwv3);
3080         size_t numtowrite = SVAL(inbuf,smb_vwv10);
3081         BOOL write_through = BITSETW(inbuf+smb_vwv7,0);
3082         ssize_t nwritten = -1;
3083         unsigned int smb_doff = SVAL(inbuf,smb_vwv11);
3084         unsigned int smblen = smb_len(inbuf);
3085         char *data;
3086         BOOL large_writeX = ((CVAL(inbuf,smb_wct) == 14) && (smblen > 0xFFFF));
3087         START_PROFILE(SMBwriteX);
3088
3089         /* If it's an IPC, pass off the pipe handler. */
3090         if (IS_IPC(conn)) {
3091                 END_PROFILE(SMBwriteX);
3092                 return reply_pipe_write_and_X(inbuf,outbuf,length,bufsize);
3093         }
3094
3095         CHECK_FSP(fsp,conn);
3096         if (!CHECK_WRITE(fsp)) {
3097                 return(ERROR_DOS(ERRDOS,ERRbadaccess));
3098         }
3099
3100         set_message(inbuf,outbuf,6,0,True);
3101   
3102         /* Deal with possible LARGE_WRITEX */
3103         if (large_writeX) {
3104                 numtowrite |= ((((size_t)SVAL(inbuf,smb_vwv9)) & 1 )<<16);
3105         }
3106
3107         if(smb_doff > smblen || (smb_doff + numtowrite > smblen)) {
3108                 END_PROFILE(SMBwriteX);
3109                 return ERROR_DOS(ERRDOS,ERRbadmem);
3110         }
3111
3112         data = smb_base(inbuf) + smb_doff;
3113
3114         if(CVAL(inbuf,smb_wct) == 14) {
3115 #ifdef LARGE_SMB_OFF_T
3116                 /*
3117                  * This is a large offset (64 bit) write.
3118                  */
3119                 startpos |= (((SMB_OFF_T)IVAL(inbuf,smb_vwv12)) << 32);
3120
3121 #else /* !LARGE_SMB_OFF_T */
3122
3123                 /*
3124                  * Ensure we haven't been sent a >32 bit offset.
3125                  */
3126
3127                 if(IVAL(inbuf,smb_vwv12) != 0) {
3128                         DEBUG(0,("reply_write_and_X - large offset (%x << 32) used and we don't support \
3129 64 bit offsets.\n", (unsigned int)IVAL(inbuf,smb_vwv12) ));
3130                         END_PROFILE(SMBwriteX);
3131                         return ERROR_DOS(ERRDOS,ERRbadaccess);
3132                 }
3133
3134 #endif /* LARGE_SMB_OFF_T */
3135         }
3136
3137         if (is_locked(fsp,(uint32)SVAL(inbuf,smb_pid),(SMB_BIG_UINT)numtowrite,(SMB_BIG_UINT)startpos, WRITE_LOCK)) {
3138                 END_PROFILE(SMBwriteX);
3139                 return ERROR_DOS(ERRDOS,ERRlock);
3140         }
3141
3142         /* X/Open SMB protocol says that, unlike SMBwrite
3143         if the length is zero then NO truncation is
3144         done, just a write of zero. To truncate a file,
3145         use SMBwrite. */
3146
3147         if(numtowrite == 0) {
3148                 nwritten = 0;
3149         } else {
3150
3151                 if (schedule_aio_write_and_X(conn, inbuf, outbuf, length, bufsize,
3152                                         fsp,data,startpos,numtowrite)) {
3153                         END_PROFILE(SMBwriteX);
3154                         return -1;
3155                 }
3156
3157                 nwritten = write_file(fsp,data,startpos,numtowrite);
3158         }
3159   
3160         if(((nwritten == 0) && (numtowrite != 0))||(nwritten < 0)) {
3161                 END_PROFILE(SMBwriteX);
3162                 return(UNIXERROR(ERRHRD,ERRdiskfull));
3163         }
3164
3165         SSVAL(outbuf,smb_vwv2,nwritten);
3166         if (large_writeX)
3167                 SSVAL(outbuf,smb_vwv4,(nwritten>>16)&1);
3168
3169         if (nwritten < (ssize_t)numtowrite) {
3170                 SCVAL(outbuf,smb_rcls,ERRHRD);
3171                 SSVAL(outbuf,smb_err,ERRdiskfull);      
3172         }
3173
3174         DEBUG(3,("writeX fnum=%d num=%d wrote=%d\n",
3175                 fsp->fnum, (int)numtowrite, (int)nwritten));
3176
3177         sync_file(conn, fsp, write_through);
3178
3179         END_PROFILE(SMBwriteX);
3180         return chain_reply(inbuf,outbuf,length,bufsize);
3181 }
3182
3183 /****************************************************************************
3184  Reply to a lseek.
3185 ****************************************************************************/
3186
3187 int reply_lseek(connection_struct *conn, char *inbuf,char *outbuf, int size, int dum_buffsize)
3188 {
3189         SMB_OFF_T startpos;
3190         SMB_OFF_T res= -1;
3191         int mode,umode;
3192         int outsize = 0;
3193         files_struct *fsp = file_fsp(inbuf,smb_vwv0);
3194         START_PROFILE(SMBlseek);
3195
3196         CHECK_FSP(fsp,conn);
3197
3198         flush_write_cache(fsp, SEEK_FLUSH);
3199
3200         mode = SVAL(inbuf,smb_vwv1) & 3;
3201         /* NB. This doesn't use IVAL_TO_SMB_OFF_T as startpos can be signed in this case. */
3202         startpos = (SMB_OFF_T)IVALS(inbuf,smb_vwv2);
3203
3204         switch (mode) {
3205                 case 0:
3206                         umode = SEEK_SET;
3207                         res = startpos;
3208                         break;
3209                 case 1:
3210                         umode = SEEK_CUR;
3211                         res = fsp->fh->pos + startpos;
3212                         break;
3213                 case 2:
3214                         umode = SEEK_END;
3215                         break;
3216                 default:
3217                         umode = SEEK_SET;
3218                         res = startpos;
3219                         break;
3220         }
3221
3222         if (umode == SEEK_END) {
3223                 if((res = SMB_VFS_LSEEK(fsp,fsp->fh->fd,startpos,umode)) == -1) {
3224                         if(errno == EINVAL) {
3225                                 SMB_OFF_T current_pos = startpos;
3226                                 SMB_STRUCT_STAT sbuf;
3227
3228                                 if(SMB_VFS_FSTAT(fsp,fsp->fh->fd, &sbuf) == -1) {
3229                                         END_PROFILE(SMBlseek);
3230                                         return(UNIXERROR(ERRDOS,ERRnoaccess));
3231                                 }
3232
3233                                 current_pos += sbuf.st_size;
3234                                 if(current_pos < 0)
3235                                         res = SMB_VFS_LSEEK(fsp,fsp->fh->fd,0,SEEK_SET);
3236                         }
3237                 }
3238
3239                 if(res == -1) {
3240                         END_PROFILE(SMBlseek);
3241                         return(UNIXERROR(ERRDOS,ERRnoaccess));
3242                 }
3243         }
3244
3245         fsp->fh->pos = res;
3246   
3247         outsize = set_message(inbuf,outbuf,2,0,True);
3248         SIVAL(outbuf,smb_vwv0,res);
3249   
3250         DEBUG(3,("lseek fnum=%d ofs=%.0f newpos = %.0f mode=%d\n",
3251                 fsp->fnum, (double)startpos, (double)res, mode));
3252
3253         END_PROFILE(SMBlseek);
3254         return(outsize);
3255 }
3256
3257 /****************************************************************************
3258  Reply to a flush.
3259 ****************************************************************************/
3260
3261 int reply_flush(connection_struct *conn, char *inbuf,char *outbuf, int size, int dum_buffsize)
3262 {
3263         int outsize = set_message(inbuf,outbuf,0,0,False);
3264         uint16 fnum = SVAL(inbuf,smb_vwv0);
3265         files_struct *fsp = file_fsp(inbuf,smb_vwv0);
3266         START_PROFILE(SMBflush);
3267
3268         if (fnum != 0xFFFF)
3269                 CHECK_FSP(fsp,conn);
3270         
3271         if (!fsp) {
3272                 file_sync_all(conn);
3273         } else {
3274                 sync_file(conn,fsp, True);
3275         }
3276         
3277         DEBUG(3,("flush\n"));
3278         END_PROFILE(SMBflush);
3279         return(outsize);
3280 }
3281
3282 /****************************************************************************
3283  Reply to a exit.
3284  conn POINTER CAN BE NULL HERE !
3285 ****************************************************************************/
3286
3287 int reply_exit(connection_struct *conn, 
3288                char *inbuf,char *outbuf, int dum_size, int dum_buffsize)
3289 {
3290         int outsize;
3291         START_PROFILE(SMBexit);
3292
3293         file_close_pid(SVAL(inbuf,smb_pid),SVAL(inbuf,smb_uid));
3294
3295         outsize = set_message(inbuf,outbuf,0,0,False);
3296
3297         DEBUG(3,("exit\n"));
3298
3299         END_PROFILE(SMBexit);
3300         return(outsize);
3301 }
3302
3303 /****************************************************************************
3304  Reply to a close - has to deal with closing a directory opened by NT SMB's.
3305 ****************************************************************************/
3306
3307 int reply_close(connection_struct *conn, char *inbuf,char *outbuf, int size,
3308                 int dum_buffsize)
3309 {
3310         NTSTATUS status = NT_STATUS_OK;
3311         int outsize = 0;
3312         files_struct *fsp = NULL;
3313         START_PROFILE(SMBclose);
3314
3315         outsize = set_message(inbuf,outbuf,0,0,False);
3316
3317         /* If it's an IPC, pass off to the pipe handler. */
3318         if (IS_IPC(conn)) {
3319                 END_PROFILE(SMBclose);
3320                 return reply_pipe_close(conn, inbuf,outbuf);
3321         }
3322
3323         fsp = file_fsp(inbuf,smb_vwv0);
3324
3325         /*
3326          * We can only use CHECK_FSP if we know it's not a directory.
3327          */
3328
3329         if(!fsp || (fsp->conn != conn) || (fsp->vuid != current_user.vuid)) {
3330                 END_PROFILE(SMBclose);
3331                 return ERROR_DOS(ERRDOS,ERRbadfid);
3332         }
3333
3334         if(fsp->is_directory) {
3335                 /*
3336                  * Special case - close NT SMB directory handle.
3337                  */
3338                 DEBUG(3,("close directory fnum=%d\n", fsp->fnum));
3339                 status = close_file(fsp,NORMAL_CLOSE);
3340         } else {
3341                 /*
3342                  * Close ordinary file.
3343                  */
3344
3345                 DEBUG(3,("close fd=%d fnum=%d (numopen=%d)\n",
3346                          fsp->fh->fd, fsp->fnum,
3347                          conn->num_files_open));
3348  
3349                 /*
3350                  * Take care of any time sent in the close.
3351                  */
3352
3353                 fsp_set_pending_modtime(fsp,
3354                                 convert_time_t_to_timespec(srv_make_unix_date3(inbuf+smb_vwv1)));
3355
3356                 /*
3357                  * close_file() returns the unix errno if an error
3358                  * was detected on close - normally this is due to
3359                  * a disk full error. If not then it was probably an I/O error.
3360                  */
3361  
3362                 status = close_file(fsp,NORMAL_CLOSE);
3363         }  
3364
3365         if(!NT_STATUS_IS_OK(status)) {
3366                 END_PROFILE(SMBclose);
3367                 return ERROR_NT(status);
3368         }
3369
3370         END_PROFILE(SMBclose);
3371         return(outsize);
3372 }
3373
3374 /****************************************************************************
3375  Reply to a writeclose (Core+ protocol).
3376 ****************************************************************************/
3377
3378 int reply_writeclose(connection_struct *conn,
3379                      char *inbuf,char *outbuf, int size, int dum_buffsize)
3380 {
3381         size_t numtowrite;
3382         ssize_t nwritten = -1;
3383         int outsize = 0;
3384         NTSTATUS close_status = NT_STATUS_OK;
3385         SMB_OFF_T startpos;
3386         char *data;
3387         struct timespec mtime;
3388         files_struct *fsp = file_fsp(inbuf,smb_vwv0);
3389         START_PROFILE(SMBwriteclose);
3390
3391         CHECK_FSP(fsp,conn);
3392         if (!CHECK_WRITE(fsp)) {
3393                 return(ERROR_DOS(ERRDOS,ERRbadaccess));
3394         }
3395
3396         numtowrite = SVAL(inbuf,smb_vwv1);
3397         startpos = IVAL_TO_SMB_OFF_T(inbuf,smb_vwv2);
3398         mtime = convert_time_t_to_timespec(srv_make_unix_date3(inbuf+smb_vwv4));
3399         data = smb_buf(inbuf) + 1;
3400   
3401         if (numtowrite && is_locked(fsp,(uint32)SVAL(inbuf,smb_pid),(SMB_BIG_UINT)numtowrite,(SMB_BIG_UINT)startpos, WRITE_LOCK)) {
3402                 END_PROFILE(SMBwriteclose);
3403                 return ERROR_DOS(ERRDOS,ERRlock);
3404         }
3405   
3406         nwritten = write_file(fsp,data,startpos,numtowrite);
3407
3408         set_filetime(conn, fsp->fsp_name, mtime);
3409   
3410         /*
3411          * More insanity. W2K only closes the file if writelen > 0.
3412          * JRA.
3413          */
3414
3415         if (numtowrite) {
3416                 DEBUG(3,("reply_writeclose: zero length write doesn't close file %s\n",
3417                         fsp->fsp_name ));
3418                 close_status = close_file(fsp,NORMAL_CLOSE);
3419         }
3420
3421         DEBUG(3,("writeclose fnum=%d num=%d wrote=%d (numopen=%d)\n",
3422                  fsp->fnum, (int)numtowrite, (int)nwritten,
3423                  conn->num_files_open));
3424   
3425         if(((nwritten == 0) && (numtowrite != 0))||(nwritten < 0)) {
3426                 END_PROFILE(SMBwriteclose);
3427                 return(UNIXERROR(ERRHRD,ERRdiskfull));
3428         }
3429  
3430         if(!NT_STATUS_IS_OK(close_status)) {
3431                 END_PROFILE(SMBwriteclose);
3432                 return ERROR_NT(close_status);
3433         }
3434  
3435         outsize = set_message(inbuf,outbuf,1,0,True);
3436   
3437         SSVAL(outbuf,smb_vwv0,nwritten);
3438         END_PROFILE(SMBwriteclose);
3439         return(outsize);
3440 }
3441
3442 #undef DBGC_CLASS
3443 #define DBGC_CLASS DBGC_LOCKING
3444
3445 /****************************************************************************
3446  Reply to a lock.
3447 ****************************************************************************/
3448
3449 int reply_lock(connection_struct *conn,
3450                char *inbuf,char *outbuf, int length, int dum_buffsize)
3451 {
3452         int outsize = set_message(inbuf,outbuf,0,0,False);
3453         SMB_BIG_UINT count,offset;
3454         NTSTATUS status;
3455         files_struct *fsp = file_fsp(inbuf,smb_vwv0);
3456         struct byte_range_lock *br_lck = NULL;
3457
3458         START_PROFILE(SMBlock);
3459
3460         CHECK_FSP(fsp,conn);
3461
3462         release_level_2_oplocks_on_change(fsp);
3463
3464         count = (SMB_BIG_UINT)IVAL(inbuf,smb_vwv1);
3465         offset = (SMB_BIG_UINT)IVAL(inbuf,smb_vwv3);
3466
3467         DEBUG(3,("lock fd=%d fnum=%d offset=%.0f count=%.0f\n",
3468                  fsp->fh->fd, fsp->fnum, (double)offset, (double)count));
3469
3470         br_lck = do_lock(smbd_messaging_context(),
3471                         fsp,
3472                         (uint32)SVAL(inbuf,smb_pid),
3473                         count,
3474                         offset,
3475                         WRITE_LOCK,
3476                         WINDOWS_LOCK,
3477                         False, /* Non-blocking lock. */
3478                         &status);
3479
3480         TALLOC_FREE(br_lck);
3481
3482         if (NT_STATUS_V(status)) {
3483                 END_PROFILE(SMBlock);
3484                 return ERROR_NT(status);
3485         }
3486
3487         END_PROFILE(SMBlock);
3488         return(outsize);
3489 }
3490
3491 /****************************************************************************
3492  Reply to a unlock.
3493 ****************************************************************************/
3494
3495 int reply_unlock(connection_struct *conn, char *inbuf,char *outbuf, int size, 
3496                  int dum_buffsize)
3497 {
3498         int outsize = set_message(inbuf,outbuf,0,0,False);
3499         SMB_BIG_UINT count,offset;
3500         NTSTATUS status;
3501         files_struct *fsp = file_fsp(inbuf,smb_vwv0);
3502         START_PROFILE(SMBunlock);
3503
3504         CHECK_FSP(fsp,conn);
3505         
3506         count = (SMB_BIG_UINT)IVAL(inbuf,smb_vwv1);
3507         offset = (SMB_BIG_UINT)IVAL(inbuf,smb_vwv3);
3508         
3509         status = do_unlock(smbd_messaging_context(),
3510                         fsp,
3511                         (uint32)SVAL(inbuf,smb_pid),
3512                         count,
3513                         offset,
3514                         WINDOWS_LOCK);
3515
3516         if (NT_STATUS_V(status)) {
3517                 END_PROFILE(SMBunlock);
3518                 return ERROR_NT(status);
3519         }
3520
3521         DEBUG( 3, ( "unlock fd=%d fnum=%d offset=%.0f count=%.0f\n",
3522                     fsp->fh->fd, fsp->fnum, (double)offset, (double)count ) );
3523         
3524         END_PROFILE(SMBunlock);
3525         return(outsize);
3526 }
3527
3528 #undef DBGC_CLASS
3529 #define DBGC_CLASS DBGC_ALL
3530
3531 /****************************************************************************
3532  Reply to a tdis.
3533  conn POINTER CAN BE NULL HERE !
3534 ****************************************************************************/
3535
3536 int reply_tdis(connection_struct *conn, 
3537                char *inbuf,char *outbuf, int dum_size, int dum_buffsize)
3538 {
3539         int outsize = set_message(inbuf,outbuf,0,0,False);
3540         uint16 vuid;
3541         START_PROFILE(SMBtdis);
3542
3543         vuid = SVAL(inbuf,smb_uid);
3544
3545         if (!conn) {
3546                 DEBUG(4,("Invalid connection in tdis\n"));
3547                 END_PROFILE(SMBtdis);
3548                 return ERROR_DOS(ERRSRV,ERRinvnid);
3549         }
3550
3551         conn->used = False;
3552
3553         close_cnum(conn,vuid);
3554   
3555         END_PROFILE(SMBtdis);
3556         return outsize;
3557 }
3558
3559 /****************************************************************************
3560  Reply to a echo.
3561  conn POINTER CAN BE NULL HERE !
3562 ****************************************************************************/
3563
3564 int reply_echo(connection_struct *conn,
3565                char *inbuf,char *outbuf, int dum_size, int dum_buffsize)
3566 {
3567         int smb_reverb = SVAL(inbuf,smb_vwv0);
3568         int seq_num;
3569         unsigned int data_len = smb_buflen(inbuf);
3570         int outsize = set_message(inbuf,outbuf,1,data_len,True);
3571         START_PROFILE(SMBecho);
3572
3573         if (data_len > BUFFER_SIZE) {
3574                 DEBUG(0,("reply_echo: data_len too large.\n"));
3575                 END_PROFILE(SMBecho);
3576                 return -1;
3577         }
3578
3579         /* copy any incoming data back out */
3580         if (data_len > 0)
3581                 memcpy(smb_buf(outbuf),smb_buf(inbuf),data_len);
3582
3583         if (smb_reverb > 100) {
3584                 DEBUG(0,("large reverb (%d)?? Setting to 100\n",smb_reverb));
3585                 smb_reverb = 100;
3586         }
3587
3588         for (seq_num =1 ; seq_num <= smb_reverb ; seq_num++) {
3589                 SSVAL(outbuf,smb_vwv0,seq_num);
3590
3591                 smb_setlen(inbuf,outbuf,outsize - 4);
3592
3593                 show_msg(outbuf);
3594                 if (!send_smb(smbd_server_fd(),outbuf))
3595                         exit_server_cleanly("reply_echo: send_smb failed.");
3596         }
3597
3598         DEBUG(3,("echo %d times\n", smb_reverb));
3599
3600         smb_echo_count++;
3601
3602         END_PROFILE(SMBecho);
3603         return -1;
3604 }
3605
3606 /****************************************************************************
3607  Reply to a printopen.
3608 ****************************************************************************/
3609
3610 int reply_printopen(connection_struct *conn, 
3611                     char *inbuf,char *outbuf, int dum_size, int dum_buffsize)
3612 {
3613         int outsize = 0;
3614         files_struct *fsp;
3615         NTSTATUS status;
3616         
3617         START_PROFILE(SMBsplopen);
3618         
3619         if (!CAN_PRINT(conn)) {
3620                 END_PROFILE(SMBsplopen);
3621                 return ERROR_DOS(ERRDOS,ERRnoaccess);
3622         }
3623
3624         /* Open for exclusive use, write only. */
3625         status = print_fsp_open(conn, NULL, &fsp);
3626
3627         if (!NT_STATUS_IS_OK(status)) {
3628                 END_PROFILE(SMBsplopen);
3629                 return(ERROR_NT(status));
3630         }
3631
3632         outsize = set_message(inbuf,outbuf,1,0,True);
3633         SSVAL(outbuf,smb_vwv0,fsp->fnum);
3634   
3635         DEBUG(3,("openprint fd=%d fnum=%d\n",
3636                  fsp->fh->fd, fsp->fnum));
3637
3638         END_PROFILE(SMBsplopen);
3639         return(outsize);
3640 }
3641
3642 /****************************************************************************
3643  Reply to a printclose.
3644 ****************************************************************************/
3645
3646 int reply_printclose(connection_struct *conn,
3647                      char *inbuf,char *outbuf, int dum_size, int dum_buffsize)
3648 {
3649         int outsize = set_message(inbuf,outbuf,0,0,False);
3650         files_struct *fsp = file_fsp(inbuf,smb_vwv0);
3651         NTSTATUS status;
3652         START_PROFILE(SMBsplclose);
3653
3654         CHECK_FSP(fsp,conn);
3655
3656         if (!CAN_PRINT(conn)) {
3657                 END_PROFILE(SMBsplclose);
3658                 return ERROR_NT(NT_STATUS_DOS(ERRSRV, ERRerror));
3659         }
3660   
3661         DEBUG(3,("printclose fd=%d fnum=%d\n",
3662                  fsp->fh->fd,fsp->fnum));
3663   
3664         status = close_file(fsp,NORMAL_CLOSE);
3665
3666         if(!NT_STATUS_IS_OK(status)) {
3667                 END_PROFILE(SMBsplclose);
3668                 return ERROR_NT(status);
3669         }
3670
3671         END_PROFILE(SMBsplclose);
3672         return(outsize);
3673 }
3674
3675 /****************************************************************************
3676  Reply to a printqueue.
3677 ****************************************************************************/
3678
3679 int reply_printqueue(connection_struct *conn,
3680                      char *inbuf,char *outbuf, int dum_size, int dum_buffsize)
3681 {
3682         int outsize = set_message(inbuf,outbuf,2,3,True);
3683         int max_count = SVAL(inbuf,smb_vwv0);
3684         int start_index = SVAL(inbuf,smb_vwv1);
3685         START_PROFILE(SMBsplretq);
3686
3687         /* we used to allow the client to get the cnum wrong, but that
3688            is really quite gross and only worked when there was only
3689            one printer - I think we should now only accept it if they
3690            get it right (tridge) */
3691         if (!CAN_PRINT(conn)) {
3692                 END_PROFILE(SMBsplretq);
3693                 return ERROR_DOS(ERRDOS,ERRnoaccess);
3694         }
3695
3696         SSVAL(outbuf,smb_vwv0,0);
3697         SSVAL(outbuf,smb_vwv1,0);
3698         SCVAL(smb_buf(outbuf),0,1);
3699         SSVAL(smb_buf(outbuf),1,0);
3700   
3701         DEBUG(3,("printqueue start_index=%d max_count=%d\n",
3702                  start_index, max_count));
3703
3704         {
3705                 print_queue_struct *queue = NULL;
3706                 print_status_struct status;
3707                 char *p = smb_buf(outbuf) + 3;
3708                 int count = print_queue_status(SNUM(conn), &queue, &status);
3709                 int num_to_get = ABS(max_count);
3710                 int first = (max_count>0?start_index:start_index+max_count+1);
3711                 int i;
3712
3713                 if (first >= count)
3714                         num_to_get = 0;
3715                 else
3716                         num_to_get = MIN(num_to_get,count-first);
3717     
3718
3719                 for (i=first;i<first+num_to_get;i++) {
3720                         srv_put_dos_date2(p,0,queue[i].time);
3721                         SCVAL(p,4,(queue[i].status==LPQ_PRINTING?2:3));
3722                         SSVAL(p,5, queue[i].job);
3723                         SIVAL(p,7,queue[i].size);
3724                         SCVAL(p,11,0);
3725                         srvstr_push(outbuf, p+12, queue[i].fs_user, 16, STR_ASCII);
3726                         p += 28;
3727                 }
3728
3729                 if (count > 0) {
3730                         outsize = set_message(inbuf,outbuf,2,28*count+3,False); 
3731                         SSVAL(outbuf,smb_vwv0,count);
3732                         SSVAL(outbuf,smb_vwv1,(max_count>0?first+count:first-1));
3733                         SCVAL(smb_buf(outbuf),0,1);
3734                         SSVAL(smb_buf(outbuf),1,28*count);
3735                 }
3736
3737                 SAFE_FREE(queue);
3738           
3739                 DEBUG(3,("%d entries returned in queue\n",count));
3740         }
3741   
3742         END_PROFILE(SMBsplretq);
3743         return(outsize);
3744 }
3745
3746 /****************************************************************************
3747  Reply to a printwrite.
3748 ****************************************************************************/
3749
3750 int reply_printwrite(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize)
3751 {
3752         int numtowrite;
3753         int outsize = set_message(inbuf,outbuf,0,0,False);
3754         char *data;
3755         files_struct *fsp = file_fsp(inbuf,smb_vwv0);
3756
3757         START_PROFILE(SMBsplwr);
3758   
3759         if (!CAN_PRINT(conn)) {
3760                 END_PROFILE(SMBsplwr);
3761                 return ERROR_DOS(ERRDOS,ERRnoaccess);
3762         }
3763
3764         CHECK_FSP(fsp,conn);
3765         if (!CHECK_WRITE(fsp)) {
3766                 return(ERROR_DOS(ERRDOS,ERRbadaccess));
3767         }
3768
3769         numtowrite = SVAL(smb_buf(inbuf),1);
3770         data = smb_buf(inbuf) + 3;
3771   
3772         if (write_file(fsp,data,-1,numtowrite) != numtowrite) {
3773                 END_PROFILE(SMBsplwr);
3774                 return(UNIXERROR(ERRHRD,ERRdiskfull));
3775         }
3776
3777         DEBUG( 3, ( "printwrite fnum=%d num=%d\n", fsp->fnum, numtowrite ) );
3778   
3779         END_PROFILE(SMBsplwr);
3780         return(outsize);
3781 }
3782
3783 /****************************************************************************
3784  Reply to a mkdir.
3785 ****************************************************************************/
3786
3787 int reply_mkdir(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize)
3788 {
3789         pstring directory;
3790         int outsize;
3791         NTSTATUS status;
3792         SMB_STRUCT_STAT sbuf;
3793
3794         START_PROFILE(SMBmkdir);
3795  
3796         srvstr_get_path(inbuf, directory, smb_buf(inbuf) + 1, sizeof(directory), 0, STR_TERMINATE, &status);
3797         if (!NT_STATUS_IS_OK(status)) {
3798                 END_PROFILE(SMBmkdir);
3799                 return ERROR_NT(status);
3800         }
3801
3802         status = resolve_dfspath(conn, SVAL(inbuf,smb_flg2) & FLAGS2_DFS_PATHNAMES, directory);
3803         if (!NT_STATUS_IS_OK(status)) {
3804                 END_PROFILE(SMBmkdir);
3805                 if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) {
3806                         return ERROR_BOTH(NT_STATUS_PATH_NOT_COVERED, ERRSRV, ERRbadpath);
3807                 }
3808                 return ERROR_NT(status);
3809         }
3810
3811         status = unix_convert(conn, directory, False, NULL, &sbuf);
3812         if (!NT_STATUS_IS_OK(status)) {
3813                 END_PROFILE(SMBmkdir);
3814                 return ERROR_NT(status);
3815         }
3816
3817         status = check_name(conn, directory);
3818         if (!NT_STATUS_IS_OK(status)) {
3819                 END_PROFILE(SMBmkdir);
3820                 return ERROR_NT(status);
3821         }
3822   
3823         status = create_directory(conn, directory);
3824
3825         DEBUG(5, ("create_directory returned %s\n", nt_errstr(status)));
3826
3827         if (!NT_STATUS_IS_OK(status)) {
3828
3829                 if (!use_nt_status()
3830                     && NT_STATUS_EQUAL(status,
3831                                        NT_STATUS_OBJECT_NAME_COLLISION)) {
3832                         /*
3833                          * Yes, in the DOS error code case we get a
3834                          * ERRDOS:ERRnoaccess here. See BASE-SAMBA3ERROR
3835                          * samba4 torture test.
3836                          */
3837                         status = NT_STATUS_DOS(ERRDOS, ERRnoaccess);
3838                 }
3839
3840                 END_PROFILE(SMBmkdir);
3841                 return ERROR_NT(status);
3842         }
3843
3844         outsize = set_message(inbuf,outbuf,0,0,False);
3845
3846         DEBUG( 3, ( "mkdir %s ret=%d\n", directory, outsize ) );
3847
3848         END_PROFILE(SMBmkdir);
3849         return(outsize);
3850 }
3851
3852 /****************************************************************************
3853  Static function used by reply_rmdir to delete an entire directory
3854  tree recursively. Return True on ok, False on fail.
3855 ****************************************************************************/
3856
3857 static BOOL recursive_rmdir(connection_struct *conn, char *directory)
3858 {
3859         const char *dname = NULL;
3860         BOOL ret = True;
3861         long offset = 0;
3862         struct smb_Dir *dir_hnd = OpenDir(conn, directory, NULL, 0);
3863
3864         if(dir_hnd == NULL)
3865                 return False;
3866
3867         while((dname = ReadDirName(dir_hnd, &offset))) {
3868                 pstring fullname;
3869                 SMB_STRUCT_STAT st;
3870
3871                 if((strcmp(dname, ".") == 0) || (strcmp(dname, "..")==0))
3872                         continue;
3873
3874                 if (!is_visible_file(conn, directory, dname, &st, False))
3875                         continue;
3876
3877                 /* Construct the full name. */
3878                 if(strlen(directory) + strlen(dname) + 1 >= sizeof(fullname)) {
3879                         errno = ENOMEM;
3880                         ret = False;
3881                         break;
3882                 }
3883
3884                 pstrcpy(fullname, directory);
3885                 pstrcat(fullname, "/");
3886                 pstrcat(fullname, dname);
3887
3888                 if(SMB_VFS_LSTAT(conn,fullname, &st) != 0) {
3889                         ret = False;
3890                         break;
3891                 }
3892
3893                 if(st.st_mode & S_IFDIR) {
3894                         if(!recursive_rmdir(conn, fullname)) {
3895                                 ret = False;
3896                                 break;
3897                         }
3898                         if(SMB_VFS_RMDIR(conn,fullname) != 0) {
3899                                 ret = False;
3900                                 break;
3901                         }
3902                 } else if(SMB_VFS_UNLINK(conn,fullname) != 0) {
3903                         ret = False;
3904                         break;
3905                 }
3906         }
3907         CloseDir(dir_hnd);
3908         return ret;
3909 }
3910
3911 /****************************************************************************
3912  The internals of the rmdir code - called elsewhere.
3913 ****************************************************************************/
3914
3915 NTSTATUS rmdir_internals(connection_struct *conn, const char *directory)
3916 {
3917         int ret;
3918         SMB_STRUCT_STAT st;
3919
3920         /* Might be a symlink. */
3921         if(SMB_VFS_LSTAT(conn, directory, &st) != 0) {
3922                 return map_nt_error_from_unix(errno);
3923         }
3924
3925         if (S_ISLNK(st.st_mode)) {
3926                 /* Is what it points to a directory ? */
3927                 if(SMB_VFS_STAT(conn, directory, &st) != 0) {
3928                         return map_nt_error_from_unix(errno);
3929                 }
3930                 if (!(S_ISDIR(st.st_mode))) {
3931                         return NT_STATUS_NOT_A_DIRECTORY;
3932                 }
3933                 ret = SMB_VFS_UNLINK(conn,directory);
3934         } else {
3935                 ret = SMB_VFS_RMDIR(conn,directory);
3936         }
3937         if (ret == 0) {
3938                 notify_fname(conn, NOTIFY_ACTION_REMOVED,
3939                              FILE_NOTIFY_CHANGE_DIR_NAME,
3940                              directory);
3941                 return NT_STATUS_OK;
3942         }
3943
3944         if(((errno == ENOTEMPTY)||(errno == EEXIST)) && lp_veto_files(SNUM(conn))) {
3945                 /* 
3946                  * Check to see if the only thing in this directory are
3947                  * vetoed files/directories. If so then delete them and
3948                  * retry. If we fail to delete any of them (and we *don't*
3949                  * do a recursive delete) then fail the rmdir.
3950                  */
3951                 const char *dname;
3952                 long dirpos = 0;
3953                 struct smb_Dir *dir_hnd = OpenDir(conn, directory, NULL, 0);
3954
3955                 if(dir_hnd == NULL) {
3956                         errno = ENOTEMPTY;
3957                         goto err;
3958                 }
3959
3960                 while ((dname = ReadDirName(dir_hnd,&dirpos))) {
3961                         if((strcmp(dname, ".") == 0) || (strcmp(dname, "..")==0))
3962                                 continue;
3963                         if (!is_visible_file(conn, directory, dname, &st, False))
3964                                 continue;
3965                         if(!IS_VETO_PATH(conn, dname)) {
3966                                 CloseDir(dir_hnd);
3967                                 errno = ENOTEMPTY;
3968                                 goto err;
3969                         }
3970                 }
3971
3972                 /* We only have veto files/directories. Recursive delete. */
3973
3974                 RewindDir(dir_hnd,&dirpos);
3975                 while ((dname = ReadDirName(dir_hnd,&dirpos))) {
3976                         pstring fullname;
3977
3978                         if((strcmp(dname, ".") == 0) || (strcmp(dname, "..")==0))
3979                                 continue;
3980                         if (!is_visible_file(conn, directory, dname, &st, False))
3981                                 continue;
3982
3983                         /* Construct the full name. */
3984                         if(strlen(directory) + strlen(dname) + 1 >= sizeof(fullname)) {
3985                                 errno = ENOMEM;
3986                                 break;
3987                         }
3988
3989                         pstrcpy(fullname, directory);
3990                         pstrcat(fullname, "/");
3991                         pstrcat(fullname, dname);
3992                    
3993                         if(SMB_VFS_LSTAT(conn,fullname, &st) != 0)
3994                                 break;
3995                         if(st.st_mode & S_IFDIR) {
3996                                 if(lp_recursive_veto_delete(SNUM(conn))) {
3997                                         if(!recursive_rmdir(conn, fullname))
3998                                                 break;
3999                                 }
4000                                 if(SMB_VFS_RMDIR(conn,fullname) != 0)
4001                                         break;
4002                         } else if(SMB_VFS_UNLINK(conn,fullname) != 0)
4003                                 break;
4004                 }
4005                 CloseDir(dir_hnd);
4006                 /* Retry the rmdir */
4007                 ret = SMB_VFS_RMDIR(conn,directory);
4008         }
4009
4010   err:
4011
4012         if (ret != 0) {
4013                 DEBUG(3,("rmdir_internals: couldn't remove directory %s : "
4014                          "%s\n", directory,strerror(errno)));
4015                 return map_nt_error_from_unix(errno);
4016         }
4017
4018         notify_fname(conn, NOTIFY_ACTION_REMOVED,
4019                      FILE_NOTIFY_CHANGE_DIR_NAME,
4020                      directory);
4021
4022         return NT_STATUS_OK;
4023 }
4024
4025 /****************************************************************************
4026  Reply to a rmdir.
4027 ****************************************************************************/
4028
4029 int reply_rmdir(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize)
4030 {
4031         pstring directory;
4032         int outsize = 0;
4033         SMB_STRUCT_STAT sbuf;
4034         NTSTATUS status;
4035         START_PROFILE(SMBrmdir);
4036
4037         srvstr_get_path(inbuf, directory, smb_buf(inbuf) + 1, sizeof(directory), 0, STR_TERMINATE, &status);
4038         if (!NT_STATUS_IS_OK(status)) {
4039                 END_PROFILE(SMBrmdir);
4040                 return ERROR_NT(status);
4041         }
4042
4043         status = resolve_dfspath(conn, SVAL(inbuf,smb_flg2) & FLAGS2_DFS_PATHNAMES, directory);
4044         if (!NT_STATUS_IS_OK(status)) {
4045                 END_PROFILE(SMBrmdir);
4046                 if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) {
4047                         return ERROR_BOTH(NT_STATUS_PATH_NOT_COVERED, ERRSRV, ERRbadpath);
4048                 }
4049                 return ERROR_NT(status);
4050         }
4051
4052         status = unix_convert(conn, directory, False, NULL, &sbuf);
4053         if (!NT_STATUS_IS_OK(status)) {
4054                 END_PROFILE(SMBrmdir);
4055                 return ERROR_NT(status);
4056         }
4057   
4058         status = check_name(conn, directory);
4059         if (!NT_STATUS_IS_OK(status)) {
4060                 END_PROFILE(SMBrmdir);
4061                 return ERROR_NT(status);
4062         }
4063
4064         dptr_closepath(directory,SVAL(inbuf,smb_pid));
4065         status = rmdir_internals(conn, directory);
4066         if (!NT_STATUS_IS_OK(status)) {
4067                 END_PROFILE(SMBrmdir);
4068                 return ERROR_NT(status);
4069         }
4070  
4071         outsize = set_message(inbuf,outbuf,0,0,False);
4072   
4073         DEBUG( 3, ( "rmdir %s\n", directory ) );
4074   
4075         END_PROFILE(SMBrmdir);
4076         return(outsize);
4077 }
4078
4079 /*******************************************************************
4080  Resolve wildcards in a filename rename.
4081  Note that name is in UNIX charset and thus potentially can be more
4082  than fstring buffer (255 bytes) especially in default UTF-8 case.
4083  Therefore, we use pstring inside and all calls should ensure that
4084  name2 is at least pstring-long (they do already)
4085 ********************************************************************/
4086
4087 static BOOL resolve_wildcards(const char *name1, char *name2)
4088 {
4089         pstring root1,root2;
4090         pstring ext1,ext2;
4091         char *p,*p2, *pname1, *pname2;
4092         int available_space, actual_space;
4093         
4094         pname1 = strrchr_m(name1,'/');
4095         pname2 = strrchr_m(name2,'/');
4096
4097         if (!pname1 || !pname2)
4098                 return(False);
4099   
4100         pstrcpy(root1,pname1);
4101         pstrcpy(root2,pname2);
4102         p = strrchr_m(root1,'.');
4103         if (p) {
4104                 *p = 0;
4105                 pstrcpy(ext1,p+1);
4106         } else {
4107                 pstrcpy(ext1,"");    
4108         }
4109         p = strrchr_m(root2,'.');
4110         if (p) {
4111                 *p = 0;
4112                 pstrcpy(ext2,p+1);
4113         } else {
4114                 pstrcpy(ext2,"");    
4115         }
4116
4117         p = root1;
4118         p2 = root2;
4119         while (*p2) {
4120                 if (*p2 == '?') {
4121                         *p2 = *p;
4122                         p2++;
4123                 } else if (*p2 == '*') {
4124                         pstrcpy(p2, p);
4125                         break;
4126                 } else {
4127                         p2++;
4128                 }
4129                 if (*p)
4130                         p++;
4131         }
4132
4133         p = ext1;
4134         p2 = ext2;
4135         while (*p2) {
4136                 if (*p2 == '?') {
4137                         *p2 = *p;
4138                         p2++;
4139                 } else if (*p2 == '*') {
4140                         pstrcpy(p2, p);
4141                         break;
4142                 } else {
4143                         p2++;
4144                 }
4145                 if (*p)
4146                         p++;
4147         }
4148
4149         available_space = sizeof(pstring) - PTR_DIFF(pname2, name2);
4150         
4151         if (ext2[0]) {
4152                 actual_space = snprintf(pname2, available_space - 1, "%s.%s", root2, ext2);
4153                 if (actual_space >= available_space - 1) {
4154                         DEBUG(1,("resolve_wildcards: can't fit resolved name into specified buffer (overrun by %d bytes)\n",
4155                                 actual_space - available_space));
4156                 }
4157         } else {
4158                 pstrcpy_base(pname2, root2, name2);
4159         }
4160
4161         return(True);
4162 }
4163
4164 /****************************************************************************
4165  Ensure open files have their names updated. Updated to notify other smbd's
4166  asynchronously.
4167 ****************************************************************************/
4168
4169 static void rename_open_files(connection_struct *conn, struct share_mode_lock *lck,
4170                                 SMB_DEV_T dev, SMB_INO_T inode, const char *newname)
4171 {
4172         files_struct *fsp;
4173         BOOL did_rename = False;
4174
4175         for(fsp = file_find_di_first(dev, inode); fsp; fsp = file_find_di_next(fsp)) {
4176                 /* fsp_name is a relative path under the fsp. To change this for other
4177                    sharepaths we need to manipulate relative paths. */
4178                 /* TODO - create the absolute path and manipulate the newname
4179                    relative to the sharepath. */
4180                 if (fsp->conn != conn) {
4181                         continue;
4182                 }
4183                 DEBUG(10,("rename_open_files: renaming file fnum %d (dev = %x, inode = %.0f) from %s -> %s\n",
4184                         fsp->fnum, (unsigned int)fsp->dev, (double)fsp->inode,
4185                         fsp->fsp_name, newname ));
4186                 string_set(&fsp->fsp_name, newname);
4187                 did_rename = True;
4188         }
4189
4190         if (!did_rename) {
4191                 DEBUG(10,("rename_open_files: no open files on dev %x, inode %.0f for %s\n",
4192                         (unsigned int)dev, (double)inode, newname ));
4193         }
4194
4195         /* Send messages to all smbd's (not ourself) that the name has changed. */
4196         rename_share_filename(smbd_messaging_context(), lck, conn->connectpath,
4197                               newname);
4198 }
4199
4200 /****************************************************************************
4201  We need to check if the source path is a parent directory of the destination
4202  (ie. a rename of /foo/bar/baz -> /foo/bar/baz/bibble/bobble. If so we must
4203  refuse the rename with a sharing violation. Under UNIX the above call can
4204  *succeed* if /foo/bar/baz is a symlink to another area in the share. We
4205  probably need to check that the client is a Windows one before disallowing
4206  this as a UNIX client (one with UNIX extensions) can know the source is a
4207  symlink and make this decision intelligently. Found by an excellent bug
4208  report from <AndyLiebman@aol.com>.
4209 ****************************************************************************/
4210
4211 static BOOL rename_path_prefix_equal(const char *src, const char *dest)
4212 {
4213         const char *psrc = src;
4214         const char *pdst = dest;
4215         size_t slen;
4216
4217         if (psrc[0] == '.' && psrc[1] == '/') {
4218                 psrc += 2;
4219         }
4220         if (pdst[0] == '.' && pdst[1] == '/') {
4221                 pdst += 2;
4222         }
4223         if ((slen = strlen(psrc)) > strlen(pdst)) {
4224                 return False;
4225         }
4226         return ((memcmp(psrc, pdst, slen) == 0) && pdst[slen] == '/');
4227 }
4228
4229 /****************************************************************************
4230  Rename an open file - given an fsp.
4231 ****************************************************************************/
4232
4233 NTSTATUS rename_internals_fsp(connection_struct *conn, files_struct *fsp, pstring newname, uint32 attrs, BOOL replace_if_exists)
4234 {
4235         SMB_STRUCT_STAT sbuf;
4236         pstring newname_last_component;
4237         NTSTATUS status = NT_STATUS_OK;
4238         BOOL dest_exists;
4239         struct share_mode_lock *lck = NULL;
4240
4241         ZERO_STRUCT(sbuf);
4242
4243         status = unix_convert(conn, newname, False, newname_last_component, &sbuf);
4244         if (!NT_STATUS_IS_OK(status)) {
4245                 return status;
4246         }
4247
4248         status = check_name(conn, newname);
4249         if (!NT_STATUS_IS_OK(status)) {
4250                 return status;
4251         }
4252   
4253         /* Ensure newname contains a '/' */
4254         if(strrchr_m(newname,'/') == 0) {
4255                 pstring tmpstr;
4256                 
4257                 pstrcpy(tmpstr, "./");
4258                 pstrcat(tmpstr, newname);
4259                 pstrcpy(newname, tmpstr);
4260         }
4261
4262         /*
4263          * Check for special case with case preserving and not
4264          * case sensitive. If the old last component differs from the original
4265          * last component only by case, then we should allow
4266          * the rename (user is trying to change the case of the
4267          * filename).
4268          */
4269
4270         if((conn->case_sensitive == False) && (conn->case_preserve == True) &&
4271                         strequal(newname, fsp->fsp_name)) {
4272                 char *p;
4273                 pstring newname_modified_last_component;
4274
4275                 /*
4276                  * Get the last component of the modified name.
4277                  * Note that we guarantee that newname contains a '/'
4278                  * character above.
4279                  */
4280                 p = strrchr_m(newname,'/');
4281                 pstrcpy(newname_modified_last_component,p+1);
4282                         
4283                 if(strcsequal(newname_modified_last_component, 
4284                               newname_last_component) == False) {
4285                         /*
4286                          * Replace the modified last component with
4287                          * the original.
4288                          */
4289                         pstrcpy(p+1, newname_last_component);
4290                 }
4291         }
4292
4293         /*
4294          * If the src and dest names are identical - including case,
4295          * don't do the rename, just return success.
4296          */
4297
4298         if (strcsequal(fsp->fsp_name, newname)) {
4299                 DEBUG(3,("rename_internals_fsp: identical names in rename %s - returning success\n",
4300                         newname));
4301                 return NT_STATUS_OK;
4302         }
4303
4304         dest_exists = vfs_object_exist(conn,newname,NULL);
4305
4306         if(!replace_if_exists && dest_exists) {
4307                 DEBUG(3,("rename_internals_fsp: dest exists doing rename %s -> %s\n",
4308                         fsp->fsp_name,newname));
4309                 return NT_STATUS_OBJECT_NAME_COLLISION;
4310         }
4311
4312         status = can_rename(conn,newname,attrs,&sbuf);
4313
4314         if (dest_exists && !NT_STATUS_IS_OK(status)) {
4315                 DEBUG(3,("rename_internals: Error %s rename %s -> %s\n",
4316                         nt_errstr(status), fsp->fsp_name,newname));
4317                 if (NT_STATUS_EQUAL(status,NT_STATUS_SHARING_VIOLATION))
4318                         status = NT_STATUS_ACCESS_DENIED;
4319                 return status;
4320         }
4321
4322         if (rename_path_prefix_equal(fsp->fsp_name, newname)) {
4323                 return NT_STATUS_ACCESS_DENIED;
4324         }
4325
4326         lck = get_share_mode_lock(NULL, fsp->dev, fsp->inode, NULL, NULL);
4327
4328         if(SMB_VFS_RENAME(conn,fsp->fsp_name, newname) == 0) {
4329                 DEBUG(3,("rename_internals_fsp: succeeded doing rename on %s -> %s\n",
4330                         fsp->fsp_name,newname));
4331                 rename_open_files(conn, lck, fsp->dev, fsp->inode, newname);
4332                 TALLOC_FREE(lck);
4333                 return NT_STATUS_OK;    
4334         }
4335
4336         TALLOC_FREE(lck);
4337
4338         if (errno == ENOTDIR || errno == EISDIR) {
4339                 status = NT_STATUS_OBJECT_NAME_COLLISION;
4340         } else {
4341                 status = map_nt_error_from_unix(errno);
4342         }
4343                 
4344         DEBUG(3,("rename_internals_fsp: Error %s rename %s -> %s\n",
4345                 nt_errstr(status), fsp->fsp_name,newname));
4346
4347         return status;
4348 }
4349
4350 /*
4351  * Do the notify calls from a rename
4352  */
4353
4354 static void notify_rename(connection_struct *conn, BOOL is_dir,
4355                           const char *oldpath, const char *newpath)
4356 {
4357         char *olddir, *newdir;
4358         const char *oldname, *newname;
4359         uint32 mask;
4360
4361         mask = is_dir ? FILE_NOTIFY_CHANGE_DIR_NAME
4362                 : FILE_NOTIFY_CHANGE_FILE_NAME;
4363
4364         if (!parent_dirname_talloc(NULL, oldpath, &olddir, &oldname)
4365             || !parent_dirname_talloc(NULL, newpath, &newdir, &newname)) {
4366                 TALLOC_FREE(olddir);
4367                 return;
4368         }
4369
4370         if (strcmp(olddir, newdir) == 0) {
4371                 notify_fname(conn, NOTIFY_ACTION_OLD_NAME, mask, oldpath);
4372                 notify_fname(conn, NOTIFY_ACTION_NEW_NAME, mask, newpath);
4373         }
4374         else {
4375                 notify_fname(conn, NOTIFY_ACTION_REMOVED, mask, oldpath);
4376                 notify_fname(conn, NOTIFY_ACTION_ADDED, mask, newpath);
4377         }
4378         TALLOC_FREE(olddir);
4379         TALLOC_FREE(newdir);
4380
4381         /* this is a strange one. w2k3 gives an additional event for
4382            CHANGE_ATTRIBUTES and CHANGE_CREATION on the new file when renaming
4383            files, but not directories */
4384         if (!is_dir) {
4385                 notify_fname(conn, NOTIFY_ACTION_MODIFIED,
4386                              FILE_NOTIFY_CHANGE_ATTRIBUTES
4387                              |FILE_NOTIFY_CHANGE_CREATION,
4388                              newpath);
4389         }
4390 }
4391
4392 /****************************************************************************
4393  The guts of the rename command, split out so it may be called by the NT SMB
4394  code. 
4395 ****************************************************************************/
4396
4397 NTSTATUS rename_internals(connection_struct *conn,
4398                                 pstring name,
4399                                 pstring newname,
4400                                 uint32 attrs,
4401                                 BOOL replace_if_exists,
4402                                 BOOL src_has_wild,
4403                                 BOOL dest_has_wild)
4404 {
4405         pstring directory;
4406         pstring mask;
4407         pstring last_component_src;
4408         pstring last_component_dest;
4409         char *p;
4410         int count=0;
4411         NTSTATUS status = NT_STATUS_OK;
4412         SMB_STRUCT_STAT sbuf1, sbuf2;
4413         struct share_mode_lock *lck = NULL;
4414         struct smb_Dir *dir_hnd = NULL;
4415         const char *dname;
4416         long offset = 0;
4417         pstring destname;
4418
4419         *directory = *mask = 0;
4420
4421         ZERO_STRUCT(sbuf1);
4422         ZERO_STRUCT(sbuf2);
4423
4424         status = unix_convert(conn, name, src_has_wild, last_component_src, &sbuf1);
4425         if (!NT_STATUS_IS_OK(status)) {
4426                 return status;
4427         }
4428
4429         status = unix_convert(conn, newname, dest_has_wild, last_component_dest, &sbuf2);
4430         if (!NT_STATUS_IS_OK(status)) {
4431                 return status;
4432         }
4433
4434         /*
4435          * Split the old name into directory and last component
4436          * strings. Note that unix_convert may have stripped off a 
4437          * leading ./ from both name and newname if the rename is 
4438          * at the root of the share. We need to make sure either both
4439          * name and newname contain a / character or neither of them do
4440          * as this is checked in resolve_wildcards().
4441          */
4442
4443         p = strrchr_m(name,'/');
4444         if (!p) {
4445                 pstrcpy(directory,".");
4446                 pstrcpy(mask,name);
4447         } else {
4448                 *p = 0;
4449                 pstrcpy(directory,name);
4450                 pstrcpy(mask,p+1);
4451                 *p = '/'; /* Replace needed for exceptional test below. */
4452         }
4453
4454         /*
4455          * We should only check the mangled cache
4456          * here if unix_convert failed. This means
4457          * that the path in 'mask' doesn't exist
4458          * on the file system and so we need to look
4459          * for a possible mangle. This patch from
4460          * Tine Smukavec <valentin.smukavec@hermes.si>.
4461          */
4462
4463         if (!VALID_STAT(sbuf1) && mangle_is_mangled(mask, conn->params)) {
4464                 mangle_check_cache( mask, sizeof(pstring)-1, conn->params );
4465         }
4466
4467         if (!src_has_wild) {
4468                 /*
4469                  * No wildcards - just process the one file.
4470                  */
4471                 BOOL is_short_name = mangle_is_8_3(name, True, conn->params);
4472
4473                 /* Add a terminating '/' to the directory name. */
4474                 pstrcat(directory,"/");
4475                 pstrcat(directory,mask);
4476                 
4477                 /* Ensure newname contains a '/' also */
4478                 if(strrchr_m(newname,'/') == 0) {
4479                         pstring tmpstr;
4480                         
4481                         pstrcpy(tmpstr, "./");
4482                         pstrcat(tmpstr, newname);
4483                         pstrcpy(newname, tmpstr);
4484                 }
4485                 
4486                 DEBUG(3, ("rename_internals: case_sensitive = %d, "
4487                           "case_preserve = %d, short case preserve = %d, "
4488                           "directory = %s, newname = %s, "
4489                           "last_component_dest = %s, is_8_3 = %d\n", 
4490                           conn->case_sensitive, conn->case_preserve,
4491                           conn->short_case_preserve, directory, 
4492                           newname, last_component_dest, is_short_name));
4493
4494                 /* Ensure the source name is valid for us to access. */
4495                 status = check_name(conn, directory);
4496                 if (!NT_STATUS_IS_OK(status)) {
4497                         return status;
4498                 }
4499
4500                 /* The dest name still may have wildcards. */
4501                 if (dest_has_wild) {
4502                         if (!resolve_wildcards(directory,newname)) {
4503                                 DEBUG(6, ("rename_internals: resolve_wildcards %s %s failed\n", 
4504                                           directory,newname));
4505                                 return NT_STATUS_NO_MEMORY;
4506                         }
4507                 }
4508                                 
4509                 /*
4510                  * Check for special case with case preserving and not
4511                  * case sensitive, if directory and newname are identical,
4512                  * and the old last component differs from the original
4513                  * last component only by case, then we should allow
4514                  * the rename (user is trying to change the case of the
4515                  * filename).
4516                  */
4517                 if((conn->case_sensitive == False) && 
4518                    (((conn->case_preserve == True) && 
4519                      (is_short_name == False)) || 
4520                     ((conn->short_case_preserve == True) && 
4521                      (is_short_name == True))) &&
4522                    strcsequal(directory, newname)) {
4523                         pstring modified_last_component;
4524
4525                         /*
4526                          * Get the last component of the modified name.
4527                          * Note that we guarantee that newname contains a '/'
4528                          * character above.
4529                          */
4530                         p = strrchr_m(newname,'/');
4531                         pstrcpy(modified_last_component,p+1);
4532                         
4533                         if(strcsequal(modified_last_component, 
4534                                       last_component_dest) == False) {
4535                                 /*
4536                                  * Replace the modified last component with
4537                                  * the original.
4538                                  */
4539                                 pstrcpy(p+1, last_component_dest);
4540                         }
4541                 }
4542         
4543                 /* Ensure the dest name is valid for us to access. */
4544                 status = check_name(conn, newname);
4545                 if (!NT_STATUS_IS_OK(status)) {
4546                         return status;
4547                 }
4548
4549                 /*
4550                  * The source object must exist.
4551                  */
4552
4553                 if (!vfs_object_exist(conn, directory, &sbuf1)) {
4554                         DEBUG(3, ("rename_internals: source doesn't exist "
4555                                   "doing rename %s -> %s\n",
4556                                 directory,newname));
4557
4558                         if (errno == ENOTDIR || errno == EISDIR
4559                             || errno == ENOENT) {
4560                                 /*
4561                                  * Must return different errors depending on
4562                                  * whether the parent directory existed or
4563                                  * not.
4564                                  */
4565
4566                                 p = strrchr_m(directory, '/');
4567                                 if (!p)
4568                                         return NT_STATUS_OBJECT_NAME_NOT_FOUND;
4569                                 *p = '\0';
4570                                 if (vfs_object_exist(conn, directory, NULL))
4571                                         return NT_STATUS_OBJECT_NAME_NOT_FOUND;
4572                                 return NT_STATUS_OBJECT_PATH_NOT_FOUND;
4573                         }
4574                         status = map_nt_error_from_unix(errno);
4575                         DEBUG(3, ("rename_internals: Error %s rename %s -> "
4576                                   "%s\n", nt_errstr(status), directory,
4577                                   newname));
4578
4579                         return status;
4580                 }
4581
4582                 status = can_rename(conn,directory,attrs,&sbuf1);
4583
4584                 if (!NT_STATUS_IS_OK(status)) {
4585                         DEBUG(3,("rename_internals: Error %s rename %s -> "
4586                                  "%s\n", nt_errstr(status), directory,
4587                                  newname));
4588                         return status;
4589                 }
4590
4591                 /*
4592                  * If the src and dest names are identical - including case,
4593                  * don't do the rename, just return success.
4594                  */
4595
4596                 if (strcsequal(directory, newname)) {
4597                         rename_open_files(conn, NULL, sbuf1.st_dev,
4598                                           sbuf1.st_ino, newname);
4599                         DEBUG(3, ("rename_internals: identical names in "
4600                                   "rename %s - returning success\n",
4601                                   directory));
4602                         return NT_STATUS_OK;
4603                 }
4604
4605                 if(!replace_if_exists && vfs_object_exist(conn,newname,NULL)) {
4606                         DEBUG(3,("rename_internals: dest exists doing "
4607                                  "rename %s -> %s\n", directory, newname));
4608                         return NT_STATUS_OBJECT_NAME_COLLISION;
4609                 }
4610
4611                 if (rename_path_prefix_equal(directory, newname)) {
4612                         return NT_STATUS_SHARING_VIOLATION;
4613                 }
4614
4615                 lck = get_share_mode_lock(NULL, sbuf1.st_dev, sbuf1.st_ino,
4616                                           NULL, NULL);
4617
4618                 if(SMB_VFS_RENAME(conn,directory, newname) == 0) {
4619                         DEBUG(3,("rename_internals: succeeded doing rename "
4620                                  "on %s -> %s\n", directory, newname));
4621                         rename_open_files(conn, lck, sbuf1.st_dev,
4622                                           sbuf1.st_ino, newname);
4623                         TALLOC_FREE(lck);
4624                         notify_rename(conn, S_ISDIR(sbuf1.st_mode),
4625                                       directory, newname);
4626                         return NT_STATUS_OK;    
4627                 }
4628
4629                 TALLOC_FREE(lck);
4630                 if (errno == ENOTDIR || errno == EISDIR) {
4631                         status = NT_STATUS_OBJECT_NAME_COLLISION;
4632                 } else {
4633                         status = map_nt_error_from_unix(errno);
4634                 }
4635                 
4636                 DEBUG(3,("rename_internals: Error %s rename %s -> %s\n",
4637                         nt_errstr(status), directory,newname));
4638
4639                 return status;
4640         }
4641
4642         /*
4643          * Wildcards - process each file that matches.
4644          */
4645         if (strequal(mask,"????????.???")) {
4646                 pstrcpy(mask,"*");
4647         }
4648                         
4649         status = check_name(conn, directory);
4650         if (!NT_STATUS_IS_OK(status)) {
4651                 return status;
4652         }
4653         
4654         dir_hnd = OpenDir(conn, directory, mask, attrs);
4655         if (dir_hnd == NULL) {
4656                 return map_nt_error_from_unix(errno);
4657         }
4658                 
4659         status = NT_STATUS_NO_SUCH_FILE;
4660         /*
4661          * Was status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
4662          * - gentest fix. JRA
4663          */
4664                         
4665         while ((dname = ReadDirName(dir_hnd, &offset))) {
4666                 pstring fname;
4667                 BOOL sysdir_entry = False;
4668
4669                 pstrcpy(fname,dname);
4670                                 
4671                 /* Quick check for "." and ".." */
4672                 if (fname[0] == '.') {
4673                         if (!fname[1] || (fname[1] == '.' && !fname[2])) {
4674                                 if (attrs & aDIR) {
4675                                         sysdir_entry = True;
4676                                 } else {
4677                                         continue;
4678                                 }
4679                         }
4680                 }
4681
4682                 if (!is_visible_file(conn, directory, dname, &sbuf1, False)) {
4683                         continue;
4684                 }
4685
4686                 if(!mask_match(fname, mask, conn->case_sensitive)) {
4687                         continue;
4688                 }
4689                                 
4690                 if (sysdir_entry) {
4691                         status = NT_STATUS_OBJECT_NAME_INVALID;
4692                         break;
4693                 }
4694
4695                 status = NT_STATUS_ACCESS_DENIED;
4696                 slprintf(fname, sizeof(fname)-1, "%s/%s", directory, dname);
4697
4698                 /* Ensure the source name is valid for us to access. */
4699                 status = check_name(conn, fname);
4700                 if (!NT_STATUS_IS_OK(status)) {
4701                         return status;
4702                 }
4703
4704                 if (!vfs_object_exist(conn, fname, &sbuf1)) {
4705                         status = NT_STATUS_OBJECT_NAME_NOT_FOUND;
4706                         DEBUG(6, ("rename %s failed. Error %s\n",
4707                                   fname, nt_errstr(status)));
4708                         continue;
4709                 }
4710                 status = can_rename(conn,fname,attrs,&sbuf1);
4711                 if (!NT_STATUS_IS_OK(status)) {
4712                         DEBUG(6, ("rename %s refused\n", fname));
4713                         continue;
4714                 }
4715                 pstrcpy(destname,newname);
4716                         
4717                 if (!resolve_wildcards(fname,destname)) {
4718                         DEBUG(6, ("resolve_wildcards %s %s failed\n", 
4719                                   fname, destname));
4720                         continue;
4721                 }
4722                                 
4723                 /* Ensure the dest name is valid for us to access. */
4724                 status = check_name(conn, destname);
4725                 if (!NT_STATUS_IS_OK(status)) {
4726                         return status;
4727                 }
4728
4729                 if (strcsequal(fname,destname)) {
4730                         rename_open_files(conn, NULL, sbuf1.st_dev,
4731                                           sbuf1.st_ino, newname);
4732                         DEBUG(3,("rename_internals: identical names "
4733                                  "in wildcard rename %s - success\n",
4734                                  fname));
4735                         count++;
4736                         status = NT_STATUS_OK;
4737                         continue;
4738                 }
4739
4740                 if (!replace_if_exists && vfs_file_exist(conn,destname, NULL)) {
4741                         DEBUG(6,("file_exist %s\n", destname));
4742                         status = NT_STATUS_OBJECT_NAME_COLLISION;
4743                         continue;
4744                 }
4745                                 
4746                 if (rename_path_prefix_equal(fname, destname)) {
4747                         return NT_STATUS_SHARING_VIOLATION;
4748                 }
4749
4750                 lck = get_share_mode_lock(NULL, sbuf1.st_dev,
4751                                           sbuf1.st_ino, NULL, NULL);
4752
4753                 if (!SMB_VFS_RENAME(conn,fname,destname)) {
4754                         rename_open_files(conn, lck, sbuf1.st_dev,
4755                                           sbuf1.st_ino, newname);
4756                         count++;
4757                         status = NT_STATUS_OK;
4758                 }
4759                 TALLOC_FREE(lck);
4760                 DEBUG(3,("rename_internals: doing rename on %s -> "
4761                          "%s\n",fname,destname));
4762         }
4763         CloseDir(dir_hnd);
4764
4765         if (count == 0 && NT_STATUS_IS_OK(status)) {
4766                 status = map_nt_error_from_unix(errno);
4767         }
4768         
4769         return status;
4770 }
4771
4772 /****************************************************************************
4773  Reply to a mv.
4774 ****************************************************************************/
4775
4776 int reply_mv(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, 
4777              int dum_buffsize)
4778 {
4779         int outsize = 0;
4780         pstring name;
4781         pstring newname;
4782         char *p;
4783         uint32 attrs = SVAL(inbuf,smb_vwv0);
4784         NTSTATUS status;
4785         BOOL src_has_wcard = False;
4786         BOOL dest_has_wcard = False;
4787
4788         START_PROFILE(SMBmv);
4789
4790         p = smb_buf(inbuf) + 1;
4791         p += srvstr_get_path_wcard(inbuf, name, p, sizeof(name), 0, STR_TERMINATE, &status, &src_has_wcard);
4792         if (!NT_STATUS_IS_OK(status)) {
4793                 END_PROFILE(SMBmv);
4794                 return ERROR_NT(status);
4795         }
4796         p++;
4797         p += srvstr_get_path_wcard(inbuf, newname, p, sizeof(newname), 0, STR_TERMINATE, &status, &dest_has_wcard);
4798         if (!NT_STATUS_IS_OK(status)) {
4799                 END_PROFILE(SMBmv);
4800                 return ERROR_NT(status);
4801         }
4802         
4803         status = resolve_dfspath_wcard(conn, SVAL(inbuf,smb_flg2) & FLAGS2_DFS_PATHNAMES, name, &src_has_wcard);
4804         if (!NT_STATUS_IS_OK(status)) {
4805                 END_PROFILE(SMBmv);
4806                 if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) {
4807                         return ERROR_BOTH(NT_STATUS_PATH_NOT_COVERED, ERRSRV, ERRbadpath);
4808                 }
4809                 return ERROR_NT(status);
4810         }
4811
4812         status = resolve_dfspath_wcard(conn, SVAL(inbuf,smb_flg2) & FLAGS2_DFS_PATHNAMES, newname, &dest_has_wcard);
4813         if (!NT_STATUS_IS_OK(status)) {
4814                 END_PROFILE(SMBmv);
4815                 if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) {
4816                         return ERROR_BOTH(NT_STATUS_PATH_NOT_COVERED, ERRSRV, ERRbadpath);
4817                 }
4818                 return ERROR_NT(status);
4819         }
4820         
4821         DEBUG(3,("reply_mv : %s -> %s\n",name,newname));
4822         
4823         status = rename_internals(conn, name, newname, attrs, False, src_has_wcard, dest_has_wcard);
4824         if (!NT_STATUS_IS_OK(status)) {
4825                 END_PROFILE(SMBmv);
4826                 if (open_was_deferred(SVAL(inbuf,smb_mid))) {
4827                         /* We have re-scheduled this call. */
4828                         return -1;
4829                 }
4830                 return ERROR_NT(status);
4831         }
4832
4833         outsize = set_message(inbuf,outbuf,0,0,False);
4834   
4835         END_PROFILE(SMBmv);
4836         return(outsize);
4837 }
4838
4839 /*******************************************************************
4840  Copy a file as part of a reply_copy.
4841 ******************************************************************/
4842
4843 /*
4844  * TODO: check error codes on all callers
4845  */
4846
4847 NTSTATUS copy_file(connection_struct *conn,
4848                         char *src,
4849                         char *dest1,
4850                         int ofun,
4851                         int count,
4852                         BOOL target_is_directory)
4853 {
4854         SMB_STRUCT_STAT src_sbuf, sbuf2;
4855         SMB_OFF_T ret=-1;
4856         files_struct *fsp1,*fsp2;
4857         pstring dest;
4858         uint32 dosattrs;
4859         uint32 new_create_disposition;
4860         NTSTATUS status;
4861  
4862         pstrcpy(dest,dest1);
4863         if (target_is_directory) {
4864                 char *p = strrchr_m(src,'/');
4865                 if (p) {
4866                         p++;
4867                 } else {
4868                         p = src;
4869                 }
4870                 pstrcat(dest,"/");
4871                 pstrcat(dest,p);
4872         }
4873
4874         if (!vfs_file_exist(conn,src,&src_sbuf)) {
4875                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
4876         }
4877
4878         if (!target_is_directory && count) {
4879                 new_create_disposition = FILE_OPEN;
4880         } else {
4881                 if (!map_open_params_to_ntcreate(dest1,0,ofun,
4882                                 NULL, NULL, &new_create_disposition, NULL)) {
4883                         return NT_STATUS_INVALID_PARAMETER;
4884                 }
4885         }
4886
4887         status = open_file_ntcreate(conn,src,&src_sbuf,
4888                         FILE_GENERIC_READ,
4889                         FILE_SHARE_READ|FILE_SHARE_WRITE,
4890                         FILE_OPEN,
4891                         0,
4892                         FILE_ATTRIBUTE_NORMAL,
4893                         INTERNAL_OPEN_ONLY,
4894                         NULL, &fsp1);
4895
4896         if (!NT_STATUS_IS_OK(status)) {
4897                 return status;
4898         }
4899
4900         dosattrs = dos_mode(conn, src, &src_sbuf);
4901         if (SMB_VFS_STAT(conn,dest,&sbuf2) == -1) {
4902                 ZERO_STRUCTP(&sbuf2);
4903         }
4904
4905         status = open_file_ntcreate(conn,dest,&sbuf2,
4906                         FILE_GENERIC_WRITE,
4907                         FILE_SHARE_READ|FILE_SHARE_WRITE,
4908                         new_create_disposition,
4909                         0,
4910                         dosattrs,
4911                         INTERNAL_OPEN_ONLY,
4912                         NULL, &fsp2);
4913
4914         if (!NT_STATUS_IS_OK(status)) {
4915                 close_file(fsp1,ERROR_CLOSE);
4916                 return status;
4917         }
4918
4919         if ((ofun&3) == 1) {
4920                 if(SMB_VFS_LSEEK(fsp2,fsp2->fh->fd,0,SEEK_END) == -1) {
4921                         DEBUG(0,("copy_file: error - vfs lseek returned error %s\n", strerror(errno) ));
4922                         /*
4923                          * Stop the copy from occurring.
4924                          */
4925                         ret = -1;
4926                         src_sbuf.st_size = 0;
4927                 }
4928         }
4929   
4930         if (src_sbuf.st_size) {
4931                 ret = vfs_transfer_file(fsp1, fsp2, src_sbuf.st_size);
4932         }
4933
4934         close_file(fsp1,NORMAL_CLOSE);
4935
4936         /* Ensure the modtime is set correctly on the destination file. */
4937         fsp_set_pending_modtime( fsp2, get_mtimespec(&src_sbuf));
4938
4939         /*
4940          * As we are opening fsp1 read-only we only expect
4941          * an error on close on fsp2 if we are out of space.
4942          * Thus we don't look at the error return from the
4943          * close of fsp1.
4944          */
4945         status = close_file(fsp2,NORMAL_CLOSE);
4946
4947         if (!NT_STATUS_IS_OK(status)) {
4948                 return status;
4949         }
4950
4951         if (ret != (SMB_OFF_T)src_sbuf.st_size) {
4952                 return NT_STATUS_DISK_FULL;
4953         }
4954
4955         return NT_STATUS_OK;
4956 }
4957
4958 /****************************************************************************
4959  Reply to a file copy.
4960 ****************************************************************************/
4961
4962 int reply_copy(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize)
4963 {
4964         int outsize = 0;
4965         pstring name;
4966         pstring directory;
4967         pstring mask,newname;
4968         char *p;
4969         int count=0;
4970         int error = ERRnoaccess;
4971         int err = 0;
4972         int tid2 = SVAL(inbuf,smb_vwv0);
4973         int ofun = SVAL(inbuf,smb_vwv1);
4974         int flags = SVAL(inbuf,smb_vwv2);
4975         BOOL target_is_directory=False;
4976         BOOL source_has_wild = False;
4977         BOOL dest_has_wild = False;
4978         SMB_STRUCT_STAT sbuf1, sbuf2;
4979         NTSTATUS status;
4980         START_PROFILE(SMBcopy);
4981
4982         *directory = *mask = 0;
4983
4984         p = smb_buf(inbuf);
4985         p += srvstr_get_path_wcard(inbuf, name, p, sizeof(name), 0, STR_TERMINATE, &status, &source_has_wild);
4986         if (!NT_STATUS_IS_OK(status)) {
4987                 END_PROFILE(SMBcopy);
4988                 return ERROR_NT(status);
4989         }
4990         p += srvstr_get_path_wcard(inbuf, newname, p, sizeof(newname), 0, STR_TERMINATE, &status, &dest_has_wild);
4991         if (!NT_STATUS_IS_OK(status)) {
4992                 END_PROFILE(SMBcopy);
4993                 return ERROR_NT(status);
4994         }
4995    
4996         DEBUG(3,("reply_copy : %s -> %s\n",name,newname));
4997    
4998         if (tid2 != conn->cnum) {
4999                 /* can't currently handle inter share copies XXXX */
5000                 DEBUG(3,("Rejecting inter-share copy\n"));
5001                 END_PROFILE(SMBcopy);
5002                 return ERROR_DOS(ERRSRV,ERRinvdevice);
5003         }
5004
5005         status = resolve_dfspath_wcard(conn, SVAL(inbuf,smb_flg2) & FLAGS2_DFS_PATHNAMES, name, &source_has_wild);
5006         if (!NT_STATUS_IS_OK(status)) {
5007                 END_PROFILE(SMBcopy);
5008                 if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) {
5009                         return ERROR_BOTH(NT_STATUS_PATH_NOT_COVERED, ERRSRV, ERRbadpath);
5010                 }
5011                 return ERROR_NT(status);
5012         }
5013
5014         status = resolve_dfspath_wcard(conn, SVAL(inbuf,smb_flg2) & FLAGS2_DFS_PATHNAMES, newname, &dest_has_wild);
5015         if (!NT_STATUS_IS_OK(status)) {
5016                 END_PROFILE(SMBcopy);
5017                 if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) {
5018                         return ERROR_BOTH(NT_STATUS_PATH_NOT_COVERED, ERRSRV, ERRbadpath);
5019                 }
5020                 return ERROR_NT(status);
5021         }
5022
5023         status = unix_convert(conn, name, source_has_wild, NULL, &sbuf1);
5024         if (!NT_STATUS_IS_OK(status)) {
5025                 END_PROFILE(SMBcopy);
5026                 return ERROR_NT(status);
5027         }
5028
5029         status = unix_convert(conn, newname, dest_has_wild, NULL, &sbuf2);
5030         if (!NT_STATUS_IS_OK(status)) {
5031                 END_PROFILE(SMBcopy);
5032                 return ERROR_NT(status);
5033         }
5034
5035         target_is_directory = VALID_STAT_OF_DIR(sbuf2);
5036
5037         if ((flags&1) && target_is_directory) {
5038                 END_PROFILE(SMBcopy);
5039                 return ERROR_DOS(ERRDOS,ERRbadfile);
5040         }
5041
5042         if ((flags&2) && !target_is_directory) {
5043                 END_PROFILE(SMBcopy);
5044                 return ERROR_DOS(ERRDOS,ERRbadpath);
5045         }
5046
5047         if ((flags&(1<<5)) && VALID_STAT_OF_DIR(sbuf1)) {
5048                 /* wants a tree copy! XXXX */
5049                 DEBUG(3,("Rejecting tree copy\n"));
5050                 END_PROFILE(SMBcopy);
5051                 return ERROR_DOS(ERRSRV,ERRerror);
5052         }
5053
5054         p = strrchr_m(name,'/');
5055         if (!p) {
5056                 pstrcpy(directory,"./");
5057                 pstrcpy(mask,name);
5058         } else {
5059                 *p = 0;
5060                 pstrcpy(directory,name);
5061                 pstrcpy(mask,p+1);
5062         }
5063
5064         /*
5065          * We should only check the mangled cache
5066          * here if unix_convert failed. This means
5067          * that the path in 'mask' doesn't exist
5068          * on the file system and so we need to look
5069          * for a possible mangle. This patch from
5070          * Tine Smukavec <valentin.smukavec@hermes.si>.
5071          */
5072
5073         if (!VALID_STAT(sbuf1) && mangle_is_mangled(mask, conn->params)) {
5074                 mangle_check_cache( mask, sizeof(pstring)-1, conn->params );
5075         }
5076
5077         if (!source_has_wild) {
5078                 pstrcat(directory,"/");
5079                 pstrcat(directory,mask);
5080                 if (dest_has_wild) {
5081                         if (!resolve_wildcards(directory,newname)) {
5082                                 END_PROFILE(SMBcopy);
5083                                 return ERROR_NT(NT_STATUS_NO_MEMORY);
5084                         }
5085                 }
5086
5087                 status = check_name(conn, directory);
5088                 if (!NT_STATUS_IS_OK(status)) {
5089                         return ERROR_NT(status);
5090                 }
5091                 
5092                 status = check_name(conn, newname);
5093                 if (!NT_STATUS_IS_OK(status)) {
5094                         return ERROR_NT(status);
5095                 }
5096                 
5097                 status = copy_file(conn,directory,newname,ofun,
5098                                         count,target_is_directory);
5099
5100                 if(!NT_STATUS_IS_OK(status)) {
5101                         END_PROFILE(SMBcopy);
5102                         return ERROR_NT(status);
5103                 } else {
5104                         count++;
5105                 }
5106         } else {
5107                 struct smb_Dir *dir_hnd = NULL;
5108                 const char *dname;
5109                 long offset = 0;
5110                 pstring destname;
5111
5112                 if (strequal(mask,"????????.???"))
5113                         pstrcpy(mask,"*");
5114
5115                 status = check_name(conn, directory);
5116                 if (!NT_STATUS_IS_OK(status)) {
5117                         return ERROR_NT(status);
5118                 }
5119                 
5120                 dir_hnd = OpenDir(conn, directory, mask, 0);
5121                 if (dir_hnd == NULL) {
5122                         status = map_nt_error_from_unix(errno);
5123                         return ERROR_NT(status);
5124                 }
5125
5126                 error = ERRbadfile;
5127
5128                 while ((dname = ReadDirName(dir_hnd, &offset))) {
5129                         pstring fname;
5130                         pstrcpy(fname,dname);
5131     
5132                         if (!is_visible_file(conn, directory, dname, &sbuf1, False)) {
5133                                 continue;
5134                         }
5135
5136                         if(!mask_match(fname, mask, conn->case_sensitive)) {
5137                                 continue;
5138                         }
5139
5140                         error = ERRnoaccess;
5141                         slprintf(fname,sizeof(fname)-1, "%s/%s",directory,dname);
5142                         pstrcpy(destname,newname);
5143                         if (!resolve_wildcards(fname,destname)) {
5144                                 continue;
5145                         }
5146
5147                         status = check_name(conn, fname);
5148                         if (!NT_STATUS_IS_OK(status)) {
5149                                 return ERROR_NT(status);
5150                         }
5151                 
5152                         status = check_name(conn, destname);
5153                         if (!NT_STATUS_IS_OK(status)) {
5154                                 return ERROR_NT(status);
5155                         }
5156                 
5157                         DEBUG(3,("reply_copy : doing copy on %s -> %s\n",fname, destname));
5158
5159                         status = copy_file(conn,fname,destname,ofun,
5160                                         count,target_is_directory);
5161                         if (NT_STATUS_IS_OK(status)) {
5162                                 count++;
5163                         }
5164                 }
5165                 CloseDir(dir_hnd);
5166         }
5167   
5168         if (count == 0) {
5169                 if(err) {
5170                         /* Error on close... */
5171                         errno = err;
5172                         END_PROFILE(SMBcopy);
5173                         return(UNIXERROR(ERRHRD,ERRgeneral));
5174                 }
5175
5176                 END_PROFILE(SMBcopy);
5177                 return ERROR_DOS(ERRDOS,error);
5178         }
5179   
5180         outsize = set_message(inbuf,outbuf,1,0,True);
5181         SSVAL(outbuf,smb_vwv0,count);
5182
5183         END_PROFILE(SMBcopy);
5184         return(outsize);
5185 }
5186
5187 /****************************************************************************
5188  Reply to a setdir.
5189 ****************************************************************************/
5190
5191 int reply_setdir(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize)
5192 {
5193         int snum;
5194         int outsize = 0;
5195         pstring newdir;
5196         NTSTATUS status;
5197
5198         START_PROFILE(pathworks_setdir);
5199   
5200         snum = SNUM(conn);
5201         if (!CAN_SETDIR(snum)) {
5202                 END_PROFILE(pathworks_setdir);
5203                 return ERROR_DOS(ERRDOS,ERRnoaccess);
5204         }
5205
5206         srvstr_get_path(inbuf, newdir, smb_buf(inbuf) + 1, sizeof(newdir), 0, STR_TERMINATE, &status);
5207         if (!NT_STATUS_IS_OK(status)) {
5208                 END_PROFILE(pathworks_setdir);
5209                 return ERROR_NT(status);
5210         }
5211   
5212         status = resolve_dfspath(conn, SVAL(inbuf,smb_flg2) & FLAGS2_DFS_PATHNAMES, newdir);
5213         if (!NT_STATUS_IS_OK(status)) {
5214                 END_PROFILE(pathworks_setdir);
5215                 if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) {
5216                         return ERROR_BOTH(NT_STATUS_PATH_NOT_COVERED, ERRSRV, ERRbadpath);
5217                 }
5218                 return ERROR_NT(status);
5219         }
5220
5221         if (strlen(newdir) != 0) {
5222                 if (!vfs_directory_exist(conn,newdir,NULL)) {
5223                         END_PROFILE(pathworks_setdir);
5224                         return ERROR_DOS(ERRDOS,ERRbadpath);
5225                 }
5226                 set_conn_connectpath(conn,newdir);
5227         }
5228   
5229         outsize = set_message(inbuf,outbuf,0,0,False);
5230         SCVAL(outbuf,smb_reh,CVAL(inbuf,smb_reh));
5231   
5232         DEBUG(3,("setdir %s\n", newdir));
5233
5234         END_PROFILE(pathworks_setdir);
5235         return(outsize);
5236 }
5237
5238 #undef DBGC_CLASS
5239 #define DBGC_CLASS DBGC_LOCKING
5240
5241 /****************************************************************************
5242  Get a lock pid, dealing with large count requests.
5243 ****************************************************************************/
5244
5245 uint32 get_lock_pid( char *data, int data_offset, BOOL large_file_format)
5246 {
5247         if(!large_file_format)
5248                 return (uint32)SVAL(data,SMB_LPID_OFFSET(data_offset));
5249         else
5250                 return (uint32)SVAL(data,SMB_LARGE_LPID_OFFSET(data_offset));
5251 }
5252
5253 /****************************************************************************
5254  Get a lock count, dealing with large count requests.
5255 ****************************************************************************/
5256
5257 SMB_BIG_UINT get_lock_count( char *data, int data_offset, BOOL large_file_format)
5258 {
5259         SMB_BIG_UINT count = 0;
5260
5261         if(!large_file_format) {
5262                 count = (SMB_BIG_UINT)IVAL(data,SMB_LKLEN_OFFSET(data_offset));
5263         } else {
5264
5265 #if defined(HAVE_LONGLONG)
5266                 count = (((SMB_BIG_UINT) IVAL(data,SMB_LARGE_LKLEN_OFFSET_HIGH(data_offset))) << 32) |
5267                         ((SMB_BIG_UINT) IVAL(data,SMB_LARGE_LKLEN_OFFSET_LOW(data_offset)));
5268 #else /* HAVE_LONGLONG */
5269
5270                 /*
5271                  * NT4.x seems to be broken in that it sends large file (64 bit)
5272                  * lockingX calls even if the CAP_LARGE_FILES was *not*
5273                  * negotiated. For boxes without large unsigned ints truncate the
5274                  * lock count by dropping the top 32 bits.
5275                  */
5276
5277                 if(IVAL(data,SMB_LARGE_LKLEN_OFFSET_HIGH(data_offset)) != 0) {
5278                         DEBUG(3,("get_lock_count: truncating lock count (high)0x%x (low)0x%x to just low count.\n",
5279                                 (unsigned int)IVAL(data,SMB_LARGE_LKLEN_OFFSET_HIGH(data_offset)),
5280                                 (unsigned int)IVAL(data,SMB_LARGE_LKLEN_OFFSET_LOW(data_offset)) ));
5281                                 SIVAL(data,SMB_LARGE_LKLEN_OFFSET_HIGH(data_offset),0);
5282                 }
5283
5284                 count = (SMB_BIG_UINT)IVAL(data,SMB_LARGE_LKLEN_OFFSET_LOW(data_offset));
5285 #endif /* HAVE_LONGLONG */
5286         }
5287
5288         return count;
5289 }
5290
5291 #if !defined(HAVE_LONGLONG)
5292 /****************************************************************************
5293  Pathetically try and map a 64 bit lock offset into 31 bits. I hate Windows :-).
5294 ****************************************************************************/
5295
5296 static uint32 map_lock_offset(uint32 high, uint32 low)
5297 {
5298         unsigned int i;
5299         uint32 mask = 0;
5300         uint32 highcopy = high;
5301  
5302         /*
5303          * Try and find out how many significant bits there are in high.
5304          */
5305  
5306         for(i = 0; highcopy; i++)
5307                 highcopy >>= 1;
5308  
5309         /*
5310          * We use 31 bits not 32 here as POSIX
5311          * lock offsets may not be negative.
5312          */
5313  
5314         mask = (~0) << (31 - i);
5315  
5316         if(low & mask)
5317                 return 0; /* Fail. */
5318  
5319         high <<= (31 - i);
5320  
5321         return (high|low);
5322 }
5323 #endif /* !defined(HAVE_LONGLONG) */
5324
5325 /****************************************************************************
5326  Get a lock offset, dealing with large offset requests.
5327 ****************************************************************************/
5328
5329 SMB_BIG_UINT get_lock_offset( char *data, int data_offset, BOOL large_file_format, BOOL *err)
5330 {
5331         SMB_BIG_UINT offset = 0;
5332
5333         *err = False;
5334
5335         if(!large_file_format) {
5336                 offset = (SMB_BIG_UINT)IVAL(data,SMB_LKOFF_OFFSET(data_offset));
5337         } else {
5338
5339 #if defined(HAVE_LONGLONG)
5340                 offset = (((SMB_BIG_UINT) IVAL(data,SMB_LARGE_LKOFF_OFFSET_HIGH(data_offset))) << 32) |
5341                                 ((SMB_BIG_UINT) IVAL(data,SMB_LARGE_LKOFF_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 mangle the
5348                  * lock offset by mapping the top 32 bits onto the lower 32.
5349                  */
5350       
5351                 if(IVAL(data,SMB_LARGE_LKOFF_OFFSET_HIGH(data_offset)) != 0) {
5352                         uint32 low = IVAL(data,SMB_LARGE_LKOFF_OFFSET_LOW(data_offset));
5353                         uint32 high = IVAL(data,SMB_LARGE_LKOFF_OFFSET_HIGH(data_offset));
5354                         uint32 new_low = 0;
5355
5356                         if((new_low = map_lock_offset(high, low)) == 0) {
5357                                 *err = True;
5358                                 return (SMB_BIG_UINT)-1;
5359                         }
5360
5361                         DEBUG(3,("get_lock_offset: truncating lock offset (high)0x%x (low)0x%x to offset 0x%x.\n",
5362                                 (unsigned int)high, (unsigned int)low, (unsigned int)new_low ));
5363                         SIVAL(data,SMB_LARGE_LKOFF_OFFSET_HIGH(data_offset),0);
5364                         SIVAL(data,SMB_LARGE_LKOFF_OFFSET_LOW(data_offset),new_low);
5365                 }
5366
5367                 offset = (SMB_BIG_UINT)IVAL(data,SMB_LARGE_LKOFF_OFFSET_LOW(data_offset));
5368 #endif /* HAVE_LONGLONG */
5369         }
5370
5371         return offset;
5372 }
5373
5374 /****************************************************************************
5375  Reply to a lockingX request.
5376 ****************************************************************************/
5377
5378 int reply_lockingX(connection_struct *conn, char *inbuf, char *outbuf,
5379                    int length, int bufsize)
5380 {
5381         files_struct *fsp = file_fsp(inbuf,smb_vwv2);
5382         unsigned char locktype = CVAL(inbuf,smb_vwv3);
5383         unsigned char oplocklevel = CVAL(inbuf,smb_vwv3+1);
5384         uint16 num_ulocks = SVAL(inbuf,smb_vwv6);
5385         uint16 num_locks = SVAL(inbuf,smb_vwv7);
5386         SMB_BIG_UINT count = 0, offset = 0;
5387         uint32 lock_pid;
5388         int32 lock_timeout = IVAL(inbuf,smb_vwv4);
5389         int i;
5390         char *data;
5391         BOOL large_file_format =
5392                 (locktype & LOCKING_ANDX_LARGE_FILES)?True:False;
5393         BOOL err;
5394         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
5395
5396         START_PROFILE(SMBlockingX);
5397         
5398         CHECK_FSP(fsp,conn);
5399         
5400         data = smb_buf(inbuf);
5401
5402         if (locktype & LOCKING_ANDX_CHANGE_LOCKTYPE) {
5403                 /* we don't support these - and CANCEL_LOCK makes w2k
5404                    and XP reboot so I don't really want to be
5405                    compatible! (tridge) */
5406                 return ERROR_NT(NT_STATUS_DOS(ERRDOS, ERRnoatomiclocks));
5407         }
5408         
5409         /* Check if this is an oplock break on a file
5410            we have granted an oplock on.
5411         */
5412         if ((locktype & LOCKING_ANDX_OPLOCK_RELEASE)) {
5413                 /* Client can insist on breaking to none. */
5414                 BOOL break_to_none = (oplocklevel == 0);
5415                 BOOL result;
5416
5417                 DEBUG(5,("reply_lockingX: oplock break reply (%u) from client "
5418                          "for fnum = %d\n", (unsigned int)oplocklevel,
5419                          fsp->fnum ));
5420
5421                 /*
5422                  * Make sure we have granted an exclusive or batch oplock on
5423                  * this file.
5424                  */
5425                 
5426                 if (fsp->oplock_type == 0) {
5427
5428                         /* The Samba4 nbench simulator doesn't understand
5429                            the difference between break to level2 and break
5430                            to none from level2 - it sends oplock break
5431                            replies in both cases. Don't keep logging an error
5432                            message here - just ignore it. JRA. */
5433
5434                         DEBUG(5,("reply_lockingX: Error : oplock break from "
5435                                  "client for fnum = %d (oplock=%d) and no "
5436                                  "oplock granted on this file (%s).\n",
5437                                  fsp->fnum, fsp->oplock_type, fsp->fsp_name));
5438
5439                         /* if this is a pure oplock break request then don't
5440                          * send a reply */
5441                         if (num_locks == 0 && num_ulocks == 0) {
5442                                 END_PROFILE(SMBlockingX);
5443                                 return -1;
5444                         } else {
5445                                 END_PROFILE(SMBlockingX);
5446                                 return ERROR_DOS(ERRDOS,ERRlock);
5447                         }
5448                 }
5449
5450                 if ((fsp->sent_oplock_break == BREAK_TO_NONE_SENT) ||
5451                     (break_to_none)) {
5452                         result = remove_oplock(fsp);
5453                 } else {
5454                         result = downgrade_oplock(fsp);
5455                 }
5456                 
5457                 if (!result) {
5458                         DEBUG(0, ("reply_lockingX: error in removing "
5459                                   "oplock on file %s\n", fsp->fsp_name));
5460                         /* Hmmm. Is this panic justified? */
5461                         smb_panic("internal tdb error");
5462                 }
5463
5464                 reply_to_oplock_break_requests(fsp);
5465
5466                 /* if this is a pure oplock break request then don't send a
5467                  * reply */
5468                 if (num_locks == 0 && num_ulocks == 0) {
5469                         /* Sanity check - ensure a pure oplock break is not a
5470                            chained request. */
5471                         if(CVAL(inbuf,smb_vwv0) != 0xff)
5472                                 DEBUG(0,("reply_lockingX: Error : pure oplock "
5473                                          "break is a chained %d request !\n",
5474                                          (unsigned int)CVAL(inbuf,smb_vwv0) ));
5475                         END_PROFILE(SMBlockingX);
5476                         return -1;
5477                 }
5478         }
5479
5480         /*
5481          * We do this check *after* we have checked this is not a oplock break
5482          * response message. JRA.
5483          */
5484         
5485         release_level_2_oplocks_on_change(fsp);
5486         
5487         /* Data now points at the beginning of the list
5488            of smb_unlkrng structs */
5489         for(i = 0; i < (int)num_ulocks; i++) {
5490                 lock_pid = get_lock_pid( data, i, large_file_format);
5491                 count = get_lock_count( data, i, large_file_format);
5492                 offset = get_lock_offset( data, i, large_file_format, &err);
5493                 
5494                 /*
5495                  * There is no error code marked "stupid client bug".... :-).
5496                  */
5497                 if(err) {
5498                         END_PROFILE(SMBlockingX);
5499                         return ERROR_DOS(ERRDOS,ERRnoaccess);
5500                 }
5501
5502                 DEBUG(10,("reply_lockingX: unlock start=%.0f, len=%.0f for "
5503                           "pid %u, file %s\n", (double)offset, (double)count,
5504                           (unsigned int)lock_pid, fsp->fsp_name ));
5505                 
5506                 status = do_unlock(smbd_messaging_context(),
5507                                 fsp,
5508                                 lock_pid,
5509                                 count,
5510                                 offset,
5511                                 WINDOWS_LOCK);
5512
5513                 if (NT_STATUS_V(status)) {
5514                         END_PROFILE(SMBlockingX);
5515                         return ERROR_NT(status);
5516                 }
5517         }
5518
5519         /* Setup the timeout in seconds. */
5520
5521         if (!lp_blocking_locks(SNUM(conn))) {
5522                 lock_timeout = 0;
5523         }
5524         
5525         /* Now do any requested locks */
5526         data += ((large_file_format ? 20 : 10)*num_ulocks);
5527         
5528         /* Data now points at the beginning of the list
5529            of smb_lkrng structs */
5530         
5531         for(i = 0; i < (int)num_locks; i++) {
5532                 enum brl_type lock_type = ((locktype & LOCKING_ANDX_SHARED_LOCK) ?
5533                                 READ_LOCK:WRITE_LOCK);
5534                 lock_pid = get_lock_pid( data, i, large_file_format);
5535                 count = get_lock_count( data, i, large_file_format);
5536                 offset = get_lock_offset( data, i, large_file_format, &err);
5537                 
5538                 /*
5539                  * There is no error code marked "stupid client bug".... :-).
5540                  */
5541                 if(err) {
5542                         END_PROFILE(SMBlockingX);
5543                         return ERROR_DOS(ERRDOS,ERRnoaccess);
5544                 }
5545                 
5546                 DEBUG(10,("reply_lockingX: lock start=%.0f, len=%.0f for pid "
5547                           "%u, file %s timeout = %d\n", (double)offset,
5548                           (double)count, (unsigned int)lock_pid,
5549                           fsp->fsp_name, (int)lock_timeout ));
5550                 
5551                 if (locktype & LOCKING_ANDX_CANCEL_LOCK) {
5552                         if (lp_blocking_locks(SNUM(conn))) {
5553
5554                                 /* Schedule a message to ourselves to
5555                                    remove the blocking lock record and
5556                                    return the right error. */
5557
5558                                 if (!blocking_lock_cancel(fsp,
5559                                                 lock_pid,
5560                                                 offset,
5561                                                 count,
5562                                                 WINDOWS_LOCK,
5563                                                 locktype,
5564                                                 NT_STATUS_FILE_LOCK_CONFLICT)) {
5565                                         END_PROFILE(SMBlockingX);
5566                                         return ERROR_NT(NT_STATUS_DOS(ERRDOS, ERRcancelviolation));
5567                                 }
5568                         }
5569                         /* Remove a matching pending lock. */
5570                         status = do_lock_cancel(fsp,
5571                                                 lock_pid,
5572                                                 count,
5573                                                 offset,
5574                                                 WINDOWS_LOCK);
5575                 } else {
5576                         BOOL blocking_lock = lock_timeout ? True : False;
5577                         BOOL defer_lock = False;
5578                         struct byte_range_lock *br_lck;
5579
5580                         br_lck = do_lock(smbd_messaging_context(),
5581                                         fsp,
5582                                         lock_pid,
5583                                         count,
5584                                         offset, 
5585                                         lock_type,
5586                                         WINDOWS_LOCK,
5587                                         blocking_lock,
5588                                         &status);
5589
5590                         if (br_lck && blocking_lock && ERROR_WAS_LOCK_DENIED(status)) {
5591                                 /* Windows internal resolution for blocking locks seems
5592                                    to be about 200ms... Don't wait for less than that. JRA. */
5593                                 if (lock_timeout != -1 && lock_timeout < lp_lock_spin_time()) {
5594                                         lock_timeout = lp_lock_spin_time();
5595                                 }
5596                                 defer_lock = True;
5597                         }
5598
5599                         /* This heuristic seems to match W2K3 very well. If a
5600                            lock sent with timeout of zero would fail with NT_STATUS_FILE_LOCK_CONFLICT
5601                            it pretends we asked for a timeout of between 150 - 300 milliseconds as
5602                            far as I can tell. Replacement for do_lock_spin(). JRA. */
5603
5604                         if (br_lck && lp_blocking_locks(SNUM(conn)) && !blocking_lock &&
5605                                         NT_STATUS_EQUAL((status), NT_STATUS_FILE_LOCK_CONFLICT)) {
5606                                 defer_lock = True;
5607                                 lock_timeout = lp_lock_spin_time();
5608                         }
5609
5610                         if (br_lck && defer_lock) {
5611                                 /*
5612                                  * A blocking lock was requested. Package up
5613                                  * this smb into a queued request and push it
5614                                  * onto the blocking lock queue.
5615                                  */
5616                                 if(push_blocking_lock_request(br_lck,
5617                                                         inbuf, length,
5618                                                         fsp,
5619                                                         lock_timeout,
5620                                                         i,
5621                                                         lock_pid,
5622                                                         lock_type,
5623                                                         WINDOWS_LOCK,
5624                                                         offset,
5625                                                         count)) {
5626                                         TALLOC_FREE(br_lck);
5627                                         END_PROFILE(SMBlockingX);
5628                                         return -1;
5629                                 }
5630                         }
5631
5632                         TALLOC_FREE(br_lck);
5633                 }
5634
5635                 if (NT_STATUS_V(status)) {
5636                         END_PROFILE(SMBlockingX);
5637                         return ERROR_NT(status);
5638                 }
5639         }
5640         
5641         /* If any of the above locks failed, then we must unlock
5642            all of the previous locks (X/Open spec). */
5643
5644         if (!(locktype & LOCKING_ANDX_CANCEL_LOCK) &&
5645                         (i != num_locks) &&
5646                         (num_locks != 0)) {
5647                 /*
5648                  * Ensure we don't do a remove on the lock that just failed,
5649                  * as under POSIX rules, if we have a lock already there, we
5650                  * will delete it (and we shouldn't) .....
5651                  */
5652                 for(i--; i >= 0; i--) {
5653                         lock_pid = get_lock_pid( data, i, large_file_format);
5654                         count = get_lock_count( data, i, large_file_format);
5655                         offset = get_lock_offset( data, i, large_file_format,
5656                                                   &err);
5657                         
5658                         /*
5659                          * There is no error code marked "stupid client
5660                          * bug".... :-).
5661                          */
5662                         if(err) {
5663                                 END_PROFILE(SMBlockingX);
5664                                 return ERROR_DOS(ERRDOS,ERRnoaccess);
5665                         }
5666                         
5667                         do_unlock(smbd_messaging_context(),
5668                                 fsp,
5669                                 lock_pid,
5670                                 count,
5671                                 offset,
5672                                 WINDOWS_LOCK);
5673                 }
5674                 END_PROFILE(SMBlockingX);
5675                 return ERROR_NT(status);
5676         }
5677
5678         set_message(inbuf,outbuf,2,0,True);
5679         
5680         DEBUG(3, ("lockingX fnum=%d type=%d num_locks=%d num_ulocks=%d\n",
5681                   fsp->fnum, (unsigned int)locktype, num_locks, num_ulocks));
5682         
5683         END_PROFILE(SMBlockingX);
5684         return chain_reply(inbuf,outbuf,length,bufsize);
5685 }
5686
5687 #undef DBGC_CLASS
5688 #define DBGC_CLASS DBGC_ALL
5689
5690 /****************************************************************************
5691  Reply to a SMBreadbmpx (read block multiplex) request.
5692 ****************************************************************************/
5693
5694 int reply_readbmpx(connection_struct *conn, char *inbuf,char *outbuf,int length,int bufsize)
5695 {
5696         ssize_t nread = -1;
5697         ssize_t total_read;
5698         char *data;
5699         SMB_OFF_T startpos;
5700         int outsize;
5701         size_t maxcount;
5702         int max_per_packet;
5703         size_t tcount;
5704         int pad;
5705         files_struct *fsp = file_fsp(inbuf,smb_vwv0);
5706         START_PROFILE(SMBreadBmpx);
5707
5708         /* this function doesn't seem to work - disable by default */
5709         if (!lp_readbmpx()) {
5710                 END_PROFILE(SMBreadBmpx);
5711                 return ERROR_DOS(ERRSRV,ERRuseSTD);
5712         }
5713
5714         outsize = set_message(inbuf,outbuf,8,0,True);
5715
5716         CHECK_FSP(fsp,conn);
5717         if (!CHECK_READ(fsp,inbuf)) {
5718                 return(ERROR_DOS(ERRDOS,ERRbadaccess));
5719         }
5720
5721         startpos = IVAL_TO_SMB_OFF_T(inbuf,smb_vwv1);
5722         maxcount = SVAL(inbuf,smb_vwv3);
5723
5724         data = smb_buf(outbuf);
5725         pad = ((long)data)%4;
5726         if (pad)
5727                 pad = 4 - pad;
5728         data += pad;
5729
5730         max_per_packet = bufsize-(outsize+pad);
5731         tcount = maxcount;
5732         total_read = 0;
5733
5734         if (is_locked(fsp,(uint32)SVAL(inbuf,smb_pid),(SMB_BIG_UINT)maxcount,(SMB_BIG_UINT)startpos, READ_LOCK)) {
5735                 END_PROFILE(SMBreadBmpx);
5736                 return ERROR_DOS(ERRDOS,ERRlock);
5737         }
5738
5739         do {
5740                 size_t N = MIN(max_per_packet,tcount-total_read);
5741   
5742                 nread = read_file(fsp,data,startpos,N);
5743
5744                 if (nread <= 0)
5745                         nread = 0;
5746
5747                 if (nread < (ssize_t)N)
5748                         tcount = total_read + nread;
5749
5750                 set_message(inbuf,outbuf,8,nread+pad,False);
5751                 SIVAL(outbuf,smb_vwv0,startpos);
5752                 SSVAL(outbuf,smb_vwv2,tcount);
5753                 SSVAL(outbuf,smb_vwv6,nread);
5754                 SSVAL(outbuf,smb_vwv7,smb_offset(data,outbuf));
5755
5756                 show_msg(outbuf);
5757                 if (!send_smb(smbd_server_fd(),outbuf))
5758                         exit_server_cleanly("reply_readbmpx: send_smb failed.");
5759
5760                 total_read += nread;
5761                 startpos += nread;
5762         } while (total_read < (ssize_t)tcount);
5763
5764         END_PROFILE(SMBreadBmpx);
5765         return(-1);
5766 }
5767
5768 /****************************************************************************
5769  Reply to a SMBsetattrE.
5770 ****************************************************************************/
5771
5772 int reply_setattrE(connection_struct *conn, char *inbuf,char *outbuf, int size, int dum_buffsize)
5773 {
5774         struct timespec ts[2];
5775         int outsize = 0;
5776         files_struct *fsp = file_fsp(inbuf,smb_vwv0);
5777         START_PROFILE(SMBsetattrE);
5778
5779         outsize = set_message(inbuf,outbuf,0,0,False);
5780
5781         if(!fsp || (fsp->conn != conn)) {
5782                 END_PROFILE(SMBsetattrE);
5783                 return ERROR_DOS(ERRDOS,ERRbadfid);
5784         }
5785
5786         /*
5787          * Convert the DOS times into unix times. Ignore create
5788          * time as UNIX can't set this.
5789          */
5790
5791         ts[0] = convert_time_t_to_timespec(srv_make_unix_date2(inbuf+smb_vwv3)); /* atime. */
5792         ts[1] = convert_time_t_to_timespec(srv_make_unix_date2(inbuf+smb_vwv5)); /* mtime. */
5793   
5794         /* 
5795          * Patch from Ray Frush <frush@engr.colostate.edu>
5796          * Sometimes times are sent as zero - ignore them.
5797          */
5798
5799         if (null_timespec(ts[0]) && null_timespec(ts[1])) {
5800                 /* Ignore request */
5801                 if( DEBUGLVL( 3 ) ) {
5802                         dbgtext( "reply_setattrE fnum=%d ", fsp->fnum);
5803                         dbgtext( "ignoring zero request - not setting timestamps of 0\n" );
5804                 }
5805                 END_PROFILE(SMBsetattrE);
5806                 return(outsize);
5807         } else if (!null_timespec(ts[0]) && null_timespec(ts[1])) {
5808                 /* set modify time = to access time if modify time was unset */
5809                 ts[1] = ts[0];
5810         }
5811
5812         /* Set the date on this file */
5813         /* Should we set pending modtime here ? JRA */
5814         if(file_ntimes(conn, fsp->fsp_name, ts)) {
5815                 END_PROFILE(SMBsetattrE);
5816                 return ERROR_DOS(ERRDOS,ERRnoaccess);
5817         }
5818   
5819         DEBUG( 3, ( "reply_setattrE fnum=%d actime=%u modtime=%u\n",
5820                 fsp->fnum,
5821                 (unsigned int)ts[0].tv_sec,
5822                 (unsigned int)ts[1].tv_sec));
5823
5824         END_PROFILE(SMBsetattrE);
5825         return(outsize);
5826 }
5827
5828
5829 /* Back from the dead for OS/2..... JRA. */
5830
5831 /****************************************************************************
5832  Reply to a SMBwritebmpx (write block multiplex primary) request.
5833 ****************************************************************************/
5834
5835 int reply_writebmpx(connection_struct *conn, char *inbuf,char *outbuf, int size, int dum_buffsize)
5836 {
5837         size_t numtowrite;
5838         ssize_t nwritten = -1;
5839         int outsize = 0;
5840         SMB_OFF_T startpos;
5841         size_t tcount;
5842         BOOL write_through;
5843         int smb_doff;
5844         char *data;
5845         files_struct *fsp = file_fsp(inbuf,smb_vwv0);
5846         START_PROFILE(SMBwriteBmpx);
5847
5848         CHECK_FSP(fsp,conn);
5849         if (!CHECK_WRITE(fsp)) {
5850                 return(ERROR_DOS(ERRDOS,ERRbadaccess));
5851         }
5852         if (HAS_CACHED_ERROR(fsp)) {
5853                 return(CACHED_ERROR(fsp));
5854         }
5855
5856         tcount = SVAL(inbuf,smb_vwv1);
5857         startpos = IVAL_TO_SMB_OFF_T(inbuf,smb_vwv3);
5858         write_through = BITSETW(inbuf+smb_vwv7,0);
5859         numtowrite = SVAL(inbuf,smb_vwv10);
5860         smb_doff = SVAL(inbuf,smb_vwv11);
5861
5862         data = smb_base(inbuf) + smb_doff;
5863
5864         /* If this fails we need to send an SMBwriteC response,
5865                 not an SMBwritebmpx - set this up now so we don't forget */
5866         SCVAL(outbuf,smb_com,SMBwritec);
5867
5868         if (is_locked(fsp,(uint32)SVAL(inbuf,smb_pid),(SMB_BIG_UINT)tcount,(SMB_BIG_UINT)startpos,WRITE_LOCK)) {
5869                 END_PROFILE(SMBwriteBmpx);
5870                 return(ERROR_DOS(ERRDOS,ERRlock));
5871         }
5872
5873         nwritten = write_file(fsp,data,startpos,numtowrite);
5874
5875         sync_file(conn, fsp, write_through);
5876   
5877         if(nwritten < (ssize_t)numtowrite) {
5878                 END_PROFILE(SMBwriteBmpx);
5879                 return(UNIXERROR(ERRHRD,ERRdiskfull));
5880         }
5881
5882         /* If the maximum to be written to this file
5883                 is greater than what we just wrote then set
5884                 up a secondary struct to be attached to this
5885                 fd, we will use this to cache error messages etc. */
5886
5887         if((ssize_t)tcount > nwritten) {
5888                 write_bmpx_struct *wbms;
5889                 if(fsp->wbmpx_ptr != NULL)
5890                         wbms = fsp->wbmpx_ptr; /* Use an existing struct */
5891                 else
5892                         wbms = SMB_MALLOC_P(write_bmpx_struct);
5893                 if(!wbms) {
5894                         DEBUG(0,("Out of memory in reply_readmpx\n"));
5895                         END_PROFILE(SMBwriteBmpx);
5896                         return(ERROR_DOS(ERRSRV,ERRnoresource));
5897                 }
5898                 wbms->wr_mode = write_through;
5899                 wbms->wr_discard = False; /* No errors yet */
5900                 wbms->wr_total_written = nwritten;
5901                 wbms->wr_errclass = 0;
5902                 wbms->wr_error = 0;
5903                 fsp->wbmpx_ptr = wbms;
5904         }
5905
5906         /* We are returning successfully, set the message type back to
5907                 SMBwritebmpx */
5908         SCVAL(outbuf,smb_com,SMBwriteBmpx);
5909   
5910         outsize = set_message(inbuf,outbuf,1,0,True);
5911   
5912         SSVALS(outbuf,smb_vwv0,-1); /* We don't support smb_remaining */
5913   
5914         DEBUG( 3, ( "writebmpx fnum=%d num=%d wrote=%d\n",
5915                         fsp->fnum, (int)numtowrite, (int)nwritten ) );
5916
5917         if (write_through && tcount==nwritten) {
5918                 /* We need to send both a primary and a secondary response */
5919                 smb_setlen(inbuf,outbuf,outsize - 4);
5920                 show_msg(outbuf);
5921                 if (!send_smb(smbd_server_fd(),outbuf))
5922                         exit_server_cleanly("reply_writebmpx: send_smb failed.");
5923
5924                 /* Now the secondary */
5925                 outsize = set_message(inbuf,outbuf,1,0,True);
5926                 SCVAL(outbuf,smb_com,SMBwritec);
5927                 SSVAL(outbuf,smb_vwv0,nwritten);
5928         }
5929
5930         END_PROFILE(SMBwriteBmpx);
5931         return(outsize);
5932 }
5933
5934 /****************************************************************************
5935  Reply to a SMBwritebs (write block multiplex secondary) request.
5936 ****************************************************************************/
5937
5938 int reply_writebs(connection_struct *conn, char *inbuf,char *outbuf, int dum_size, int dum_buffsize)
5939 {
5940         size_t numtowrite;
5941         ssize_t nwritten = -1;
5942         int outsize = 0;
5943         SMB_OFF_T startpos;
5944         size_t tcount;
5945         BOOL write_through;
5946         int smb_doff;
5947         char *data;
5948         write_bmpx_struct *wbms;
5949         BOOL send_response = False; 
5950         files_struct *fsp = file_fsp(inbuf,smb_vwv0);
5951         START_PROFILE(SMBwriteBs);
5952
5953         CHECK_FSP(fsp,conn);
5954         if (!CHECK_WRITE(fsp)) {
5955                 return(ERROR_DOS(ERRDOS,ERRbadaccess));
5956         }
5957
5958         tcount = SVAL(inbuf,smb_vwv1);
5959         startpos = IVAL_TO_SMB_OFF_T(inbuf,smb_vwv2);
5960         numtowrite = SVAL(inbuf,smb_vwv6);
5961         smb_doff = SVAL(inbuf,smb_vwv7);
5962
5963         data = smb_base(inbuf) + smb_doff;
5964
5965         /* We need to send an SMBwriteC response, not an SMBwritebs */
5966         SCVAL(outbuf,smb_com,SMBwritec);
5967
5968         /* This fd should have an auxiliary struct attached,
5969                 check that it does */
5970         wbms = fsp->wbmpx_ptr;
5971         if(!wbms) {
5972                 END_PROFILE(SMBwriteBs);
5973                 return(-1);
5974         }
5975
5976         /* If write through is set we can return errors, else we must cache them */
5977         write_through = wbms->wr_mode;
5978
5979         /* Check for an earlier error */
5980         if(wbms->wr_discard) {
5981                 END_PROFILE(SMBwriteBs);
5982                 return -1; /* Just discard the packet */
5983         }
5984
5985         nwritten = write_file(fsp,data,startpos,numtowrite);
5986
5987         sync_file(conn, fsp, write_through);
5988   
5989         if (nwritten < (ssize_t)numtowrite) {
5990                 if(write_through) {
5991                         /* We are returning an error - we can delete the aux struct */
5992                         if (wbms)
5993                                 free((char *)wbms);
5994                         fsp->wbmpx_ptr = NULL;
5995                         END_PROFILE(SMBwriteBs);
5996                         return(ERROR_DOS(ERRHRD,ERRdiskfull));
5997                 }
5998                 wbms->wr_errclass = ERRHRD;
5999                 wbms->wr_error = ERRdiskfull;
6000                 wbms->wr_status = NT_STATUS_DISK_FULL;
6001                 wbms->wr_discard = True;
6002                 END_PROFILE(SMBwriteBs);
6003                 return -1;
6004         }
6005
6006         /* Increment the total written, if this matches tcount
6007                 we can discard the auxiliary struct (hurrah !) and return a writeC */
6008         wbms->wr_total_written += nwritten;
6009         if(wbms->wr_total_written >= tcount) {
6010                 if (write_through) {
6011                         outsize = set_message(inbuf,outbuf,1,0,True);
6012                         SSVAL(outbuf,smb_vwv0,wbms->wr_total_written);    
6013                         send_response = True;
6014                 }
6015
6016                 free((char *)wbms);
6017                 fsp->wbmpx_ptr = NULL;
6018         }
6019
6020         if(send_response) {
6021                 END_PROFILE(SMBwriteBs);
6022                 return(outsize);
6023         }
6024
6025         END_PROFILE(SMBwriteBs);
6026         return(-1);
6027 }
6028
6029 /****************************************************************************
6030  Reply to a SMBgetattrE.
6031 ****************************************************************************/
6032
6033 int reply_getattrE(connection_struct *conn, char *inbuf,char *outbuf, int size, int dum_buffsize)
6034 {
6035         SMB_STRUCT_STAT sbuf;
6036         int outsize = 0;
6037         int mode;
6038         files_struct *fsp = file_fsp(inbuf,smb_vwv0);
6039         START_PROFILE(SMBgetattrE);
6040
6041         outsize = set_message(inbuf,outbuf,11,0,True);
6042
6043         if(!fsp || (fsp->conn != conn)) {
6044                 END_PROFILE(SMBgetattrE);
6045                 return ERROR_DOS(ERRDOS,ERRbadfid);
6046         }
6047
6048         /* Do an fstat on this file */
6049         if(fsp_stat(fsp, &sbuf)) {
6050                 END_PROFILE(SMBgetattrE);
6051                 return(UNIXERROR(ERRDOS,ERRnoaccess));
6052         }
6053   
6054         mode = dos_mode(conn,fsp->fsp_name,&sbuf);
6055   
6056         /*
6057          * Convert the times into dos times. Set create
6058          * date to be last modify date as UNIX doesn't save
6059          * this.
6060          */
6061
6062         srv_put_dos_date2(outbuf,smb_vwv0,get_create_time(&sbuf,lp_fake_dir_create_times(SNUM(conn))));
6063         srv_put_dos_date2(outbuf,smb_vwv2,sbuf.st_atime);
6064         /* Should we check pending modtime here ? JRA */
6065         srv_put_dos_date2(outbuf,smb_vwv4,sbuf.st_mtime);
6066
6067         if (mode & aDIR) {
6068                 SIVAL(outbuf,smb_vwv6,0);
6069                 SIVAL(outbuf,smb_vwv8,0);
6070         } else {
6071                 uint32 allocation_size = get_allocation_size(conn,fsp, &sbuf);
6072                 SIVAL(outbuf,smb_vwv6,(uint32)sbuf.st_size);
6073                 SIVAL(outbuf,smb_vwv8,allocation_size);
6074         }
6075         SSVAL(outbuf,smb_vwv10, mode);
6076   
6077         DEBUG( 3, ( "reply_getattrE fnum=%d\n", fsp->fnum));
6078   
6079         END_PROFILE(SMBgetattrE);
6080         return(outsize);
6081 }