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