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