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