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