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