s3: smbd: Make extract_snapshot_token() a wrapper for extract_snapshot_token_internal().
[Samba.git] / source3 / smbd / smb2_reply.c
blob90aa92193b954cf9d28984a9699ef05f533e41a1
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 /****************************************************************************
247 Check the path for an SMB2 DFS path.
248 SMB2 DFS paths look like hostname\share (followed by a possible \extrapath.
249 Path returned from here must look like:
250 hostname/share (followed by a possible /extrapath).
251 ****************************************************************************/
253 static NTSTATUS check_path_syntax_smb2_msdfs(char *path)
255 char *share = NULL;
256 char *remaining_path = NULL;
257 /* No SMB2 names can start with '\\' */
258 if (path[0] == '\\') {
259 return NT_STATUS_OBJECT_NAME_INVALID;
262 * smbclient libraries sometimes set the DFS flag and send
263 * local pathnames. Cope with this by just calling
264 * check_path_syntax() on the whole path if it doesn't
265 * look like a DFS path, similar to what parse_dfs_path() does.
267 /* servername should be at path[0] */
268 share = strchr(path, '\\');
269 if (share == NULL) {
270 return check_path_syntax(path);
272 *share++ = '/';
273 remaining_path = strchr(share, '\\');
274 if (remaining_path == NULL) {
275 /* Only hostname\share. We're done. */
276 return NT_STATUS_OK;
278 *remaining_path++ = '/';
279 return check_path_syntax(remaining_path);
282 NTSTATUS check_path_syntax_smb2(char *path, bool dfs_path)
284 if (dfs_path) {
285 return check_path_syntax_smb2_msdfs(path);
286 } else {
287 return check_path_syntax(path);
291 /****************************************************************************
292 Pull a string and check the path allowing a wildcard - provide for error return.
293 Passes in posix flag.
294 ****************************************************************************/
296 static size_t srvstr_get_path_internal(TALLOC_CTX *ctx,
297 const char *base_ptr,
298 uint16_t smb_flags2,
299 char **pp_dest,
300 const char *src,
301 size_t src_len,
302 int flags,
303 bool posix_pathnames,
304 NTSTATUS *err)
306 size_t ret;
307 char *dst = NULL;
309 *pp_dest = NULL;
311 ret = srvstr_pull_talloc(ctx, base_ptr, smb_flags2, pp_dest, src,
312 src_len, flags);
314 if (!*pp_dest) {
315 *err = NT_STATUS_INVALID_PARAMETER;
316 return ret;
319 dst = *pp_dest;
321 if (smb_flags2 & FLAGS2_DFS_PATHNAMES) {
323 * A valid DFS path looks either like
324 * /server/share
325 * \server\share
326 * (there may be more components after).
327 * Either way it must have at least two separators.
329 * Ensure we end up as /server/share
330 * so we don't need to special case
331 * separator characters elsewhere in
332 * the code.
334 char *server = NULL;
335 char *share = NULL;
336 char *remaining_path = NULL;
337 char path_sep = 0;
339 if (posix_pathnames && (dst[0] == '/')) {
340 path_sep = dst[0];
341 } else if (dst[0] == '\\') {
342 path_sep = dst[0];
345 if (path_sep == 0) {
346 goto local_path;
349 * May be a DFS path.
350 * We need some heuristics here,
351 * as clients differ on what constitutes
352 * a well-formed DFS path. If the path
353 * appears malformed, just fall back to
354 * processing as a local path.
356 server = dst;
359 * Cosmetic fix for Linux-only DFS clients.
360 * The Linux kernel SMB1 client has a bug - it sends
361 * DFS pathnames as:
363 * \\server\share\path
365 * Causing us to mis-parse server,share,remaining_path here
366 * and jump into 'goto local_path' at 'share\path' instead
367 * of 'path'.
369 * This doesn't cause an error as the limits on share names
370 * are similar to those on pathnames.
372 * parse_dfs_path() which we call before filename parsing
373 * copes with this by calling trim_char on the leading '\'
374 * characters before processing.
375 * Do the same here so logging of pathnames looks better.
377 if (server[1] == path_sep) {
378 trim_char(&server[1], path_sep, '\0');
382 * Look to see if we also have /share following.
384 share = strchr(server+1, path_sep);
385 if (share == NULL) {
386 goto local_path;
389 * It's a well formed DFS path with
390 * at least server and share components.
391 * Replace the slashes with '/' and
392 * pass the remainder to local_path.
394 *server = '/';
395 *share = '/';
397 * Skip past share so we don't pass the
398 * sharename into check_path_syntax().
400 remaining_path = strchr(share+1, path_sep);
401 if (remaining_path == NULL) {
403 * If no remaining path this was
404 * a bare /server/share path. Just return.
406 *err = NT_STATUS_OK;
407 return ret;
409 *remaining_path = '/';
410 dst = remaining_path + 1;
411 /* dst now points at any following components. */
414 local_path:
416 if (posix_pathnames) {
417 *err = check_path_syntax_posix(dst);
418 } else {
419 *err = check_path_syntax(dst);
422 return ret;
425 /****************************************************************************
426 Pull a string and check the path - provide for error return.
427 ****************************************************************************/
429 size_t srvstr_get_path(TALLOC_CTX *ctx,
430 const char *base_ptr,
431 uint16_t smb_flags2,
432 char **pp_dest,
433 const char *src,
434 size_t src_len,
435 int flags,
436 NTSTATUS *err)
438 return srvstr_get_path_internal(ctx,
439 base_ptr,
440 smb_flags2,
441 pp_dest,
442 src,
443 src_len,
444 flags,
445 false,
446 err);
449 /****************************************************************************
450 Pull a string and check the path - provide for error return.
451 posix_pathnames version.
452 ****************************************************************************/
454 size_t srvstr_get_path_posix(TALLOC_CTX *ctx,
455 const char *base_ptr,
456 uint16_t smb_flags2,
457 char **pp_dest,
458 const char *src,
459 size_t src_len,
460 int flags,
461 NTSTATUS *err)
463 return srvstr_get_path_internal(ctx,
464 base_ptr,
465 smb_flags2,
466 pp_dest,
467 src,
468 src_len,
469 flags,
470 true,
471 err);
475 size_t srvstr_get_path_req(TALLOC_CTX *mem_ctx, struct smb_request *req,
476 char **pp_dest, const char *src, int flags,
477 NTSTATUS *err)
479 ssize_t bufrem = smbreq_bufrem(req, src);
481 if (bufrem == 0) {
482 *err = NT_STATUS_INVALID_PARAMETER;
483 return 0;
486 if (req->posix_pathnames) {
487 return srvstr_get_path_internal(mem_ctx,
488 (const char *)req->inbuf,
489 req->flags2,
490 pp_dest,
491 src,
492 bufrem,
493 flags,
494 true,
495 err);
496 } else {
497 return srvstr_get_path_internal(mem_ctx,
498 (const char *)req->inbuf,
499 req->flags2,
500 pp_dest,
501 src,
502 bufrem,
503 flags,
504 false,
505 err);
510 * pull a string from the smb_buf part of a packet. In this case the
511 * string can either be null terminated or it can be terminated by the
512 * end of the smbbuf area
514 size_t srvstr_pull_req_talloc(TALLOC_CTX *ctx, struct smb_request *req,
515 char **dest, const uint8_t *src, int flags)
517 ssize_t bufrem = smbreq_bufrem(req, src);
519 if (bufrem == 0) {
520 return 0;
523 return pull_string_talloc(ctx, req->inbuf, req->flags2, dest, src,
524 bufrem, flags);
527 /****************************************************************************
528 Check if we have a correct fsp pointing to a file. Basic check for open fsp.
529 ****************************************************************************/
531 bool check_fsp_open(connection_struct *conn, struct smb_request *req,
532 files_struct *fsp)
534 if ((fsp == NULL) || (conn == NULL)) {
535 reply_nterror(req, NT_STATUS_INVALID_HANDLE);
536 return False;
538 if ((conn != fsp->conn) || (req->vuid != fsp->vuid)) {
539 reply_nterror(req, NT_STATUS_INVALID_HANDLE);
540 return False;
542 return True;
545 /****************************************************************************
546 Check if we have a correct fsp pointing to a file.
547 ****************************************************************************/
549 bool check_fsp(connection_struct *conn, struct smb_request *req,
550 files_struct *fsp)
552 if (!check_fsp_open(conn, req, fsp)) {
553 return False;
555 if (fsp->fsp_flags.is_directory) {
556 reply_nterror(req, NT_STATUS_INVALID_DEVICE_REQUEST);
557 return False;
559 if (fsp_get_pathref_fd(fsp) == -1) {
560 reply_nterror(req, NT_STATUS_ACCESS_DENIED);
561 return False;
563 fsp->num_smb_operations++;
564 return True;
567 /****************************************************************************
568 Check if we have a correct fsp pointing to a quota fake file. Replacement for
569 the CHECK_NTQUOTA_HANDLE_OK macro.
570 ****************************************************************************/
572 bool check_fsp_ntquota_handle(connection_struct *conn, struct smb_request *req,
573 files_struct *fsp)
575 if (!check_fsp_open(conn, req, fsp)) {
576 return false;
579 if (fsp->fsp_flags.is_directory) {
580 return false;
583 if (fsp->fake_file_handle == NULL) {
584 return false;
587 if (fsp->fake_file_handle->type != FAKE_FILE_TYPE_QUOTA) {
588 return false;
591 if (fsp->fake_file_handle->private_data == NULL) {
592 return false;
595 return true;
598 /****************************************************************************
599 Return the port number we've bound to on a socket.
600 ****************************************************************************/
602 static int get_socket_port(int fd)
604 struct samba_sockaddr saddr = {
605 .sa_socklen = sizeof(struct sockaddr_storage),
608 if (fd == -1) {
609 return -1;
612 if (getsockname(fd, &saddr.u.sa, &saddr.sa_socklen) < 0) {
613 int level = (errno == ENOTCONN) ? 2 : 0;
614 DEBUG(level, ("getsockname failed. Error was %s\n",
615 strerror(errno)));
616 return -1;
619 #if defined(HAVE_IPV6)
620 if (saddr.u.sa.sa_family == AF_INET6) {
621 return ntohs(saddr.u.in6.sin6_port);
623 #endif
624 if (saddr.u.sa.sa_family == AF_INET) {
625 return ntohs(saddr.u.in.sin_port);
627 return -1;
630 static bool netbios_session_retarget(struct smbXsrv_connection *xconn,
631 const char *name, int name_type)
633 char *trim_name;
634 char *trim_name_type;
635 const char *retarget_parm;
636 char *retarget;
637 char *p;
638 int retarget_type = 0x20;
639 int retarget_port = NBT_SMB_PORT;
640 struct sockaddr_storage retarget_addr;
641 struct sockaddr_in *in_addr;
642 bool ret = false;
643 uint8_t outbuf[10];
645 if (get_socket_port(xconn->transport.sock) != NBT_SMB_PORT) {
646 return false;
649 trim_name = talloc_strdup(talloc_tos(), name);
650 if (trim_name == NULL) {
651 goto fail;
653 trim_char(trim_name, ' ', ' ');
655 trim_name_type = talloc_asprintf(trim_name, "%s#%2.2x", trim_name,
656 name_type);
657 if (trim_name_type == NULL) {
658 goto fail;
661 retarget_parm = lp_parm_const_string(-1, "netbios retarget",
662 trim_name_type, NULL);
663 if (retarget_parm == NULL) {
664 retarget_parm = lp_parm_const_string(-1, "netbios retarget",
665 trim_name, NULL);
667 if (retarget_parm == NULL) {
668 goto fail;
671 retarget = talloc_strdup(trim_name, retarget_parm);
672 if (retarget == NULL) {
673 goto fail;
676 DEBUG(10, ("retargeting %s to %s\n", trim_name_type, retarget));
678 p = strchr(retarget, ':');
679 if (p != NULL) {
680 *p++ = '\0';
681 retarget_port = atoi(p);
684 p = strchr_m(retarget, '#');
685 if (p != NULL) {
686 *p++ = '\0';
687 if (sscanf(p, "%x", &retarget_type) != 1) {
688 goto fail;
692 ret = resolve_name(retarget, &retarget_addr, retarget_type, false);
693 if (!ret) {
694 DEBUG(10, ("could not resolve %s\n", retarget));
695 goto fail;
698 if (retarget_addr.ss_family != AF_INET) {
699 DEBUG(10, ("Retarget target not an IPv4 addr\n"));
700 goto fail;
703 in_addr = (struct sockaddr_in *)(void *)&retarget_addr;
705 _smb_setlen(outbuf, 6);
706 SCVAL(outbuf, 0, 0x84);
707 *(uint32_t *)(outbuf+4) = in_addr->sin_addr.s_addr;
708 *(uint16_t *)(outbuf+8) = htons(retarget_port);
710 if (!smb1_srv_send(xconn, (char *)outbuf, false, 0, false,
711 NULL)) {
712 exit_server_cleanly("netbios_session_retarget: smb1_srv_send "
713 "failed.");
716 ret = true;
717 fail:
718 TALLOC_FREE(trim_name);
719 return ret;
722 static void reply_called_name_not_present(char *outbuf)
724 smb_setlen(outbuf, 1);
725 SCVAL(outbuf, 0, 0x83);
726 SCVAL(outbuf, 4, 0x82);
729 /****************************************************************************
730 Reply to a (netbios-level) special message.
731 ****************************************************************************/
733 void reply_special(struct smbXsrv_connection *xconn, char *inbuf, size_t inbuf_size)
735 struct smbd_server_connection *sconn = xconn->client->sconn;
736 int msg_type = CVAL(inbuf,0);
737 int msg_flags = CVAL(inbuf,1);
739 * We only really use 4 bytes of the outbuf, but for the smb_setlen
740 * calculation & friends (smb1_srv_send uses that) we need the full smb
741 * header.
743 char outbuf[smb_size];
745 memset(outbuf, '\0', sizeof(outbuf));
747 smb_setlen(outbuf,0);
749 switch (msg_type) {
750 case NBSSrequest: /* session request */
752 /* inbuf_size is guarenteed to be at least 4. */
753 fstring name1,name2;
754 int name_type1, name_type2;
755 int name_len1, name_len2;
757 *name1 = *name2 = 0;
759 if (xconn->transport.nbt.got_session) {
760 exit_server_cleanly("multiple session request not permitted");
763 SCVAL(outbuf,0,NBSSpositive);
764 SCVAL(outbuf,3,0);
766 /* inbuf_size is guaranteed to be at least 4. */
767 name_len1 = name_len((unsigned char *)(inbuf+4),inbuf_size - 4);
768 if (name_len1 <= 0 || name_len1 > inbuf_size - 4) {
769 DEBUG(0,("Invalid name length in session request\n"));
770 reply_called_name_not_present(outbuf);
771 break;
773 name_len2 = name_len((unsigned char *)(inbuf+4+name_len1),inbuf_size - 4 - name_len1);
774 if (name_len2 <= 0 || name_len2 > inbuf_size - 4 - name_len1) {
775 DEBUG(0,("Invalid name length in session request\n"));
776 reply_called_name_not_present(outbuf);
777 break;
780 name_type1 = name_extract((unsigned char *)inbuf,
781 inbuf_size,(unsigned int)4,name1);
782 name_type2 = name_extract((unsigned char *)inbuf,
783 inbuf_size,(unsigned int)(4 + name_len1),name2);
785 if (name_type1 == -1 || name_type2 == -1) {
786 DEBUG(0,("Invalid name type in session request\n"));
787 reply_called_name_not_present(outbuf);
788 break;
791 DEBUG(2,("netbios connect: name1=%s0x%x name2=%s0x%x\n",
792 name1, name_type1, name2, name_type2));
794 if (netbios_session_retarget(xconn, name1, name_type1)) {
795 exit_server_cleanly("retargeted client");
799 * Windows NT/2k uses "*SMBSERVER" and XP uses
800 * "*SMBSERV" arrggg!!!
802 if (strequal(name1, "*SMBSERVER ")
803 || strequal(name1, "*SMBSERV ")) {
804 char *raddr;
806 raddr = tsocket_address_inet_addr_string(sconn->remote_address,
807 talloc_tos());
808 if (raddr == NULL) {
809 exit_server_cleanly("could not allocate raddr");
812 fstrcpy(name1, raddr);
815 set_local_machine_name(name1, True);
816 set_remote_machine_name(name2, True);
818 if (is_ipaddress(sconn->remote_hostname)) {
819 char *p = discard_const_p(char, sconn->remote_hostname);
821 talloc_free(p);
823 sconn->remote_hostname = talloc_strdup(sconn,
824 get_remote_machine_name());
825 if (sconn->remote_hostname == NULL) {
826 exit_server_cleanly("could not copy remote name");
828 xconn->remote_hostname = sconn->remote_hostname;
831 DEBUG(2,("netbios connect: local=%s remote=%s, name type = %x\n",
832 get_local_machine_name(), get_remote_machine_name(),
833 name_type2));
835 if (name_type2 == 'R') {
836 /* We are being asked for a pathworks session ---
837 no thanks! */
838 reply_called_name_not_present(outbuf);
839 break;
842 reload_services(sconn, conn_snum_used, true);
843 reopen_logs();
845 xconn->transport.nbt.got_session = true;
846 break;
849 case 0x89: /* session keepalive request
850 (some old clients produce this?) */
851 SCVAL(outbuf,0,NBSSkeepalive);
852 SCVAL(outbuf,3,0);
853 break;
855 case NBSSpositive: /* positive session response */
856 case NBSSnegative: /* negative session response */
857 case NBSSretarget: /* retarget session response */
858 DEBUG(0,("Unexpected session response\n"));
859 break;
861 case NBSSkeepalive: /* session keepalive */
862 default:
863 return;
866 DEBUG(5,("init msg_type=0x%x msg_flags=0x%x\n",
867 msg_type, msg_flags));
869 if (!smb1_srv_send(xconn, outbuf, false, 0, false, NULL)) {
870 exit_server_cleanly("reply_special: smb1_srv_send failed.");
873 if (CVAL(outbuf, 0) != 0x82) {
874 exit_server_cleanly("invalid netbios session");
876 return;
879 /*******************************************************************
880 * unlink a file with all relevant access checks
881 *******************************************************************/
883 NTSTATUS unlink_internals(connection_struct *conn,
884 struct smb_request *req,
885 uint32_t dirtype,
886 struct files_struct *dirfsp,
887 struct smb_filename *smb_fname)
889 uint32_t fattr;
890 files_struct *fsp;
891 uint32_t dirtype_orig = dirtype;
892 NTSTATUS status;
893 int ret;
894 struct smb2_create_blobs *posx = NULL;
896 if (dirtype == 0) {
897 dirtype = FILE_ATTRIBUTE_NORMAL;
900 DBG_DEBUG("%s, dirtype = %d\n",
901 smb_fname_str_dbg(smb_fname),
902 dirtype);
904 if (!CAN_WRITE(conn)) {
905 return NT_STATUS_MEDIA_WRITE_PROTECTED;
908 ret = vfs_stat(conn, smb_fname);
909 if (ret != 0) {
910 return map_nt_error_from_unix(errno);
913 fattr = fdos_mode(smb_fname->fsp);
915 if (dirtype & FILE_ATTRIBUTE_NORMAL) {
916 dirtype = FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_ARCHIVE|FILE_ATTRIBUTE_READONLY;
919 dirtype &= (FILE_ATTRIBUTE_DIRECTORY|FILE_ATTRIBUTE_ARCHIVE|FILE_ATTRIBUTE_READONLY|FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM);
920 if (!dirtype) {
921 return NT_STATUS_NO_SUCH_FILE;
924 if (!dir_check_ftype(fattr, dirtype)) {
925 if (fattr & FILE_ATTRIBUTE_DIRECTORY) {
926 return NT_STATUS_FILE_IS_A_DIRECTORY;
928 return NT_STATUS_NO_SUCH_FILE;
931 if (dirtype_orig & 0x8000) {
932 /* These will never be set for POSIX. */
933 return NT_STATUS_NO_SUCH_FILE;
936 #if 0
937 if ((fattr & dirtype) & FILE_ATTRIBUTE_DIRECTORY) {
938 return NT_STATUS_FILE_IS_A_DIRECTORY;
941 if ((fattr & ~dirtype) & (FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM)) {
942 return NT_STATUS_NO_SUCH_FILE;
945 if (dirtype & 0xFF00) {
946 /* These will never be set for POSIX. */
947 return NT_STATUS_NO_SUCH_FILE;
950 dirtype &= 0xFF;
951 if (!dirtype) {
952 return NT_STATUS_NO_SUCH_FILE;
955 /* Can't delete a directory. */
956 if (fattr & FILE_ATTRIBUTE_DIRECTORY) {
957 return NT_STATUS_FILE_IS_A_DIRECTORY;
959 #endif
961 #if 0 /* JRATEST */
962 else if (dirtype & FILE_ATTRIBUTE_DIRECTORY) /* Asked for a directory and it isn't. */
963 return NT_STATUS_OBJECT_NAME_INVALID;
964 #endif /* JRATEST */
966 if (smb_fname->flags & SMB_FILENAME_POSIX_PATH) {
967 status = make_smb2_posix_create_ctx(
968 talloc_tos(), &posx, 0777);
969 if (!NT_STATUS_IS_OK(status)) {
970 DBG_WARNING("make_smb2_posix_create_ctx failed: %s\n",
971 nt_errstr(status));
972 return status;
976 /* On open checks the open itself will check the share mode, so
977 don't do it here as we'll get it wrong. */
979 status = SMB_VFS_CREATE_FILE
980 (conn, /* conn */
981 req, /* req */
982 dirfsp, /* dirfsp */
983 smb_fname, /* fname */
984 DELETE_ACCESS, /* access_mask */
985 FILE_SHARE_NONE, /* share_access */
986 FILE_OPEN, /* create_disposition*/
987 FILE_NON_DIRECTORY_FILE, /* create_options */
988 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
989 0, /* oplock_request */
990 NULL, /* lease */
991 0, /* allocation_size */
992 0, /* private_flags */
993 NULL, /* sd */
994 NULL, /* ea_list */
995 &fsp, /* result */
996 NULL, /* pinfo */
997 posx, /* in_context_blobs */
998 NULL); /* out_context_blobs */
1000 TALLOC_FREE(posx);
1002 if (!NT_STATUS_IS_OK(status)) {
1003 DBG_DEBUG("SMB_VFS_CREATEFILE failed: %s\n",
1004 nt_errstr(status));
1005 return status;
1008 status = can_set_delete_on_close(fsp, fattr);
1009 if (!NT_STATUS_IS_OK(status)) {
1010 DBG_DEBUG("can_set_delete_on_close for file %s - "
1011 "(%s)\n",
1012 smb_fname_str_dbg(smb_fname),
1013 nt_errstr(status));
1014 close_file_free(req, &fsp, NORMAL_CLOSE);
1015 return status;
1018 /* The set is across all open files on this dev/inode pair. */
1019 if (!set_delete_on_close(fsp, True,
1020 conn->session_info->security_token,
1021 conn->session_info->unix_token)) {
1022 close_file_free(req, &fsp, NORMAL_CLOSE);
1023 return NT_STATUS_ACCESS_DENIED;
1026 return close_file_free(req, &fsp, NORMAL_CLOSE);
1029 /****************************************************************************
1030 Fake (read/write) sendfile. Returns -1 on read or write fail.
1031 ****************************************************************************/
1033 ssize_t fake_sendfile(struct smbXsrv_connection *xconn, files_struct *fsp,
1034 off_t startpos, size_t nread)
1036 size_t bufsize;
1037 size_t tosend = nread;
1038 char *buf;
1040 if (nread == 0) {
1041 return 0;
1044 bufsize = MIN(nread, 65536);
1046 if (!(buf = SMB_MALLOC_ARRAY(char, bufsize))) {
1047 return -1;
1050 while (tosend > 0) {
1051 ssize_t ret;
1052 size_t cur_read;
1054 cur_read = MIN(tosend, bufsize);
1055 ret = read_file(fsp,buf,startpos,cur_read);
1056 if (ret == -1) {
1057 SAFE_FREE(buf);
1058 return -1;
1061 /* If we had a short read, fill with zeros. */
1062 if (ret < cur_read) {
1063 memset(buf + ret, '\0', cur_read - ret);
1066 ret = write_data(xconn->transport.sock, buf, cur_read);
1067 if (ret != cur_read) {
1068 int saved_errno = errno;
1070 * Try and give an error message saying what
1071 * client failed.
1073 DEBUG(0, ("write_data failed for client %s. "
1074 "Error %s\n",
1075 smbXsrv_connection_dbg(xconn),
1076 strerror(saved_errno)));
1077 SAFE_FREE(buf);
1078 errno = saved_errno;
1079 return -1;
1081 tosend -= cur_read;
1082 startpos += cur_read;
1085 SAFE_FREE(buf);
1086 return (ssize_t)nread;
1089 /****************************************************************************
1090 Deal with the case of sendfile reading less bytes from the file than
1091 requested. Fill with zeros (all we can do). Returns 0 on success
1092 ****************************************************************************/
1094 ssize_t sendfile_short_send(struct smbXsrv_connection *xconn,
1095 files_struct *fsp,
1096 ssize_t nread,
1097 size_t headersize,
1098 size_t smb_maxcnt)
1100 #define SHORT_SEND_BUFSIZE 1024
1101 if (nread < headersize) {
1102 DEBUG(0,("sendfile_short_send: sendfile failed to send "
1103 "header for file %s (%s). Terminating\n",
1104 fsp_str_dbg(fsp), strerror(errno)));
1105 return -1;
1108 nread -= headersize;
1110 if (nread < smb_maxcnt) {
1111 char buf[SHORT_SEND_BUFSIZE] = { 0 };
1113 DEBUG(0,("sendfile_short_send: filling truncated file %s "
1114 "with zeros !\n", fsp_str_dbg(fsp)));
1116 while (nread < smb_maxcnt) {
1118 * We asked for the real file size and told sendfile
1119 * to not go beyond the end of the file. But it can
1120 * happen that in between our fstat call and the
1121 * sendfile call the file was truncated. This is very
1122 * bad because we have already announced the larger
1123 * number of bytes to the client.
1125 * The best we can do now is to send 0-bytes, just as
1126 * a read from a hole in a sparse file would do.
1128 * This should happen rarely enough that I don't care
1129 * about efficiency here :-)
1131 size_t to_write;
1132 ssize_t ret;
1134 to_write = MIN(SHORT_SEND_BUFSIZE, smb_maxcnt - nread);
1135 ret = write_data(xconn->transport.sock, buf, to_write);
1136 if (ret != to_write) {
1137 int saved_errno = errno;
1139 * Try and give an error message saying what
1140 * client failed.
1142 DEBUG(0, ("write_data failed for client %s. "
1143 "Error %s\n",
1144 smbXsrv_connection_dbg(xconn),
1145 strerror(saved_errno)));
1146 errno = saved_errno;
1147 return -1;
1149 nread += to_write;
1153 return 0;
1156 /*******************************************************************
1157 Check if a user is allowed to rename a file.
1158 ********************************************************************/
1160 static NTSTATUS can_rename(connection_struct *conn, files_struct *fsp,
1161 uint16_t dirtype)
1163 if (!CAN_WRITE(conn)) {
1164 return NT_STATUS_MEDIA_WRITE_PROTECTED;
1167 if ((dirtype & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM)) !=
1168 (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM)) {
1169 /* Only bother to read the DOS attribute if we might deny the
1170 rename on the grounds of attribute mismatch. */
1171 uint32_t fmode = fdos_mode(fsp);
1172 if ((fmode & ~dirtype) & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM)) {
1173 return NT_STATUS_NO_SUCH_FILE;
1177 if (S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
1178 if (fsp->posix_flags & FSP_POSIX_FLAGS_RENAME) {
1179 return NT_STATUS_OK;
1182 /* If no pathnames are open below this
1183 directory, allow the rename. */
1185 if (lp_strict_rename(SNUM(conn))) {
1187 * Strict rename, check open file db.
1189 if (have_file_open_below(fsp->conn, fsp->fsp_name)) {
1190 return NT_STATUS_ACCESS_DENIED;
1192 } else if (file_find_subpath(fsp)) {
1194 * No strict rename, just look in local process.
1196 return NT_STATUS_ACCESS_DENIED;
1198 return NT_STATUS_OK;
1201 if (fsp->access_mask & (DELETE_ACCESS|FILE_WRITE_ATTRIBUTES)) {
1202 return NT_STATUS_OK;
1205 return NT_STATUS_ACCESS_DENIED;
1208 /****************************************************************************
1209 Ensure open files have their names updated. Updated to notify other smbd's
1210 asynchronously.
1211 ****************************************************************************/
1213 static void rename_open_files(connection_struct *conn,
1214 struct share_mode_lock *lck,
1215 struct file_id id,
1216 uint32_t orig_name_hash,
1217 const struct smb_filename *smb_fname_dst)
1219 files_struct *fsp;
1220 bool did_rename = False;
1221 NTSTATUS status;
1222 uint32_t new_name_hash = 0;
1224 for(fsp = file_find_di_first(conn->sconn, id, false); fsp;
1225 fsp = file_find_di_next(fsp, false)) {
1226 SMB_STRUCT_STAT fsp_orig_sbuf;
1227 struct file_id_buf idbuf;
1228 /* fsp_name is a relative path under the fsp. To change this for other
1229 sharepaths we need to manipulate relative paths. */
1230 /* TODO - create the absolute path and manipulate the newname
1231 relative to the sharepath. */
1232 if (!strequal(fsp->conn->connectpath, conn->connectpath)) {
1233 continue;
1235 if (fsp->name_hash != orig_name_hash) {
1236 continue;
1238 DBG_DEBUG("renaming file %s "
1239 "(file_id %s) from %s -> %s\n",
1240 fsp_fnum_dbg(fsp),
1241 file_id_str_buf(fsp->file_id, &idbuf),
1242 fsp_str_dbg(fsp),
1243 smb_fname_str_dbg(smb_fname_dst));
1246 * The incoming smb_fname_dst here has an
1247 * invalid stat struct (it must not have
1248 * existed for the rename to succeed).
1249 * Preserve the existing stat from the
1250 * open fsp after fsp_set_smb_fname()
1251 * overwrites with the invalid stat.
1253 * We will do an fstat before returning
1254 * any of this metadata to the client anyway.
1256 fsp_orig_sbuf = fsp->fsp_name->st;
1257 status = fsp_set_smb_fname(fsp, smb_fname_dst);
1258 if (NT_STATUS_IS_OK(status)) {
1259 did_rename = True;
1260 new_name_hash = fsp->name_hash;
1261 /* Restore existing stat. */
1262 fsp->fsp_name->st = fsp_orig_sbuf;
1266 if (!did_rename) {
1267 struct file_id_buf idbuf;
1268 DBG_DEBUG("no open files on file_id %s "
1269 "for %s\n",
1270 file_id_str_buf(id, &idbuf),
1271 smb_fname_str_dbg(smb_fname_dst));
1274 /* Send messages to all smbd's (not ourself) that the name has changed. */
1275 rename_share_filename(conn->sconn->msg_ctx, lck, id, conn->connectpath,
1276 orig_name_hash, new_name_hash,
1277 smb_fname_dst);
1281 /****************************************************************************
1282 We need to check if the source path is a parent directory of the destination
1283 (ie. a rename of /foo/bar/baz -> /foo/bar/baz/bibble/bobble. If so we must
1284 refuse the rename with a sharing violation. Under UNIX the above call can
1285 *succeed* if /foo/bar/baz is a symlink to another area in the share. We
1286 probably need to check that the client is a Windows one before disallowing
1287 this as a UNIX client (one with UNIX extensions) can know the source is a
1288 symlink and make this decision intelligently. Found by an excellent bug
1289 report from <AndyLiebman@aol.com>.
1290 ****************************************************************************/
1292 static bool rename_path_prefix_equal(const struct smb_filename *smb_fname_src,
1293 const struct smb_filename *smb_fname_dst)
1295 const char *psrc = smb_fname_src->base_name;
1296 const char *pdst = smb_fname_dst->base_name;
1297 size_t slen;
1299 if (psrc[0] == '.' && psrc[1] == '/') {
1300 psrc += 2;
1302 if (pdst[0] == '.' && pdst[1] == '/') {
1303 pdst += 2;
1305 if ((slen = strlen(psrc)) > strlen(pdst)) {
1306 return False;
1308 return ((memcmp(psrc, pdst, slen) == 0) && pdst[slen] == '/');
1312 * Do the notify calls from a rename
1315 static void notify_rename(connection_struct *conn, bool is_dir,
1316 const struct smb_filename *smb_fname_src,
1317 const struct smb_filename *smb_fname_dst)
1319 char *parent_dir_src = NULL;
1320 char *parent_dir_dst = NULL;
1321 uint32_t mask;
1323 mask = is_dir ? FILE_NOTIFY_CHANGE_DIR_NAME
1324 : FILE_NOTIFY_CHANGE_FILE_NAME;
1326 if (!parent_dirname(talloc_tos(), smb_fname_src->base_name,
1327 &parent_dir_src, NULL) ||
1328 !parent_dirname(talloc_tos(), smb_fname_dst->base_name,
1329 &parent_dir_dst, NULL)) {
1330 goto out;
1333 if (strcmp(parent_dir_src, parent_dir_dst) == 0) {
1334 notify_fname(conn, NOTIFY_ACTION_OLD_NAME, mask,
1335 smb_fname_src->base_name);
1336 notify_fname(conn, NOTIFY_ACTION_NEW_NAME, mask,
1337 smb_fname_dst->base_name);
1339 else {
1340 notify_fname(conn, NOTIFY_ACTION_REMOVED, mask,
1341 smb_fname_src->base_name);
1342 notify_fname(conn, NOTIFY_ACTION_ADDED, mask,
1343 smb_fname_dst->base_name);
1346 /* this is a strange one. w2k3 gives an additional event for
1347 CHANGE_ATTRIBUTES and CHANGE_CREATION on the new file when renaming
1348 files, but not directories */
1349 if (!is_dir) {
1350 notify_fname(conn, NOTIFY_ACTION_MODIFIED,
1351 FILE_NOTIFY_CHANGE_ATTRIBUTES
1352 |FILE_NOTIFY_CHANGE_CREATION,
1353 smb_fname_dst->base_name);
1355 out:
1356 TALLOC_FREE(parent_dir_src);
1357 TALLOC_FREE(parent_dir_dst);
1360 /****************************************************************************
1361 Returns an error if the parent directory for a filename is open in an
1362 incompatible way.
1363 ****************************************************************************/
1365 static NTSTATUS parent_dirname_compatible_open(connection_struct *conn,
1366 const struct smb_filename *smb_fname_dst_in)
1368 struct smb_filename *smb_fname_parent = NULL;
1369 struct file_id id;
1370 files_struct *fsp = NULL;
1371 int ret;
1372 NTSTATUS status;
1374 status = SMB_VFS_PARENT_PATHNAME(conn,
1375 talloc_tos(),
1376 smb_fname_dst_in,
1377 &smb_fname_parent,
1378 NULL);
1379 if (!NT_STATUS_IS_OK(status)) {
1380 return status;
1383 ret = vfs_stat(conn, smb_fname_parent);
1384 if (ret == -1) {
1385 return map_nt_error_from_unix(errno);
1389 * We're only checking on this smbd here, mostly good
1390 * enough.. and will pass tests.
1393 id = vfs_file_id_from_sbuf(conn, &smb_fname_parent->st);
1394 for (fsp = file_find_di_first(conn->sconn, id, true); fsp;
1395 fsp = file_find_di_next(fsp, true)) {
1396 if (fsp->access_mask & DELETE_ACCESS) {
1397 return NT_STATUS_SHARING_VIOLATION;
1400 return NT_STATUS_OK;
1403 /****************************************************************************
1404 Rename an open file - given an fsp.
1405 ****************************************************************************/
1407 NTSTATUS rename_internals_fsp(connection_struct *conn,
1408 files_struct *fsp,
1409 struct files_struct *dst_dirfsp,
1410 struct smb_filename *smb_fname_dst_in,
1411 const char *dst_original_lcomp,
1412 uint32_t attrs,
1413 bool replace_if_exists)
1415 TALLOC_CTX *ctx = talloc_tos();
1416 struct smb_filename *parent_dir_fname_dst = NULL;
1417 struct smb_filename *parent_dir_fname_dst_atname = NULL;
1418 struct smb_filename *parent_dir_fname_src = NULL;
1419 struct smb_filename *parent_dir_fname_src_atname = NULL;
1420 struct smb_filename *smb_fname_dst = NULL;
1421 NTSTATUS status = NT_STATUS_OK;
1422 struct share_mode_lock *lck = NULL;
1423 uint32_t access_mask = SEC_DIR_ADD_FILE;
1424 bool dst_exists, old_is_stream, new_is_stream;
1425 int ret;
1426 bool case_sensitive = (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) ?
1427 true : conn->case_sensitive;
1428 bool case_preserve = (fsp->posix_flags & FSP_POSIX_FLAGS_OPEN) ?
1429 true : conn->case_preserve;
1431 status = parent_dirname_compatible_open(conn, smb_fname_dst_in);
1432 if (!NT_STATUS_IS_OK(status)) {
1433 return status;
1436 if (file_has_open_streams(fsp)) {
1437 return NT_STATUS_ACCESS_DENIED;
1440 /* Make a copy of the dst smb_fname structs */
1442 smb_fname_dst = cp_smb_filename(ctx, smb_fname_dst_in);
1443 if (smb_fname_dst == NULL) {
1444 status = NT_STATUS_NO_MEMORY;
1445 goto out;
1449 * Check for special case with case preserving and not
1450 * case sensitive. If the new last component differs from the original
1451 * last component only by case, then we should allow
1452 * the rename (user is trying to change the case of the
1453 * filename).
1455 if (!case_sensitive && case_preserve &&
1456 strequal(fsp->fsp_name->base_name, smb_fname_dst->base_name) &&
1457 strequal(fsp->fsp_name->stream_name, smb_fname_dst->stream_name)) {
1458 char *fname_dst_parent = NULL;
1459 const char *fname_dst_lcomp = NULL;
1460 char *orig_lcomp_path = NULL;
1461 char *orig_lcomp_stream = NULL;
1462 bool ok = true;
1465 * Split off the last component of the processed
1466 * destination name. We will compare this to
1467 * the split components of dst_original_lcomp.
1469 if (!parent_dirname(ctx,
1470 smb_fname_dst->base_name,
1471 &fname_dst_parent,
1472 &fname_dst_lcomp)) {
1473 status = NT_STATUS_NO_MEMORY;
1474 goto out;
1478 * The dst_original_lcomp component contains
1479 * the last_component of the path + stream
1480 * name (if a stream exists).
1482 * Split off the stream name so we
1483 * can check them separately.
1486 if (fsp->posix_flags & FSP_POSIX_FLAGS_PATHNAMES) {
1487 /* POSIX - no stream component. */
1488 orig_lcomp_path = talloc_strdup(ctx,
1489 dst_original_lcomp);
1490 if (orig_lcomp_path == NULL) {
1491 ok = false;
1493 } else {
1494 ok = split_stream_filename(ctx,
1495 dst_original_lcomp,
1496 &orig_lcomp_path,
1497 &orig_lcomp_stream);
1500 if (!ok) {
1501 TALLOC_FREE(fname_dst_parent);
1502 status = NT_STATUS_NO_MEMORY;
1503 goto out;
1506 /* If the base names only differ by case, use original. */
1507 if(!strcsequal(fname_dst_lcomp, orig_lcomp_path)) {
1508 char *tmp;
1510 * Replace the modified last component with the
1511 * original.
1513 if (!ISDOT(fname_dst_parent)) {
1514 tmp = talloc_asprintf(smb_fname_dst,
1515 "%s/%s",
1516 fname_dst_parent,
1517 orig_lcomp_path);
1518 } else {
1519 tmp = talloc_strdup(smb_fname_dst,
1520 orig_lcomp_path);
1522 if (tmp == NULL) {
1523 status = NT_STATUS_NO_MEMORY;
1524 TALLOC_FREE(fname_dst_parent);
1525 TALLOC_FREE(orig_lcomp_path);
1526 TALLOC_FREE(orig_lcomp_stream);
1527 goto out;
1529 TALLOC_FREE(smb_fname_dst->base_name);
1530 smb_fname_dst->base_name = tmp;
1533 /* If the stream_names only differ by case, use original. */
1534 if(!strcsequal(smb_fname_dst->stream_name,
1535 orig_lcomp_stream)) {
1536 /* Use the original stream. */
1537 char *tmp = talloc_strdup(smb_fname_dst,
1538 orig_lcomp_stream);
1539 if (tmp == NULL) {
1540 status = NT_STATUS_NO_MEMORY;
1541 TALLOC_FREE(fname_dst_parent);
1542 TALLOC_FREE(orig_lcomp_path);
1543 TALLOC_FREE(orig_lcomp_stream);
1544 goto out;
1546 TALLOC_FREE(smb_fname_dst->stream_name);
1547 smb_fname_dst->stream_name = tmp;
1549 TALLOC_FREE(fname_dst_parent);
1550 TALLOC_FREE(orig_lcomp_path);
1551 TALLOC_FREE(orig_lcomp_stream);
1555 * If the src and dest names are identical - including case,
1556 * don't do the rename, just return success.
1559 if (strcsequal(fsp->fsp_name->base_name, smb_fname_dst->base_name) &&
1560 strcsequal(fsp->fsp_name->stream_name,
1561 smb_fname_dst->stream_name)) {
1562 DEBUG(3, ("rename_internals_fsp: identical names in rename %s "
1563 "- returning success\n",
1564 smb_fname_str_dbg(smb_fname_dst)));
1565 status = NT_STATUS_OK;
1566 goto out;
1569 old_is_stream = is_ntfs_stream_smb_fname(fsp->fsp_name);
1570 new_is_stream = is_ntfs_stream_smb_fname(smb_fname_dst);
1572 /* Return the correct error code if both names aren't streams. */
1573 if (!old_is_stream && new_is_stream) {
1574 status = NT_STATUS_OBJECT_NAME_INVALID;
1575 goto out;
1578 if (old_is_stream && !new_is_stream) {
1579 status = NT_STATUS_INVALID_PARAMETER;
1580 goto out;
1583 dst_exists = vfs_stat(conn, smb_fname_dst) == 0;
1585 if(!replace_if_exists && dst_exists) {
1586 DEBUG(3, ("rename_internals_fsp: dest exists doing rename "
1587 "%s -> %s\n", smb_fname_str_dbg(fsp->fsp_name),
1588 smb_fname_str_dbg(smb_fname_dst)));
1589 status = NT_STATUS_OBJECT_NAME_COLLISION;
1590 goto out;
1594 * Drop the pathref fsp on the destination otherwise we trip upon in in
1595 * the below check for open files check.
1597 if (smb_fname_dst_in->fsp != NULL) {
1598 fd_close(smb_fname_dst_in->fsp);
1599 file_free(NULL, smb_fname_dst_in->fsp);
1600 SMB_ASSERT(smb_fname_dst_in->fsp == NULL);
1603 if (dst_exists) {
1604 struct file_id fileid = vfs_file_id_from_sbuf(conn,
1605 &smb_fname_dst->st);
1606 files_struct *dst_fsp = file_find_di_first(conn->sconn,
1607 fileid, true);
1608 /* The file can be open when renaming a stream */
1609 if (dst_fsp && !new_is_stream) {
1610 DEBUG(3, ("rename_internals_fsp: Target file open\n"));
1611 status = NT_STATUS_ACCESS_DENIED;
1612 goto out;
1616 /* Ensure we have a valid stat struct for the source. */
1617 status = vfs_stat_fsp(fsp);
1618 if (!NT_STATUS_IS_OK(status)) {
1619 goto out;
1622 status = can_rename(conn, fsp, attrs);
1624 if (!NT_STATUS_IS_OK(status)) {
1625 DEBUG(3, ("rename_internals_fsp: Error %s rename %s -> %s\n",
1626 nt_errstr(status), smb_fname_str_dbg(fsp->fsp_name),
1627 smb_fname_str_dbg(smb_fname_dst)));
1628 if (NT_STATUS_EQUAL(status,NT_STATUS_SHARING_VIOLATION))
1629 status = NT_STATUS_ACCESS_DENIED;
1630 goto out;
1633 if (rename_path_prefix_equal(fsp->fsp_name, smb_fname_dst)) {
1634 status = NT_STATUS_ACCESS_DENIED;
1635 goto out;
1638 /* Do we have rights to move into the destination ? */
1639 if (S_ISDIR(fsp->fsp_name->st.st_ex_mode)) {
1640 /* We're moving a directory. */
1641 access_mask = SEC_DIR_ADD_SUBDIR;
1645 * Get a pathref on the destination parent directory, so
1646 * we can call check_parent_access_fsp().
1648 status = parent_pathref(ctx,
1649 conn->cwd_fsp,
1650 smb_fname_dst,
1651 &parent_dir_fname_dst,
1652 &parent_dir_fname_dst_atname);
1653 if (!NT_STATUS_IS_OK(status)) {
1654 goto out;
1657 status = check_parent_access_fsp(parent_dir_fname_dst->fsp,
1658 access_mask);
1659 if (!NT_STATUS_IS_OK(status)) {
1660 DBG_INFO("check_parent_access_fsp on "
1661 "dst %s returned %s\n",
1662 smb_fname_str_dbg(smb_fname_dst),
1663 nt_errstr(status));
1664 goto out;
1668 * If the target existed, make sure the destination
1669 * atname has the same stat struct.
1671 parent_dir_fname_dst_atname->st = smb_fname_dst->st;
1674 * It's very common that source and
1675 * destination directories are the same.
1676 * Optimize by not opening the
1677 * second parent_pathref if we know
1678 * this is the case.
1681 status = SMB_VFS_PARENT_PATHNAME(conn,
1682 ctx,
1683 fsp->fsp_name,
1684 &parent_dir_fname_src,
1685 &parent_dir_fname_src_atname);
1686 if (!NT_STATUS_IS_OK(status)) {
1687 goto out;
1691 * We do a case-sensitive string comparison. We want to be *sure*
1692 * this is the same path. The worst that can happen if
1693 * the case doesn't match is we lose out on the optimization,
1694 * the code still works.
1696 * We can ignore twrp fields here. Rename is not allowed on
1697 * shadow copy handles.
1700 if (strcmp(parent_dir_fname_src->base_name,
1701 parent_dir_fname_dst->base_name) == 0) {
1703 * parent directory is the same for source
1704 * and destination.
1706 /* Reparent the src_atname to the parent_dir_dest fname. */
1707 parent_dir_fname_src_atname = talloc_move(
1708 parent_dir_fname_dst,
1709 &parent_dir_fname_src_atname);
1710 /* Free the unneeded duplicate parent name. */
1711 TALLOC_FREE(parent_dir_fname_src);
1713 * And make the source parent name a copy of the
1714 * destination parent name.
1716 parent_dir_fname_src = parent_dir_fname_dst;
1719 * Ensure we have a pathref fsp on the
1720 * parent_dir_fname_src_atname to match the code in the else
1721 * branch where we use parent_pathref().
1723 status = reference_smb_fname_fsp_link(
1724 parent_dir_fname_src_atname,
1725 fsp->fsp_name);
1726 if (!NT_STATUS_IS_OK(status)) {
1727 goto out;
1729 } else {
1731 * source and destination parent directories are
1732 * different.
1734 * Get a pathref on the source parent directory, so
1735 * we can do a relative rename.
1737 TALLOC_FREE(parent_dir_fname_src);
1738 status = parent_pathref(ctx,
1739 conn->cwd_fsp,
1740 fsp->fsp_name,
1741 &parent_dir_fname_src,
1742 &parent_dir_fname_src_atname);
1743 if (!NT_STATUS_IS_OK(status)) {
1744 goto out;
1749 * Some modules depend on the source smb_fname having a valid stat.
1750 * The parent_dir_fname_src_atname is the relative name of the
1751 * currently open file, so just copy the stat from the open fsp.
1753 parent_dir_fname_src_atname->st = fsp->fsp_name->st;
1755 lck = get_existing_share_mode_lock(talloc_tos(), fsp->file_id);
1758 * We have the file open ourselves, so not being able to get the
1759 * corresponding share mode lock is a fatal error.
1762 SMB_ASSERT(lck != NULL);
1764 ret = SMB_VFS_RENAMEAT(conn,
1765 parent_dir_fname_src->fsp,
1766 parent_dir_fname_src_atname,
1767 parent_dir_fname_dst->fsp,
1768 parent_dir_fname_dst_atname);
1769 if (ret == 0) {
1770 uint32_t create_options = fh_get_private_options(fsp->fh);
1772 DEBUG(3, ("rename_internals_fsp: succeeded doing rename on "
1773 "%s -> %s\n", smb_fname_str_dbg(fsp->fsp_name),
1774 smb_fname_str_dbg(smb_fname_dst)));
1776 notify_rename(conn,
1777 fsp->fsp_flags.is_directory,
1778 fsp->fsp_name,
1779 smb_fname_dst);
1781 rename_open_files(conn, lck, fsp->file_id, fsp->name_hash,
1782 smb_fname_dst);
1784 if (!fsp->fsp_flags.is_directory &&
1785 !(fsp->posix_flags & FSP_POSIX_FLAGS_PATHNAMES) &&
1786 (lp_map_archive(SNUM(conn)) ||
1787 lp_store_dos_attributes(SNUM(conn))))
1790 * We must set the archive bit on the newly renamed
1791 * file.
1793 status = vfs_stat_fsp(fsp);
1794 if (NT_STATUS_IS_OK(status)) {
1795 uint32_t old_dosmode;
1796 old_dosmode = fdos_mode(fsp);
1798 * We can use fsp->fsp_name here as it has
1799 * already been changed to the new name.
1801 SMB_ASSERT(fsp->fsp_name->fsp == fsp);
1802 file_set_dosmode(conn,
1803 fsp->fsp_name,
1804 old_dosmode | FILE_ATTRIBUTE_ARCHIVE,
1805 NULL,
1806 true);
1811 * A rename acts as a new file create w.r.t. allowing an initial delete
1812 * on close, probably because in Windows there is a new handle to the
1813 * new file. If initial delete on close was requested but not
1814 * originally set, we need to set it here. This is probably not 100% correct,
1815 * but will work for the CIFSFS client which in non-posix mode
1816 * depends on these semantics. JRA.
1819 if (create_options & FILE_DELETE_ON_CLOSE) {
1820 status = can_set_delete_on_close(fsp, 0);
1822 if (NT_STATUS_IS_OK(status)) {
1823 /* Note that here we set the *initial* delete on close flag,
1824 * not the regular one. The magic gets handled in close. */
1825 fsp->fsp_flags.initial_delete_on_close = true;
1828 TALLOC_FREE(lck);
1829 status = NT_STATUS_OK;
1830 goto out;
1833 TALLOC_FREE(lck);
1835 if (errno == ENOTDIR || errno == EISDIR) {
1836 status = NT_STATUS_OBJECT_NAME_COLLISION;
1837 } else {
1838 status = map_nt_error_from_unix(errno);
1841 DEBUG(3, ("rename_internals_fsp: Error %s rename %s -> %s\n",
1842 nt_errstr(status), smb_fname_str_dbg(fsp->fsp_name),
1843 smb_fname_str_dbg(smb_fname_dst)));
1845 out:
1848 * parent_dir_fname_src may be a copy of parent_dir_fname_dst.
1849 * See the optimization for same source and destination directory
1850 * above. Only free one in that case.
1852 if (parent_dir_fname_src != parent_dir_fname_dst) {
1853 TALLOC_FREE(parent_dir_fname_src);
1855 TALLOC_FREE(parent_dir_fname_dst);
1856 TALLOC_FREE(smb_fname_dst);
1858 return status;
1861 /****************************************************************************
1862 The guts of the rename command, split out so it may be called by the NT SMB
1863 code.
1864 ****************************************************************************/
1866 NTSTATUS rename_internals(TALLOC_CTX *ctx,
1867 connection_struct *conn,
1868 struct smb_request *req,
1869 struct files_struct *src_dirfsp,
1870 struct smb_filename *smb_fname_src,
1871 struct files_struct *dst_dirfsp,
1872 struct smb_filename *smb_fname_dst,
1873 const char *dst_original_lcomp,
1874 uint32_t attrs,
1875 bool replace_if_exists,
1876 uint32_t access_mask)
1878 NTSTATUS status = NT_STATUS_OK;
1879 int create_options = 0;
1880 struct smb2_create_blobs *posx = NULL;
1881 struct files_struct *fsp = NULL;
1882 bool posix_pathname = (smb_fname_src->flags & SMB_FILENAME_POSIX_PATH);
1883 bool case_sensitive = posix_pathname ? true : conn->case_sensitive;
1884 bool case_preserve = posix_pathname ? true : conn->case_preserve;
1885 bool short_case_preserve = posix_pathname ? true :
1886 conn->short_case_preserve;
1888 if (posix_pathname) {
1889 status = make_smb2_posix_create_ctx(talloc_tos(), &posx, 0777);
1890 if (!NT_STATUS_IS_OK(status)) {
1891 DBG_WARNING("make_smb2_posix_create_ctx failed: %s\n",
1892 nt_errstr(status));
1893 goto out;
1897 DBG_NOTICE("case_sensitive = %d, "
1898 "case_preserve = %d, short case preserve = %d, "
1899 "directory = %s, newname = %s, "
1900 "last_component_dest = %s\n",
1901 case_sensitive, case_preserve,
1902 short_case_preserve,
1903 smb_fname_str_dbg(smb_fname_src),
1904 smb_fname_str_dbg(smb_fname_dst),
1905 dst_original_lcomp);
1907 ZERO_STRUCT(smb_fname_src->st);
1909 status = openat_pathref_fsp(conn->cwd_fsp, smb_fname_src);
1910 if (!NT_STATUS_IS_OK(status)) {
1911 if (!NT_STATUS_EQUAL(status,
1912 NT_STATUS_OBJECT_NAME_NOT_FOUND)) {
1913 goto out;
1916 * Possible symlink src.
1918 if (!(smb_fname_src->flags & SMB_FILENAME_POSIX_PATH)) {
1919 goto out;
1921 if (!S_ISLNK(smb_fname_src->st.st_ex_mode)) {
1922 goto out;
1926 if (S_ISDIR(smb_fname_src->st.st_ex_mode)) {
1927 create_options |= FILE_DIRECTORY_FILE;
1930 status = SMB_VFS_CREATE_FILE(
1931 conn, /* conn */
1932 req, /* req */
1933 src_dirfsp, /* dirfsp */
1934 smb_fname_src, /* fname */
1935 access_mask, /* access_mask */
1936 (FILE_SHARE_READ | /* share_access */
1937 FILE_SHARE_WRITE),
1938 FILE_OPEN, /* create_disposition*/
1939 create_options, /* create_options */
1940 0, /* file_attributes */
1941 0, /* oplock_request */
1942 NULL, /* lease */
1943 0, /* allocation_size */
1944 0, /* private_flags */
1945 NULL, /* sd */
1946 NULL, /* ea_list */
1947 &fsp, /* result */
1948 NULL, /* pinfo */
1949 posx, /* in_context_blobs */
1950 NULL); /* out_context_blobs */
1952 if (!NT_STATUS_IS_OK(status)) {
1953 DBG_NOTICE("Could not open rename source %s: %s\n",
1954 smb_fname_str_dbg(smb_fname_src),
1955 nt_errstr(status));
1956 goto out;
1959 status = rename_internals_fsp(conn,
1960 fsp,
1961 dst_dirfsp,
1962 smb_fname_dst,
1963 dst_original_lcomp,
1964 attrs,
1965 replace_if_exists);
1967 close_file_free(req, &fsp, NORMAL_CLOSE);
1969 DBG_NOTICE("Error %s rename %s -> %s\n",
1970 nt_errstr(status), smb_fname_str_dbg(smb_fname_src),
1971 smb_fname_str_dbg(smb_fname_dst));
1973 out:
1974 TALLOC_FREE(posx);
1975 return status;
1978 /*******************************************************************
1979 Copy a file as part of a reply_copy.
1980 ******************************************************************/
1983 * TODO: check error codes on all callers
1986 NTSTATUS copy_file(TALLOC_CTX *ctx,
1987 connection_struct *conn,
1988 struct smb_filename *smb_fname_src,
1989 struct smb_filename *smb_fname_dst,
1990 uint32_t new_create_disposition)
1992 struct smb_filename *smb_fname_dst_tmp = NULL;
1993 off_t ret=-1;
1994 files_struct *fsp1,*fsp2;
1995 uint32_t dosattrs;
1996 NTSTATUS status;
1999 smb_fname_dst_tmp = cp_smb_filename(ctx, smb_fname_dst);
2000 if (smb_fname_dst_tmp == NULL) {
2001 return NT_STATUS_NO_MEMORY;
2004 status = vfs_file_exist(conn, smb_fname_src);
2005 if (!NT_STATUS_IS_OK(status)) {
2006 goto out;
2009 status = openat_pathref_fsp(conn->cwd_fsp, smb_fname_src);
2010 if (!NT_STATUS_IS_OK(status)) {
2011 goto out;
2014 /* Open the src file for reading. */
2015 status = SMB_VFS_CREATE_FILE(
2016 conn, /* conn */
2017 NULL, /* req */
2018 NULL, /* dirfsp */
2019 smb_fname_src, /* fname */
2020 FILE_GENERIC_READ, /* access_mask */
2021 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share_access */
2022 FILE_OPEN, /* create_disposition*/
2023 0, /* create_options */
2024 FILE_ATTRIBUTE_NORMAL, /* file_attributes */
2025 INTERNAL_OPEN_ONLY, /* oplock_request */
2026 NULL, /* lease */
2027 0, /* allocation_size */
2028 0, /* private_flags */
2029 NULL, /* sd */
2030 NULL, /* ea_list */
2031 &fsp1, /* result */
2032 NULL, /* psbuf */
2033 NULL, NULL); /* create context */
2035 if (!NT_STATUS_IS_OK(status)) {
2036 goto out;
2039 dosattrs = fdos_mode(fsp1);
2041 if (SMB_VFS_STAT(conn, smb_fname_dst_tmp) == -1) {
2042 ZERO_STRUCTP(&smb_fname_dst_tmp->st);
2045 status = openat_pathref_fsp(conn->cwd_fsp, smb_fname_dst);
2046 if (!NT_STATUS_IS_OK(status) &&
2047 !NT_STATUS_EQUAL(status, NT_STATUS_OBJECT_NAME_NOT_FOUND))
2049 goto out;
2052 /* Open the dst file for writing. */
2053 status = SMB_VFS_CREATE_FILE(
2054 conn, /* conn */
2055 NULL, /* req */
2056 NULL, /* dirfsp */
2057 smb_fname_dst, /* fname */
2058 FILE_GENERIC_WRITE, /* access_mask */
2059 FILE_SHARE_READ | FILE_SHARE_WRITE, /* share_access */
2060 new_create_disposition, /* create_disposition*/
2061 0, /* create_options */
2062 dosattrs, /* file_attributes */
2063 INTERNAL_OPEN_ONLY, /* oplock_request */
2064 NULL, /* lease */
2065 0, /* allocation_size */
2066 0, /* private_flags */
2067 NULL, /* sd */
2068 NULL, /* ea_list */
2069 &fsp2, /* result */
2070 NULL, /* psbuf */
2071 NULL, NULL); /* create context */
2073 if (!NT_STATUS_IS_OK(status)) {
2074 close_file_free(NULL, &fsp1, ERROR_CLOSE);
2075 goto out;
2078 /* Do the actual copy. */
2079 if (smb_fname_src->st.st_ex_size) {
2080 ret = vfs_transfer_file(fsp1, fsp2, smb_fname_src->st.st_ex_size);
2081 } else {
2082 ret = 0;
2085 close_file_free(NULL, &fsp1, NORMAL_CLOSE);
2087 /* Ensure the modtime is set correctly on the destination file. */
2088 set_close_write_time(fsp2, smb_fname_src->st.st_ex_mtime);
2091 * As we are opening fsp1 read-only we only expect
2092 * an error on close on fsp2 if we are out of space.
2093 * Thus we don't look at the error return from the
2094 * close of fsp1.
2096 status = close_file_free(NULL, &fsp2, NORMAL_CLOSE);
2098 if (!NT_STATUS_IS_OK(status)) {
2099 goto out;
2102 if (ret != (off_t)smb_fname_src->st.st_ex_size) {
2103 status = NT_STATUS_DISK_FULL;
2104 goto out;
2107 status = NT_STATUS_OK;
2109 out:
2110 TALLOC_FREE(smb_fname_dst_tmp);
2111 return status;
2114 /****************************************************************************
2115 Get a lock offset, dealing with large offset requests.
2116 ****************************************************************************/
2118 uint64_t get_lock_offset(const uint8_t *data, int data_offset,
2119 bool large_file_format)
2121 uint64_t offset = 0;
2123 if(!large_file_format) {
2124 offset = (uint64_t)IVAL(data,SMB_LKOFF_OFFSET(data_offset));
2125 } else {
2127 * No BVAL, this is reversed!
2129 offset = (((uint64_t) IVAL(data,SMB_LARGE_LKOFF_OFFSET_HIGH(data_offset))) << 32) |
2130 ((uint64_t) IVAL(data,SMB_LARGE_LKOFF_OFFSET_LOW(data_offset)));
2133 return offset;
2136 struct smbd_do_unlocking_state {
2137 struct files_struct *fsp;
2138 uint16_t num_ulocks;
2139 struct smbd_lock_element *ulocks;
2140 NTSTATUS status;
2143 static void smbd_do_unlocking_fn(
2144 struct share_mode_lock *lck,
2145 void *private_data)
2147 struct smbd_do_unlocking_state *state = private_data;
2148 struct files_struct *fsp = state->fsp;
2149 uint16_t i;
2151 for (i = 0; i < state->num_ulocks; i++) {
2152 struct smbd_lock_element *e = &state->ulocks[i];
2154 DBG_DEBUG("unlock start=%"PRIu64", len=%"PRIu64" for "
2155 "pid %"PRIu64", file %s\n",
2156 e->offset,
2157 e->count,
2158 e->smblctx,
2159 fsp_str_dbg(fsp));
2161 if (e->brltype != UNLOCK_LOCK) {
2162 /* this can only happen with SMB2 */
2163 state->status = NT_STATUS_INVALID_PARAMETER;
2164 return;
2167 state->status = do_unlock(
2168 fsp, e->smblctx, e->count, e->offset, e->lock_flav);
2170 DBG_DEBUG("do_unlock returned %s\n",
2171 nt_errstr(state->status));
2173 if (!NT_STATUS_IS_OK(state->status)) {
2174 return;
2178 share_mode_wakeup_waiters(fsp->file_id);
2181 NTSTATUS smbd_do_unlocking(struct smb_request *req,
2182 files_struct *fsp,
2183 uint16_t num_ulocks,
2184 struct smbd_lock_element *ulocks)
2186 struct smbd_do_unlocking_state state = {
2187 .fsp = fsp,
2188 .num_ulocks = num_ulocks,
2189 .ulocks = ulocks,
2191 NTSTATUS status;
2193 DBG_NOTICE("%s num_ulocks=%"PRIu16"\n", fsp_fnum_dbg(fsp), num_ulocks);
2195 status = share_mode_do_locked_vfs_allowed(
2196 fsp->file_id, smbd_do_unlocking_fn, &state);
2198 if (!NT_STATUS_IS_OK(status)) {
2199 DBG_DEBUG("share_mode_do_locked_vfs_allowed failed: %s\n",
2200 nt_errstr(status));
2201 return status;
2203 if (!NT_STATUS_IS_OK(state.status)) {
2204 DBG_DEBUG("smbd_do_unlocking_fn failed: %s\n",
2205 nt_errstr(status));
2206 return state.status;
2209 return NT_STATUS_OK;