s3: Add SMB_VFS_CREATE_FILE to the vfs layer
[kai/samba.git] / source3 / smbd / reply.c
1 /*
2    Unix SMB/CIFS implementation.
3    Main SMB reply routines
4    Copyright (C) Andrew Tridgell 1992-1998
5    Copyright (C) Andrew Bartlett      2001
6    Copyright (C) Jeremy Allison 1992-2007.
7    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 extern uint32 global_client_caps;
33
34 extern bool global_encrypted_passwords_negotiated;
35
36 /****************************************************************************
37  Ensure we check the path in *exactly* the same way as W2K for a findfirst/findnext
38  path or anything including wildcards.
39  We're assuming here that '/' is not the second byte in any multibyte char
40  set (a safe assumption). '\\' *may* be the second byte in a multibyte char
41  set.
42 ****************************************************************************/
43
44 /* Custom version for processing POSIX paths. */
45 #define IS_PATH_SEP(c,posix_only) ((c) == '/' || (!(posix_only) && (c) == '\\'))
46
47 static NTSTATUS check_path_syntax_internal(char *path,
48                                            bool posix_path,
49                                            bool *p_last_component_contains_wcard)
50 {
51         char *d = path;
52         const char *s = path;
53         NTSTATUS ret = NT_STATUS_OK;
54         bool start_of_name_component = True;
55         bool stream_started = false;
56
57         *p_last_component_contains_wcard = False;
58
59         while (*s) {
60                 if (stream_started) {
61                         switch (*s) {
62                         case '/':
63                         case '\\':
64                                 return NT_STATUS_OBJECT_NAME_INVALID;
65                         case ':':
66                                 if (s[1] == '\0') {
67                                         return NT_STATUS_OBJECT_NAME_INVALID;
68                                 }
69                                 if (strchr_m(&s[1], ':')) {
70                                         return NT_STATUS_OBJECT_NAME_INVALID;
71                                 }
72                                 if (StrCaseCmp(s, ":$DATA") != 0) {
73                                         return NT_STATUS_INVALID_PARAMETER;
74                                 }
75                                 break;
76                         }
77                 }
78
79                 if (!stream_started && *s == ':') {
80                         if (*p_last_component_contains_wcard) {
81                                 return NT_STATUS_OBJECT_NAME_INVALID;
82                         }
83                         /* stream names allow more characters than file names */
84                         stream_started = true;
85                         start_of_name_component = false;
86                         posix_path = true;
87
88                         if (s[1] == '\0') {
89                                 return NT_STATUS_OBJECT_NAME_INVALID;
90                         }
91                 }
92
93                 if (!stream_started && IS_PATH_SEP(*s,posix_path)) {
94                         /*
95                          * Safe to assume is not the second part of a mb char
96                          * as this is handled below.
97                          */
98                         /* Eat multiple '/' or '\\' */
99                         while (IS_PATH_SEP(*s,posix_path)) {
100                                 s++;
101                         }
102                         if ((d != path) && (*s != '\0')) {
103                                 /* We only care about non-leading or trailing '/' or '\\' */
104                                 *d++ = '/';
105                         }
106
107                         start_of_name_component = True;
108                         /* New component. */
109                         *p_last_component_contains_wcard = False;
110                         continue;
111                 }
112
113                 if (start_of_name_component) {
114                         if ((s[0] == '.') && (s[1] == '.') && (IS_PATH_SEP(s[2],posix_path) || s[2] == '\0')) {
115                                 /* Uh oh - "/../" or "\\..\\"  or "/..\0" or "\\..\0" ! */
116
117                                 /*
118                                  * No mb char starts with '.' so we're safe checking the directory separator here.
119                                  */
120
121                                 /* If  we just added a '/' - delete it */
122                                 if ((d > path) && (*(d-1) == '/')) {
123                                         *(d-1) = '\0';
124                                         d--;
125                                 }
126
127                                 /* Are we at the start ? Can't go back further if so. */
128                                 if (d <= path) {
129                                         ret = NT_STATUS_OBJECT_PATH_SYNTAX_BAD;
130                                         break;
131                                 }
132                                 /* Go back one level... */
133                                 /* We know this is safe as '/' cannot be part of a mb sequence. */
134                                 /* NOTE - if this assumption is invalid we are not in good shape... */
135                                 /* Decrement d first as d points to the *next* char to write into. */
136                                 for (d--; d > path; d--) {
137                                         if (*d == '/')
138                                                 break;
139                                 }
140                                 s += 2; /* Else go past the .. */
141                                 /* We're still at the start of a name component, just the previous one. */
142                                 continue;
143
144                         } else if ((s[0] == '.') && ((s[1] == '\0') || IS_PATH_SEP(s[1],posix_path))) {
145                                 if (posix_path) {
146                                         /* Eat the '.' */
147                                         s++;
148                                         continue;
149                                 }
150                         }
151
152                 }
153
154                 if (!(*s & 0x80)) {
155                         if (!posix_path) {
156                                 if (*s <= 0x1f || *s == '|') {
157                                         return NT_STATUS_OBJECT_NAME_INVALID;
158                                 }
159                                 switch (*s) {
160                                         case '*':
161                                         case '?':
162                                         case '<':
163                                         case '>':
164                                         case '"':
165                                                 *p_last_component_contains_wcard = True;
166                                                 break;
167                                         default:
168                                                 break;
169                                 }
170                         }
171                         *d++ = *s++;
172                 } else {
173                         size_t siz;
174                         /* Get the size of the next MB character. */
175                         next_codepoint(s,&siz);
176                         switch(siz) {
177                                 case 5:
178                                         *d++ = *s++;
179                                         /*fall through*/
180                                 case 4:
181                                         *d++ = *s++;
182                                         /*fall through*/
183                                 case 3:
184                                         *d++ = *s++;
185                                         /*fall through*/
186                                 case 2:
187                                         *d++ = *s++;
188                                         /*fall through*/
189                                 case 1:
190                                         *d++ = *s++;
191                                         break;
192                                 default:
193                                         DEBUG(0,("check_path_syntax_internal: character length assumptions invalid !\n"));
194                                         *d = '\0';
195                                         return NT_STATUS_INVALID_PARAMETER;
196                         }
197                 }
198                 start_of_name_component = False;
199         }
200
201         *d = '\0';
202
203         return ret;
204 }
205
206 /****************************************************************************
207  Ensure we check the path in *exactly* the same way as W2K for regular pathnames.
208  No wildcards allowed.
209 ****************************************************************************/
210
211 NTSTATUS check_path_syntax(char *path)
212 {
213         bool ignore;
214         return check_path_syntax_internal(path, False, &ignore);
215 }
216
217 /****************************************************************************
218  Ensure we check the path in *exactly* the same way as W2K for regular pathnames.
219  Wildcards allowed - p_contains_wcard returns true if the last component contained
220  a wildcard.
221 ****************************************************************************/
222
223 NTSTATUS check_path_syntax_wcard(char *path, bool *p_contains_wcard)
224 {
225         return check_path_syntax_internal(path, False, p_contains_wcard);
226 }
227
228 /****************************************************************************
229  Check the path for a POSIX client.
230  We're assuming here that '/' is not the second byte in any multibyte char
231  set (a safe assumption).
232 ****************************************************************************/
233
234 NTSTATUS check_path_syntax_posix(char *path)
235 {
236         bool ignore;
237         return check_path_syntax_internal(path, True, &ignore);
238 }
239
240 /****************************************************************************
241  Pull a string and check the path allowing a wilcard - provide for error return.
242 ****************************************************************************/
243
244 size_t srvstr_get_path_wcard(TALLOC_CTX *ctx,
245                         const char *base_ptr,
246                         uint16 smb_flags2,
247                         char **pp_dest,
248                         const char *src,
249                         size_t src_len,
250                         int flags,
251                         NTSTATUS *err,
252                         bool *contains_wcard)
253 {
254         size_t ret;
255
256         *pp_dest = NULL;
257
258         ret = srvstr_pull_talloc(ctx, base_ptr, smb_flags2, pp_dest, src,
259                                  src_len, flags);
260
261         if (!*pp_dest) {
262                 *err = NT_STATUS_INVALID_PARAMETER;
263                 return ret;
264         }
265
266         *contains_wcard = False;
267
268         if (smb_flags2 & FLAGS2_DFS_PATHNAMES) {
269                 /*
270                  * For a DFS path the function parse_dfs_path()
271                  * will do the path processing, just make a copy.
272                  */
273                 *err = NT_STATUS_OK;
274                 return ret;
275         }
276
277         if (lp_posix_pathnames()) {
278                 *err = check_path_syntax_posix(*pp_dest);
279         } else {
280                 *err = check_path_syntax_wcard(*pp_dest, contains_wcard);
281         }
282
283         return ret;
284 }
285
286 /****************************************************************************
287  Pull a string and check the path - provide for error return.
288 ****************************************************************************/
289
290 size_t srvstr_get_path(TALLOC_CTX *ctx,
291                         const char *base_ptr,
292                         uint16 smb_flags2,
293                         char **pp_dest,
294                         const char *src,
295                         size_t src_len,
296                         int flags,
297                         NTSTATUS *err)
298 {
299         bool ignore;
300         return srvstr_get_path_wcard(ctx, base_ptr, smb_flags2, pp_dest, src,
301                                      src_len, flags, err, &ignore);
302 }
303
304 size_t srvstr_get_path_req_wcard(TALLOC_CTX *mem_ctx, struct smb_request *req,
305                                  char **pp_dest, const char *src, int flags,
306                                  NTSTATUS *err, bool *contains_wcard)
307 {
308         return srvstr_get_path_wcard(mem_ctx, (char *)req->inbuf, req->flags2,
309                                      pp_dest, src, smbreq_bufrem(req, src),
310                                      flags, err, contains_wcard);
311 }
312
313 size_t srvstr_get_path_req(TALLOC_CTX *mem_ctx, struct smb_request *req,
314                            char **pp_dest, const char *src, int flags,
315                            NTSTATUS *err)
316 {
317         bool ignore;
318         return srvstr_get_path_req_wcard(mem_ctx, req, pp_dest, src,
319                                          flags, err, &ignore);
320 }
321
322 /****************************************************************************
323  Check if we have a correct fsp pointing to a file. Basic check for open fsp.
324 ****************************************************************************/
325
326 bool check_fsp_open(connection_struct *conn, struct smb_request *req,
327                     files_struct *fsp)
328 {
329         if (!(fsp) || !(conn)) {
330                 reply_nterror(req, NT_STATUS_INVALID_HANDLE);
331                 return False;
332         }
333         if (((conn) != (fsp)->conn) || req->vuid != (fsp)->vuid) {
334                 reply_nterror(req, NT_STATUS_INVALID_HANDLE);
335                 return False;
336         }
337         return True;
338 }
339
340 /****************************************************************************
341  Check if we have a correct fsp pointing to a file.
342 ****************************************************************************/
343
344 bool check_fsp(connection_struct *conn, struct smb_request *req,
345                files_struct *fsp)
346 {
347         if (!check_fsp_open(conn, req, fsp)) {
348                 return False;
349         }
350         if ((fsp)->is_directory) {
351                 reply_nterror(req, NT_STATUS_INVALID_DEVICE_REQUEST);
352                 return False;
353         }
354         if ((fsp)->fh->fd == -1) {
355                 reply_nterror(req, NT_STATUS_ACCESS_DENIED);
356                 return False;
357         }
358         (fsp)->num_smb_operations++;
359         return True;
360 }
361
362 /****************************************************************************
363  Check if we have a correct fsp pointing to a quota fake file. Replacement for
364  the CHECK_NTQUOTA_HANDLE_OK macro.
365 ****************************************************************************/
366
367 bool check_fsp_ntquota_handle(connection_struct *conn, struct smb_request *req,
368                               files_struct *fsp)
369 {
370         if (!check_fsp_open(conn, req, fsp)) {
371                 return false;
372         }
373
374         if (fsp->is_directory) {
375                 return false;
376         }
377
378         if (fsp->fake_file_handle == NULL) {
379                 return false;
380         }
381
382         if (fsp->fake_file_handle->type != FAKE_FILE_TYPE_QUOTA) {
383                 return false;
384         }
385
386         if (fsp->fake_file_handle->private_data == NULL) {
387                 return false;
388         }
389
390         return true;
391 }
392
393 /****************************************************************************
394  Check if we have a correct fsp. Replacement for the FSP_BELONGS_CONN macro
395 ****************************************************************************/
396
397 bool fsp_belongs_conn(connection_struct *conn, struct smb_request *req,
398                       files_struct *fsp)
399 {
400         if ((fsp) && (conn) && ((conn)==(fsp)->conn)
401             && (req->vuid == (fsp)->vuid)) {
402                 return True;
403         }
404
405         reply_nterror(req, NT_STATUS_INVALID_HANDLE);
406         return False;
407 }
408
409 /****************************************************************************
410  Reply to a (netbios-level) special message.
411 ****************************************************************************/
412
413 void reply_special(char *inbuf)
414 {
415         int msg_type = CVAL(inbuf,0);
416         int msg_flags = CVAL(inbuf,1);
417         fstring name1,name2;
418         char name_type = 0;
419
420         /*
421          * We only really use 4 bytes of the outbuf, but for the smb_setlen
422          * calculation & friends (srv_send_smb uses that) we need the full smb
423          * header.
424          */
425         char outbuf[smb_size];
426
427         static bool already_got_session = False;
428
429         *name1 = *name2 = 0;
430
431         memset(outbuf, '\0', sizeof(outbuf));
432
433         smb_setlen(outbuf,0);
434
435         switch (msg_type) {
436         case 0x81: /* session request */
437
438                 if (already_got_session) {
439                         exit_server_cleanly("multiple session request not permitted");
440                 }
441
442                 SCVAL(outbuf,0,0x82);
443                 SCVAL(outbuf,3,0);
444                 if (name_len(inbuf+4) > 50 || 
445                     name_len(inbuf+4 + name_len(inbuf + 4)) > 50) {
446                         DEBUG(0,("Invalid name length in session request\n"));
447                         return;
448                 }
449                 name_extract(inbuf,4,name1);
450                 name_type = name_extract(inbuf,4 + name_len(inbuf + 4),name2);
451                 DEBUG(2,("netbios connect: name1=%s name2=%s\n",
452                          name1,name2));      
453
454                 set_local_machine_name(name1, True);
455                 set_remote_machine_name(name2, True);
456
457                 DEBUG(2,("netbios connect: local=%s remote=%s, name type = %x\n",
458                          get_local_machine_name(), get_remote_machine_name(),
459                          name_type));
460
461                 if (name_type == 'R') {
462                         /* We are being asked for a pathworks session --- 
463                            no thanks! */
464                         SCVAL(outbuf, 0,0x83);
465                         break;
466                 }
467
468                 /* only add the client's machine name to the list
469                    of possibly valid usernames if we are operating
470                    in share mode security */
471                 if (lp_security() == SEC_SHARE) {
472                         add_session_user(get_remote_machine_name());
473                 }
474
475                 reload_services(True);
476                 reopen_logs();
477
478                 already_got_session = True;
479                 break;
480
481         case 0x89: /* session keepalive request 
482                       (some old clients produce this?) */
483                 SCVAL(outbuf,0,SMBkeepalive);
484                 SCVAL(outbuf,3,0);
485                 break;
486
487         case 0x82: /* positive session response */
488         case 0x83: /* negative session response */
489         case 0x84: /* retarget session response */
490                 DEBUG(0,("Unexpected session response\n"));
491                 break;
492
493         case SMBkeepalive: /* session keepalive */
494         default:
495                 return;
496         }
497
498         DEBUG(5,("init msg_type=0x%x msg_flags=0x%x\n",
499                     msg_type, msg_flags));
500
501         srv_send_smb(smbd_server_fd(), outbuf, false);
502         return;
503 }
504
505 /****************************************************************************
506  Reply to a tcon.
507  conn POINTER CAN BE NULL HERE !
508 ****************************************************************************/
509
510 void reply_tcon(struct smb_request *req)
511 {
512         connection_struct *conn = req->conn;
513         const char *service;
514         char *service_buf = NULL;
515         char *password = NULL;
516         char *dev = NULL;
517         int pwlen=0;
518         NTSTATUS nt_status;
519         const char *p;
520         DATA_BLOB password_blob;
521         TALLOC_CTX *ctx = talloc_tos();
522
523         START_PROFILE(SMBtcon);
524
525         if (req->buflen < 4) {
526                 reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
527                 END_PROFILE(SMBtcon);
528                 return;
529         }
530
531         p = (const char *)req->buf + 1;
532         p += srvstr_pull_req_talloc(ctx, req, &service_buf, p, STR_TERMINATE);
533         p += 1;
534         pwlen = srvstr_pull_req_talloc(ctx, req, &password, p, STR_TERMINATE);
535         p += pwlen+1;
536         p += srvstr_pull_req_talloc(ctx, req, &dev, p, STR_TERMINATE);
537         p += 1;
538
539         if (service_buf == NULL || password == NULL || dev == NULL) {
540                 reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
541                 END_PROFILE(SMBtcon);
542                 return;
543         }
544         p = strrchr_m(service_buf,'\\');
545         if (p) {
546                 service = p+1;
547         } else {
548                 service = service_buf;
549         }
550
551         password_blob = data_blob(password, pwlen+1);
552
553         conn = make_connection(service,password_blob,dev,req->vuid,&nt_status);
554         req->conn = conn;
555
556         data_blob_clear_free(&password_blob);
557
558         if (!conn) {
559                 reply_nterror(req, nt_status);
560                 END_PROFILE(SMBtcon);
561                 return;
562         }
563
564         reply_outbuf(req, 2, 0);
565         SSVAL(req->outbuf,smb_vwv0,max_recv);
566         SSVAL(req->outbuf,smb_vwv1,conn->cnum);
567         SSVAL(req->outbuf,smb_tid,conn->cnum);
568
569         DEBUG(3,("tcon service=%s cnum=%d\n",
570                  service, conn->cnum));
571
572         END_PROFILE(SMBtcon);
573         return;
574 }
575
576 /****************************************************************************
577  Reply to a tcon and X.
578  conn POINTER CAN BE NULL HERE !
579 ****************************************************************************/
580
581 void reply_tcon_and_X(struct smb_request *req)
582 {
583         connection_struct *conn = req->conn;
584         const char *service = NULL;
585         DATA_BLOB password;
586         TALLOC_CTX *ctx = talloc_tos();
587         /* what the cleint thinks the device is */
588         char *client_devicetype = NULL;
589         /* what the server tells the client the share represents */
590         const char *server_devicetype;
591         NTSTATUS nt_status;
592         int passlen;
593         char *path = NULL;
594         const char *p, *q;
595         uint16 tcon_flags;
596
597         START_PROFILE(SMBtconX);
598
599         if (req->wct < 4) {
600                 reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
601                 END_PROFILE(SMBtconX);
602                 return;
603         }
604
605         passlen = SVAL(req->vwv+3, 0);
606         tcon_flags = SVAL(req->vwv+2, 0);
607
608         /* we might have to close an old one */
609         if ((tcon_flags & 0x1) && conn) {
610                 close_cnum(conn,req->vuid);
611                 req->conn = NULL;
612                 conn = NULL;
613         }
614
615         if ((passlen > MAX_PASS_LEN) || (passlen >= req->buflen)) {
616                 reply_doserror(req, ERRDOS, ERRbuftoosmall);
617                 END_PROFILE(SMBtconX);
618                 return;
619         }
620
621         if (global_encrypted_passwords_negotiated) {
622                 password = data_blob_talloc(talloc_tos(), req->buf, passlen);
623                 if (lp_security() == SEC_SHARE) {
624                         /*
625                          * Security = share always has a pad byte
626                          * after the password.
627                          */
628                         p = (const char *)req->buf + passlen + 1;
629                 } else {
630                         p = (const char *)req->buf + passlen;
631                 }
632         } else {
633                 password = data_blob_talloc(talloc_tos(), req->buf, passlen+1);
634                 /* Ensure correct termination */
635                 password.data[passlen]=0;
636                 p = (const char *)req->buf + passlen + 1;
637         }
638
639         p += srvstr_pull_req_talloc(ctx, req, &path, p, STR_TERMINATE);
640
641         if (path == NULL) {
642                 data_blob_clear_free(&password);
643                 reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
644                 END_PROFILE(SMBtconX);
645                 return;
646         }
647
648         /*
649          * the service name can be either: \\server\share
650          * or share directly like on the DELL PowerVault 705
651          */
652         if (*path=='\\') {
653                 q = strchr_m(path+2,'\\');
654                 if (!q) {
655                         data_blob_clear_free(&password);
656                         reply_doserror(req, ERRDOS, ERRnosuchshare);
657                         END_PROFILE(SMBtconX);
658                         return;
659                 }
660                 service = q+1;
661         } else {
662                 service = path;
663         }
664
665         p += srvstr_pull_talloc(ctx, req->inbuf, req->flags2,
666                                 &client_devicetype, p,
667                                 MIN(6, smbreq_bufrem(req, p)), STR_ASCII);
668
669         if (client_devicetype == NULL) {
670                 data_blob_clear_free(&password);
671                 reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
672                 END_PROFILE(SMBtconX);
673                 return;
674         }
675
676         DEBUG(4,("Client requested device type [%s] for share [%s]\n", client_devicetype, service));
677
678         conn = make_connection(service, password, client_devicetype,
679                                req->vuid, &nt_status);
680         req->conn =conn;
681
682         data_blob_clear_free(&password);
683
684         if (!conn) {
685                 reply_nterror(req, nt_status);
686                 END_PROFILE(SMBtconX);
687                 return;
688         }
689
690         if ( IS_IPC(conn) )
691                 server_devicetype = "IPC";
692         else if ( IS_PRINT(conn) )
693                 server_devicetype = "LPT1:";
694         else
695                 server_devicetype = "A:";
696
697         if (Protocol < PROTOCOL_NT1) {
698                 reply_outbuf(req, 2, 0);
699                 if (message_push_string(&req->outbuf, server_devicetype,
700                                         STR_TERMINATE|STR_ASCII) == -1) {
701                         reply_nterror(req, NT_STATUS_NO_MEMORY);
702                         END_PROFILE(SMBtconX);
703                         return;
704                 }
705         } else {
706                 /* NT sets the fstype of IPC$ to the null string */
707                 const char *fstype = IS_IPC(conn) ? "" : lp_fstype(SNUM(conn));
708
709                 if (tcon_flags & TCONX_FLAG_EXTENDED_RESPONSE) {
710                         /* Return permissions. */
711                         uint32 perm1 = 0;
712                         uint32 perm2 = 0;
713
714                         reply_outbuf(req, 7, 0);
715
716                         if (IS_IPC(conn)) {
717                                 perm1 = FILE_ALL_ACCESS;
718                                 perm2 = FILE_ALL_ACCESS;
719                         } else {
720                                 perm1 = CAN_WRITE(conn) ?
721                                                 SHARE_ALL_ACCESS :
722                                                 SHARE_READ_ONLY;
723                         }
724
725                         SIVAL(req->outbuf, smb_vwv3, perm1);
726                         SIVAL(req->outbuf, smb_vwv5, perm2);
727                 } else {
728                         reply_outbuf(req, 3, 0);
729                 }
730
731                 if ((message_push_string(&req->outbuf, server_devicetype,
732                                          STR_TERMINATE|STR_ASCII) == -1)
733                     || (message_push_string(&req->outbuf, fstype,
734                                             STR_TERMINATE) == -1)) {
735                         reply_nterror(req, NT_STATUS_NO_MEMORY);
736                         END_PROFILE(SMBtconX);
737                         return;
738                 }
739
740                 /* what does setting this bit do? It is set by NT4 and
741                    may affect the ability to autorun mounted cdroms */
742                 SSVAL(req->outbuf, smb_vwv2, SMB_SUPPORT_SEARCH_BITS|
743                       (lp_csc_policy(SNUM(conn)) << 2));
744
745                 if (lp_msdfs_root(SNUM(conn)) && lp_host_msdfs()) {
746                         DEBUG(2,("Serving %s as a Dfs root\n",
747                                  lp_servicename(SNUM(conn)) ));
748                         SSVAL(req->outbuf, smb_vwv2,
749                               SMB_SHARE_IN_DFS | SVAL(req->outbuf, smb_vwv2));
750                 }
751         }
752
753
754         DEBUG(3,("tconX service=%s \n",
755                  service));
756
757         /* set the incoming and outgoing tid to the just created one */
758         SSVAL(req->inbuf,smb_tid,conn->cnum);
759         SSVAL(req->outbuf,smb_tid,conn->cnum);
760
761         END_PROFILE(SMBtconX);
762
763         chain_reply(req);
764         return;
765 }
766
767 /****************************************************************************
768  Reply to an unknown type.
769 ****************************************************************************/
770
771 void reply_unknown_new(struct smb_request *req, uint8 type)
772 {
773         DEBUG(0, ("unknown command type (%s): type=%d (0x%X)\n",
774                   smb_fn_name(type), type, type));
775         reply_doserror(req, ERRSRV, ERRunknownsmb);
776         return;
777 }
778
779 /****************************************************************************
780  Reply to an ioctl.
781  conn POINTER CAN BE NULL HERE !
782 ****************************************************************************/
783
784 void reply_ioctl(struct smb_request *req)
785 {
786         connection_struct *conn = req->conn;
787         uint16 device;
788         uint16 function;
789         uint32 ioctl_code;
790         int replysize;
791         char *p;
792
793         START_PROFILE(SMBioctl);
794
795         if (req->wct < 3) {
796                 reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
797                 END_PROFILE(SMBioctl);
798                 return;
799         }
800
801         device     = SVAL(req->vwv+1, 0);
802         function   = SVAL(req->vwv+2, 0);
803         ioctl_code = (device << 16) + function;
804
805         DEBUG(4, ("Received IOCTL (code 0x%x)\n", ioctl_code));
806
807         switch (ioctl_code) {
808             case IOCTL_QUERY_JOB_INFO:
809                     replysize = 32;
810                     break;
811             default:
812                     reply_doserror(req, ERRSRV, ERRnosupport);
813                     END_PROFILE(SMBioctl);
814                     return;
815         }
816
817         reply_outbuf(req, 8, replysize+1);
818         SSVAL(req->outbuf,smb_vwv1,replysize); /* Total data bytes returned */
819         SSVAL(req->outbuf,smb_vwv5,replysize); /* Data bytes this buffer */
820         SSVAL(req->outbuf,smb_vwv6,52);        /* Offset to data */
821         p = smb_buf(req->outbuf);
822         memset(p, '\0', replysize+1); /* valgrind-safe. */
823         p += 1;          /* Allow for alignment */
824
825         switch (ioctl_code) {
826                 case IOCTL_QUERY_JOB_INFO:                  
827                 {
828                         files_struct *fsp = file_fsp(
829                                 req, SVAL(req->vwv+0, 0));
830                         if (!fsp) {
831                                 reply_doserror(req, ERRDOS, ERRbadfid);
832                                 END_PROFILE(SMBioctl);
833                                 return;
834                         }
835                         SSVAL(p,0,fsp->rap_print_jobid);             /* Job number */
836                         srvstr_push((char *)req->outbuf, req->flags2, p+2,
837                                     global_myname(), 15,
838                                     STR_TERMINATE|STR_ASCII);
839                         if (conn) {
840                                 srvstr_push((char *)req->outbuf, req->flags2,
841                                             p+18, lp_servicename(SNUM(conn)),
842                                             13, STR_TERMINATE|STR_ASCII);
843                         } else {
844                                 memset(p+18, 0, 13);
845                         }
846                         break;
847                 }
848         }
849
850         END_PROFILE(SMBioctl);
851         return;
852 }
853
854 /****************************************************************************
855  Strange checkpath NTSTATUS mapping.
856 ****************************************************************************/
857
858 static NTSTATUS map_checkpath_error(uint16_t flags2, NTSTATUS status)
859 {
860         /* Strange DOS error code semantics only for checkpath... */
861         if (!(flags2 & FLAGS2_32_BIT_ERROR_CODES)) {
862                 if (NT_STATUS_EQUAL(NT_STATUS_OBJECT_NAME_INVALID,status)) {
863                         /* We need to map to ERRbadpath */
864                         return NT_STATUS_OBJECT_PATH_NOT_FOUND;
865                 }
866         }
867         return status;
868 }
869
870 /****************************************************************************
871  Reply to a checkpath.
872 ****************************************************************************/
873
874 void reply_checkpath(struct smb_request *req)
875 {
876         connection_struct *conn = req->conn;
877         char *name = NULL;
878         SMB_STRUCT_STAT sbuf;
879         NTSTATUS status;
880         TALLOC_CTX *ctx = talloc_tos();
881
882         START_PROFILE(SMBcheckpath);
883
884         srvstr_get_path_req(ctx, req, &name, (const char *)req->buf + 1,
885                             STR_TERMINATE, &status);
886
887         if (!NT_STATUS_IS_OK(status)) {
888                 status = map_checkpath_error(req->flags2, status);
889                 reply_nterror(req, status);
890                 END_PROFILE(SMBcheckpath);
891                 return;
892         }
893
894         status = resolve_dfspath(ctx, conn,
895                         req->flags2 & FLAGS2_DFS_PATHNAMES,
896                         name,
897                         &name);
898         if (!NT_STATUS_IS_OK(status)) {
899                 if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) {
900                         reply_botherror(req, NT_STATUS_PATH_NOT_COVERED,
901                                         ERRSRV, ERRbadpath);
902                         END_PROFILE(SMBcheckpath);
903                         return;
904                 }
905                 goto path_err;
906         }
907
908         DEBUG(3,("reply_checkpath %s mode=%d\n", name, (int)SVAL(req->vwv+0, 0)));
909
910         status = unix_convert(ctx, conn, name, False, &name, NULL, &sbuf);
911         if (!NT_STATUS_IS_OK(status)) {
912                 goto path_err;
913         }
914
915         status = check_name(conn, name);
916         if (!NT_STATUS_IS_OK(status)) {
917                 DEBUG(3,("reply_checkpath: check_name of %s failed (%s)\n",name,nt_errstr(status)));
918                 goto path_err;
919         }
920
921         if (!VALID_STAT(sbuf) && (SMB_VFS_STAT(conn,name,&sbuf) != 0)) {
922                 DEBUG(3,("reply_checkpath: stat of %s failed (%s)\n",name,strerror(errno)));
923                 status = map_nt_error_from_unix(errno);
924                 goto path_err;
925         }
926
927         if (!S_ISDIR(sbuf.st_mode)) {
928                 reply_botherror(req, NT_STATUS_NOT_A_DIRECTORY,
929                                 ERRDOS, ERRbadpath);
930                 END_PROFILE(SMBcheckpath);
931                 return;
932         }
933
934         reply_outbuf(req, 0, 0);
935
936         END_PROFILE(SMBcheckpath);
937         return;
938
939   path_err:
940
941         END_PROFILE(SMBcheckpath);
942
943         /* We special case this - as when a Windows machine
944                 is parsing a path is steps through the components
945                 one at a time - if a component fails it expects
946                 ERRbadpath, not ERRbadfile.
947         */
948         status = map_checkpath_error(req->flags2, status);
949         if (NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
950                 /*
951                  * Windows returns different error codes if
952                  * the parent directory is valid but not the
953                  * last component - it returns NT_STATUS_OBJECT_NAME_NOT_FOUND
954                  * for that case and NT_STATUS_OBJECT_PATH_NOT_FOUND
955                  * if the path is invalid.
956                  */
957                 reply_botherror(req, NT_STATUS_OBJECT_NAME_NOT_FOUND,
958                                 ERRDOS, ERRbadpath);
959                 return;
960         }
961
962         reply_nterror(req, status);
963 }
964
965 /****************************************************************************
966  Reply to a getatr.
967 ****************************************************************************/
968
969 void reply_getatr(struct smb_request *req)
970 {
971         connection_struct *conn = req->conn;
972         char *fname = NULL;
973         SMB_STRUCT_STAT sbuf;
974         int mode=0;
975         SMB_OFF_T size=0;
976         time_t mtime=0;
977         const char *p;
978         NTSTATUS status;
979         TALLOC_CTX *ctx = talloc_tos();
980
981         START_PROFILE(SMBgetatr);
982
983         p = (const char *)req->buf + 1;
984         p += srvstr_get_path_req(ctx, req, &fname, p, STR_TERMINATE, &status);
985         if (!NT_STATUS_IS_OK(status)) {
986                 reply_nterror(req, status);
987                 END_PROFILE(SMBgetatr);
988                 return;
989         }
990
991         status = resolve_dfspath(ctx, conn,
992                                 req->flags2 & FLAGS2_DFS_PATHNAMES,
993                                 fname,
994                                 &fname);
995         if (!NT_STATUS_IS_OK(status)) {
996                 if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) {
997                         reply_botherror(req, NT_STATUS_PATH_NOT_COVERED,
998                                         ERRSRV, ERRbadpath);
999                         END_PROFILE(SMBgetatr);
1000                         return;
1001                 }
1002                 reply_nterror(req, status);
1003                 END_PROFILE(SMBgetatr);
1004                 return;
1005         }
1006
1007         /* dos smetimes asks for a stat of "" - it returns a "hidden directory"
1008                 under WfWg - weird! */
1009         if (*fname == '\0') {
1010                 mode = aHIDDEN | aDIR;
1011                 if (!CAN_WRITE(conn)) {
1012                         mode |= aRONLY;
1013                 }
1014                 size = 0;
1015                 mtime = 0;
1016         } else {
1017                 status = unix_convert(ctx, conn, fname, False, &fname, NULL,&sbuf);
1018                 if (!NT_STATUS_IS_OK(status)) {
1019                         reply_nterror(req, status);
1020                         END_PROFILE(SMBgetatr);
1021                         return;
1022                 }
1023                 status = check_name(conn, fname);
1024                 if (!NT_STATUS_IS_OK(status)) {
1025                         DEBUG(3,("reply_getatr: check_name of %s failed (%s)\n",fname,nt_errstr(status)));
1026                         reply_nterror(req, status);
1027                         END_PROFILE(SMBgetatr);
1028                         return;
1029                 }
1030                 if (!VALID_STAT(sbuf) && (SMB_VFS_STAT(conn,fname,&sbuf) != 0)) {
1031                         DEBUG(3,("reply_getatr: stat of %s failed (%s)\n",fname,strerror(errno)));
1032                         reply_unixerror(req, ERRDOS,ERRbadfile);
1033                         END_PROFILE(SMBgetatr);
1034                         return;
1035                 }
1036
1037                 mode = dos_mode(conn,fname,&sbuf);
1038                 size = sbuf.st_size;
1039                 mtime = sbuf.st_mtime;
1040                 if (mode & aDIR) {
1041                         size = 0;
1042                 }
1043         }
1044
1045         reply_outbuf(req, 10, 0);
1046
1047         SSVAL(req->outbuf,smb_vwv0,mode);
1048         if(lp_dos_filetime_resolution(SNUM(conn)) ) {
1049                 srv_put_dos_date3((char *)req->outbuf,smb_vwv1,mtime & ~1);
1050         } else {
1051                 srv_put_dos_date3((char *)req->outbuf,smb_vwv1,mtime);
1052         }
1053         SIVAL(req->outbuf,smb_vwv3,(uint32)size);
1054
1055         if (Protocol >= PROTOCOL_NT1) {
1056                 SSVAL(req->outbuf, smb_flg2,
1057                       SVAL(req->outbuf, smb_flg2) | FLAGS2_IS_LONG_NAME);
1058         }
1059
1060         DEBUG(3,("reply_getatr: name=%s mode=%d size=%u\n", fname, mode, (unsigned int)size ) );
1061
1062         END_PROFILE(SMBgetatr);
1063         return;
1064 }
1065
1066 /****************************************************************************
1067  Reply to a setatr.
1068 ****************************************************************************/
1069
1070 void reply_setatr(struct smb_request *req)
1071 {
1072         struct timespec ts[2];
1073         connection_struct *conn = req->conn;
1074         char *fname = NULL;
1075         int mode;
1076         time_t mtime;
1077         SMB_STRUCT_STAT sbuf;
1078         const char *p;
1079         NTSTATUS status;
1080         TALLOC_CTX *ctx = talloc_tos();
1081
1082         START_PROFILE(SMBsetatr);
1083
1084         ZERO_STRUCT(ts);
1085
1086         if (req->wct < 2) {
1087                 reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
1088                 return;
1089         }
1090
1091         p = (const char *)req->buf + 1;
1092         p += srvstr_get_path_req(ctx, req, &fname, p, STR_TERMINATE, &status);
1093         if (!NT_STATUS_IS_OK(status)) {
1094                 reply_nterror(req, status);
1095                 END_PROFILE(SMBsetatr);
1096                 return;
1097         }
1098
1099         status = resolve_dfspath(ctx, conn,
1100                                 req->flags2 & FLAGS2_DFS_PATHNAMES,
1101                                 fname,
1102                                 &fname);
1103         if (!NT_STATUS_IS_OK(status)) {
1104                 if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) {
1105                         reply_botherror(req, NT_STATUS_PATH_NOT_COVERED,
1106                                         ERRSRV, ERRbadpath);
1107                         END_PROFILE(SMBsetatr);
1108                         return;
1109                 }
1110                 reply_nterror(req, status);
1111                 END_PROFILE(SMBsetatr);
1112                 return;
1113         }
1114
1115         status = unix_convert(ctx, conn, fname, False, &fname, NULL, &sbuf);
1116         if (!NT_STATUS_IS_OK(status)) {
1117                 reply_nterror(req, status);
1118                 END_PROFILE(SMBsetatr);
1119                 return;
1120         }
1121
1122         status = check_name(conn, fname);
1123         if (!NT_STATUS_IS_OK(status)) {
1124                 reply_nterror(req, status);
1125                 END_PROFILE(SMBsetatr);
1126                 return;
1127         }
1128
1129         if (fname[0] == '.' && fname[1] == '\0') {
1130                 /*
1131                  * Not sure here is the right place to catch this
1132                  * condition. Might be moved to somewhere else later -- vl
1133                  */
1134                 reply_nterror(req, NT_STATUS_ACCESS_DENIED);
1135                 END_PROFILE(SMBsetatr);
1136                 return;
1137         }
1138
1139         mode = SVAL(req->vwv+0, 0);
1140         mtime = srv_make_unix_date3(req->vwv+1);
1141
1142         ts[1] = convert_time_t_to_timespec(mtime);
1143         status = smb_set_file_time(conn, NULL, fname,
1144                                    &sbuf, ts, true);
1145         if (!NT_STATUS_IS_OK(status)) {
1146                 reply_unixerror(req, ERRDOS, ERRnoaccess);
1147                 END_PROFILE(SMBsetatr);
1148                 return;
1149         }
1150
1151         if (mode != FILE_ATTRIBUTE_NORMAL) {
1152                 if (VALID_STAT_OF_DIR(sbuf))
1153                         mode |= aDIR;
1154                 else
1155                         mode &= ~aDIR;
1156
1157                 if (file_set_dosmode(conn,fname,mode,&sbuf,NULL,false) != 0) {
1158                         reply_unixerror(req, ERRDOS, ERRnoaccess);
1159                         END_PROFILE(SMBsetatr);
1160                         return;
1161                 }
1162         }
1163
1164         reply_outbuf(req, 0, 0);
1165
1166         DEBUG( 3, ( "setatr name=%s mode=%d\n", fname, mode ) );
1167
1168         END_PROFILE(SMBsetatr);
1169         return;
1170 }
1171
1172 /****************************************************************************
1173  Reply to a dskattr.
1174 ****************************************************************************/
1175
1176 void reply_dskattr(struct smb_request *req)
1177 {
1178         connection_struct *conn = req->conn;
1179         uint64_t dfree,dsize,bsize;
1180         START_PROFILE(SMBdskattr);
1181
1182         if (get_dfree_info(conn,".",True,&bsize,&dfree,&dsize) == (uint64_t)-1) {
1183                 reply_unixerror(req, ERRHRD, ERRgeneral);
1184                 END_PROFILE(SMBdskattr);
1185                 return;
1186         }
1187
1188         reply_outbuf(req, 5, 0);
1189
1190         if (Protocol <= PROTOCOL_LANMAN2) {
1191                 double total_space, free_space;
1192                 /* we need to scale this to a number that DOS6 can handle. We
1193                    use floating point so we can handle large drives on systems
1194                    that don't have 64 bit integers 
1195
1196                    we end up displaying a maximum of 2G to DOS systems
1197                 */
1198                 total_space = dsize * (double)bsize;
1199                 free_space = dfree * (double)bsize;
1200
1201                 dsize = (uint64_t)((total_space+63*512) / (64*512));
1202                 dfree = (uint64_t)((free_space+63*512) / (64*512));
1203
1204                 if (dsize > 0xFFFF) dsize = 0xFFFF;
1205                 if (dfree > 0xFFFF) dfree = 0xFFFF;
1206
1207                 SSVAL(req->outbuf,smb_vwv0,dsize);
1208                 SSVAL(req->outbuf,smb_vwv1,64); /* this must be 64 for dos systems */
1209                 SSVAL(req->outbuf,smb_vwv2,512); /* and this must be 512 */
1210                 SSVAL(req->outbuf,smb_vwv3,dfree);
1211         } else {
1212                 SSVAL(req->outbuf,smb_vwv0,dsize);
1213                 SSVAL(req->outbuf,smb_vwv1,bsize/512);
1214                 SSVAL(req->outbuf,smb_vwv2,512);
1215                 SSVAL(req->outbuf,smb_vwv3,dfree);
1216         }
1217
1218         DEBUG(3,("dskattr dfree=%d\n", (unsigned int)dfree));
1219
1220         END_PROFILE(SMBdskattr);
1221         return;
1222 }
1223
1224 /****************************************************************************
1225  Reply to a search.
1226  Can be called from SMBsearch, SMBffirst or SMBfunique.
1227 ****************************************************************************/
1228
1229 void reply_search(struct smb_request *req)
1230 {
1231         connection_struct *conn = req->conn;
1232         const char *mask = NULL;
1233         char *directory = NULL;
1234         char *fname = NULL;
1235         SMB_OFF_T size;
1236         uint32 mode;
1237         time_t date;
1238         uint32 dirtype;
1239         unsigned int numentries = 0;
1240         unsigned int maxentries = 0;
1241         bool finished = False;
1242         const char *p;
1243         int status_len;
1244         char *path = NULL;
1245         char status[21];
1246         int dptr_num= -1;
1247         bool check_descend = False;
1248         bool expect_close = False;
1249         NTSTATUS nt_status;
1250         bool mask_contains_wcard = False;
1251         bool allow_long_path_components = (req->flags2 & FLAGS2_LONG_PATH_COMPONENTS) ? True : False;
1252         TALLOC_CTX *ctx = talloc_tos();
1253         bool ask_sharemode = lp_parm_bool(SNUM(conn), "smbd", "search ask sharemode", true);
1254
1255         START_PROFILE(SMBsearch);
1256
1257         if (req->wct < 2) {
1258                 reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
1259                 END_PROFILE(SMBsearch);
1260                 return;
1261         }
1262
1263         if (lp_posix_pathnames()) {
1264                 reply_unknown_new(req, req->cmd);
1265                 END_PROFILE(SMBsearch);
1266                 return;
1267         }
1268
1269         /* If we were called as SMBffirst then we must expect close. */
1270         if(req->cmd == SMBffirst) {
1271                 expect_close = True;
1272         }
1273
1274         reply_outbuf(req, 1, 3);
1275         maxentries = SVAL(req->vwv+0, 0);
1276         dirtype = SVAL(req->vwv+1, 0);
1277         p = (const char *)req->buf + 1;
1278         p += srvstr_get_path_req_wcard(ctx, req, &path, p, STR_TERMINATE,
1279                                        &nt_status, &mask_contains_wcard);
1280         if (!NT_STATUS_IS_OK(nt_status)) {
1281                 reply_nterror(req, nt_status);
1282                 END_PROFILE(SMBsearch);
1283                 return;
1284         }
1285
1286         nt_status = resolve_dfspath_wcard(ctx, conn,
1287                                           req->flags2 & FLAGS2_DFS_PATHNAMES,
1288                                           path,
1289                                           &path,
1290                                           &mask_contains_wcard);
1291         if (!NT_STATUS_IS_OK(nt_status)) {
1292                 if (NT_STATUS_EQUAL(nt_status,NT_STATUS_PATH_NOT_COVERED)) {
1293                         reply_botherror(req, NT_STATUS_PATH_NOT_COVERED,
1294                                         ERRSRV, ERRbadpath);
1295                         END_PROFILE(SMBsearch);
1296                         return;
1297                 }
1298                 reply_nterror(req, nt_status);
1299                 END_PROFILE(SMBsearch);
1300                 return;
1301         }
1302
1303         p++;
1304         status_len = SVAL(p, 0);
1305         p += 2;
1306
1307         /* dirtype &= ~aDIR; */
1308
1309         if (status_len == 0) {
1310                 SMB_STRUCT_STAT sbuf;
1311
1312                 nt_status = unix_convert(ctx, conn, path, True,
1313                                 &directory, NULL, &sbuf);
1314                 if (!NT_STATUS_IS_OK(nt_status)) {
1315                         reply_nterror(req, nt_status);
1316                         END_PROFILE(SMBsearch);
1317                         return;
1318                 }
1319
1320                 nt_status = check_name(conn, directory);
1321                 if (!NT_STATUS_IS_OK(nt_status)) {
1322                         reply_nterror(req, nt_status);
1323                         END_PROFILE(SMBsearch);
1324                         return;
1325                 }
1326
1327                 p = strrchr_m(directory,'/');
1328                 if ((p != NULL) && (*directory != '/')) {
1329                         mask = p + 1;
1330                         directory = talloc_strndup(ctx, directory,
1331                                                    PTR_DIFF(p, directory));
1332                 } else {
1333                         mask = directory;
1334                         directory = talloc_strdup(ctx,".");
1335                 }
1336
1337                 if (!directory) {
1338                         reply_nterror(req, NT_STATUS_NO_MEMORY);
1339                         END_PROFILE(SMBsearch);
1340                         return;
1341                 }
1342
1343                 memset((char *)status,'\0',21);
1344                 SCVAL(status,0,(dirtype & 0x1F));
1345
1346                 nt_status = dptr_create(conn,
1347                                         directory,
1348                                         True,
1349                                         expect_close,
1350                                         req->smbpid,
1351                                         mask,
1352                                         mask_contains_wcard,
1353                                         dirtype,
1354                                         &conn->dirptr);
1355                 if (!NT_STATUS_IS_OK(nt_status)) {
1356                         reply_nterror(req, nt_status);
1357                         END_PROFILE(SMBsearch);
1358                         return;
1359                 }
1360                 dptr_num = dptr_dnum(conn->dirptr);
1361         } else {
1362                 int status_dirtype;
1363
1364                 memcpy(status,p,21);
1365                 status_dirtype = CVAL(status,0) & 0x1F;
1366                 if (status_dirtype != (dirtype & 0x1F)) {
1367                         dirtype = status_dirtype;
1368                 }
1369
1370                 conn->dirptr = dptr_fetch(status+12,&dptr_num);
1371                 if (!conn->dirptr) {
1372                         goto SearchEmpty;
1373                 }
1374                 string_set(&conn->dirpath,dptr_path(dptr_num));
1375                 mask = dptr_wcard(dptr_num);
1376                 if (!mask) {
1377                         goto SearchEmpty;
1378                 }
1379                 /*
1380                  * For a 'continue' search we have no string. So
1381                  * check from the initial saved string.
1382                  */
1383                 mask_contains_wcard = ms_has_wild(mask);
1384                 dirtype = dptr_attr(dptr_num);
1385         }
1386
1387         DEBUG(4,("dptr_num is %d\n",dptr_num));
1388
1389         if ((dirtype&0x1F) == aVOLID) {
1390                 char buf[DIR_STRUCT_SIZE];
1391                 memcpy(buf,status,21);
1392                 if (!make_dir_struct(ctx,buf,"???????????",volume_label(SNUM(conn)),
1393                                 0,aVOLID,0,!allow_long_path_components)) {
1394                         reply_nterror(req, NT_STATUS_NO_MEMORY);
1395                         END_PROFILE(SMBsearch);
1396                         return;
1397                 }
1398                 dptr_fill(buf+12,dptr_num);
1399                 if (dptr_zero(buf+12) && (status_len==0)) {
1400                         numentries = 1;
1401                 } else {
1402                         numentries = 0;
1403                 }
1404                 if (message_push_blob(&req->outbuf,
1405                                       data_blob_const(buf, sizeof(buf)))
1406                     == -1) {
1407                         reply_nterror(req, NT_STATUS_NO_MEMORY);
1408                         END_PROFILE(SMBsearch);
1409                         return;
1410                 }
1411         } else {
1412                 unsigned int i;
1413                 maxentries = MIN(
1414                         maxentries,
1415                         ((BUFFER_SIZE -
1416                           ((uint8 *)smb_buf(req->outbuf) + 3 - req->outbuf))
1417                          /DIR_STRUCT_SIZE));
1418
1419                 DEBUG(8,("dirpath=<%s> dontdescend=<%s>\n",
1420                         conn->dirpath,lp_dontdescend(SNUM(conn))));
1421                 if (in_list(conn->dirpath, lp_dontdescend(SNUM(conn)),True)) {
1422                         check_descend = True;
1423                 }
1424
1425                 for (i=numentries;(i<maxentries) && !finished;i++) {
1426                         finished = !get_dir_entry(ctx,
1427                                                   conn,
1428                                                   mask,
1429                                                   dirtype,
1430                                                   &fname,
1431                                                   &size,
1432                                                   &mode,
1433                                                   &date,
1434                                                   check_descend,
1435                                                   ask_sharemode);
1436                         if (!finished) {
1437                                 char buf[DIR_STRUCT_SIZE];
1438                                 memcpy(buf,status,21);
1439                                 if (!make_dir_struct(ctx,
1440                                                 buf,
1441                                                 mask,
1442                                                 fname,
1443                                                 size,
1444                                                 mode,
1445                                                 date,
1446                                                 !allow_long_path_components)) {
1447                                         reply_nterror(req, NT_STATUS_NO_MEMORY);
1448                                         END_PROFILE(SMBsearch);
1449                                         return;
1450                                 }
1451                                 if (!dptr_fill(buf+12,dptr_num)) {
1452                                         break;
1453                                 }
1454                                 if (message_push_blob(&req->outbuf,
1455                                                       data_blob_const(buf, sizeof(buf)))
1456                                     == -1) {
1457                                         reply_nterror(req, NT_STATUS_NO_MEMORY);
1458                                         END_PROFILE(SMBsearch);
1459                                         return;
1460                                 }
1461                                 numentries++;
1462                         }
1463                 }
1464         }
1465
1466   SearchEmpty:
1467
1468         /* If we were called as SMBffirst with smb_search_id == NULL
1469                 and no entries were found then return error and close dirptr 
1470                 (X/Open spec) */
1471
1472         if (numentries == 0) {
1473                 dptr_close(&dptr_num);
1474         } else if(expect_close && status_len == 0) {
1475                 /* Close the dptr - we know it's gone */
1476                 dptr_close(&dptr_num);
1477         }
1478
1479         /* If we were called as SMBfunique, then we can close the dirptr now ! */
1480         if(dptr_num >= 0 && req->cmd == SMBfunique) {
1481                 dptr_close(&dptr_num);
1482         }
1483
1484         if ((numentries == 0) && !mask_contains_wcard) {
1485                 reply_botherror(req, STATUS_NO_MORE_FILES, ERRDOS, ERRnofiles);
1486                 END_PROFILE(SMBsearch);
1487                 return;
1488         }
1489
1490         SSVAL(req->outbuf,smb_vwv0,numentries);
1491         SSVAL(req->outbuf,smb_vwv1,3 + numentries * DIR_STRUCT_SIZE);
1492         SCVAL(smb_buf(req->outbuf),0,5);
1493         SSVAL(smb_buf(req->outbuf),1,numentries*DIR_STRUCT_SIZE);
1494
1495         /* The replies here are never long name. */
1496         SSVAL(req->outbuf, smb_flg2,
1497               SVAL(req->outbuf, smb_flg2) & (~FLAGS2_IS_LONG_NAME));
1498         if (!allow_long_path_components) {
1499                 SSVAL(req->outbuf, smb_flg2,
1500                       SVAL(req->outbuf, smb_flg2)
1501                       & (~FLAGS2_LONG_PATH_COMPONENTS));
1502         }
1503
1504         /* This SMB *always* returns ASCII names. Remove the unicode bit in flags2. */
1505         SSVAL(req->outbuf, smb_flg2,
1506               (SVAL(req->outbuf, smb_flg2) & (~FLAGS2_UNICODE_STRINGS)));
1507
1508         if (!directory) {
1509                 directory = dptr_path(dptr_num);
1510         }
1511
1512         DEBUG(4,("%s mask=%s path=%s dtype=%d nument=%u of %u\n",
1513                 smb_fn_name(req->cmd),
1514                 mask,
1515                 directory ? directory : "./",
1516                 dirtype,
1517                 numentries,
1518                 maxentries ));
1519
1520         END_PROFILE(SMBsearch);
1521         return;
1522 }
1523
1524 /****************************************************************************
1525  Reply to a fclose (stop directory search).
1526 ****************************************************************************/
1527
1528 void reply_fclose(struct smb_request *req)
1529 {
1530         int status_len;
1531         char status[21];
1532         int dptr_num= -2;
1533         const char *p;
1534         char *path = NULL;
1535         NTSTATUS err;
1536         bool path_contains_wcard = False;
1537         TALLOC_CTX *ctx = talloc_tos();
1538
1539         START_PROFILE(SMBfclose);
1540
1541         if (lp_posix_pathnames()) {
1542                 reply_unknown_new(req, req->cmd);
1543                 END_PROFILE(SMBfclose);
1544                 return;
1545         }
1546
1547         p = (const char *)req->buf + 1;
1548         p += srvstr_get_path_req_wcard(ctx, req, &path, p, STR_TERMINATE,
1549                                        &err, &path_contains_wcard);
1550         if (!NT_STATUS_IS_OK(err)) {
1551                 reply_nterror(req, err);
1552                 END_PROFILE(SMBfclose);
1553                 return;
1554         }
1555         p++;
1556         status_len = SVAL(p,0);
1557         p += 2;
1558
1559         if (status_len == 0) {
1560                 reply_doserror(req, ERRSRV, ERRsrverror);
1561                 END_PROFILE(SMBfclose);
1562                 return;
1563         }
1564
1565         memcpy(status,p,21);
1566
1567         if(dptr_fetch(status+12,&dptr_num)) {
1568                 /*  Close the dptr - we know it's gone */
1569                 dptr_close(&dptr_num);
1570         }
1571
1572         reply_outbuf(req, 1, 0);
1573         SSVAL(req->outbuf,smb_vwv0,0);
1574
1575         DEBUG(3,("search close\n"));
1576
1577         END_PROFILE(SMBfclose);
1578         return;
1579 }
1580
1581 /****************************************************************************
1582  Reply to an open.
1583 ****************************************************************************/
1584
1585 void reply_open(struct smb_request *req)
1586 {
1587         connection_struct *conn = req->conn;
1588         char *fname = NULL;
1589         uint32 fattr=0;
1590         SMB_OFF_T size = 0;
1591         time_t mtime=0;
1592         int info;
1593         SMB_STRUCT_STAT sbuf;
1594         files_struct *fsp;
1595         int oplock_request;
1596         int deny_mode;
1597         uint32 dos_attr;
1598         uint32 access_mask;
1599         uint32 share_mode;
1600         uint32 create_disposition;
1601         uint32 create_options = 0;
1602         NTSTATUS status;
1603         TALLOC_CTX *ctx = talloc_tos();
1604
1605         START_PROFILE(SMBopen);
1606
1607         if (req->wct < 2) {
1608                 reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
1609                 END_PROFILE(SMBopen);
1610                 return;
1611         }
1612
1613         oplock_request = CORE_OPLOCK_REQUEST(req->inbuf);
1614         deny_mode = SVAL(req->vwv+0, 0);
1615         dos_attr = SVAL(req->vwv+1, 0);
1616
1617         srvstr_get_path_req(ctx, req, &fname, (const char *)req->buf+1,
1618                             STR_TERMINATE, &status);
1619         if (!NT_STATUS_IS_OK(status)) {
1620                 reply_nterror(req, status);
1621                 END_PROFILE(SMBopen);
1622                 return;
1623         }
1624
1625         if (!map_open_params_to_ntcreate(
1626                     fname, deny_mode, OPENX_FILE_EXISTS_OPEN, &access_mask,
1627                     &share_mode, &create_disposition, &create_options)) {
1628                 reply_nterror(req, NT_STATUS_DOS(ERRDOS, ERRbadaccess));
1629                 END_PROFILE(SMBopen);
1630                 return;
1631         }
1632
1633         status = SMB_VFS_CREATE_FILE(
1634                 conn,                                   /* conn */
1635                 req,                                    /* req */
1636                 0,                                      /* root_dir_fid */
1637                 fname,                                  /* fname */
1638                 access_mask,                            /* access_mask */
1639                 share_mode,                             /* share_access */
1640                 create_disposition,                     /* create_disposition*/
1641                 create_options,                         /* create_options */
1642                 dos_attr,                               /* file_attributes */
1643                 oplock_request,                         /* oplock_request */
1644                 0,                                      /* allocation_size */
1645                 NULL,                                   /* sd */
1646                 NULL,                                   /* ea_list */
1647                 &fsp,                                   /* result */
1648                 &info,                                  /* pinfo */
1649                 &sbuf);                                 /* psbuf */
1650
1651         if (!NT_STATUS_IS_OK(status)) {
1652                 if (open_was_deferred(req->mid)) {
1653                         /* We have re-scheduled this call. */
1654                         END_PROFILE(SMBopen);
1655                         return;
1656                 }
1657                 reply_openerror(req, status);
1658                 END_PROFILE(SMBopen);
1659                 return;
1660         }
1661
1662         size = sbuf.st_size;
1663         fattr = dos_mode(conn,fsp->fsp_name,&sbuf);
1664         mtime = sbuf.st_mtime;
1665
1666         if (fattr & aDIR) {
1667                 DEBUG(3,("attempt to open a directory %s\n",fsp->fsp_name));
1668                 close_file(req, fsp, ERROR_CLOSE);
1669                 reply_doserror(req, ERRDOS,ERRnoaccess);
1670                 END_PROFILE(SMBopen);
1671                 return;
1672         }
1673
1674         reply_outbuf(req, 7, 0);
1675         SSVAL(req->outbuf,smb_vwv0,fsp->fnum);
1676         SSVAL(req->outbuf,smb_vwv1,fattr);
1677         if(lp_dos_filetime_resolution(SNUM(conn)) ) {
1678                 srv_put_dos_date3((char *)req->outbuf,smb_vwv2,mtime & ~1);
1679         } else {
1680                 srv_put_dos_date3((char *)req->outbuf,smb_vwv2,mtime);
1681         }
1682         SIVAL(req->outbuf,smb_vwv4,(uint32)size);
1683         SSVAL(req->outbuf,smb_vwv6,deny_mode);
1684
1685         if (oplock_request && lp_fake_oplocks(SNUM(conn))) {
1686                 SCVAL(req->outbuf,smb_flg,
1687                       CVAL(req->outbuf,smb_flg)|CORE_OPLOCK_GRANTED);
1688         }
1689
1690         if(EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type)) {
1691                 SCVAL(req->outbuf,smb_flg,
1692                       CVAL(req->outbuf,smb_flg)|CORE_OPLOCK_GRANTED);
1693         }
1694         END_PROFILE(SMBopen);
1695         return;
1696 }
1697
1698 /****************************************************************************
1699  Reply to an open and X.
1700 ****************************************************************************/
1701
1702 void reply_open_and_X(struct smb_request *req)
1703 {
1704         connection_struct *conn = req->conn;
1705         char *fname = NULL;
1706         uint16 open_flags;
1707         int deny_mode;
1708         uint32 smb_attr;
1709         /* Breakout the oplock request bits so we can set the
1710                 reply bits separately. */
1711         int ex_oplock_request;
1712         int core_oplock_request;
1713         int oplock_request;
1714 #if 0
1715         int smb_sattr = SVAL(req->vwv+4, 0);
1716         uint32 smb_time = make_unix_date3(req->vwv+6);
1717 #endif
1718         int smb_ofun;
1719         uint32 fattr=0;
1720         int mtime=0;
1721         SMB_STRUCT_STAT sbuf;
1722         int smb_action = 0;
1723         files_struct *fsp;
1724         NTSTATUS status;
1725         uint64_t allocation_size;
1726         ssize_t retval = -1;
1727         uint32 access_mask;
1728         uint32 share_mode;
1729         uint32 create_disposition;
1730         uint32 create_options = 0;
1731         TALLOC_CTX *ctx = talloc_tos();
1732
1733         START_PROFILE(SMBopenX);
1734
1735         if (req->wct < 15) {
1736                 reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
1737                 END_PROFILE(SMBopenX);
1738                 return;
1739         }
1740
1741         open_flags = SVAL(req->vwv+2, 0);
1742         deny_mode = SVAL(req->vwv+3, 0);
1743         smb_attr = SVAL(req->vwv+5, 0);
1744         ex_oplock_request = EXTENDED_OPLOCK_REQUEST(req->inbuf);
1745         core_oplock_request = CORE_OPLOCK_REQUEST(req->inbuf);
1746         oplock_request = ex_oplock_request | core_oplock_request;
1747         smb_ofun = SVAL(req->vwv+8, 0);
1748         allocation_size = (uint64_t)IVAL(req->vwv+9, 0);
1749
1750         /* If it's an IPC, pass off the pipe handler. */
1751         if (IS_IPC(conn)) {
1752                 if (lp_nt_pipe_support()) {
1753                         reply_open_pipe_and_X(conn, req);
1754                 } else {
1755                         reply_doserror(req, ERRSRV, ERRaccess);
1756                 }
1757                 END_PROFILE(SMBopenX);
1758                 return;
1759         }
1760
1761         /* XXXX we need to handle passed times, sattr and flags */
1762         srvstr_get_path_req(ctx, req, &fname, (const char *)req->buf,
1763                         STR_TERMINATE, &status);
1764         if (!NT_STATUS_IS_OK(status)) {
1765                 reply_nterror(req, status);
1766                 END_PROFILE(SMBopenX);
1767                 return;
1768         }
1769
1770         if (!map_open_params_to_ntcreate(
1771                     fname, deny_mode, smb_ofun, &access_mask,
1772                     &share_mode, &create_disposition, &create_options)) {
1773                 reply_nterror(req, NT_STATUS_DOS(ERRDOS, ERRbadaccess));
1774                 END_PROFILE(SMBopenX);
1775                 return;
1776         }
1777
1778         status = SMB_VFS_CREATE_FILE(
1779                 conn,                                   /* conn */
1780                 req,                                    /* req */
1781                 0,                                      /* root_dir_fid */
1782                 fname,                                  /* fname */
1783                 access_mask,                            /* access_mask */
1784                 share_mode,                             /* share_access */
1785                 create_disposition,                     /* create_disposition*/
1786                 create_options,                         /* create_options */
1787                 smb_attr,                               /* file_attributes */
1788                 oplock_request,                         /* oplock_request */
1789                 0,                                      /* allocation_size */
1790                 NULL,                                   /* sd */
1791                 NULL,                                   /* ea_list */
1792                 &fsp,                                   /* result */
1793                 &smb_action,                            /* pinfo */
1794                 &sbuf);                                 /* psbuf */
1795
1796         if (!NT_STATUS_IS_OK(status)) {
1797                 END_PROFILE(SMBopenX);
1798                 if (open_was_deferred(req->mid)) {
1799                         /* We have re-scheduled this call. */
1800                         return;
1801                 }
1802                 reply_openerror(req, status);
1803                 return;
1804         }
1805
1806         /* Setting the "size" field in vwv9 and vwv10 causes the file to be set to this size,
1807            if the file is truncated or created. */
1808         if (((smb_action == FILE_WAS_CREATED) || (smb_action == FILE_WAS_OVERWRITTEN)) && allocation_size) {
1809                 fsp->initial_allocation_size = smb_roundup(fsp->conn, allocation_size);
1810                 if (vfs_allocate_file_space(fsp, fsp->initial_allocation_size) == -1) {
1811                         close_file(req, fsp, ERROR_CLOSE);
1812                         reply_nterror(req, NT_STATUS_DISK_FULL);
1813                         END_PROFILE(SMBopenX);
1814                         return;
1815                 }
1816                 retval = vfs_set_filelen(fsp, (SMB_OFF_T)allocation_size);
1817                 if (retval < 0) {
1818                         close_file(req, fsp, ERROR_CLOSE);
1819                         reply_nterror(req, NT_STATUS_DISK_FULL);
1820                         END_PROFILE(SMBopenX);
1821                         return;
1822                 }
1823                 sbuf.st_size = get_allocation_size(conn,fsp,&sbuf);
1824         }
1825
1826         fattr = dos_mode(conn,fsp->fsp_name,&sbuf);
1827         mtime = sbuf.st_mtime;
1828         if (fattr & aDIR) {
1829                 close_file(req, fsp, ERROR_CLOSE);
1830                 reply_doserror(req, ERRDOS, ERRnoaccess);
1831                 END_PROFILE(SMBopenX);
1832                 return;
1833         }
1834
1835         /* If the caller set the extended oplock request bit
1836                 and we granted one (by whatever means) - set the
1837                 correct bit for extended oplock reply.
1838         */
1839
1840         if (ex_oplock_request && lp_fake_oplocks(SNUM(conn))) {
1841                 smb_action |= EXTENDED_OPLOCK_GRANTED;
1842         }
1843
1844         if(ex_oplock_request && EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type)) {
1845                 smb_action |= EXTENDED_OPLOCK_GRANTED;
1846         }
1847
1848         /* If the caller set the core oplock request bit
1849                 and we granted one (by whatever means) - set the
1850                 correct bit for core oplock reply.
1851         */
1852
1853         if (open_flags & EXTENDED_RESPONSE_REQUIRED) {
1854                 reply_outbuf(req, 19, 0);
1855         } else {
1856                 reply_outbuf(req, 15, 0);
1857         }
1858
1859         if (core_oplock_request && lp_fake_oplocks(SNUM(conn))) {
1860                 SCVAL(req->outbuf, smb_flg,
1861                       CVAL(req->outbuf,smb_flg)|CORE_OPLOCK_GRANTED);
1862         }
1863
1864         if(core_oplock_request && EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type)) {
1865                 SCVAL(req->outbuf, smb_flg,
1866                       CVAL(req->outbuf,smb_flg)|CORE_OPLOCK_GRANTED);
1867         }
1868
1869         SSVAL(req->outbuf,smb_vwv2,fsp->fnum);
1870         SSVAL(req->outbuf,smb_vwv3,fattr);
1871         if(lp_dos_filetime_resolution(SNUM(conn)) ) {
1872                 srv_put_dos_date3((char *)req->outbuf,smb_vwv4,mtime & ~1);
1873         } else {
1874                 srv_put_dos_date3((char *)req->outbuf,smb_vwv4,mtime);
1875         }
1876         SIVAL(req->outbuf,smb_vwv6,(uint32)sbuf.st_size);
1877         SSVAL(req->outbuf,smb_vwv8,GET_OPENX_MODE(deny_mode));
1878         SSVAL(req->outbuf,smb_vwv11,smb_action);
1879
1880         if (open_flags & EXTENDED_RESPONSE_REQUIRED) {
1881                 SIVAL(req->outbuf, smb_vwv15, STD_RIGHT_ALL_ACCESS);
1882         }
1883
1884         END_PROFILE(SMBopenX);
1885         chain_reply(req);
1886         return;
1887 }
1888
1889 /****************************************************************************
1890  Reply to a SMBulogoffX.
1891 ****************************************************************************/
1892
1893 void reply_ulogoffX(struct smb_request *req)
1894 {
1895         user_struct *vuser;
1896
1897         START_PROFILE(SMBulogoffX);
1898
1899         vuser = get_valid_user_struct(req->vuid);
1900
1901         if(vuser == NULL) {
1902                 DEBUG(3,("ulogoff, vuser id %d does not map to user.\n",
1903                          req->vuid));
1904         }
1905
1906         /* in user level security we are supposed to close any files
1907                 open by this user */
1908         if ((vuser != NULL) && (lp_security() != SEC_SHARE)) {
1909                 file_close_user(req->vuid);
1910         }
1911
1912         invalidate_vuid(req->vuid);
1913
1914         reply_outbuf(req, 2, 0);
1915
1916         DEBUG( 3, ( "ulogoffX vuid=%d\n", req->vuid ) );
1917
1918         END_PROFILE(SMBulogoffX);
1919         chain_reply(req);
1920 }
1921
1922 /****************************************************************************
1923  Reply to a mknew or a create.
1924 ****************************************************************************/
1925
1926 void reply_mknew(struct smb_request *req)
1927 {
1928         connection_struct *conn = req->conn;
1929         char *fname = NULL;
1930         uint32 fattr = 0;
1931         struct timespec ts[2];
1932         files_struct *fsp;
1933         int oplock_request = 0;
1934         SMB_STRUCT_STAT sbuf;
1935         NTSTATUS status;
1936         uint32 access_mask = FILE_GENERIC_READ | FILE_GENERIC_WRITE;
1937         uint32 share_mode = FILE_SHARE_READ|FILE_SHARE_WRITE;
1938         uint32 create_disposition;
1939         uint32 create_options = 0;
1940         TALLOC_CTX *ctx = talloc_tos();
1941
1942         START_PROFILE(SMBcreate);
1943
1944         if (req->wct < 3) {
1945                 reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
1946                 END_PROFILE(SMBcreate);
1947                 return;
1948         }
1949
1950         fattr = SVAL(req->vwv+0, 0);
1951         oplock_request = CORE_OPLOCK_REQUEST(req->inbuf);
1952
1953         ts[1] = convert_time_t_to_timespec(srv_make_unix_date3(req->vwv+1));
1954                         /* mtime. */
1955
1956         srvstr_get_path_req(ctx, req, &fname, (const char *)req->buf + 1,
1957                             STR_TERMINATE, &status);
1958         if (!NT_STATUS_IS_OK(status)) {
1959                 reply_nterror(req, status);
1960                 END_PROFILE(SMBcreate);
1961                 return;
1962         }
1963
1964         if (fattr & aVOLID) {
1965                 DEBUG(0,("Attempt to create file (%s) with volid set - "
1966                         "please report this\n", fname));
1967         }
1968
1969         if(req->cmd == SMBmknew) {
1970                 /* We should fail if file exists. */
1971                 create_disposition = FILE_CREATE;
1972         } else {
1973                 /* Create if file doesn't exist, truncate if it does. */
1974                 create_disposition = FILE_OVERWRITE_IF;
1975         }
1976
1977         status = SMB_VFS_CREATE_FILE(
1978                 conn,                                   /* conn */
1979                 req,                                    /* req */
1980                 0,                                      /* root_dir_fid */
1981                 fname,                                  /* fname */
1982                 access_mask,                            /* access_mask */
1983                 share_mode,                             /* share_access */
1984                 create_disposition,                     /* create_disposition*/
1985                 create_options,                         /* create_options */
1986                 fattr,                                  /* file_attributes */
1987                 oplock_request,                         /* oplock_request */
1988                 0,                                      /* allocation_size */
1989                 NULL,                                   /* sd */
1990                 NULL,                                   /* ea_list */
1991                 &fsp,                                   /* result */
1992                 NULL,                                   /* pinfo */
1993                 &sbuf);                                 /* psbuf */
1994
1995         if (!NT_STATUS_IS_OK(status)) {
1996                 END_PROFILE(SMBcreate);
1997                 if (open_was_deferred(req->mid)) {
1998                         /* We have re-scheduled this call. */
1999                         return;
2000                 }
2001                 reply_openerror(req, status);
2002                 return;
2003         }
2004
2005         ts[0] = get_atimespec(&sbuf); /* atime. */
2006         status = smb_set_file_time(conn, fsp, fsp->fsp_name, &sbuf, ts, true);
2007         if (!NT_STATUS_IS_OK(status)) {
2008                 END_PROFILE(SMBcreate);
2009                 reply_openerror(req, status);
2010                 return;
2011         }
2012
2013         reply_outbuf(req, 1, 0);
2014         SSVAL(req->outbuf,smb_vwv0,fsp->fnum);
2015
2016         if (oplock_request && lp_fake_oplocks(SNUM(conn))) {
2017                 SCVAL(req->outbuf,smb_flg,
2018                                 CVAL(req->outbuf,smb_flg)|CORE_OPLOCK_GRANTED);
2019         }
2020
2021         if(EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type)) {
2022                 SCVAL(req->outbuf,smb_flg,
2023                                 CVAL(req->outbuf,smb_flg)|CORE_OPLOCK_GRANTED);
2024         }
2025
2026         DEBUG( 2, ( "reply_mknew: file %s\n", fsp->fsp_name ) );
2027         DEBUG( 3, ( "reply_mknew %s fd=%d dmode=0x%x\n",
2028                     fsp->fsp_name, fsp->fh->fd, (unsigned int)fattr ) );
2029
2030         END_PROFILE(SMBcreate);
2031         return;
2032 }
2033
2034 /****************************************************************************
2035  Reply to a create temporary file.
2036 ****************************************************************************/
2037
2038 void reply_ctemp(struct smb_request *req)
2039 {
2040         connection_struct *conn = req->conn;
2041         char *fname = NULL;
2042         uint32 fattr;
2043         files_struct *fsp;
2044         int oplock_request;
2045         int tmpfd;
2046         SMB_STRUCT_STAT sbuf;
2047         char *s;
2048         NTSTATUS status;
2049         TALLOC_CTX *ctx = talloc_tos();
2050
2051         START_PROFILE(SMBctemp);
2052
2053         if (req->wct < 3) {
2054                 reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
2055                 END_PROFILE(SMBctemp);
2056                 return;
2057         }
2058
2059         fattr = SVAL(req->vwv+0, 0);
2060         oplock_request = CORE_OPLOCK_REQUEST(req->inbuf);
2061
2062         srvstr_get_path_req(ctx, req, &fname, (const char *)req->buf+1,
2063                             STR_TERMINATE, &status);
2064         if (!NT_STATUS_IS_OK(status)) {
2065                 reply_nterror(req, status);
2066                 END_PROFILE(SMBctemp);
2067                 return;
2068         }
2069         if (*fname) {
2070                 fname = talloc_asprintf(ctx,
2071                                 "%s/TMXXXXXX",
2072                                 fname);
2073         } else {
2074                 fname = talloc_strdup(ctx, "TMXXXXXX");
2075         }
2076
2077         if (!fname) {
2078                 reply_nterror(req, NT_STATUS_NO_MEMORY);
2079                 END_PROFILE(SMBctemp);
2080                 return;
2081         }
2082
2083         status = resolve_dfspath(ctx, conn,
2084                                 req->flags2 & FLAGS2_DFS_PATHNAMES,
2085                                 fname,
2086                                 &fname);
2087         if (!NT_STATUS_IS_OK(status)) {
2088                 if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) {
2089                         reply_botherror(req, NT_STATUS_PATH_NOT_COVERED,
2090                                         ERRSRV, ERRbadpath);
2091                         END_PROFILE(SMBctemp);
2092                         return;
2093                 }
2094                 reply_nterror(req, status);
2095                 END_PROFILE(SMBctemp);
2096                 return;
2097         }
2098
2099         status = unix_convert(ctx, conn, fname, False, &fname, NULL, &sbuf);
2100         if (!NT_STATUS_IS_OK(status)) {
2101                 reply_nterror(req, status);
2102                 END_PROFILE(SMBctemp);
2103                 return;
2104         }
2105
2106         status = check_name(conn, fname);
2107         if (!NT_STATUS_IS_OK(status)) {
2108                 reply_nterror(req, status);
2109                 END_PROFILE(SMBctemp);
2110                 return;
2111         }
2112
2113         tmpfd = smb_mkstemp(fname);
2114         if (tmpfd == -1) {
2115                 reply_unixerror(req, ERRDOS, ERRnoaccess);
2116                 END_PROFILE(SMBctemp);
2117                 return;
2118         }
2119
2120         SMB_VFS_STAT(conn,fname,&sbuf);
2121
2122         /* We should fail if file does not exist. */
2123         status = open_file_ntcreate(conn, req, fname, &sbuf,
2124                                 FILE_GENERIC_READ | FILE_GENERIC_WRITE,
2125                                 FILE_SHARE_READ|FILE_SHARE_WRITE,
2126                                 FILE_OPEN,
2127                                 0,
2128                                 fattr,
2129                                 oplock_request,
2130                                 NULL, &fsp);
2131
2132         /* close fd from smb_mkstemp() */
2133         close(tmpfd);
2134
2135         if (!NT_STATUS_IS_OK(status)) {
2136                 if (open_was_deferred(req->mid)) {
2137                         /* We have re-scheduled this call. */
2138                         END_PROFILE(SMBctemp);
2139                         return;
2140                 }
2141                 reply_openerror(req, status);
2142                 END_PROFILE(SMBctemp);
2143                 return;
2144         }
2145
2146         reply_outbuf(req, 1, 0);
2147         SSVAL(req->outbuf,smb_vwv0,fsp->fnum);
2148
2149         /* the returned filename is relative to the directory */
2150         s = strrchr_m(fsp->fsp_name, '/');
2151         if (!s) {
2152                 s = fsp->fsp_name;
2153         } else {
2154                 s++;
2155         }
2156
2157 #if 0
2158         /* Tested vs W2K3 - this doesn't seem to be here - null terminated filename is the only
2159            thing in the byte section. JRA */
2160         SSVALS(p, 0, -1); /* what is this? not in spec */
2161 #endif
2162         if (message_push_string(&req->outbuf, s, STR_ASCII|STR_TERMINATE)
2163             == -1) {
2164                 reply_nterror(req, NT_STATUS_NO_MEMORY);
2165                 END_PROFILE(SMBctemp);
2166                 return;
2167         }
2168
2169         if (oplock_request && lp_fake_oplocks(SNUM(conn))) {
2170                 SCVAL(req->outbuf, smb_flg,
2171                       CVAL(req->outbuf,smb_flg)|CORE_OPLOCK_GRANTED);
2172         }
2173
2174         if (EXCLUSIVE_OPLOCK_TYPE(fsp->oplock_type)) {
2175                 SCVAL(req->outbuf, smb_flg,
2176                       CVAL(req->outbuf,smb_flg)|CORE_OPLOCK_GRANTED);
2177         }
2178
2179         DEBUG( 2, ( "reply_ctemp: created temp file %s\n", fsp->fsp_name ) );
2180         DEBUG( 3, ( "reply_ctemp %s fd=%d umode=0%o\n", fsp->fsp_name,
2181                     fsp->fh->fd, (unsigned int)sbuf.st_mode ) );
2182
2183         END_PROFILE(SMBctemp);
2184         return;
2185 }
2186
2187 /*******************************************************************
2188  Check if a user is allowed to rename a file.
2189 ********************************************************************/
2190
2191 static NTSTATUS can_rename(connection_struct *conn, files_struct *fsp,
2192                            uint16 dirtype, SMB_STRUCT_STAT *pst)
2193 {
2194         uint32 fmode;
2195
2196         if (!CAN_WRITE(conn)) {
2197                 return NT_STATUS_MEDIA_WRITE_PROTECTED;
2198         }
2199
2200         fmode = dos_mode(conn, fsp->fsp_name, pst);
2201         if ((fmode & ~dirtype) & (aHIDDEN | aSYSTEM)) {
2202                 return NT_STATUS_NO_SUCH_FILE;
2203         }
2204
2205         if (S_ISDIR(pst->st_mode)) {
2206                 return NT_STATUS_OK;
2207         }
2208
2209         if (fsp->access_mask & (DELETE_ACCESS|FILE_WRITE_ATTRIBUTES)) {
2210                 return NT_STATUS_OK;
2211         }
2212
2213         return NT_STATUS_ACCESS_DENIED;
2214 }
2215
2216 /*******************************************************************
2217  * unlink a file with all relevant access checks
2218  *******************************************************************/
2219
2220 static NTSTATUS do_unlink(connection_struct *conn,
2221                         struct smb_request *req,
2222                         const char *fname,
2223                         uint32 dirtype)
2224 {
2225         SMB_STRUCT_STAT sbuf;
2226         uint32 fattr;
2227         files_struct *fsp;
2228         uint32 dirtype_orig = dirtype;
2229         NTSTATUS status;
2230
2231         DEBUG(10,("do_unlink: %s, dirtype = %d\n", fname, dirtype ));
2232
2233         if (!CAN_WRITE(conn)) {
2234                 return NT_STATUS_MEDIA_WRITE_PROTECTED;
2235         }
2236
2237         if (SMB_VFS_LSTAT(conn,fname,&sbuf) != 0) {
2238                 return map_nt_error_from_unix(errno);
2239         }
2240
2241         fattr = dos_mode(conn,fname,&sbuf);
2242
2243         if (dirtype & FILE_ATTRIBUTE_NORMAL) {
2244                 dirtype = aDIR|aARCH|aRONLY;
2245         }
2246
2247         dirtype &= (aDIR|aARCH|aRONLY|aHIDDEN|aSYSTEM);
2248         if (!dirtype) {
2249                 return NT_STATUS_NO_SUCH_FILE;
2250         }
2251
2252         if (!dir_check_ftype(conn, fattr, dirtype)) {
2253                 if (fattr & aDIR) {
2254                         return NT_STATUS_FILE_IS_A_DIRECTORY;
2255                 }
2256                 return NT_STATUS_NO_SUCH_FILE;
2257         }
2258
2259         if (dirtype_orig & 0x8000) {
2260                 /* These will never be set for POSIX. */
2261                 return NT_STATUS_NO_SUCH_FILE;
2262         }
2263
2264 #if 0
2265         if ((fattr & dirtype) & FILE_ATTRIBUTE_DIRECTORY) {
2266                 return NT_STATUS_FILE_IS_A_DIRECTORY;
2267         }
2268
2269         if ((fattr & ~dirtype) & (FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM)) {
2270                 return NT_STATUS_NO_SUCH_FILE;
2271         }
2272
2273         if (dirtype & 0xFF00) {
2274                 /* These will never be set for POSIX. */
2275                 return NT_STATUS_NO_SUCH_FILE;
2276         }
2277
2278         dirtype &= 0xFF;
2279         if (!dirtype) {
2280                 return NT_STATUS_NO_SUCH_FILE;
2281         }
2282
2283         /* Can't delete a directory. */
2284         if (fattr & aDIR) {
2285                 return NT_STATUS_FILE_IS_A_DIRECTORY;
2286         }
2287 #endif
2288
2289 #if 0 /* JRATEST */
2290         else if (dirtype & aDIR) /* Asked for a directory and it isn't. */
2291                 return NT_STATUS_OBJECT_NAME_INVALID;
2292 #endif /* JRATEST */
2293
2294         /* Fix for bug #3035 from SATOH Fumiyasu <fumiyas@miraclelinux.com>
2295
2296           On a Windows share, a file with read-only dosmode can be opened with
2297           DELETE_ACCESS. But on a Samba share (delete readonly = no), it
2298           fails with NT_STATUS_CANNOT_DELETE error.
2299
2300           This semantic causes a problem that a user can not
2301           rename a file with read-only dosmode on a Samba share
2302           from a Windows command prompt (i.e. cmd.exe, but can rename
2303           from Windows Explorer).
2304         */
2305
2306         if (!lp_delete_readonly(SNUM(conn))) {
2307                 if (fattr & aRONLY) {
2308                         return NT_STATUS_CANNOT_DELETE;
2309                 }
2310         }
2311
2312         /* On open checks the open itself will check the share mode, so
2313            don't do it here as we'll get it wrong. */
2314
2315         status = create_file_unixpath
2316                 (conn,                  /* conn */
2317                  req,                   /* req */
2318                  fname,                 /* fname */
2319                  DELETE_ACCESS,         /* access_mask */
2320                  FILE_SHARE_NONE,       /* share_access */
2321                  FILE_OPEN,             /* create_disposition*/
2322                  FILE_NON_DIRECTORY_FILE, /* create_options */
2323                  FILE_ATTRIBUTE_NORMAL, /* file_attributes */
2324                  0,                     /* oplock_request */
2325                  0,                     /* allocation_size */
2326                  NULL,                  /* sd */
2327                  NULL,                  /* ea_list */
2328                  &fsp,                  /* result */
2329                  NULL,                  /* pinfo */
2330                  &sbuf);                /* psbuf */
2331
2332         if (!NT_STATUS_IS_OK(status)) {
2333                 DEBUG(10, ("create_file_unixpath failed: %s\n",
2334                            nt_errstr(status)));
2335                 return status;
2336         }
2337
2338         /* The set is across all open files on this dev/inode pair. */
2339         if (!set_delete_on_close(fsp, True, &conn->server_info->utok)) {
2340                 close_file(req, fsp, NORMAL_CLOSE);
2341                 return NT_STATUS_ACCESS_DENIED;
2342         }
2343
2344         return close_file(req, fsp, NORMAL_CLOSE);
2345 }
2346
2347 /****************************************************************************
2348  The guts of the unlink command, split out so it may be called by the NT SMB
2349  code.
2350 ****************************************************************************/
2351
2352 NTSTATUS unlink_internals(connection_struct *conn, struct smb_request *req,
2353                           uint32 dirtype, const char *name_in, bool has_wild)
2354 {
2355         const char *directory = NULL;
2356         char *mask = NULL;
2357         char *name = NULL;
2358         char *p = NULL;
2359         int count=0;
2360         NTSTATUS status = NT_STATUS_OK;
2361         SMB_STRUCT_STAT sbuf;
2362         TALLOC_CTX *ctx = talloc_tos();
2363
2364         status = unix_convert(ctx, conn, name_in, has_wild, &name, NULL, &sbuf);
2365         if (!NT_STATUS_IS_OK(status)) {
2366                 return status;
2367         }
2368
2369         p = strrchr_m(name,'/');
2370         if (!p) {
2371                 directory = talloc_strdup(ctx, ".");
2372                 if (!directory) {
2373                         return NT_STATUS_NO_MEMORY;
2374                 }
2375                 mask = name;
2376         } else {
2377                 *p = 0;
2378                 directory = name;
2379                 mask = p+1;
2380         }
2381
2382         /*
2383          * We should only check the mangled cache
2384          * here if unix_convert failed. This means
2385          * that the path in 'mask' doesn't exist
2386          * on the file system and so we need to look
2387          * for a possible mangle. This patch from
2388          * Tine Smukavec <valentin.smukavec@hermes.si>.
2389          */
2390
2391         if (!VALID_STAT(sbuf) && mangle_is_mangled(mask,conn->params)) {
2392                 char *new_mask = NULL;
2393                 mangle_lookup_name_from_8_3(ctx,
2394                                 mask,
2395                                 &new_mask,
2396                                 conn->params );
2397                 if (new_mask) {
2398                         mask = new_mask;
2399                 }
2400         }
2401
2402         if (!has_wild) {
2403                 directory = talloc_asprintf(ctx,
2404                                 "%s/%s",
2405                                 directory,
2406                                 mask);
2407                 if (!directory) {
2408                         return NT_STATUS_NO_MEMORY;
2409                 }
2410                 if (dirtype == 0) {
2411                         dirtype = FILE_ATTRIBUTE_NORMAL;
2412                 }
2413
2414                 status = check_name(conn, directory);
2415                 if (!NT_STATUS_IS_OK(status)) {
2416                         return status;
2417                 }
2418
2419                 status = do_unlink(conn, req, directory, dirtype);
2420                 if (!NT_STATUS_IS_OK(status)) {
2421                         return status;
2422                 }
2423
2424                 count++;
2425         } else {
2426                 struct smb_Dir *dir_hnd = NULL;
2427                 long offset = 0;
2428                 const char *dname;
2429
2430                 if ((dirtype & SAMBA_ATTRIBUTES_MASK) == aDIR) {
2431                         return NT_STATUS_OBJECT_NAME_INVALID;
2432                 }
2433
2434                 if (strequal(mask,"????????.???")) {
2435                         mask[0] = '*';
2436                         mask[1] = '\0';
2437                 }
2438
2439                 status = check_name(conn, directory);
2440                 if (!NT_STATUS_IS_OK(status)) {
2441                         return status;
2442                 }
2443
2444                 dir_hnd = OpenDir(talloc_tos(), conn, directory, mask,
2445                                   dirtype);
2446                 if (dir_hnd == NULL) {
2447                         return map_nt_error_from_unix(errno);
2448                 }
2449
2450                 /* XXXX the CIFS spec says that if bit0 of the flags2 field is set then
2451                    the pattern matches against the long name, otherwise the short name 
2452                    We don't implement this yet XXXX
2453                 */
2454
2455                 status = NT_STATUS_NO_SUCH_FILE;
2456
2457                 while ((dname = ReadDirName(dir_hnd, &offset))) {
2458                         SMB_STRUCT_STAT st;
2459                         char *fname = NULL;
2460
2461                         if (!is_visible_file(conn, directory, dname, &st, True)) {
2462                                 continue;
2463                         }
2464
2465                         /* Quick check for "." and ".." */
2466                         if (ISDOT(dname) || ISDOTDOT(dname)) {
2467                                 continue;
2468                         }
2469
2470                         if(!mask_match(dname, mask, conn->case_sensitive)) {
2471                                 continue;
2472                         }
2473
2474                         fname = talloc_asprintf(ctx, "%s/%s",
2475                                         directory,
2476                                         dname);
2477                         if (!fname) {
2478                                 return NT_STATUS_NO_MEMORY;
2479                         }
2480
2481                         status = check_name(conn, fname);
2482                         if (!NT_STATUS_IS_OK(status)) {
2483                                 TALLOC_FREE(dir_hnd);
2484                                 return status;
2485                         }
2486
2487                         status = do_unlink(conn, req, fname, dirtype);
2488                         if (!NT_STATUS_IS_OK(status)) {
2489                                 TALLOC_FREE(fname);
2490                                 continue;
2491                         }
2492
2493                         count++;
2494                         DEBUG(3,("unlink_internals: successful unlink [%s]\n",
2495                                  fname));
2496
2497                         TALLOC_FREE(fname);
2498                 }
2499                 TALLOC_FREE(dir_hnd);
2500         }
2501
2502         if (count == 0 && NT_STATUS_IS_OK(status) && errno != 0) {
2503                 status = map_nt_error_from_unix(errno);
2504         }
2505
2506         return status;
2507 }
2508
2509 /****************************************************************************
2510  Reply to a unlink
2511 ****************************************************************************/
2512
2513 void reply_unlink(struct smb_request *req)
2514 {
2515         connection_struct *conn = req->conn;
2516         char *name = NULL;
2517         uint32 dirtype;
2518         NTSTATUS status;
2519         bool path_contains_wcard = False;
2520         TALLOC_CTX *ctx = talloc_tos();
2521
2522         START_PROFILE(SMBunlink);
2523
2524         if (req->wct < 1) {
2525                 reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
2526                 END_PROFILE(SMBunlink);
2527                 return;
2528         }
2529
2530         dirtype = SVAL(req->vwv+0, 0);
2531
2532         srvstr_get_path_req_wcard(ctx, req, &name, (const char *)req->buf + 1,
2533                                   STR_TERMINATE, &status,
2534                                   &path_contains_wcard);
2535         if (!NT_STATUS_IS_OK(status)) {
2536                 reply_nterror(req, status);
2537                 END_PROFILE(SMBunlink);
2538                 return;
2539         }
2540
2541         status = resolve_dfspath_wcard(ctx, conn,
2542                                        req->flags2 & FLAGS2_DFS_PATHNAMES,
2543                                        name,
2544                                        &name,
2545                                        &path_contains_wcard);
2546         if (!NT_STATUS_IS_OK(status)) {
2547                 if (NT_STATUS_EQUAL(status,NT_STATUS_PATH_NOT_COVERED)) {
2548                         reply_botherror(req, NT_STATUS_PATH_NOT_COVERED,
2549                                         ERRSRV, ERRbadpath);
2550                         END_PROFILE(SMBunlink);
2551                         return;
2552                 }
2553                 reply_nterror(req, status);
2554                 END_PROFILE(SMBunlink);
2555                 return;
2556         }
2557
2558         DEBUG(3,("reply_unlink : %s\n",name));
2559
2560         status = unlink_internals(conn, req, dirtype, name,
2561                                   path_contains_wcard);
2562         if (!NT_STATUS_IS_OK(status)) {
2563                 if (open_was_deferred(req->mid)) {
2564                         /* We have re-scheduled this call. */
2565                         END_PROFILE(SMBunlink);
2566                         return;
2567                 }
2568                 reply_nterror(req, status);
2569                 END_PROFILE(SMBunlink);
2570                 return;
2571         }
2572
2573         reply_outbuf(req, 0, 0);
2574         END_PROFILE(SMBunlink);
2575
2576         return;
2577 }
2578
2579 /****************************************************************************
2580  Fail for readbraw.
2581 ****************************************************************************/
2582
2583 static void fail_readraw(void)
2584 {
2585         const char *errstr = talloc_asprintf(talloc_tos(),
2586                         "FAIL ! reply_readbraw: socket write fail (%s)",
2587                         strerror(errno));
2588         if (!errstr) {
2589                 errstr = "";
2590         }
2591         exit_server_cleanly(errstr);
2592 }
2593
2594 /****************************************************************************
2595  Fake (read/write) sendfile. Returns -1 on read or write fail.
2596 ****************************************************************************/
2597
2598 static ssize_t fake_sendfile(files_struct *fsp, SMB_OFF_T startpos,
2599                              size_t nread)
2600 {
2601         size_t bufsize;
2602         size_t tosend = nread;
2603         char *buf;
2604
2605         if (nread == 0) {
2606                 return 0;
2607         }
2608
2609         bufsize = MIN(nread, 65536);
2610
2611         if (!(buf = SMB_MALLOC_ARRAY(char, bufsize))) {
2612                 return -1;
2613         }
2614
2615         while (tosend > 0) {
2616                 ssize_t ret;
2617                 size_t cur_read;
2618
2619                 if (tosend > bufsize) {
2620                         cur_read = bufsize;
2621                 } else {
2622                         cur_read = tosend;
2623                 }
2624                 ret = read_file(fsp,buf,startpos,cur_read);
2625                 if (ret == -1) {
2626                         SAFE_FREE(buf);
2627                         return -1;
2628                 }
2629
2630                 /* If we had a short read, fill with zeros. */
2631                 if (ret < cur_read) {
2632                         memset(buf, '\0', cur_read - ret);
2633                 }
2634
2635                 if (write_data(smbd_server_fd(),buf,cur_read) != cur_read) {
2636                         SAFE_FREE(buf);
2637                         return -1;
2638                 }
2639                 tosend -= cur_read;
2640                 startpos += cur_read;
2641         }
2642
2643         SAFE_FREE(buf);
2644         return (ssize_t)nread;
2645 }
2646
2647 /****************************************************************************
2648  Return a readbraw error (4 bytes of zero).
2649 ****************************************************************************/
2650
2651 static void reply_readbraw_error(void)
2652 {
2653         char header[4];
2654         SIVAL(header,0,0);
2655         if (write_data(smbd_server_fd(),header,4) != 4) {
2656                 fail_readraw();
2657         }
2658 }
2659
2660 /****************************************************************************
2661  Use sendfile in readbraw.
2662 ****************************************************************************/
2663
2664 void send_file_readbraw(connection_struct *conn,
2665                         files_struct *fsp,
2666                         SMB_OFF_T startpos,
2667                         size_t nread,
2668                         ssize_t mincount)
2669 {
2670         char *outbuf = NULL;
2671         ssize_t ret=0;
2672
2673 #if defined(WITH_SENDFILE)
2674         /*
2675          * We can only use sendfile on a non-chained packet 
2676          * but we can use on a non-oplocked file. tridge proved this
2677          * on a train in Germany :-). JRA.
2678          * reply_readbraw has already checked the length.
2679          */
2680
2681         if ( (chain_size == 0) && (nread > 0) && (fsp->base_fsp == NULL) &&
2682             (fsp->wcp == NULL) && lp_use_sendfile(SNUM(conn)) ) {
2683                 char header[4];
2684                 DATA_BLOB header_blob;
2685
2686                 _smb_setlen(header,nread);
2687                 header_blob = data_blob_const(header, 4);
2688
2689                 if (SMB_VFS_SENDFILE(smbd_server_fd(), fsp,
2690                                 &header_blob, startpos, nread) == -1) {
2691                         /* Returning ENOSYS means no data at all was sent.
2692                          * Do this as a normal read. */
2693                         if (errno == ENOSYS) {
2694                                 goto normal_readbraw;
2695                         }
2696
2697                         /*
2698                          * Special hack for broken Linux with no working sendfile. If we
2699                          * return EINTR we sent the header but not the rest of the data.
2700                          * Fake this up by doing read/write calls.
2701                          */
2702                         if (errno == EINTR) {
2703                                 /* Ensure we don't do this again. */
2704                                 set_use_sendfile(SNUM(conn), False);
2705                                 DEBUG(0,("send_file_readbraw: sendfile not available. Faking..\n"));
2706
2707                                 if (fake_sendfile(fsp, startpos, nread) == -1) {
2708                                         DEBUG(0,("send_file_readbraw: fake_sendfile failed for file %s (%s).\n",
2709                                                 fsp->fsp_name, strerror(errno) ));
2710                                         exit_server_cleanly("send_file_readbraw fake_sendfile failed");
2711                                 }
2712                                 return;
2713                         }
2714
2715                         DEBUG(0,("send_file_readbraw: sendfile failed for file %s (%s). Terminating\n",
2716                                 fsp->fsp_name, strerror(errno) ));
2717                         exit_server_cleanly("send_file_readbraw sendfile failed");
2718                 }
2719
2720                 return;
2721         }
2722 #endif
2723
2724 normal_readbraw:
2725
2726         outbuf = TALLOC_ARRAY(NULL, char, nread+4);
2727         if (!outbuf) {
2728                 DEBUG(0,("send_file_readbraw: TALLOC_ARRAY failed for size %u.\n",
2729                         (unsigned)(nread+4)));
2730                 reply_readbraw_error();
2731                 return;
2732         }
2733
2734         if (nread > 0) {
2735                 ret = read_file(fsp,outbuf+4,startpos,nread);
2736 #if 0 /* mincount appears to be ignored in a W2K server. JRA. */
2737                 if (ret < mincount)
2738                         ret = 0;
2739 #else
2740                 if (ret < nread)
2741                         ret = 0;
2742 #endif
2743         }
2744
2745         _smb_setlen(outbuf,ret);
2746         if (write_data(smbd_server_fd(),outbuf,4+ret) != 4+ret)
2747                 fail_readraw();
2748
2749         TALLOC_FREE(outbuf);
2750 }
2751
2752 /****************************************************************************
2753  Reply to a readbraw (core+ protocol).
2754 ****************************************************************************/
2755
2756 void reply_readbraw(struct smb_request *req)
2757 {
2758         connection_struct *conn = req->conn;
2759         ssize_t maxcount,mincount;
2760         size_t nread = 0;
2761         SMB_OFF_T startpos;
2762         files_struct *fsp;
2763         SMB_STRUCT_STAT st;
2764         SMB_OFF_T size = 0;
2765
2766         START_PROFILE(SMBreadbraw);
2767
2768         if (srv_is_signing_active() || is_encrypted_packet(req->inbuf)) {
2769                 exit_server_cleanly("reply_readbraw: SMB signing/sealing is active - "
2770                         "raw reads/writes are disallowed.");
2771         }
2772
2773         if (req->wct < 8) {
2774                 reply_readbraw_error();
2775                 END_PROFILE(SMBreadbraw);
2776                 return;
2777         }
2778
2779         /*
2780          * Special check if an oplock break has been issued
2781          * and the readraw request croses on the wire, we must
2782          * return a zero length response here.
2783          */
2784
2785         fsp = file_fsp(req, SVAL(req->vwv+0, 0));
2786
2787         /*
2788          * We have to do a check_fsp by hand here, as
2789          * we must always return 4 zero bytes on error,
2790          * not a NTSTATUS.
2791          */
2792
2793         if (!fsp || !conn || conn != fsp->conn ||
2794                         req->vuid != fsp->vuid ||
2795                         fsp->is_directory || fsp->fh->fd == -1) {
2796                 /*
2797                  * fsp could be NULL here so use the value from the packet. JRA.
2798                  */
2799                 DEBUG(3,("reply_readbraw: fnum %d not valid "
2800                         "- cache prime?\n",
2801                         (int)SVAL(req->vwv+0, 0)));
2802                 reply_readbraw_error();
2803                 END_PROFILE(SMBreadbraw);
2804                 return;
2805         }
2806
2807         /* Do a "by hand" version of CHECK_READ. */
2808         if (!(fsp->can_read ||
2809                         ((req->flags2 & FLAGS2_READ_PERMIT_EXECUTE) &&
2810                                 (fsp->access_mask & FILE_EXECUTE)))) {
2811                 DEBUG(3,("reply_readbraw: fnum %d not readable.\n",
2812                                 (int)SVAL(req->vwv+0, 0)));
2813                 reply_readbraw_error();
2814                 END_PROFILE(SMBreadbraw);
2815                 return;
2816         }
2817
2818         flush_write_cache(fsp, READRAW_FLUSH);
2819
2820         startpos = IVAL_TO_SMB_OFF_T(req->vwv+1, 0);
2821         if(req->wct == 10) {
2822                 /*
2823                  * This is a large offset (64 bit) read.
2824                  */
2825 #ifdef LARGE_SMB_OFF_T
2826
2827                 startpos |= (((SMB_OFF_T)IVAL(req->vwv+8, 0)) << 32);
2828
2829 #else /* !LARGE_SMB_OFF_T */
2830
2831                 /*
2832                  * Ensure we haven't been sent a >32 bit offset.
2833                  */
2834
2835                 if(IVAL(req->vwv+8, 0) != 0) {
2836                         DEBUG(0,("reply_readbraw: large offset "
2837                                 "(%x << 32) used and we don't support "
2838                                 "64 bit offsets.\n",
2839                         (unsigned int)IVAL(req->vwv+8, 0) ));
2840                         reply_readbraw_error();
2841                         END_PROFILE(SMBreadbraw);
2842                         return;
2843                 }
2844
2845 #endif /* LARGE_SMB_OFF_T */
2846
2847                 if(startpos < 0) {
2848                         DEBUG(0,("reply_readbraw: negative 64 bit "
2849                                 "readraw offset (%.0f) !\n",
2850                                 (double)startpos ));
2851                         reply_readbraw_error();
2852                         END_PROFILE(SMBreadbraw);
2853                         return;
2854                 }      
2855         }
2856
2857         maxcount = (SVAL(req->vwv+3, 0) & 0xFFFF);
2858         mincount = (SVAL(req->vwv+4, 0) & 0xFFFF);
2859
2860         /* ensure we don't overrun the packet size */
2861         maxcount = MIN(65535,maxcount);
2862
2863         if (is_locked(fsp,(uint32)req->smbpid,
2864                         (uint64_t)maxcount,
2865                         (uint64_t)startpos,
2866                         READ_LOCK)) {
2867                 reply_readbraw_error();
2868                 END_PROFILE(SMBreadbraw);
2869                 return;
2870         }
2871
2872         if (SMB_VFS_FSTAT(fsp, &st) == 0) {
2873                 size = st.st_size;
2874         }
2875
2876         if (startpos >= size) {
2877                 nread = 0;
2878         } else {
2879                 nread = MIN(maxcount,(size - startpos));
2880         }
2881
2882 #if 0 /* mincount appears to be ignored in a W2K server. JRA. */
2883         if (nread < mincount)
2884                 nread = 0;
2885 #endif
2886
2887         DEBUG( 3, ( "reply_readbraw: fnum=%d start=%.0f max=%lu "
2888                 "min=%lu nread=%lu\n",
2889                 fsp->fnum, (double)startpos,
2890                 (unsigned long)maxcount,
2891                 (unsigned long)mincount,
2892                 (unsigned long)nread ) );
2893
2894         send_file_readbraw(conn, fsp, startpos, nread, mincount);
2895
2896         DEBUG(5,("reply_readbraw finished\n"));
2897         END_PROFILE(SMBreadbraw);
2898 }
2899
2900 #undef DBGC_CLASS
2901 #define DBGC_CLASS DBGC_LOCKING
2902
2903 /****************************************************************************
2904  Reply to a lockread (core+ protocol).
2905 ****************************************************************************/
2906
2907 void reply_lockread(struct smb_request *req)
2908 {
2909         connection_struct *conn = req->conn;
2910         ssize_t nread = -1;
2911         char *data;
2912         SMB_OFF_T startpos;
2913         size_t numtoread;
2914         NTSTATUS status;
2915         files_struct *fsp;
2916         struct byte_range_lock *br_lck = NULL;
2917         char *p = NULL;
2918
2919         START_PROFILE(SMBlockread);
2920
2921         if (req->wct < 5) {
2922                 reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
2923                 END_PROFILE(SMBlockread);
2924                 return;
2925         }
2926
2927         fsp = file_fsp(req, SVAL(req->vwv+0, 0));
2928
2929         if (!check_fsp(conn, req, fsp)) {
2930                 END_PROFILE(SMBlockread);
2931                 return;
2932         }
2933
2934         if (!CHECK_READ(fsp,req)) {
2935                 reply_doserror(req, ERRDOS, ERRbadaccess);
2936                 END_PROFILE(SMBlockread);
2937                 return;
2938         }
2939
2940         release_level_2_oplocks_on_change(fsp);
2941
2942         numtoread = SVAL(req->vwv+1, 0);
2943         startpos = IVAL_TO_SMB_OFF_T(req->vwv+2, 0);
2944
2945         numtoread = MIN(BUFFER_SIZE - (smb_size + 3*2 + 3), numtoread);
2946
2947         reply_outbuf(req, 5, numtoread + 3);
2948
2949         data = smb_buf(req->outbuf) + 3;
2950
2951         /*
2952          * NB. Discovered by Menny Hamburger at Mainsoft. This is a core+
2953          * protocol request that predates the read/write lock concept. 
2954          * Thus instead of asking for a read lock here we need to ask
2955          * for a write lock. JRA.
2956          * Note that the requested lock size is unaffected by max_recv.
2957          */
2958
2959         br_lck = do_lock(smbd_messaging_context(),
2960                         fsp,
2961                         req->smbpid,
2962                         (uint64_t)numtoread,
2963                         (uint64_t)startpos,
2964                         WRITE_LOCK,
2965                         WINDOWS_LOCK,
2966                         False, /* Non-blocking lock. */
2967                         &status,
2968                         NULL);
2969         TALLOC_FREE(br_lck);
2970
2971         if (NT_STATUS_V(status)) {
2972                 reply_nterror(req, status);
2973                 END_PROFILE(SMBlockread);
2974                 return;
2975         }
2976
2977         /*
2978          * However the requested READ size IS affected by max_recv. Insanity.... JRA.
2979          */
2980
2981         if (numtoread > max_recv) {
2982                 DEBUG(0,("reply_lockread: requested read size (%u) is greater than maximum allowed (%u). \
2983 Returning short read of maximum allowed for compatibility with Windows 2000.\n",
2984                         (unsigned int)numtoread, (unsigned int)max_recv ));
2985                 numtoread = MIN(numtoread,max_recv);
2986         }
2987         nread = read_file(fsp,data,startpos,numtoread);
2988
2989         if (nread < 0) {
2990                 reply_unixerror(req, ERRDOS, ERRnoaccess);
2991                 END_PROFILE(SMBlockread);
2992                 return;
2993         }
2994
2995         srv_set_message((char *)req->outbuf, 5, nread+3, False);
2996
2997         SSVAL(req->outbuf,smb_vwv0,nread);
2998         SSVAL(req->outbuf,smb_vwv5,nread+3);
2999         p = smb_buf(req->outbuf);
3000         SCVAL(p,0,0); /* pad byte. */
3001         SSVAL(p,1,nread);
3002
3003         DEBUG(3,("lockread fnum=%d num=%d nread=%d\n",
3004                  fsp->fnum, (int)numtoread, (int)nread));
3005
3006         END_PROFILE(SMBlockread);
3007         return;
3008 }
3009
3010 #undef DBGC_CLASS
3011 #define DBGC_CLASS DBGC_ALL
3012
3013 /****************************************************************************
3014  Reply to a read.
3015 ****************************************************************************/
3016
3017 void reply_read(struct smb_request *req)
3018 {
3019         connection_struct *conn = req->conn;
3020         size_t numtoread;
3021         ssize_t nread = 0;
3022         char *data;
3023         SMB_OFF_T startpos;
3024         int outsize = 0;
3025         files_struct *fsp;
3026
3027         START_PROFILE(SMBread);
3028
3029         if (req->wct < 3) {
3030                 reply_nterror(req, NT_STATUS_INVALID_PARAMETER);
3031                 END_PROFILE(SMBread);
3032                 return;
3033         }
3034
3035         fsp = file_fsp(req, SVAL(req->vwv+0, 0));
3036
3037         if (!check_fsp(conn, req, fsp)) {
3038                 END_PROFILE(SMBread);
3039                 return;
3040         }
3041
3042         if (!CHECK_READ(fsp,req)) {
3043                 reply_doserror(req, ERRDOS, ERRbadaccess);
3044                 END_PROFILE(SMBread);
3045                 return;
3046         }
3047
3048         numtoread = SVAL(req->vwv+1, 0);
3049         startpos = IVAL_TO_SMB_OFF_T(req->vwv+2, 0);
3050
3051         numtoread = MIN(BUFFER_SIZE-outsize,numtoread);
3052
3053         /*
3054          * The requested read size cannot be greater than max_recv. JRA.
3055          */
3056         if (numtoread > max_recv) {
3057                 DEBUG(0,("reply_read: requested read size (%u) is greater than maximum allowed (%u). \
3058 Returning short read of maximum allowed for compatibility with Windows 2000.\n",
3059                         (unsigned int)numtoread, (unsigned int)max_recv ));
3060                 numtoread = MIN(numtoread,max_recv);
3061         }
3062
3063         reply_outbuf(req, 5, numtoread+3);
3064
3065         data = smb_buf(req->outbuf) + 3;
3066
3067         if (is_locked(fsp, (uint32)req->smbpid, (uint64_t)numtoread,
3068                       (uint64_t)startpos, READ_LOCK)) {
3069                 reply_doserror(req, ERRDOS,ERRlock);
3070                 END_PROFILE(SMBread);
3071                 return;
3072         }
3073
3074         if (numtoread > 0)
3075                 nread = read_file(fsp,data,startpos,numtoread);
3076
3077         if (nread < 0) {
3078                 reply_unixerror(req, ERRDOS,ERRnoaccess);
3079                 END_PROFILE(SMBread);
3080                 return;
3081         }
3082
3083         srv_set_message((char *)req->outbuf, 5, nread+3, False);
3084
3085         SSVAL(req->outbuf,smb_vwv0,nread);
3086         SSVAL(req->outbuf,smb_vwv5,nread+3);
3087         SCVAL(smb_buf(req->outbuf),0,1);
3088         SSVAL(smb_buf(req->outbuf),1,nread);
3089
3090         DEBUG( 3, ( "read fnum=%d num=%d nread=%d\n",
3091                 fsp->fnum, (int)numtoread, (int)nread ) );
3092
3093         END_PROFILE(SMBread);
3094         return;
3095 }
3096
3097 /****************************************************************************
3098  Setup readX header.
3099 ****************************************************************************/
3100
3101 static int setup_readX_header(char *outbuf, size_t smb_maxcnt)
3102 {
3103         int outsize;
3104         char *data;
3105
3106         outsize = srv_set_message(outbuf,12,smb_maxcnt,False);
3107         data = smb_buf(outbuf);
3108
3109         memset(outbuf+smb_vwv0,'\0',24); /* valgrind init. */
3110
3111         SCVAL(outbuf,smb_vwv0,0xFF);
3112         SSVAL(outbuf,smb_vwv2,0xFFFF); /* Remaining - must be -1. */
3113         SSVAL(outbuf,smb_vwv5,smb_maxcnt);
3114         SSVAL(outbuf,smb_vwv6,smb_offset(data,outbuf));
3115         SSVAL(outbuf,smb_vwv7,(smb_maxcnt >> 16));
3116         SSVAL(smb_buf(outbuf),-2,smb_maxcnt);
3117         /* Reset the outgoing length, set_message truncates at 0x1FFFF. */
3118         _smb_setlen_large(outbuf,(smb_size + 12*2 + smb_maxcnt - 4));
3119         return outsize;
3120 }
3121
3122 /****************************************************************************
3123  Reply to a read and X - possibly using sendfile.
3124 ****************************************************************************/
3125
3126 static void send_file_readX(connection_struct *conn, struct smb_request *req,
3127                             files_struct *fsp, SMB_OFF_T startpos,
3128                             size_t smb_maxcnt)
3129 {
3130         SMB_STRUCT_STAT sbuf;
3131         ssize_t nread = -1;
3132
3133         if(SMB_VFS_FSTAT(fsp, &sbuf) == -1) {
3134                 reply_unixerror(req, ERRDOS, ERRnoaccess);
3135                 return;
3136         }
3137
3138         if (startpos > sbuf.st_size) {
3139                 smb_maxcnt = 0;
3140         } else if (smb_maxcnt > (sbuf.st_size - startpos)) {
3141                 smb_maxcnt = (sbuf.st_size - startpos);
3142         }
3143
3144         if (smb_maxcnt == 0) {
3145                 goto normal_read;
3146         }
3147
3148 #if defined(WITH_SENDFILE)
3149         /*
3150          * We can only use sendfile on a non-chained packet
3151          * but we can use on a non-oplocked file. tridge proved this
3152          * on a train in Germany :-). JRA.
3153          */
3154
3155         if ((chain_size == 0) && (CVAL(req->vwv+0, 0) == 0xFF) &&
3156             !is_encrypted_packet(req->inbuf) && (fsp->base_fsp == NULL) &&
3157             lp_use_sendfile(SNUM(conn)) && (fsp->wcp == NULL) ) {
3158                 uint8 headerbuf[smb_size + 12 * 2];
3159                 DATA_BLOB header;
3160
3161                 /*
3162                  * Set up the packet header before send. We
3163                  * assume here the sendfile will work (get the
3164                  * correct amount of data).
3165                  */
3166
3167                 header = data_blob_const(headerbuf, sizeof(headerbuf));
3168
3169                 construct_reply_common_req(req, (char *)headerbuf);
3170                 setup_readX_header((char *)headerbuf, smb_maxcnt);
3171
3172                 if ((nread = SMB_VFS_SENDFILE(smbd_server_fd(), fsp, &header, startpos, smb_maxcnt)) == -1) {
3173                         /* Returning ENOSYS or EINVAL means no data at all was sent. 
3174                            Do this as a normal read. */
3175                         if (errno == ENOSYS || errno == EINVAL) {
3176                                 goto normal_read;
3177                         }
3178
3179                         /*
3180                          * Special hack for broken Linux with no working sendfile. If we
3181                          * return EINTR we sent the header but not the rest of the data.
3182                          * Fake this up by doing read/write calls.
3183                          */
3184
3185                         if (errno == EINTR) {
3186                                 /* Ensure we don't do this again. */
3187                                 set_use_sendfile(SNUM(conn), False);
3188                                 DEBUG(0,("send_file_readX: sendfile not available. Faking..\n"));
3189                                 nread = fake_sendfile(fsp, startpos,
3190                                                       smb_maxcnt);
3191                                 if (nread == -1) {
3192                                         DEBUG(0,("send_file_readX: fake_sendfile failed for file %s (%s).\n",
3193                                                 fsp->fsp_name, strerror(errno) ));
3194                                         exit_server_cleanly("send_file_readX: fake_sendfile failed");
3195                                 }
3196                                 DEBUG( 3, ( "send_file_readX: fake_sendfile fnum=%d max=%d nread=%d\n",