s3: smbd: Correctly process SMB3 POSIX paths in create.
[Samba.git] / source3 / smbd / smb2_reply.c
blob85d057386d5258075a41a26845798ece135a8ecf
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
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.
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.
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/>.
23 This file handles most of the reply_ calls that the server
24 makes to handle specific protocols
27 #include "includes.h"
28 #include "libsmb/namequery.h"
29 #include "system/filesys.h"
30 #include "printing.h"
31 #include "locking/share_mode_lock.h"
32 #include "smbd/smbd.h"
33 #include "smbd/globals.h"
34 #include "smbd/smbXsrv_open.h"
35 #include "fake_file.h"
36 #include "rpc_client/rpc_client.h"
37 #include "../librpc/gen_ndr/ndr_spoolss_c.h"
38 #include "rpc_client/cli_spoolss.h"
39 #include "rpc_client/init_spoolss.h"
40 #include "rpc_server/rpc_ncacn_np.h"
41 #include "libcli/security/security.h"
42 #include "libsmb/nmblib.h"
43 #include "auth.h"
44 #include "smbprofile.h"
45 #include "../lib/tsocket/tsocket.h"
46 #include "lib/util/tevent_ntstatus.h"
47 #include "libcli/smb/smb_signing.h"
48 #include "lib/util/sys_rw_data.h"
49 #include "librpc/gen_ndr/open_files.h"
50 #include "libcli/smb/smb2_posix.h"
51 #include "lib/util/string_wrappers.h"
52 #include "source3/printing/rap_jobid.h"
53 #include "source3/lib/substitute.h"
55 /****************************************************************************
56 Ensure we check the path in *exactly* the same way as W2K for a findfirst/findnext
57 path or anything including wildcards.
58 We're assuming here that '/' is not the second byte in any multibyte char
59 set (a safe assumption). '\\' *may* be the second byte in a multibyte char
60 set.
61 ****************************************************************************/
63 /* Custom version for processing POSIX paths. */
64 #define IS_PATH_SEP(c,posix_only) ((c) == '/' || (!(posix_only) && (c) == '\\'))
66 static NTSTATUS check_path_syntax_internal(char *path,
67 bool posix_path)
69 char *d = path;
70 const char *s = path;
71 NTSTATUS ret = NT_STATUS_OK;
72 bool start_of_name_component = True;
73 bool stream_started = false;
74 bool last_component_contains_wcard = false;
76 while (*s) {
77 if (stream_started) {
78 switch (*s) {
79 case '/':
80 case '\\':
81 return NT_STATUS_OBJECT_NAME_INVALID;
82 case ':':
83 if (s[1] == '\0') {
84 return NT_STATUS_OBJECT_NAME_INVALID;
86 if (strchr_m(&s[1], ':')) {
87 return NT_STATUS_OBJECT_NAME_INVALID;
89 break;
93 if ((*s == ':') && !posix_path && !stream_started) {
94 if (last_component_contains_wcard) {
95 return NT_STATUS_OBJECT_NAME_INVALID;
97 /* Stream names allow more characters than file names.
98 We're overloading posix_path here to allow a wider
99 range of characters. If stream_started is true this
100 is still a Windows path even if posix_path is true.
101 JRA.
103 stream_started = true;
104 start_of_name_component = false;
105 posix_path = true;
107 if (s[1] == '\0') {
108 return NT_STATUS_OBJECT_NAME_INVALID;
112 if (!stream_started && IS_PATH_SEP(*s,posix_path)) {
114 * Safe to assume is not the second part of a mb char
115 * as this is handled below.
117 /* Eat multiple '/' or '\\' */
118 while (IS_PATH_SEP(*s,posix_path)) {
119 s++;
121 if ((d != path) && (*s != '\0')) {
122 /* We only care about non-leading or trailing '/' or '\\' */
123 *d++ = '/';
126 start_of_name_component = True;
127 /* New component. */
128 last_component_contains_wcard = false;
129 continue;
132 if (start_of_name_component) {
133 if ((s[0] == '.') && (s[1] == '.') && (IS_PATH_SEP(s[2],posix_path) || s[2] == '\0')) {
134 /* Uh oh - "/../" or "\\..\\" or "/..\0" or "\\..\0" ! */
137 * No mb char starts with '.' so we're safe checking the directory separator here.
140 /* If we just added a '/' - delete it */
141 if ((d > path) && (*(d-1) == '/')) {
142 *(d-1) = '\0';
143 d--;
146 /* Are we at the start ? Can't go back further if so. */
147 if (d <= path) {
148 ret = NT_STATUS_OBJECT_PATH_SYNTAX_BAD;
149 break;
151 /* Go back one level... */
152 /* We know this is safe as '/' cannot be part of a mb sequence. */
153 /* NOTE - if this assumption is invalid we are not in good shape... */
154 /* Decrement d first as d points to the *next* char to write into. */
155 for (d--; d > path; d--) {
156 if (*d == '/')
157 break;
159 s += 2; /* Else go past the .. */
160 /* We're still at the start of a name component, just the previous one. */
161 continue;
163 } else if ((s[0] == '.') && ((s[1] == '\0') || IS_PATH_SEP(s[1],posix_path))) {
164 if (posix_path) {
165 /* Eat the '.' */
166 s++;
167 continue;
173 if (!(*s & 0x80)) {
174 if (!posix_path) {
175 if (*s <= 0x1f || *s == '|') {
176 return NT_STATUS_OBJECT_NAME_INVALID;
178 switch (*s) {
179 case '*':
180 case '?':
181 case '<':
182 case '>':
183 case '"':
184 last_component_contains_wcard = true;
185 break;
186 default:
187 break;
190 *d++ = *s++;
191 } else {
192 size_t siz;
193 /* Get the size of the next MB character. */
194 next_codepoint(s,&siz);
195 switch(siz) {
196 case 5:
197 *d++ = *s++;
198 FALL_THROUGH;
199 case 4:
200 *d++ = *s++;
201 FALL_THROUGH;
202 case 3:
203 *d++ = *s++;
204 FALL_THROUGH;
205 case 2:
206 *d++ = *s++;
207 FALL_THROUGH;
208 case 1:
209 *d++ = *s++;
210 break;
211 default:
212 DEBUG(0,("check_path_syntax_internal: character length assumptions invalid !\n"));
213 *d = '\0';
214 return NT_STATUS_INVALID_PARAMETER;
217 start_of_name_component = False;
220 *d = '\0';
222 return ret;
225 /****************************************************************************
226 Ensure we check the path in *exactly* the same way as W2K for regular pathnames.
227 No wildcards allowed.
228 ****************************************************************************/
230 NTSTATUS check_path_syntax(char *path)
232 return check_path_syntax_internal(path, false);
235 /****************************************************************************
236 Check the path for a POSIX client.
237 We're assuming here that '/' is not the second byte in any multibyte char
238 set (a safe assumption).
239 ****************************************************************************/
241 NTSTATUS check_path_syntax_posix(char *path)
243 return check_path_syntax_internal(path, true);
246 NTSTATUS check_path_syntax_smb2(char *path)
248 return check_path_syntax_internal(path, false);
251 NTSTATUS check_path_syntax_smb2_posix(char *path)
253 return check_path_syntax_internal(path, true);
256 /****************************************************************************
257 SMB2-only code to strip an MSDFS prefix from an incoming pathname.
258 ****************************************************************************/
260 NTSTATUS smb2_strip_dfs_path(const char *in_path, const char **out_path)
262 const char *path = in_path;
264 /* Match the Windows 2022 behavior for an empty DFS pathname. */
265 if (*path == '\0') {
266 return NT_STATUS_INVALID_PARAMETER;
268 /* Stip any leading '\\' characters - MacOSX client behavior. */
269 while (*path == '\\') {
270 path++;
272 /* We should now be pointing at the server name. Go past it. */
273 for (;;) {
274 if (*path == '\0') {
275 /* End of complete path. Exit OK. */
276 goto out;
278 if (*path == '\\') {
279 /* End of server name. Go past and break. */
280 path++;
281 break;
283 path++; /* Continue looking for end of server name or string. */
286 /* We should now be pointing at the share name. Go past it. */
287 for (;;) {
288 if (*path == '\0') {
289 /* End of complete path. Exit OK. */
290 goto out;
292 if (*path == '\\') {
293 /* End of share name. Go past and break. */
294 path++;
295 break;
297 if (*path == ':') {
298 /* Only invalid character in sharename. */
299 return NT_STATUS_OBJECT_NAME_INVALID;
301 path++; /* Continue looking for end of share name or string. */
304 /* path now points at the start of the real filename (if any). */
306 out:
307 /* We have stripped the DFS path prefix (if any). */
308 *out_path = path;
309 return NT_STATUS_OK;
312 /****************************************************************************
313 Pull a string and check the path allowing a wildcard - provide for error return.
314 Passes in posix flag.
315 ****************************************************************************/
317 static size_t srvstr_get_path_internal(TALLOC_CTX *ctx,
318 const char *base_ptr,
319 uint16_t smb_flags2,
320 char **pp_dest,
321 const char *src,
322 size_t src_len,
323 int flags,
324 bool posix_pathnames,
325 NTSTATUS *err)
327 size_t ret;
328 char *dst = NULL;
330 *pp_dest = NULL;
332 ret = srvstr_pull_talloc(ctx, base_ptr, smb_flags2, pp_dest, src,
333 src_len, flags);
335 if (!*pp_dest) {
336 *err = NT_STATUS_INVALID_PARAMETER;
337 return ret;
340 dst = *pp_dest;
342 if (smb_flags2 & FLAGS2_DFS_PATHNAMES) {
344 * A valid DFS path looks either like
345 * /server/share
346 * \server\share
347 * (there may be more components after).
348 * Either way it must have at least two separators.
350 * Ensure we end up as /server/share
351 * so we don't need to special case
352 * separator characters elsewhere in
353 * the code.
355 char *server = NULL;
356 char *share = NULL;
357 char *remaining_path = NULL;
358 char path_sep = 0;
360 if (posix_pathnames && (dst[0] == '/')) {
361 path_sep = dst[0];
362 } else if (dst[0] == '\\') {
363 path_sep = dst[0];
366 if (path_sep == 0) {
367 goto local_path;
370 * May be a DFS path.
371 * We need some heuristics here,
372 * as clients differ on what constitutes
373 * a well-formed DFS path. If the path
374 * appears malformed, just fall back to
375 * processing as a local path.
377 server = dst;
380 * Cosmetic fix for Linux-only DFS clients.
381 * The Linux kernel SMB1 client has a bug - it sends
382 * DFS pathnames as:
384 * \\server\share\path
386 * Causing us to mis-parse server,share,remaining_path here
387 * and jump into 'goto local_path' at 'share\path' instead
388 * of 'path'.
390 * This doesn't cause an error as the limits on share names
391 * are similar to those on pathnames.
393 * parse_dfs_path() which we call before filename parsing
394 * copes with this by calling trim_char on the leading '\'
395 * characters before processing.
396 * Do the same here so logging of pathnames looks better.
398 if (server[1] == path_sep) {
399 trim_char(&server[1], path_sep, '\0');
403 * Look to see if we also have /share following.
405 share = strchr(server+1, path_sep);
406 if (share == NULL) {
407 goto local_path;
410 * It's a well formed DFS path with
411 * at least server and share components.
412 * Replace the slashes with '/' and
413 * pass the remainder to local_path.
415 *server = '/';
416 *share = '/';
418 * Skip past share so we don't pass the
419 * sharename into check_path_syntax().
421 remaining_path = strchr(share+1, path_sep);
422 if (remaining_path == NULL) {
424 * If no remaining path this was
425 * a bare /server/share path. Just return.
427 *err = NT_STATUS_OK;
428 return ret;
430 *remaining_path = '/';
431 dst = remaining_path + 1;
432 /* dst now points at any following components. */
435 local_path:
437 if (posix_pathnames) {
438 *err = check_path_syntax_posix(dst);
439 } else {
440 *err = check_path_syntax(dst);
443 return ret;
446 /****************************************************************************
447 Pull a string and check the path - provide for error return.
448 ****************************************************************************/
450 size_t srvstr_get_path(TALLOC_CTX *ctx,
451 const char *base_ptr,
452 uint16_t smb_flags2,
453 char **pp_dest,
454 const char *src,
455 size_t src_len,
456 int flags,
457 NTSTATUS *err)
459 return srvstr_get_path_internal(ctx,
460 base_ptr,
461 smb_flags2,
462 pp_dest,
463 src,
464 src_len,
465 flags,
466 false,
467 err);
470 /****************************************************************************
471 Pull a string and check the path - provide for error return.
472 posix_pathnames version.
473 ****************************************************************************/
475 size_t srvstr_get_path_posix(TALLOC_CTX *ctx,
476 const char *base_ptr,
477 uint16_t smb_flags2,
478 char **pp_dest,
479 const char *src,
480 size_t src_len,
481 int flags,
482 NTSTATUS *err)
484 return srvstr_get_path_internal(ctx,
485 base_ptr,
486 smb_flags2,
487 pp_dest,
488 src,
489 src_len,
490 flags,
491 true,
492 err);
496 size_t srvstr_get_path_req(TALLOC_CTX *mem_ctx, struct smb_request *req,
497 char **pp_dest, const char *src, int flags,
498 NTSTATUS *err)
500 ssize_t bufrem = smbreq_bufrem(req, src);
502 if (bufrem == 0) {
503 *err = NT_STATUS_INVALID_PARAMETER;
504 return 0;
507 if (req->posix_pathnames) {
508 return srvstr_get_path_internal(mem_ctx,
509 (const char *)req->inbuf,
510 req->flags2,
511 pp_dest,
512 src,
513 bufrem,
514 flags,
515 true,
516 err);
517 } else {
518 return srvstr_get_path_internal(mem_ctx,
519 (const char *)req->inbuf,
520 req->flags2,
521 pp_dest,
522 src,
523 bufrem,
524 flags,
525 false,
526 err);
531 * pull a string from the smb_buf part of a packet. In this case the
532 * string can either be null terminated or it can be terminated by the
533 * end of the smbbuf area
535 size_t srvstr_pull_req_talloc(TALLOC_CTX *ctx, struct smb_request *req,
536 char **dest, const uint8_t *src, int flags)
538 ssize_t bufrem = smbreq_bufrem(req, src);
540 if (bufrem == 0) {
541 return 0;
544 return pull_string_talloc(ctx, req->inbuf, req->flags2, dest, src,
545 bufrem, flags);
548 /****************************************************************************
549 Check if we have a correct fsp pointing to a quota fake file. Replacement for
550 the CHECK_NTQUOTA_HANDLE_OK macro.
551 ****************************************************************************/
553 bool check_fsp_ntquota_handle(connection_struct *conn, struct smb_request *req,
554 files_struct *fsp)
556 if ((fsp == NULL) || (conn == NULL)) {
557 return false;
560 if ((conn != fsp->conn) || (req->vuid != fsp->vuid)) {
561 return false;
564 if (fsp->fsp_flags.is_directory) {
565 return false;
568 if (fsp->fake_file_handle == NULL) {
569 return false;
572 if (fsp->fake_file_handle->type != FAKE_FILE_TYPE_QUOTA) {
573 return false;
576 if (fsp->fake_file_handle->private_data == NULL) {
577 return false;
580 return true;
583 /****************************************************************************
584 Return the port number we've bound to on a socket.
585 ****************************************************************************/
587 static int get_socket_port(int fd)
589 struct samba_sockaddr saddr = {
590 .sa_socklen = sizeof(struct sockaddr_storage),
593 if (fd == -1) {
594 return -1;
597 if (getsockname(fd, &saddr.u.sa, &saddr.sa_socklen) < 0) {
598 int level = (errno == ENOTCONN) ? 2 : 0;
599 DEBUG(level, ("getsockname failed. Error was %s\n",
600 strerror(errno)));
601 return -1;
604 #if defined(HAVE_IPV6)
605 if (saddr.u.sa.sa_family == AF_INET6) {
606 return ntohs(saddr.u.in6.sin6_port);
608 #endif
609 if (saddr.u.sa.sa_family == AF_INET) {
610 return ntohs(saddr.u.in.sin_port);
612 return -1;
615 static bool netbios_session_retarget(struct smbXsrv_connection *xconn,
616 const char *name, int name_type)
618 char *trim_name;
619 char *trim_name_type;
620 const char *retarget_parm;
621 char *retarget;
622 char *p;
623 int retarget_type = 0x20;
624 int retarget_port = NBT_SMB_PORT;
625 struct sockaddr_storage retarget_addr;
626 struct sockaddr_in *in_addr;
627 bool ret = false;
628 uint8_t outbuf[10];
630 if (get_socket_port(xconn->transport.sock) != NBT_SMB_PORT) {
631 return false;
634 trim_name = talloc_strdup(talloc_tos(), name);
635 if (trim_name == NULL) {
636 goto fail;
638 trim_char(trim_name, ' ', ' ');
640 trim_name_type = talloc_asprintf(trim_name, "%s#%2.2x", trim_name,
641 name_type);
642 if (trim_name_type == NULL) {
643 goto fail;
646 retarget_parm = lp_parm_const_string(-1, "netbios retarget",
647 trim_name_type, NULL);
648 if (retarget_parm == NULL) {
649 retarget_parm = lp_parm_const_string(-1, "netbios retarget",
650 trim_name, NULL);
652 if (retarget_parm == NULL) {
653 goto fail;
656 retarget = talloc_strdup(trim_name, retarget_parm);
657 if (retarget == NULL) {
658 goto fail;
661 DEBUG(10, ("retargeting %s to %s\n", trim_name_type, retarget));
663 p = strchr(retarget, ':');
664 if (p != NULL) {
665 *p++ = '\0';
666 retarget_port = atoi(p);
669 p = strchr_m(retarget, '#');
670 if (p != NULL) {
671 *p++ = '\0';
672 if (sscanf(p, "%x", &retarget_type) != 1) {
673 goto fail;
677 ret = resolve_name(retarget, &retarget_addr, retarget_type, false);
678 if (!ret) {
679 DEBUG(10, ("could not resolve %s\n", retarget));
680 goto fail;
683 if (retarget_addr.ss_family != AF_INET) {
684 DEBUG(10, ("Retarget target not an IPv4 addr\n"));
685 goto fail;
688 in_addr = (struct sockaddr_in *)(void *)&retarget_addr;
690 _smb_setlen(outbuf, 6);
691 SCVAL(outbuf, 0, 0x84);
692 *(uint32_t *)(outbuf+4) = in_addr->sin_addr.s_addr;
693 *(uint16_t *)(outbuf+8) = htons(retarget_port);
695 if (!smb1_srv_send(xconn, (char *)outbuf, false, 0, false,
696 NULL)) {
697 exit_server_cleanly("netbios_session_retarget: smb1_srv_send "
698 "failed.");
701 ret = true;
702 fail:
703 TALLOC_FREE(trim_name);
704 return ret;
707 static void reply_called_name_not_present(char *outbuf)
709 smb_setlen(outbuf, 1);
710 SCVAL(outbuf, 0, 0x83);
711 SCVAL(outbuf, 4, 0x82);
714 /****************************************************************************
715 Reply to a (netbios-level) special message.
716 ****************************************************************************/
718 void reply_special(struct smbXsrv_connection *xconn, char *inbuf, size_t inbuf_size)
720 struct smbd_server_connection *sconn = xconn->client->sconn;
721 int msg_type = CVAL(inbuf,0);
722 int msg_flags = CVAL(inbuf,1);
724 * We only really use 4 bytes of the outbuf, but for the smb_setlen
725 * calculation & friends (smb1_srv_send uses that) we need the full smb
726 * header.
728 char outbuf[smb_size];
730 memset(outbuf, '\0', sizeof(outbuf));
732 smb_setlen(outbuf,0);
734 switch (msg_type) {
735 case NBSSrequest: /* session request */
737 /* inbuf_size is guarenteed to be at least 4. */
738 fstring name1,name2;
739 int name_type1, name_type2;
740 int name_len1, name_len2;
742 *name1 = *name2 = 0;
744 if (xconn->transport.nbt.got_session) {
745 exit_server_cleanly("multiple session request not permitted");
748 SCVAL(outbuf,0,NBSSpositive);
749 SCVAL(outbuf,3,0);
751 /* inbuf_size is guaranteed to be at least 4. */
752 name_len1 = name_len((unsigned char *)(inbuf+4),inbuf_size - 4);
753 if (name_len1 <= 0 || name_len1 > inbuf_size - 4) {
754 DEBUG(0,("Invalid name length in session request\n"));
755 reply_called_name_not_present(outbuf);
756 break;
758 name_len2 = name_len((unsigned char *)(inbuf+4+name_len1),inbuf_size - 4 - name_len1);
759 if (name_len2 <= 0 || name_len2 > inbuf_size - 4 - name_len1) {
760 DEBUG(0,("Invalid name length in session request\n"));
761 reply_called_name_not_present(outbuf);
762 break;
765 name_type1 = name_extract((unsigned char *)inbuf,
766 inbuf_size,(unsigned int)4,name1);
767 name_type2 = name_extract((unsigned char *)inbuf,
768 inbuf_size,(unsigned int)(4 + name_len1),name2);
770 if (name_type1 == -1 || name_type2 == -1) {
771 DEBUG(0,("Invalid name type in session request\n"));
772 reply_called_name_not_present(outbuf);
773 break;
776 DEBUG(2,("netbios connect: name1=%s0x%x name2=%s0x%x\n",
777 name1, name_type1, name2, name_type2));
779 if (netbios_session_retarget(xconn, name1, name_type1)) {
780 exit_server_cleanly("retargeted client");
784 * Windows NT/2k uses "*SMBSERVER" and XP uses
785 * "*SMBSERV" arrggg!!!
787 if (strequal(name1, "*SMBSERVER ")
788 || strequal(name1, "*SMBSERV ")) {
789 char *raddr;
791 raddr = tsocket_address_inet_addr_string(sconn->remote_address,
792 talloc_tos());
793 if (raddr == NULL) {
794 exit_server_cleanly("could not allocate raddr");
797 fstrcpy(name1, raddr);
800 set_local_machine_name(name1, True);
801 set_remote_machine_name(name2, True);
803 if (is_ipaddress(sconn->remote_hostname)) {
804 char *p = discard_const_p(char, sconn->remote_hostname);
806 talloc_free(p);
808 sconn->remote_hostname = talloc_strdup(sconn,
809 get_remote_machine_name());
810 if (sconn->remote_hostname == NULL) {
811 exit_server_cleanly("could not copy remote name");
813 xconn->remote_hostname = sconn->remote_hostname;
816 DEBUG(2,("netbios connect: local=%s remote=%s, name type = %x\n",
817 get_local_machine_name(), get_remote_machine_name(),
818 name_type2));
820 if (name_type2 == 'R') {
821 /* We are being asked for a pathworks session ---
822 no thanks! */
823 reply_called_name_not_present(outbuf);
824 break;
827 reload_services(sconn, conn_snum_used, true);
828 reopen_logs();
830 xconn->transport.nbt.got_session = true;
831 break;
834 case 0x89: /* session keepalive request
835 (some old clients produce this?) */
836 SCVAL(outbuf,0,NBSSkeepalive);
837 SCVAL(outbuf,3,0);
838 break;
840 case NBSSpositive: /* positive session response */
841 case NBSSnegative: /* negative session response */
842 case NBSSretarget: /* retarget session response */
843 DEBUG(0,("Unexpected session response\n"));
844 break;
846 case NBSSkeepalive: /* session keepalive */
847 default:
848 return;
851 DEBUG(5,("init msg_type=0x%x msg_flags=0x%x\n",
852 msg_type, msg_flags));
854 if (!smb1_srv_send(xconn, outbuf, false, 0, false, NULL)) {
855 exit_server_cleanly("reply_special: smb1_srv_send failed.");
858 if (CVAL(outbuf, 0) != 0x82) {
859 exit_server_cleanly("invalid netbios session");
861 return;
864 /*******************************************************************
865 * unlink a file with all relevant access checks
866 *******************************************************************/
868 NTSTATUS unlink_internals(connection_struct *conn,
869 struct smb_request *req,
870 uint32_t dirtype,
871 struct files_struct *dirfsp,
872 struct smb_filename *smb_fname)
874 uint32_t fattr;
875 files_struct *fsp;
876 uint32_t dirtype_orig = dirtype;
877 NTSTATUS status;
878 int ret;
879 struct smb2_create_blobs *posx = NULL;
881 if (dirtype == 0) {
882 dirtype = FILE_ATTRIBUTE_NORMAL;
885 DBG_DEBUG("%s, dirtype = %d\n",
886 smb_fname_str_dbg(smb_fname),
887 dirtype);
889 if (!CAN_WRITE(conn)) {
890 return NT_STATUS_MEDIA_WRITE_PROTECTED;
893 ret = vfs_stat(conn, smb_fname);
894 if (ret != 0) {
895 return map_nt_error_from_unix(errno);
898 fattr = fdos_mode(smb_fname->fsp);
900 if (dirtype & FILE_ATTRIBUTE_NORMAL) {
901 dirtype = FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_ARCHIVE|FILE_ATTRIBUTE_READONLY;
904 dirtype &= (FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_ARCHIVE|FILE_ATTRIBUTE_READONLY|FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM);
905 if (!dirtype) {
906 return NT_STATUS_NO_SUCH_FILE;
909 if (!dir_check_ftype(fattr, dirtype)) {
910 if (fattr & FILE_ATTRIBUTE_DIRECTORY) {
911 return NT_STATUS_FILE_IS_A_DIRECTORY;
913 return NT_STATUS_NO_SUCH_FILE;
916 if (dirtype_orig & 0x8000) {
917 /* These will never be set for POSIX. */
918 return NT_STATUS_NO_SUCH_FILE;
921 #if 0
922 if ((fattr & dirtype) & FILE_ATTRIBUTE_DIRECTORY) {
923 return NT_STATUS_FILE_IS_A_DIRECTORY;
926 if ((fattr & ~dirtype) & (FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM)) {
927 return NT_STATUS_NO_SUCH_FILE;
930 if (dirtype & 0xFF00) {
931 /* These will never be set for POSIX. */
932 return NT_STATUS_NO_SUCH_FILE;
935 dirtype &= 0xFF;
936 if (!dirtype) {
937 return NT_STATUS_NO_SUCH_FILE;
940 /* Can't delete a directory. */
941 if (fattr & FILE_ATTRIBUTE_DIRECTORY) {
942 return NT_STATUS_FILE_IS_A_DIRECTORY;
944 #endif
946 #if 0 /* JRATEST */
947 else if (dirtype & FILE_ATTRIBUTE_DIRECTORY) /* Asked for a directory and it isn't. */
948 return NT_STATUS_OBJECT_NAME_INVALID;
949 #endif /* JRATEST */
951 if (smb_fname->flags & SMB_FILENAME_POSIX_PATH) {
952 status = make_smb2_posix_create_ctx(
953 talloc_tos(), &posx, 0777);
954 if (!NT_STATUS_IS_OK(status)) {
955 DBG_WARNING("make_smb2_posix_create_ctx failed: %s\n",
956 nt_errstr(status));
957 return status;
961 /* On open checks the open itself will check the share mode, so
962 don't do it here as we'll get it wrong. */
964 status = SMB_VFS_CREATE_FILE
965 (conn, /* conn */
966 req, /* req */
967 dirfsp, /* dirfsp */
968 smb_fname, /* fname */
969 DELETE_ACCESS, /* access_mask */
970 FILE_SHARE_NONE, /* share_access */
971 FILE_OPEN, /* create_disposition*/
972 FILE_NON_DIRECTORY_FILE, /* create_options */
973 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
974 0, /* oplock_request */
975 NULL, /* lease */
976 0, /* allocation_size */
977 0, /* private_flags */
978 NULL, /* sd */
979 NULL, /* ea_list */
980 &fsp, /* result */
981 NULL, /* pinfo */
982 posx, /* in_context_blobs */
983 NULL); /* out_context_blobs */
985 TALLOC_FREE(posx);
987 if (!NT_STATUS_IS_OK(status)) {
988 DBG_DEBUG("SMB_VFS_CREATEFILE failed: %s\n",
989 nt_errstr(status));
990 return status;
993 status = can_set_delete_on_close(fsp, fattr);
994 if (!NT_STATUS_IS_OK(status)) {
995 DBG_DEBUG("can_set_delete_on_close for file %s - "
996 "(%s)\n",
997 smb_fname_str_dbg(smb_fname),
998 nt_errstr(status));
999 close_file_free(req, &fsp, NORMAL_CLOSE);
1000 return status;
1003 /* The set is across all open files on this dev/inode pair. */
1004 if (!set_delete_on_close(fsp, True,
1005 conn->session_info->security_token,
1006 conn->session_info->unix_token)) {
1007 close_file_free(req, &fsp, NORMAL_CLOSE);
1008 return NT_STATUS_ACCESS_DENIED;
1011 return close_file_free(req, &fsp, NORMAL_CLOSE);
1014 /****************************************************************************
1015 Fake (read/write) sendfile. Returns -1 on read or write fail.
1016 ****************************************************************************/
1018 ssize_t fake_sendfile(struct smbXsrv_connection *xconn, files_struct *fsp,
1019 off_t startpos, size_t nread)
1021 size_t bufsize;
1022 size_t tosend = nread;
1023 char *buf;
1025 if (nread == 0) {
1026 return 0;
1029 bufsize = MIN(nread, 65536);
1031 if (!(buf = SMB_MALLOC_ARRAY(char, bufsize))) {
1032 return -1;
1035 while (tosend > 0) {
1036 ssize_t ret;
1037 size_t cur_read;
1039 cur_read = MIN(tosend, bufsize);
1040 ret = read_file(fsp,buf,startpos,cur_read);
1041 if (ret == -1) {
1042 SAFE_FREE(buf);
1043 return -1;
1046 /* If we had a short read, fill with zeros. */
1047 if (ret < cur_read) {
1048 memset(buf + ret, '\0', cur_read - ret);
1051 ret = write_data(xconn->transport.sock, buf, cur_read);
1052 if (ret != cur_read) {
1053 int saved_errno = errno;
1055 * Try and give an error message saying what
1056 * client failed.
1058 DEBUG(0, ("write_data failed for client %s. "
1059 "Error %s\n",
1060 smbXsrv_connection_dbg(xconn),
1061 strerror(saved_errno)));
1062 SAFE_FREE(buf);
1063 errno = saved_errno;
1064 return -1;
1066 tosend -= cur_read;
1067 startpos += cur_read;
1070 SAFE_FREE(buf);
1071 return (ssize_t)nread;
1074 /****************************************************************************
1075 Deal with the case of sendfile reading less bytes from the file than
1076 requested. Fill with zeros (all we can do). Returns 0 on success
1077 ****************************************************************************/
1079 ssize_t sendfile_short_send(struct smbXsrv_connection *xconn,
1080 files_struct *fsp,
1081 ssize_t nread,
1082 size_t headersize,
1083 size_t smb_maxcnt)
1085 #define SHORT_SEND_BUFSIZE 1024
1086 if (nread < headersize) {
1087 DEBUG(0,("sendfile_short_send: sendfile failed to send "
1088 "header for file %s (%s). Terminating\n",
1089 fsp_str_dbg(fsp), strerror(errno)));
1090 return -1;
1093 nread -= headersize;
1095 if (nread < smb_maxcnt) {
1096 char buf[SHORT_SEND_BUFSIZE] = { 0 };
1098 DEBUG(0,("sendfile_short_send: filling truncated file %s "
1099 "with zeros !\n", fsp_str_dbg(fsp)));
1101 while (nread < smb_maxcnt) {
1103 * We asked for the real file size and told sendfile
1104 * to not go beyond the end of the file. But it can
1105 * happen that in between our fstat call and the
1106 * sendfile call the file was truncated. This is very
1107 * bad because we have already announced the larger
1108 * number of bytes to the client.
1110 * The best we can do now is to send 0-bytes, just as
1111 * a read from a hole in a sparse file would do.
1113 * This should happen rarely enough that I don't care
1114 * about efficiency here :-)
1116 size_t to_write;
1117 ssize_t ret;
1119 to_write = MIN(SHORT_SEND_BUFSIZE, smb_maxcnt - nread);
1120 ret = write_data(xconn->transport.sock, buf, to_write);
1121 if (ret != to_write) {
1122 int saved_errno = errno;
1124 * Try and give an error message saying what
1125 * client failed.
1127 DEBUG(0, ("write_data failed for client %s. "
1128 "Error %s\n",
1129 smbXsrv_connection_dbg(xconn),
1130 strerror(saved_errno)));
1131 errno = saved_errno;
1132 return -1;
1134 nread += to_write;
1138 return 0;
1141 /*******************************************************************
1142 Check if a user is allowed to rename a file.
1143 ********************************************************************/
1145 static NTSTATUS can_rename(connection_struct *conn, files_struct *fsp,
1146 uint16_t dirtype)
1148 if (!CAN_WRITE(conn)) {
1149 return NT_STATUS_MEDIA_WRITE_PROTECTED;
1152 if ((dirtype & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM)) !=
1153 (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM)) {
1154 /* Only bother to read the DOS attribute if we might deny the
1155 rename on the grounds of attribute mismatch. */
1156 uint32_t fmode = fdos_mode(fsp);
1157 if ((fmode & ~dirtype) & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM)) {
1158 return NT_STATUS_NO_SUCH_FILE;
1162 if (S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
1163 if (fsp->posix_flags & FSP_POSIX_FLAGS_RENAME) {
1164 return NT_STATUS_OK;
1167 /* If no pathnames are open below this
1168 directory, allow the rename. */
1170 if (lp_strict_rename(SNUM(conn))) {
1172 * Strict rename, check open file db.
1174 if (have_file_open_below(fsp->conn, fsp->fsp_name)) {
1175 return NT_STATUS_ACCESS_DENIED;
1177 } else if (file_find_subpath(fsp)) {
1179 * No strict rename, just look in local process.
1181 return NT_STATUS_ACCESS_DENIED;
1183 return NT_STATUS_OK;
1186 if (fsp->access_mask & (DELETE_ACCESS|FILE_WRITE_ATTRIBUTES)) {
1187 return NT_STATUS_OK;
1190 return NT_STATUS_ACCESS_DENIED;
1193 /****************************************************************************
1194 Ensure open files have their names updated. Updated to notify other smbd's
1195 asynchronously.
1196 ****************************************************************************/
1198 static void rename_open_files(connection_struct *conn,
1199 struct share_mode_lock *lck,
1200 struct file_id id,
1201 uint32_t orig_name_hash,
1202 const struct smb_filename *smb_fname_dst)
1204 files_struct *fsp;
1205 bool did_rename = False;
1206 NTSTATUS status;
1207 uint32_t new_name_hash = 0;
1209 for(fsp = file_find_di_first(conn->sconn, id, false); fsp;
1210 fsp = file_find_di_next(fsp, false)) {
1211 SMB_STRUCT_STAT fsp_orig_sbuf;
1212 struct file_id_buf idbuf;
1213 /* fsp_name is a relative path under the fsp. To change this for other
1214 sharepaths we need to manipulate relative paths. */
1215 /* TODO - create the absolute path and manipulate the newname
1216 relative to the sharepath. */
1217 if (!strequal(fsp->conn->connectpath, conn->connectpath)) {
1218 continue;
1220 if (fsp->name_hash != orig_name_hash) {
1221 continue;
1223 DBG_DEBUG("renaming file %s "
1224 "(file_id %s) from %s -> %s\n",
1225 fsp_fnum_dbg(fsp),
1226 file_id_str_buf(fsp->file_id, &idbuf),
1227 fsp_str_dbg(fsp),
1228 smb_fname_str_dbg(smb_fname_dst));
1231 * The incoming smb_fname_dst here has an
1232 * invalid stat struct (it must not have
1233 * existed for the rename to succeed).
1234 * Preserve the existing stat from the
1235 * open fsp after fsp_set_smb_fname()
1236 * overwrites with the invalid stat.
1238 * We will do an fstat before returning
1239 * any of this metadata to the client anyway.
1241 fsp_orig_sbuf = fsp->fsp_name->st;
1242 status = fsp_set_smb_fname(fsp, smb_fname_dst);
1243 if (NT_STATUS_IS_OK(status)) {
1244 did_rename = True;
1245 new_name_hash = fsp->name_hash;
1246 /* Restore existing stat. */
1247 fsp->fsp_name->st = fsp_orig_sbuf;
1251 if (!did_rename) {
1252 struct file_id_buf idbuf;
1253 DBG_DEBUG("no open files on file_id %s "
1254 "for %s\n",
1255 file_id_str_buf(id, &idbuf),
1256 smb_fname_str_dbg(smb_fname_dst));
1259 /* Send messages to all smbd's (not ourself) that the name has changed. */
1260 rename_share_filename(conn->sconn->msg_ctx, lck, id, conn->connectpath,
1261 orig_name_hash, new_name_hash,
1262 smb_fname_dst);
1266 /****************************************************************************
1267 We need to check if the source path is a parent directory of the destination
1268 (ie. a rename of /foo/bar/baz -> /foo/bar/baz/bibble/bobble. If so we must
1269 refuse the rename with a sharing violation. Under UNIX the above call can
1270 *succeed* if /foo/bar/baz is a symlink to another area in the share. We
1271 probably need to check that the client is a Windows one before disallowing
1272 this as a UNIX client (one with UNIX extensions) can know the source is a
1273 symlink and make this decision intelligently. Found by an excellent bug
1274 report from <AndyLiebman@aol.com>.
1275 ****************************************************************************/
1277 static bool rename_path_prefix_equal(const struct smb_filename *smb_fname_src,
1278 const struct smb_filename *smb_fname_dst)
1280 const char *psrc = smb_fname_src->base_name;
1281 const char *pdst = smb_fname_dst->base_name;
1282 size_t slen;
1284 if (psrc[0] == '.' && psrc[1] == '/') {
1285 psrc += 2;
1287 if (pdst[0] == '.' && pdst[1] == '/') {
1288 pdst += 2;
1290 if ((slen = strlen(psrc)) > strlen(pdst)) {
1291 return False;
1293 return ((memcmp(psrc, pdst, slen) == 0) && pdst[slen] == '/');
1297 * Do the notify calls from a rename
1300 static void notify_rename(connection_struct *conn, bool is_dir,
1301 const struct smb_filename *smb_fname_src,
1302 const struct smb_filename *smb_fname_dst)
1304 char *parent_dir_src = NULL;
1305 char *parent_dir_dst = NULL;
1306 uint32_t mask;
1308 mask = is_dir ? FILE_NOTIFY_CHANGE_DIR_NAME
1309 : FILE_NOTIFY_CHANGE_FILE_NAME;
1311 if (!parent_dirname(talloc_tos(), smb_fname_src->base_name,
1312 &parent_dir_src, NULL) ||
1313 !parent_dirname(talloc_tos(), smb_fname_dst->base_name,
1314 &parent_dir_dst, NULL)) {
1315 goto out;
1318 if (strcmp(parent_dir_src, parent_dir_dst) == 0) {
1319 notify_fname(conn, NOTIFY_ACTION_OLD_NAME, mask,
1320 smb_fname_src->base_name);
1321 notify_fname(conn, NOTIFY_ACTION_NEW_NAME, mask,
1322 smb_fname_dst->base_name);
1324 else {
1325 notify_fname(conn, NOTIFY_ACTION_REMOVED, mask,
1326 smb_fname_src->base_name);
1327 notify_fname(conn, NOTIFY_ACTION_ADDED, mask,
1328 smb_fname_dst->base_name);
1331 /* this is a strange one. w2k3 gives an additional event for
1332 CHANGE_ATTRIBUTES and CHANGE_CREATION on the new file when renaming
1333 files, but not directories */
1334 if (!is_dir) {
1335 notify_fname(conn, NOTIFY_ACTION_MODIFIED,
1336 FILE_NOTIFY_CHANGE_ATTRIBUTES
1337 |FILE_NOTIFY_CHANGE_CREATION,
1338 smb_fname_dst->base_name);
1340 out:
1341 TALLOC_FREE(parent_dir_src);
1342 TALLOC_FREE(parent_dir_dst);
1345 /****************************************************************************
1346 Returns an error if the parent directory for a filename is open in an
1347 incompatible way.
1348 ****************************************************************************/
1350 static NTSTATUS parent_dirname_compatible_open(connection_struct *conn,
1351 const struct smb_filename *smb_fname_dst_in)
1353 struct smb_filename *smb_fname_parent = NULL;
1354 struct file_id id;
1355 files_struct *fsp = NULL;
1356 int ret;
1357 NTSTATUS status;
1359 status = SMB_VFS_PARENT_PATHNAME(conn,
1360 talloc_tos(),
1361 smb_fname_dst_in,
1362 &smb_fname_parent,
1363 NULL);
1364 if (!NT_STATUS_IS_OK(status)) {
1365 return status;
1368 ret = vfs_stat(conn, smb_fname_parent);
1369 if (ret == -1) {
1370 return map_nt_error_from_unix(errno);
1374 * We're only checking on this smbd here, mostly good
1375 * enough.. and will pass tests.
1378 id = vfs_file_id_from_sbuf(conn, &smb_fname_parent->st);
1379 for (fsp = file_find_di_first(conn->sconn, id, true); fsp;
1380 fsp = file_find_di_next(fsp, true)) {
1381 if (fsp->access_mask & DELETE_ACCESS) {
1382 return NT_STATUS_SHARING_VIOLATION;
1385 return NT_STATUS_OK;
1388 /****************************************************************************
1389 Rename an open file - given an fsp.
1390 ****************************************************************************/
1392 NTSTATUS rename_internals_fsp(connection_struct *conn,
1393 files_struct *fsp,
1394 struct files_struct *dst_dirfsp,
1395 struct smb_filename *smb_fname_dst_in,
1396 const char *dst_original_lcomp,
1397 uint32_t attrs,
1398 bool replace_if_exists)
1400 TALLOC_CTX *ctx = talloc_tos();
1401 struct smb_filename *parent_dir_fname_dst = NULL;
1402 struct smb_filename *parent_dir_fname_dst_atname = NULL;
1403 struct smb_filename *parent_dir_fname_src = NULL;
1404 struct smb_filename *parent_dir_fname_src_atname = NULL;
1405 struct smb_filename *smb_fname_dst = NULL;
1406 NTSTATUS status = NT_STATUS_OK;
1407 struct share_mode_lock *lck = NULL;
1408 uint32_t access_mask = SEC_DIR_ADD_FILE;
1409 bool dst_exists, old_is_stream, new_is_stream;
1410 int ret;
1411 bool case_sensitive = (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) ?
1412 true : conn->case_sensitive;
1413 bool case_preserve = (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) ?
1414 true : conn->case_preserve;
1416 status = parent_dirname_compatible_open(conn, smb_fname_dst_in);
1417 if (!NT_STATUS_IS_OK(status)) {
1418 return status;
1421 if (file_has_open_streams(fsp)) {
1422 return NT_STATUS_ACCESS_DENIED;
1425 /* Make a copy of the dst smb_fname structs */
1427 smb_fname_dst = cp_smb_filename(ctx, smb_fname_dst_in);
1428 if (smb_fname_dst == NULL) {
1429 status = NT_STATUS_NO_MEMORY;
1430 goto out;
1434 * Check for special case with case preserving and not
1435 * case sensitive. If the new last component differs from the original
1436 * last component only by case, then we should allow
1437 * the rename (user is trying to change the case of the
1438 * filename).
1440 if (!case_sensitive && case_preserve &&
1441 strequal(fsp->fsp_name->base_name, smb_fname_dst->base_name) &&
1442 strequal(fsp->fsp_name->stream_name, smb_fname_dst->stream_name)) {
1443 char *fname_dst_parent = NULL;
1444 const char *fname_dst_lcomp = NULL;
1445 char *orig_lcomp_path = NULL;
1446 char *orig_lcomp_stream = NULL;
1447 bool ok = true;
1450 * Split off the last component of the processed
1451 * destination name. We will compare this to
1452 * the split components of dst_original_lcomp.
1454 if (!parent_dirname(ctx,
1455 smb_fname_dst->base_name,
1456 &fname_dst_parent,
1457 &fname_dst_lcomp)) {
1458 status = NT_STATUS_NO_MEMORY;
1459 goto out;
1463 * The dst_original_lcomp component contains
1464 * the last_component of the path + stream
1465 * name (if a stream exists).
1467 * Split off the stream name so we
1468 * can check them separately.
1471 if (fsp->posix_flags & FSP_POSIX_FLAGS_PATHNAMES) {
1472 /* POSIX - no stream component. */
1473 orig_lcomp_path = talloc_strdup(ctx,
1474 dst_original_lcomp);
1475 if (orig_lcomp_path == NULL) {
1476 ok = false;
1478 } else {
1479 ok = split_stream_filename(ctx,
1480 dst_original_lcomp,
1481 &orig_lcomp_path,
1482 &orig_lcomp_stream);
1485 if (!ok) {
1486 TALLOC_FREE(fname_dst_parent);
1487 status = NT_STATUS_NO_MEMORY;
1488 goto out;
1491 /* If the base names only differ by case, use original. */
1492 if(!strcsequal(fname_dst_lcomp, orig_lcomp_path)) {
1493 char *tmp;
1495 * Replace the modified last component with the
1496 * original.
1498 if (!ISDOT(fname_dst_parent)) {
1499 tmp = talloc_asprintf(smb_fname_dst,
1500 "%s/%s",
1501 fname_dst_parent,
1502 orig_lcomp_path);
1503 } else {
1504 tmp = talloc_strdup(smb_fname_dst,
1505 orig_lcomp_path);
1507 if (tmp == NULL) {
1508 status = NT_STATUS_NO_MEMORY;
1509 TALLOC_FREE(fname_dst_parent);
1510 TALLOC_FREE(orig_lcomp_path);
1511 TALLOC_FREE(orig_lcomp_stream);
1512 goto out;
1514 TALLOC_FREE(smb_fname_dst->base_name);
1515 smb_fname_dst->base_name = tmp;
1518 /* If the stream_names only differ by case, use original. */
1519 if(!strcsequal(smb_fname_dst->stream_name,
1520 orig_lcomp_stream)) {
1521 /* Use the original stream. */
1522 char *tmp = talloc_strdup(smb_fname_dst,
1523 orig_lcomp_stream);
1524 if (tmp == NULL) {
1525 status = NT_STATUS_NO_MEMORY;
1526 TALLOC_FREE(fname_dst_parent);
1527 TALLOC_FREE(orig_lcomp_path);
1528 TALLOC_FREE(orig_lcomp_stream);
1529 goto out;
1531 TALLOC_FREE(smb_fname_dst->stream_name);
1532 smb_fname_dst->stream_name = tmp;
1534 TALLOC_FREE(fname_dst_parent);
1535 TALLOC_FREE(orig_lcomp_path);
1536 TALLOC_FREE(orig_lcomp_stream);
1540 * If the src and dest names are identical - including case,
1541 * don't do the rename, just return success.
1544 if (strcsequal(fsp->fsp_name->base_name, smb_fname_dst->base_name) &&
1545 strcsequal(fsp->fsp_name->stream_name,
1546 smb_fname_dst->stream_name)) {
1547 DEBUG(3, ("rename_internals_fsp: identical names in rename %s "
1548 "- returning success\n",
1549 smb_fname_str_dbg(smb_fname_dst)));
1550 status = NT_STATUS_OK;
1551 goto out;
1554 old_is_stream = is_ntfs_stream_smb_fname(fsp->fsp_name);
1555 new_is_stream = is_ntfs_stream_smb_fname(smb_fname_dst);
1557 /* Return the correct error code if both names aren't streams. */
1558 if (!old_is_stream && new_is_stream) {
1559 status = NT_STATUS_OBJECT_NAME_INVALID;
1560 goto out;
1563 if (old_is_stream && !new_is_stream) {
1564 status = NT_STATUS_INVALID_PARAMETER;
1565 goto out;
1568 dst_exists = vfs_stat(conn, smb_fname_dst) == 0;
1570 if(!replace_if_exists && dst_exists) {
1571 DEBUG(3, ("rename_internals_fsp: dest exists doing rename "
1572 "%s -> %s\n", smb_fname_str_dbg(fsp->fsp_name),
1573 smb_fname_str_dbg(smb_fname_dst)));
1574 status = NT_STATUS_OBJECT_NAME_COLLISION;
1575 goto out;
1579 * Drop the pathref fsp on the destination otherwise we trip upon in in
1580 * the below check for open files check.
1582 if (smb_fname_dst_in->fsp != NULL) {
1583 fd_close(smb_fname_dst_in->fsp);
1584 file_free(NULL, smb_fname_dst_in->fsp);
1585 SMB_ASSERT(smb_fname_dst_in->fsp == NULL);
1588 if (dst_exists) {
1589 struct file_id fileid = vfs_file_id_from_sbuf(conn,
1590 &smb_fname_dst->st);
1591 files_struct *dst_fsp = file_find_di_first(conn->sconn,
1592 fileid, true);
1593 /* The file can be open when renaming a stream */
1594 if (dst_fsp && !new_is_stream) {
1595 DEBUG(3, ("rename_internals_fsp: Target file open\n"));
1596 status = NT_STATUS_ACCESS_DENIED;
1597 goto out;
1601 /* Ensure we have a valid stat struct for the source. */
1602 status = vfs_stat_fsp(fsp);
1603 if (!NT_STATUS_IS_OK(status)) {
1604 goto out;
1607 status = can_rename(conn, fsp, attrs);
1609 if (!NT_STATUS_IS_OK(status)) {
1610 DEBUG(3, ("rename_internals_fsp: Error %s rename %s -> %s\n",
1611 nt_errstr(status), smb_fname_str_dbg(fsp->fsp_name),
1612 smb_fname_str_dbg(smb_fname_dst)));
1613 if (NT_STATUS_EQUAL(status,NT_STATUS_SHARING_VIOLATION))
1614 status = NT_STATUS_ACCESS_DENIED;
1615 goto out;
1618 if (rename_path_prefix_equal(fsp->fsp_name, smb_fname_dst)) {
1619 status = NT_STATUS_ACCESS_DENIED;
1620 goto out;
1623 /* Do we have rights to move into the destination ? */
1624 if (S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
1625 /* We're moving a directory. */
1626 access_mask = SEC_DIR_ADD_SUBDIR;
1630 * Get a pathref on the destination parent directory, so
1631 * we can call check_parent_access_fsp().
1633 status = parent_pathref(ctx,
1634 conn->cwd_fsp,
1635 smb_fname_dst,
1636 &parent_dir_fname_dst,
1637 &parent_dir_fname_dst_atname);
1638 if (!NT_STATUS_IS_OK(status)) {
1639 goto out;
1642 status = check_parent_access_fsp(parent_dir_fname_dst->fsp,
1643 access_mask);
1644 if (!NT_STATUS_IS_OK(status)) {
1645 DBG_INFO("check_parent_access_fsp on "
1646 "dst %s returned %s\n",
1647 smb_fname_str_dbg(smb_fname_dst),
1648 nt_errstr(status));
1649 goto out;
1653 * If the target existed, make sure the destination
1654 * atname has the same stat struct.
1656 parent_dir_fname_dst_atname->st = smb_fname_dst->st;
1659 * It's very common that source and
1660 * destination directories are the same.
1661 * Optimize by not opening the
1662 * second parent_pathref if we know
1663 * this is the case.
1666 status = SMB_VFS_PARENT_PATHNAME(conn,
1667 ctx,
1668 fsp->fsp_name,
1669 &parent_dir_fname_src,
1670 &parent_dir_fname_src_atname);
1671 if (!NT_STATUS_IS_OK(status)) {
1672 goto out;
1676 * We do a case-sensitive string comparison. We want to be *sure*
1677 * this is the same path. The worst that can happen if
1678 * the case doesn't match is we lose out on the optimization,
1679 * the code still works.
1681 * We can ignore twrp fields here. Rename is not allowed on
1682 * shadow copy handles.
1685 if (strcmp(parent_dir_fname_src->base_name,
1686 parent_dir_fname_dst->base_name) == 0) {
1688 * parent directory is the same for source
1689 * and destination.
1691 /* Reparent the src_atname to the parent_dir_dest fname. */
1692 parent_dir_fname_src_atname = talloc_move(
1693 parent_dir_fname_dst,
1694 &parent_dir_fname_src_atname);
1695 /* Free the unneeded duplicate parent name. */
1696 TALLOC_FREE(parent_dir_fname_src);
1698 * And make the source parent name a copy of the
1699 * destination parent name.
1701 parent_dir_fname_src = parent_dir_fname_dst;
1704 * Ensure we have a pathref fsp on the
1705 * parent_dir_fname_src_atname to match the code in the else
1706 * branch where we use parent_pathref().
1708 status = reference_smb_fname_fsp_link(
1709 parent_dir_fname_src_atname,
1710 fsp->fsp_name);
1711 if (!NT_STATUS_IS_OK(status)) {
1712 goto out;
1714 } else {
1716 * source and destination parent directories are
1717 * different.
1719 * Get a pathref on the source parent directory, so
1720 * we can do a relative rename.
1722 TALLOC_FREE(parent_dir_fname_src);
1723 status = parent_pathref(ctx,
1724 conn->cwd_fsp,
1725 fsp->fsp_name,
1726 &parent_dir_fname_src,
1727 &parent_dir_fname_src_atname);
1728 if (!NT_STATUS_IS_OK(status)) {
1729 goto out;
1734 * Some modules depend on the source smb_fname having a valid stat.
1735 * The parent_dir_fname_src_atname is the relative name of the
1736 * currently open file, so just copy the stat from the open fsp.
1738 parent_dir_fname_src_atname->st = fsp->fsp_name->st;
1740 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
1743 * We have the file open ourselves, so not being able to get the
1744 * corresponding share mode lock is a fatal error.
1747 SMB_ASSERT(lck != NULL);
1749 ret = SMB_VFS_RENAMEAT(conn,
1750 parent_dir_fname_src->fsp,
1751 parent_dir_fname_src_atname,
1752 parent_dir_fname_dst->fsp,
1753 parent_dir_fname_dst_atname);
1754 if (ret == 0) {
1755 uint32_t create_options = fh_get_private_options(fsp->fh);
1757 DEBUG(3, ("rename_internals_fsp: succeeded doing rename on "
1758 "%s -> %s\n", smb_fname_str_dbg(fsp->fsp_name),
1759 smb_fname_str_dbg(smb_fname_dst)));
1761 notify_rename(conn,
1762 fsp->fsp_flags.is_directory,
1763 fsp->fsp_name,
1764 smb_fname_dst);
1766 rename_open_files(conn, lck, fsp->file_id, fsp->name_hash,
1767 smb_fname_dst);
1769 if (!fsp->fsp_flags.is_directory &&
1770 !(fsp->posix_flags & FSP_POSIX_FLAGS_PATHNAMES) &&
1771 (lp_map_archive(SNUM(conn)) ||
1772 lp_store_dos_attributes(SNUM(conn))))
1775 * We must set the archive bit on the newly renamed
1776 * file.
1778 status = vfs_stat_fsp(fsp);
1779 if (NT_STATUS_IS_OK(status)) {
1780 uint32_t old_dosmode;
1781 old_dosmode = fdos_mode(fsp);
1783 * We can use fsp->fsp_name here as it has
1784 * already been changed to the new name.
1786 SMB_ASSERT(fsp->fsp_name->fsp == fsp);
1787 file_set_dosmode(conn,
1788 fsp->fsp_name,
1789 old_dosmode | FILE_ATTRIBUTE_ARCHIVE,
1790 NULL,
1791 true);
1796 * A rename acts as a new file create w.r.t. allowing an initial delete
1797 * on close, probably because in Windows there is a new handle to the
1798 * new file. If initial delete on close was requested but not
1799 * originally set, we need to set it here. This is probably not 100% correct,
1800 * but will work for the CIFSFS client which in non-posix mode
1801 * depends on these semantics. JRA.
1804 if (create_options & FILE_DELETE_ON_CLOSE) {
1805 status = can_set_delete_on_close(fsp, 0);
1807 if (NT_STATUS_IS_OK(status)) {
1808 /* Note that here we set the *initial* delete on close flag,
1809 * not the regular one. The magic gets handled in close. */
1810 fsp->fsp_flags.initial_delete_on_close = true;
1813 TALLOC_FREE(lck);
1814 status = NT_STATUS_OK;
1815 goto out;
1818 TALLOC_FREE(lck);
1820 if (errno == ENOTDIR || errno == EISDIR) {
1821 status = NT_STATUS_OBJECT_NAME_COLLISION;
1822 } else {
1823 status = map_nt_error_from_unix(errno);
1826 DEBUG(3, ("rename_internals_fsp: Error %s rename %s -> %s\n",
1827 nt_errstr(status), smb_fname_str_dbg(fsp->fsp_name),
1828 smb_fname_str_dbg(smb_fname_dst)));
1830 out:
1833 * parent_dir_fname_src may be a copy of parent_dir_fname_dst.
1834 * See the optimization for same source and destination directory
1835 * above. Only free one in that case.
1837 if (parent_dir_fname_src != parent_dir_fname_dst) {
1838 TALLOC_FREE(parent_dir_fname_src);
1840 TALLOC_FREE(parent_dir_fname_dst);
1841 TALLOC_FREE(smb_fname_dst);
1843 return status;
1846 /****************************************************************************
1847 The guts of the rename command, split out so it may be called by the NT SMB
1848 code.
1849 ****************************************************************************/
1851 NTSTATUS rename_internals(TALLOC_CTX *ctx,
1852 connection_struct *conn,
1853 struct smb_request *req,
1854 struct files_struct *src_dirfsp,
1855 struct smb_filename *smb_fname_src,
1856 struct files_struct *dst_dirfsp,
1857 struct smb_filename *smb_fname_dst,
1858 const char *dst_original_lcomp,
1859 uint32_t attrs,
1860 bool replace_if_exists,
1861 uint32_t access_mask)
1863 NTSTATUS status = NT_STATUS_OK;
1864 int create_options = 0;
1865 struct smb2_create_blobs *posx = NULL;
1866 struct files_struct *fsp = NULL;
1867 bool posix_pathname = (smb_fname_src->flags & SMB_FILENAME_POSIX_PATH);
1868 bool case_sensitive = posix_pathname ? true : conn->case_sensitive;
1869 bool case_preserve = posix_pathname ? true : conn->case_preserve;
1870 bool short_case_preserve = posix_pathname ? true :
1871 conn->short_case_preserve;
1873 if (posix_pathname) {
1874 status = make_smb2_posix_create_ctx(talloc_tos(), &posx, 0777);
1875 if (!NT_STATUS_IS_OK(status)) {
1876 DBG_WARNING("make_smb2_posix_create_ctx failed: %s\n",
1877 nt_errstr(status));
1878 goto out;
1882 DBG_NOTICE("case_sensitive = %d, "
1883 "case_preserve = %d, short case preserve = %d, "
1884 "directory = %s, newname = %s, "
1885 "last_component_dest = %s\n",
1886 case_sensitive, case_preserve,
1887 short_case_preserve,
1888 smb_fname_str_dbg(smb_fname_src),
1889 smb_fname_str_dbg(smb_fname_dst),
1890 dst_original_lcomp);
1892 ZERO_STRUCT(smb_fname_src->st);
1894 status = openat_pathref_fsp(conn->cwd_fsp, smb_fname_src);
1895 if (!NT_STATUS_IS_OK(status)) {
1896 if (!NT_STATUS_EQUAL(status,
1897 NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
1898 goto out;
1901 * Possible symlink src.
1903 if (!(smb_fname_src->flags & SMB_FILENAME_POSIX_PATH)) {
1904 goto out;
1906 if (!S_ISLNK(smb_fname_src->st.st_ex_mode)) {
1907 goto out;
1911 if (S_ISDIR(smb_fname_src->st.st_ex_mode)) {
1912 create_options |= FILE_DIRECTORY_FILE;
1915 status = SMB_VFS_CREATE_FILE(
1916 conn, /* conn */
1917 req, /* req */
1918 src_dirfsp, /* dirfsp */
1919 smb_fname_src, /* fname */
1920 access_mask, /* access_mask */
1921 (FILE_SHARE_READ | /* share_access */
1922 FILE_SHARE_WRITE),
1923 FILE_OPEN, /* create_disposition*/
1924 create_options, /* create_options */
1925 0, /* file_attributes */
1926 0, /* oplock_request */
1927 NULL, /* lease */
1928 0, /* allocation_size */
1929 0, /* private_flags */
1930 NULL, /* sd */
1931 NULL, /* ea_list */
1932 &fsp, /* result */
1933 NULL, /* pinfo */
1934 posx, /* in_context_blobs */
1935 NULL); /* out_context_blobs */
1937 if (!NT_STATUS_IS_OK(status)) {
1938 DBG_NOTICE("Could not open rename source %s: %s\n",
1939 smb_fname_str_dbg(smb_fname_src),
1940 nt_errstr(status));
1941 goto out;
1944 status = rename_internals_fsp(conn,
1945 fsp,
1946 dst_dirfsp,
1947 smb_fname_dst,
1948 dst_original_lcomp,
1949 attrs,
1950 replace_if_exists);
1952 close_file_free(req, &fsp, NORMAL_CLOSE);
1954 DBG_NOTICE("Error %s rename %s -> %s\n",
1955 nt_errstr(status), smb_fname_str_dbg(smb_fname_src),
1956 smb_fname_str_dbg(smb_fname_dst));
1958 out:
1959 TALLOC_FREE(posx);
1960 return status;
1963 /*******************************************************************
1964 Copy a file as part of a reply_copy.
1965 ******************************************************************/
1968 * TODO: check error codes on all callers
1971 NTSTATUS copy_file(TALLOC_CTX *ctx,
1972 connection_struct *conn,
1973 struct smb_filename *smb_fname_src,
1974 struct smb_filename *smb_fname_dst,
1975 uint32_t new_create_disposition)
1977 struct smb_filename *smb_fname_dst_tmp = NULL;
1978 off_t ret=-1;
1979 files_struct *fsp1,*fsp2;
1980 uint32_t dosattrs;
1981 NTSTATUS status;
1984 smb_fname_dst_tmp = cp_smb_filename(ctx, smb_fname_dst);
1985 if (smb_fname_dst_tmp == NULL) {
1986 return NT_STATUS_NO_MEMORY;
1989 status = vfs_file_exist(conn, smb_fname_src);
1990 if (!NT_STATUS_IS_OK(status)) {
1991 goto out;
1994 status = openat_pathref_fsp(conn->cwd_fsp, smb_fname_src);
1995 if (!NT_STATUS_IS_OK(status)) {
1996 goto out;
1999 /* Open the src file for reading. */
2000 status = SMB_VFS_CREATE_FILE(
2001 conn, /* conn */
2002 NULL, /* req */
2003 NULL, /* dirfsp */
2004 smb_fname_src, /* fname */
2005 FILE_GENERIC_READ, /* access_mask */
2006 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share_access */
2007 FILE_OPEN, /* create_disposition*/
2008 0, /* create_options */
2009 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
2010 INTERNAL_OPEN_ONLY, /* oplock_request */
2011 NULL, /* lease */
2012 0, /* allocation_size */
2013 0, /* private_flags */
2014 NULL, /* sd */
2015 NULL, /* ea_list */
2016 &fsp1, /* result */
2017 NULL, /* psbuf */
2018 NULL, NULL); /* create context */
2020 if (!NT_STATUS_IS_OK(status)) {
2021 goto out;
2024 dosattrs = fdos_mode(fsp1);
2026 if (SMB_VFS_STAT(conn, smb_fname_dst_tmp) == -1) {
2027 ZERO_STRUCTP(&smb_fname_dst_tmp->st);
2030 status = openat_pathref_fsp(conn->cwd_fsp, smb_fname_dst);
2031 if (!NT_STATUS_IS_OK(status) &&
2032 !NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND))
2034 goto out;
2037 /* Open the dst file for writing. */
2038 status = SMB_VFS_CREATE_FILE(
2039 conn, /* conn */
2040 NULL, /* req */
2041 NULL, /* dirfsp */
2042 smb_fname_dst, /* fname */
2043 FILE_GENERIC_WRITE, /* access_mask */
2044 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share_access */
2045 new_create_disposition, /* create_disposition*/
2046 0, /* create_options */
2047 dosattrs, /* file_attributes */
2048 INTERNAL_OPEN_ONLY, /* oplock_request */
2049 NULL, /* lease */
2050 0, /* allocation_size */
2051 0, /* private_flags */
2052 NULL, /* sd */
2053 NULL, /* ea_list */
2054 &fsp2, /* result */
2055 NULL, /* psbuf */
2056 NULL, NULL); /* create context */
2058 if (!NT_STATUS_IS_OK(status)) {
2059 close_file_free(NULL, &fsp1, ERROR_CLOSE);
2060 goto out;
2063 /* Do the actual copy. */
2064 if (smb_fname_src->st.st_ex_size) {
2065 ret = vfs_transfer_file(fsp1, fsp2, smb_fname_src->st.st_ex_size);
2066 } else {
2067 ret = 0;
2070 close_file_free(NULL, &fsp1, NORMAL_CLOSE);
2072 /* Ensure the modtime is set correctly on the destination file. */
2073 set_close_write_time(fsp2, smb_fname_src->st.st_ex_mtime);
2076 * As we are opening fsp1 read-only we only expect
2077 * an error on close on fsp2 if we are out of space.
2078 * Thus we don't look at the error return from the
2079 * close of fsp1.
2081 status = close_file_free(NULL, &fsp2, NORMAL_CLOSE);
2083 if (!NT_STATUS_IS_OK(status)) {
2084 goto out;
2087 if (ret != (off_t)smb_fname_src->st.st_ex_size) {
2088 status = NT_STATUS_DISK_FULL;
2089 goto out;
2092 status = NT_STATUS_OK;
2094 out:
2095 TALLOC_FREE(smb_fname_dst_tmp);
2096 return status;
2099 /****************************************************************************
2100 Get a lock offset, dealing with large offset requests.
2101 ****************************************************************************/
2103 uint64_t get_lock_offset(const uint8_t *data, int data_offset,
2104 bool large_file_format)
2106 uint64_t offset = 0;
2108 if(!large_file_format) {
2109 offset = (uint64_t)IVAL(data,SMB_LKOFF_OFFSET(data_offset));
2110 } else {
2112 * No BVAL, this is reversed!
2114 offset = (((uint64_t) IVAL(data,SMB_LARGE_LKOFF_OFFSET_HIGH(data_offset))) << 32) |
2115 ((uint64_t) IVAL(data,SMB_LARGE_LKOFF_OFFSET_LOW(data_offset)));
2118 return offset;
2121 struct smbd_do_unlocking_state {
2122 struct files_struct *fsp;
2123 uint16_t num_ulocks;
2124 struct smbd_lock_element *ulocks;
2125 NTSTATUS status;
2128 static void smbd_do_unlocking_fn(
2129 struct share_mode_lock *lck,
2130 void *private_data)
2132 struct smbd_do_unlocking_state *state = private_data;
2133 struct files_struct *fsp = state->fsp;
2134 uint16_t i;
2136 for (i = 0; i < state->num_ulocks; i++) {
2137 struct smbd_lock_element *e = &state->ulocks[i];
2139 DBG_DEBUG("unlock start=%"PRIu64", len=%"PRIu64" for "
2140 "pid %"PRIu64", file %s\n",
2141 e->offset,
2142 e->count,
2143 e->smblctx,
2144 fsp_str_dbg(fsp));
2146 if (e->brltype != UNLOCK_LOCK) {
2147 /* this can only happen with SMB2 */
2148 state->status = NT_STATUS_INVALID_PARAMETER;
2149 return;
2152 state->status = do_unlock(
2153 fsp, e->smblctx, e->count, e->offset, e->lock_flav);
2155 DBG_DEBUG("do_unlock returned %s\n",
2156 nt_errstr(state->status));
2158 if (!NT_STATUS_IS_OK(state->status)) {
2159 return;
2163 share_mode_wakeup_waiters(fsp->file_id);
2166 NTSTATUS smbd_do_unlocking(struct smb_request *req,
2167 files_struct *fsp,
2168 uint16_t num_ulocks,
2169 struct smbd_lock_element *ulocks)
2171 struct smbd_do_unlocking_state state = {
2172 .fsp = fsp,
2173 .num_ulocks = num_ulocks,
2174 .ulocks = ulocks,
2176 NTSTATUS status;
2178 DBG_NOTICE("%s num_ulocks=%"PRIu16"\n", fsp_fnum_dbg(fsp), num_ulocks);
2180 status = share_mode_do_locked_vfs_allowed(
2181 fsp->file_id, smbd_do_unlocking_fn, &state);
2183 if (!NT_STATUS_IS_OK(status)) {
2184 DBG_DEBUG("share_mode_do_locked_vfs_allowed failed: %s\n",
2185 nt_errstr(status));
2186 return status;
2188 if (!NT_STATUS_IS_OK(state.status)) {
2189 DBG_DEBUG("smbd_do_unlocking_fn failed: %s\n",
2190 nt_errstr(status));
2191 return state.status;
2194 return NT_STATUS_OK;