1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * Copyright (C) 2016 Namjae Jeon <linkinjeon@kernel.org>
4 * Copyright (C) 2018 Samsung Electronics Co., Ltd.
7 #include <linux/inetdevice.h>
8 #include <net/addrconf.h>
9 #include <linux/syscalls.h>
10 #include <linux/namei.h>
11 #include <linux/statfs.h>
12 #include <linux/ethtool.h>
13 #include <linux/falloc.h>
14 #include <linux/mount.h>
15 #include <linux/filelock.h>
24 #include "connection.h"
25 #include "transport_ipc.h"
26 #include "transport_rdma.h"
28 #include "vfs_cache.h"
32 #include "smb_common.h"
33 #include "smbstatus.h"
34 #include "ksmbd_work.h"
35 #include "mgmt/user_config.h"
36 #include "mgmt/share_config.h"
37 #include "mgmt/tree_connect.h"
38 #include "mgmt/user_session.h"
39 #include "mgmt/ksmbd_ida.h"
42 static void __wbuf(struct ksmbd_work *work, void **req, void **rsp)
44 if (work->next_smb2_rcv_hdr_off) {
45 *req = ksmbd_req_buf_next(work);
46 *rsp = ksmbd_resp_buf_next(work);
48 *req = smb2_get_msg(work->request_buf);
49 *rsp = smb2_get_msg(work->response_buf);
53 #define WORK_BUFFERS(w, rq, rs) __wbuf((w), (void **)&(rq), (void **)&(rs))
56 * check_session_id() - check for valid session id in smb header
57 * @conn: connection instance
58 * @id: session id from smb header
60 * Return: 1 if valid session id, otherwise 0
62 static inline bool check_session_id(struct ksmbd_conn *conn, u64 id)
64 struct ksmbd_session *sess;
66 if (id == 0 || id == -1)
69 sess = ksmbd_session_lookup_all(conn, id);
72 pr_err("Invalid user session id: %llu\n", id);
76 struct channel *lookup_chann_list(struct ksmbd_session *sess, struct ksmbd_conn *conn)
78 return xa_load(&sess->ksmbd_chann_list, (long)conn);
82 * smb2_get_ksmbd_tcon() - get tree connection information using a tree id.
85 * Return: 0 if there is a tree connection matched or these are
86 * skipable commands, otherwise error
88 int smb2_get_ksmbd_tcon(struct ksmbd_work *work)
90 struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
91 unsigned int cmd = le16_to_cpu(req_hdr->Command);
94 if (cmd == SMB2_TREE_CONNECT_HE ||
95 cmd == SMB2_CANCEL_HE ||
96 cmd == SMB2_LOGOFF_HE) {
97 ksmbd_debug(SMB, "skip to check tree connect request\n");
101 if (xa_empty(&work->sess->tree_conns)) {
102 ksmbd_debug(SMB, "NO tree connected\n");
106 tree_id = le32_to_cpu(req_hdr->Id.SyncId.TreeId);
109 * If request is not the first in Compound request,
110 * Just validate tree id in header with work->tcon->id.
112 if (work->next_smb2_rcv_hdr_off) {
114 pr_err("The first operation in the compound does not have tcon\n");
117 if (tree_id != UINT_MAX && work->tcon->id != tree_id) {
118 pr_err("tree id(%u) is different with id(%u) in first operation\n",
119 tree_id, work->tcon->id);
125 work->tcon = ksmbd_tree_conn_lookup(work->sess, tree_id);
127 pr_err("Invalid tid %d\n", tree_id);
135 * smb2_set_err_rsp() - set error response code on smb response
136 * @work: smb work containing response buffer
138 void smb2_set_err_rsp(struct ksmbd_work *work)
140 struct smb2_err_rsp *err_rsp;
142 if (work->next_smb2_rcv_hdr_off)
143 err_rsp = ksmbd_resp_buf_next(work);
145 err_rsp = smb2_get_msg(work->response_buf);
147 if (err_rsp->hdr.Status != STATUS_STOPPED_ON_SYMLINK) {
150 err_rsp->StructureSize = SMB2_ERROR_STRUCTURE_SIZE2_LE;
151 err_rsp->ErrorContextCount = 0;
152 err_rsp->Reserved = 0;
153 err_rsp->ByteCount = 0;
154 err_rsp->ErrorData[0] = 0;
155 err = ksmbd_iov_pin_rsp(work, (void *)err_rsp,
156 __SMB2_HEADER_STRUCTURE_SIZE +
157 SMB2_ERROR_STRUCTURE_SIZE2);
159 work->send_no_response = 1;
164 * is_smb2_neg_cmd() - is it smb2 negotiation command
165 * @work: smb work containing smb header
167 * Return: true if smb2 negotiation command, otherwise false
169 bool is_smb2_neg_cmd(struct ksmbd_work *work)
171 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
173 /* is it SMB2 header ? */
174 if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
177 /* make sure it is request not response message */
178 if (hdr->Flags & SMB2_FLAGS_SERVER_TO_REDIR)
181 if (hdr->Command != SMB2_NEGOTIATE)
188 * is_smb2_rsp() - is it smb2 response
189 * @work: smb work containing smb response buffer
191 * Return: true if smb2 response, otherwise false
193 bool is_smb2_rsp(struct ksmbd_work *work)
195 struct smb2_hdr *hdr = smb2_get_msg(work->response_buf);
197 /* is it SMB2 header ? */
198 if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
201 /* make sure it is response not request message */
202 if (!(hdr->Flags & SMB2_FLAGS_SERVER_TO_REDIR))
209 * get_smb2_cmd_val() - get smb command code from smb header
210 * @work: smb work containing smb request buffer
212 * Return: smb2 request command value
214 u16 get_smb2_cmd_val(struct ksmbd_work *work)
216 struct smb2_hdr *rcv_hdr;
218 if (work->next_smb2_rcv_hdr_off)
219 rcv_hdr = ksmbd_req_buf_next(work);
221 rcv_hdr = smb2_get_msg(work->request_buf);
222 return le16_to_cpu(rcv_hdr->Command);
226 * set_smb2_rsp_status() - set error response code on smb2 header
227 * @work: smb work containing response buffer
228 * @err: error response code
230 void set_smb2_rsp_status(struct ksmbd_work *work, __le32 err)
232 struct smb2_hdr *rsp_hdr;
234 rsp_hdr = smb2_get_msg(work->response_buf);
235 rsp_hdr->Status = err;
239 work->next_smb2_rcv_hdr_off = 0;
240 smb2_set_err_rsp(work);
244 * init_smb2_neg_rsp() - initialize smb2 response for negotiate command
245 * @work: smb work containing smb request buffer
247 * smb2 negotiate response is sent in reply of smb1 negotiate command for
248 * dialect auto-negotiation.
250 int init_smb2_neg_rsp(struct ksmbd_work *work)
252 struct smb2_hdr *rsp_hdr;
253 struct smb2_negotiate_rsp *rsp;
254 struct ksmbd_conn *conn = work->conn;
257 rsp_hdr = smb2_get_msg(work->response_buf);
258 memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
259 rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
260 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
261 rsp_hdr->CreditRequest = cpu_to_le16(2);
262 rsp_hdr->Command = SMB2_NEGOTIATE;
263 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
264 rsp_hdr->NextCommand = 0;
265 rsp_hdr->MessageId = 0;
266 rsp_hdr->Id.SyncId.ProcessId = 0;
267 rsp_hdr->Id.SyncId.TreeId = 0;
268 rsp_hdr->SessionId = 0;
269 memset(rsp_hdr->Signature, 0, 16);
271 rsp = smb2_get_msg(work->response_buf);
273 WARN_ON(ksmbd_conn_good(conn));
275 rsp->StructureSize = cpu_to_le16(65);
276 ksmbd_debug(SMB, "conn->dialect 0x%x\n", conn->dialect);
277 rsp->DialectRevision = cpu_to_le16(conn->dialect);
278 /* Not setting conn guid rsp->ServerGUID, as it
279 * not used by client for identifying connection
281 rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
282 /* Default Max Message Size till SMB2.0, 64K*/
283 rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
284 rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
285 rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);
287 rsp->SystemTime = cpu_to_le64(ksmbd_systime());
288 rsp->ServerStartTime = 0;
290 rsp->SecurityBufferOffset = cpu_to_le16(128);
291 rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
292 ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) +
293 le16_to_cpu(rsp->SecurityBufferOffset));
294 rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
295 if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY)
296 rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
297 err = ksmbd_iov_pin_rsp(work, rsp,
298 sizeof(struct smb2_negotiate_rsp) + AUTH_GSS_LENGTH);
301 conn->use_spnego = true;
303 ksmbd_conn_set_need_negotiate(conn);
308 * smb2_set_rsp_credits() - set number of credits in response buffer
309 * @work: smb work containing smb response buffer
311 int smb2_set_rsp_credits(struct ksmbd_work *work)
313 struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
314 struct smb2_hdr *hdr = ksmbd_resp_buf_next(work);
315 struct ksmbd_conn *conn = work->conn;
316 unsigned short credits_requested, aux_max;
317 unsigned short credit_charge, credits_granted = 0;
319 if (work->send_no_response)
322 hdr->CreditCharge = req_hdr->CreditCharge;
324 if (conn->total_credits > conn->vals->max_credits) {
325 hdr->CreditRequest = 0;
326 pr_err("Total credits overflow: %d\n", conn->total_credits);
330 credit_charge = max_t(unsigned short,
331 le16_to_cpu(req_hdr->CreditCharge), 1);
332 if (credit_charge > conn->total_credits) {
333 ksmbd_debug(SMB, "Insufficient credits granted, given: %u, granted: %u\n",
334 credit_charge, conn->total_credits);
338 conn->total_credits -= credit_charge;
339 conn->outstanding_credits -= credit_charge;
340 credits_requested = max_t(unsigned short,
341 le16_to_cpu(req_hdr->CreditRequest), 1);
343 /* according to smb2.credits smbtorture, Windows server
344 * 2016 or later grant up to 8192 credits at once.
346 * TODO: Need to adjuct CreditRequest value according to
349 if (hdr->Command == SMB2_NEGOTIATE)
352 aux_max = conn->vals->max_credits - conn->total_credits;
353 credits_granted = min_t(unsigned short, credits_requested, aux_max);
355 conn->total_credits += credits_granted;
356 work->credits_granted += credits_granted;
358 if (!req_hdr->NextCommand) {
359 /* Update CreditRequest in last request */
360 hdr->CreditRequest = cpu_to_le16(work->credits_granted);
363 "credits: requested[%d] granted[%d] total_granted[%d]\n",
364 credits_requested, credits_granted,
365 conn->total_credits);
370 * init_chained_smb2_rsp() - initialize smb2 chained response
371 * @work: smb work containing smb response buffer
373 static void init_chained_smb2_rsp(struct ksmbd_work *work)
375 struct smb2_hdr *req = ksmbd_req_buf_next(work);
376 struct smb2_hdr *rsp = ksmbd_resp_buf_next(work);
377 struct smb2_hdr *rsp_hdr;
378 struct smb2_hdr *rcv_hdr;
379 int next_hdr_offset = 0;
382 /* Len of this response = updated RFC len - offset of previous cmd
383 * in the compound rsp
386 /* Storing the current local FID which may be needed by subsequent
387 * command in the compound request
389 if (req->Command == SMB2_CREATE && rsp->Status == STATUS_SUCCESS) {
390 work->compound_fid = ((struct smb2_create_rsp *)rsp)->VolatileFileId;
391 work->compound_pfid = ((struct smb2_create_rsp *)rsp)->PersistentFileId;
392 work->compound_sid = le64_to_cpu(rsp->SessionId);
395 len = get_rfc1002_len(work->response_buf) - work->next_smb2_rsp_hdr_off;
396 next_hdr_offset = le32_to_cpu(req->NextCommand);
398 new_len = ALIGN(len, 8);
399 work->iov[work->iov_idx].iov_len += (new_len - len);
400 inc_rfc1001_len(work->response_buf, new_len - len);
401 rsp->NextCommand = cpu_to_le32(new_len);
403 work->next_smb2_rcv_hdr_off += next_hdr_offset;
404 work->curr_smb2_rsp_hdr_off = work->next_smb2_rsp_hdr_off;
405 work->next_smb2_rsp_hdr_off += new_len;
407 "Compound req new_len = %d rcv off = %d rsp off = %d\n",
408 new_len, work->next_smb2_rcv_hdr_off,
409 work->next_smb2_rsp_hdr_off);
411 rsp_hdr = ksmbd_resp_buf_next(work);
412 rcv_hdr = ksmbd_req_buf_next(work);
414 if (!(rcv_hdr->Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
415 ksmbd_debug(SMB, "related flag should be set\n");
416 work->compound_fid = KSMBD_NO_FID;
417 work->compound_pfid = KSMBD_NO_FID;
419 memset((char *)rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
420 rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
421 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
422 rsp_hdr->Command = rcv_hdr->Command;
425 * Message is response. We don't grant oplock yet.
427 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR |
428 SMB2_FLAGS_RELATED_OPERATIONS);
429 rsp_hdr->NextCommand = 0;
430 rsp_hdr->MessageId = rcv_hdr->MessageId;
431 rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
432 rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
433 rsp_hdr->SessionId = rcv_hdr->SessionId;
434 memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);
438 * is_chained_smb2_message() - check for chained command
439 * @work: smb work containing smb request buffer
441 * Return: true if chained request, otherwise false
443 bool is_chained_smb2_message(struct ksmbd_work *work)
445 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
446 unsigned int len, next_cmd;
448 if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
451 hdr = ksmbd_req_buf_next(work);
452 next_cmd = le32_to_cpu(hdr->NextCommand);
454 if ((u64)work->next_smb2_rcv_hdr_off + next_cmd +
455 __SMB2_HEADER_STRUCTURE_SIZE >
456 get_rfc1002_len(work->request_buf)) {
457 pr_err("next command(%u) offset exceeds smb msg size\n",
462 if ((u64)get_rfc1002_len(work->response_buf) + MAX_CIFS_SMALL_BUFFER_SIZE >
464 pr_err("next response offset exceeds response buffer size\n");
468 ksmbd_debug(SMB, "got SMB2 chained command\n");
469 init_chained_smb2_rsp(work);
471 } else if (work->next_smb2_rcv_hdr_off) {
473 * This is last request in chained command,
474 * align response to 8 byte
476 len = ALIGN(get_rfc1002_len(work->response_buf), 8);
477 len = len - get_rfc1002_len(work->response_buf);
479 ksmbd_debug(SMB, "padding len %u\n", len);
480 work->iov[work->iov_idx].iov_len += len;
481 inc_rfc1001_len(work->response_buf, len);
483 work->curr_smb2_rsp_hdr_off = work->next_smb2_rsp_hdr_off;
489 * init_smb2_rsp_hdr() - initialize smb2 response
490 * @work: smb work containing smb request buffer
494 int init_smb2_rsp_hdr(struct ksmbd_work *work)
496 struct smb2_hdr *rsp_hdr = smb2_get_msg(work->response_buf);
497 struct smb2_hdr *rcv_hdr = smb2_get_msg(work->request_buf);
499 memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
500 rsp_hdr->ProtocolId = rcv_hdr->ProtocolId;
501 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
502 rsp_hdr->Command = rcv_hdr->Command;
505 * Message is response. We don't grant oplock yet.
507 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
508 rsp_hdr->NextCommand = 0;
509 rsp_hdr->MessageId = rcv_hdr->MessageId;
510 rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
511 rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
512 rsp_hdr->SessionId = rcv_hdr->SessionId;
513 memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);
519 * smb2_allocate_rsp_buf() - allocate smb2 response buffer
520 * @work: smb work containing smb request buffer
522 * Return: 0 on success, otherwise -ENOMEM
524 int smb2_allocate_rsp_buf(struct ksmbd_work *work)
526 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
527 size_t small_sz = MAX_CIFS_SMALL_BUFFER_SIZE;
528 size_t large_sz = small_sz + work->conn->vals->max_trans_size;
529 size_t sz = small_sz;
530 int cmd = le16_to_cpu(hdr->Command);
532 if (cmd == SMB2_IOCTL_HE || cmd == SMB2_QUERY_DIRECTORY_HE)
535 if (cmd == SMB2_QUERY_INFO_HE) {
536 struct smb2_query_info_req *req;
538 req = smb2_get_msg(work->request_buf);
539 if ((req->InfoType == SMB2_O_INFO_FILE &&
540 (req->FileInfoClass == FILE_FULL_EA_INFORMATION ||
541 req->FileInfoClass == FILE_ALL_INFORMATION)) ||
542 req->InfoType == SMB2_O_INFO_SECURITY)
546 /* allocate large response buf for chained commands */
547 if (le32_to_cpu(hdr->NextCommand) > 0)
550 work->response_buf = kvzalloc(sz, GFP_KERNEL);
551 if (!work->response_buf)
554 work->response_sz = sz;
559 * smb2_check_user_session() - check for valid session for a user
560 * @work: smb work containing smb request buffer
562 * Return: 0 on success, otherwise error
564 int smb2_check_user_session(struct ksmbd_work *work)
566 struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
567 struct ksmbd_conn *conn = work->conn;
568 unsigned int cmd = le16_to_cpu(req_hdr->Command);
569 unsigned long long sess_id;
572 * SMB2_ECHO, SMB2_NEGOTIATE, SMB2_SESSION_SETUP command do not
573 * require a session id, so no need to validate user session's for
576 if (cmd == SMB2_ECHO_HE || cmd == SMB2_NEGOTIATE_HE ||
577 cmd == SMB2_SESSION_SETUP_HE)
580 if (!ksmbd_conn_good(conn))
583 sess_id = le64_to_cpu(req_hdr->SessionId);
586 * If request is not the first in Compound request,
587 * Just validate session id in header with work->sess->id.
589 if (work->next_smb2_rcv_hdr_off) {
591 pr_err("The first operation in the compound does not have sess\n");
594 if (sess_id != ULLONG_MAX && work->sess->id != sess_id) {
595 pr_err("session id(%llu) is different with the first operation(%lld)\n",
596 sess_id, work->sess->id);
602 /* Check for validity of user session */
603 work->sess = ksmbd_session_lookup_all(conn, sess_id);
606 ksmbd_debug(SMB, "Invalid user session, Uid %llu\n", sess_id);
611 * smb2_get_name() - get filename string from on the wire smb format
612 * @src: source buffer
613 * @maxlen: maxlen of source string
614 * @local_nls: nls_table pointer
616 * Return: matching converted filename on success, otherwise error ptr
619 smb2_get_name(const char *src, const int maxlen, struct nls_table *local_nls)
623 name = smb_strndup_from_utf16(src, maxlen, 1, local_nls);
625 pr_err("failed to get name %ld\n", PTR_ERR(name));
629 ksmbd_conv_path_to_unix(name);
630 ksmbd_strip_last_slash(name);
634 int setup_async_work(struct ksmbd_work *work, void (*fn)(void **), void **arg)
636 struct ksmbd_conn *conn = work->conn;
639 id = ksmbd_acquire_async_msg_id(&conn->async_ida);
641 pr_err("Failed to alloc async message id\n");
644 work->asynchronous = true;
648 "Send interim Response to inform async request id : %d\n",
651 work->cancel_fn = fn;
652 work->cancel_argv = arg;
654 if (list_empty(&work->async_request_entry)) {
655 spin_lock(&conn->request_lock);
656 list_add_tail(&work->async_request_entry, &conn->async_requests);
657 spin_unlock(&conn->request_lock);
663 void release_async_work(struct ksmbd_work *work)
665 struct ksmbd_conn *conn = work->conn;
667 spin_lock(&conn->request_lock);
668 list_del_init(&work->async_request_entry);
669 spin_unlock(&conn->request_lock);
671 work->asynchronous = 0;
672 work->cancel_fn = NULL;
673 kfree(work->cancel_argv);
674 work->cancel_argv = NULL;
675 if (work->async_id) {
676 ksmbd_release_id(&conn->async_ida, work->async_id);
681 void smb2_send_interim_resp(struct ksmbd_work *work, __le32 status)
683 struct smb2_hdr *rsp_hdr;
684 struct ksmbd_work *in_work = ksmbd_alloc_work_struct();
686 if (allocate_interim_rsp_buf(in_work)) {
687 pr_err("smb_allocate_rsp_buf failed!\n");
688 ksmbd_free_work_struct(in_work);
692 in_work->conn = work->conn;
693 memcpy(smb2_get_msg(in_work->response_buf), ksmbd_resp_buf_next(work),
694 __SMB2_HEADER_STRUCTURE_SIZE);
696 rsp_hdr = smb2_get_msg(in_work->response_buf);
697 rsp_hdr->Flags |= SMB2_FLAGS_ASYNC_COMMAND;
698 rsp_hdr->Id.AsyncId = cpu_to_le64(work->async_id);
699 smb2_set_err_rsp(in_work);
700 rsp_hdr->Status = status;
702 ksmbd_conn_write(in_work);
703 ksmbd_free_work_struct(in_work);
706 static __le32 smb2_get_reparse_tag_special_file(umode_t mode)
708 if (S_ISDIR(mode) || S_ISREG(mode))
712 return IO_REPARSE_TAG_LX_SYMLINK_LE;
713 else if (S_ISFIFO(mode))
714 return IO_REPARSE_TAG_LX_FIFO_LE;
715 else if (S_ISSOCK(mode))
716 return IO_REPARSE_TAG_AF_UNIX_LE;
717 else if (S_ISCHR(mode))
718 return IO_REPARSE_TAG_LX_CHR_LE;
719 else if (S_ISBLK(mode))
720 return IO_REPARSE_TAG_LX_BLK_LE;
726 * smb2_get_dos_mode() - get file mode in dos format from unix mode
727 * @stat: kstat containing file mode
728 * @attribute: attribute flags
730 * Return: converted dos mode
732 static int smb2_get_dos_mode(struct kstat *stat, int attribute)
736 if (S_ISDIR(stat->mode)) {
737 attr = FILE_ATTRIBUTE_DIRECTORY |
738 (attribute & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM));
740 attr = (attribute & 0x00005137) | FILE_ATTRIBUTE_ARCHIVE;
741 attr &= ~(FILE_ATTRIBUTE_DIRECTORY);
742 if (S_ISREG(stat->mode) && (server_conf.share_fake_fscaps &
743 FILE_SUPPORTS_SPARSE_FILES))
744 attr |= FILE_ATTRIBUTE_SPARSE_FILE;
746 if (smb2_get_reparse_tag_special_file(stat->mode))
747 attr |= FILE_ATTRIBUTE_REPARSE_POINT;
753 static void build_preauth_ctxt(struct smb2_preauth_neg_context *pneg_ctxt,
756 pneg_ctxt->ContextType = SMB2_PREAUTH_INTEGRITY_CAPABILITIES;
757 pneg_ctxt->DataLength = cpu_to_le16(38);
758 pneg_ctxt->HashAlgorithmCount = cpu_to_le16(1);
759 pneg_ctxt->Reserved = cpu_to_le32(0);
760 pneg_ctxt->SaltLength = cpu_to_le16(SMB311_SALT_SIZE);
761 get_random_bytes(pneg_ctxt->Salt, SMB311_SALT_SIZE);
762 pneg_ctxt->HashAlgorithms = hash_id;
765 static void build_encrypt_ctxt(struct smb2_encryption_neg_context *pneg_ctxt,
768 pneg_ctxt->ContextType = SMB2_ENCRYPTION_CAPABILITIES;
769 pneg_ctxt->DataLength = cpu_to_le16(4);
770 pneg_ctxt->Reserved = cpu_to_le32(0);
771 pneg_ctxt->CipherCount = cpu_to_le16(1);
772 pneg_ctxt->Ciphers[0] = cipher_type;
775 static void build_sign_cap_ctxt(struct smb2_signing_capabilities *pneg_ctxt,
778 pneg_ctxt->ContextType = SMB2_SIGNING_CAPABILITIES;
779 pneg_ctxt->DataLength =
780 cpu_to_le16((sizeof(struct smb2_signing_capabilities) + 2)
781 - sizeof(struct smb2_neg_context));
782 pneg_ctxt->Reserved = cpu_to_le32(0);
783 pneg_ctxt->SigningAlgorithmCount = cpu_to_le16(1);
784 pneg_ctxt->SigningAlgorithms[0] = sign_algo;
787 static void build_posix_ctxt(struct smb2_posix_neg_context *pneg_ctxt)
789 pneg_ctxt->ContextType = SMB2_POSIX_EXTENSIONS_AVAILABLE;
790 pneg_ctxt->DataLength = cpu_to_le16(POSIX_CTXT_DATA_LEN);
791 /* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */
792 pneg_ctxt->Name[0] = 0x93;
793 pneg_ctxt->Name[1] = 0xAD;
794 pneg_ctxt->Name[2] = 0x25;
795 pneg_ctxt->Name[3] = 0x50;
796 pneg_ctxt->Name[4] = 0x9C;
797 pneg_ctxt->Name[5] = 0xB4;
798 pneg_ctxt->Name[6] = 0x11;
799 pneg_ctxt->Name[7] = 0xE7;
800 pneg_ctxt->Name[8] = 0xB4;
801 pneg_ctxt->Name[9] = 0x23;
802 pneg_ctxt->Name[10] = 0x83;
803 pneg_ctxt->Name[11] = 0xDE;
804 pneg_ctxt->Name[12] = 0x96;
805 pneg_ctxt->Name[13] = 0x8B;
806 pneg_ctxt->Name[14] = 0xCD;
807 pneg_ctxt->Name[15] = 0x7C;
810 static unsigned int assemble_neg_contexts(struct ksmbd_conn *conn,
811 struct smb2_negotiate_rsp *rsp)
813 char * const pneg_ctxt = (char *)rsp +
814 le32_to_cpu(rsp->NegotiateContextOffset);
815 int neg_ctxt_cnt = 1;
819 "assemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
820 build_preauth_ctxt((struct smb2_preauth_neg_context *)pneg_ctxt,
821 conn->preauth_info->Preauth_HashId);
822 ctxt_size = sizeof(struct smb2_preauth_neg_context);
824 if (conn->cipher_type) {
825 /* Round to 8 byte boundary */
826 ctxt_size = round_up(ctxt_size, 8);
828 "assemble SMB2_ENCRYPTION_CAPABILITIES context\n");
829 build_encrypt_ctxt((struct smb2_encryption_neg_context *)
830 (pneg_ctxt + ctxt_size),
833 ctxt_size += sizeof(struct smb2_encryption_neg_context) + 2;
836 /* compression context not yet supported */
837 WARN_ON(conn->compress_algorithm != SMB3_COMPRESS_NONE);
839 if (conn->posix_ext_supported) {
840 ctxt_size = round_up(ctxt_size, 8);
842 "assemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
843 build_posix_ctxt((struct smb2_posix_neg_context *)
844 (pneg_ctxt + ctxt_size));
846 ctxt_size += sizeof(struct smb2_posix_neg_context);
849 if (conn->signing_negotiated) {
850 ctxt_size = round_up(ctxt_size, 8);
852 "assemble SMB2_SIGNING_CAPABILITIES context\n");
853 build_sign_cap_ctxt((struct smb2_signing_capabilities *)
854 (pneg_ctxt + ctxt_size),
855 conn->signing_algorithm);
857 ctxt_size += sizeof(struct smb2_signing_capabilities) + 2;
860 rsp->NegotiateContextCount = cpu_to_le16(neg_ctxt_cnt);
861 return ctxt_size + AUTH_GSS_PADDING;
864 static __le32 decode_preauth_ctxt(struct ksmbd_conn *conn,
865 struct smb2_preauth_neg_context *pneg_ctxt,
869 * sizeof(smb2_preauth_neg_context) assumes SMB311_SALT_SIZE Salt,
870 * which may not be present. Only check for used HashAlgorithms[1].
873 sizeof(struct smb2_neg_context) + MIN_PREAUTH_CTXT_DATA_LEN)
874 return STATUS_INVALID_PARAMETER;
876 if (pneg_ctxt->HashAlgorithms != SMB2_PREAUTH_INTEGRITY_SHA512)
877 return STATUS_NO_PREAUTH_INTEGRITY_HASH_OVERLAP;
879 conn->preauth_info->Preauth_HashId = SMB2_PREAUTH_INTEGRITY_SHA512;
880 return STATUS_SUCCESS;
883 static void decode_encrypt_ctxt(struct ksmbd_conn *conn,
884 struct smb2_encryption_neg_context *pneg_ctxt,
890 if (sizeof(struct smb2_encryption_neg_context) > ctxt_len) {
891 pr_err("Invalid SMB2_ENCRYPTION_CAPABILITIES context size\n");
895 conn->cipher_type = 0;
897 cph_cnt = le16_to_cpu(pneg_ctxt->CipherCount);
898 cphs_size = cph_cnt * sizeof(__le16);
900 if (sizeof(struct smb2_encryption_neg_context) + cphs_size >
902 pr_err("Invalid cipher count(%d)\n", cph_cnt);
906 if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION_OFF)
909 for (i = 0; i < cph_cnt; i++) {
910 if (pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_GCM ||
911 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_CCM ||
912 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_CCM ||
913 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_GCM) {
914 ksmbd_debug(SMB, "Cipher ID = 0x%x\n",
915 pneg_ctxt->Ciphers[i]);
916 conn->cipher_type = pneg_ctxt->Ciphers[i];
923 * smb3_encryption_negotiated() - checks if server and client agreed on enabling encryption
924 * @conn: smb connection
926 * Return: true if connection should be encrypted, else false
928 bool smb3_encryption_negotiated(struct ksmbd_conn *conn)
930 if (!conn->ops->generate_encryptionkey)
934 * SMB 3.0 and 3.0.2 dialects use the SMB2_GLOBAL_CAP_ENCRYPTION flag.
935 * SMB 3.1.1 uses the cipher_type field.
937 return (conn->vals->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION) ||
941 static void decode_compress_ctxt(struct ksmbd_conn *conn,
942 struct smb2_compression_capabilities_context *pneg_ctxt)
944 conn->compress_algorithm = SMB3_COMPRESS_NONE;
947 static void decode_sign_cap_ctxt(struct ksmbd_conn *conn,
948 struct smb2_signing_capabilities *pneg_ctxt,
952 int i, sign_alos_size;
954 if (sizeof(struct smb2_signing_capabilities) > ctxt_len) {
955 pr_err("Invalid SMB2_SIGNING_CAPABILITIES context length\n");
959 conn->signing_negotiated = false;
960 sign_algo_cnt = le16_to_cpu(pneg_ctxt->SigningAlgorithmCount);
961 sign_alos_size = sign_algo_cnt * sizeof(__le16);
963 if (sizeof(struct smb2_signing_capabilities) + sign_alos_size >
965 pr_err("Invalid signing algorithm count(%d)\n", sign_algo_cnt);
969 for (i = 0; i < sign_algo_cnt; i++) {
970 if (pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_HMAC_SHA256_LE ||
971 pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_AES_CMAC_LE) {
972 ksmbd_debug(SMB, "Signing Algorithm ID = 0x%x\n",
973 pneg_ctxt->SigningAlgorithms[i]);
974 conn->signing_negotiated = true;
975 conn->signing_algorithm =
976 pneg_ctxt->SigningAlgorithms[i];
982 static __le32 deassemble_neg_contexts(struct ksmbd_conn *conn,
983 struct smb2_negotiate_req *req,
984 unsigned int len_of_smb)
986 /* +4 is to account for the RFC1001 len field */
987 struct smb2_neg_context *pctx = (struct smb2_neg_context *)req;
988 int i = 0, len_of_ctxts;
989 unsigned int offset = le32_to_cpu(req->NegotiateContextOffset);
990 unsigned int neg_ctxt_cnt = le16_to_cpu(req->NegotiateContextCount);
991 __le32 status = STATUS_INVALID_PARAMETER;
993 ksmbd_debug(SMB, "decoding %d negotiate contexts\n", neg_ctxt_cnt);
994 if (len_of_smb <= offset) {
995 ksmbd_debug(SMB, "Invalid response: negotiate context offset\n");
999 len_of_ctxts = len_of_smb - offset;
1001 while (i++ < neg_ctxt_cnt) {
1004 if (len_of_ctxts < (int)sizeof(struct smb2_neg_context))
1007 pctx = (struct smb2_neg_context *)((char *)pctx + offset);
1008 clen = le16_to_cpu(pctx->DataLength);
1009 ctxt_len = clen + sizeof(struct smb2_neg_context);
1011 if (ctxt_len > len_of_ctxts)
1014 if (pctx->ContextType == SMB2_PREAUTH_INTEGRITY_CAPABILITIES) {
1016 "deassemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
1017 if (conn->preauth_info->Preauth_HashId)
1020 status = decode_preauth_ctxt(conn,
1021 (struct smb2_preauth_neg_context *)pctx,
1023 if (status != STATUS_SUCCESS)
1025 } else if (pctx->ContextType == SMB2_ENCRYPTION_CAPABILITIES) {
1027 "deassemble SMB2_ENCRYPTION_CAPABILITIES context\n");
1028 if (conn->cipher_type)
1031 decode_encrypt_ctxt(conn,
1032 (struct smb2_encryption_neg_context *)pctx,
1034 } else if (pctx->ContextType == SMB2_COMPRESSION_CAPABILITIES) {
1036 "deassemble SMB2_COMPRESSION_CAPABILITIES context\n");
1037 if (conn->compress_algorithm)
1040 decode_compress_ctxt(conn,
1041 (struct smb2_compression_capabilities_context *)pctx);
1042 } else if (pctx->ContextType == SMB2_NETNAME_NEGOTIATE_CONTEXT_ID) {
1044 "deassemble SMB2_NETNAME_NEGOTIATE_CONTEXT_ID context\n");
1045 } else if (pctx->ContextType == SMB2_POSIX_EXTENSIONS_AVAILABLE) {
1047 "deassemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
1048 conn->posix_ext_supported = true;
1049 } else if (pctx->ContextType == SMB2_SIGNING_CAPABILITIES) {
1051 "deassemble SMB2_SIGNING_CAPABILITIES context\n");
1053 decode_sign_cap_ctxt(conn,
1054 (struct smb2_signing_capabilities *)pctx,
1058 /* offsets must be 8 byte aligned */
1059 offset = (ctxt_len + 7) & ~0x7;
1060 len_of_ctxts -= offset;
1066 * smb2_handle_negotiate() - handler for smb2 negotiate command
1067 * @work: smb work containing smb request buffer
1071 int smb2_handle_negotiate(struct ksmbd_work *work)
1073 struct ksmbd_conn *conn = work->conn;
1074 struct smb2_negotiate_req *req = smb2_get_msg(work->request_buf);
1075 struct smb2_negotiate_rsp *rsp = smb2_get_msg(work->response_buf);
1077 unsigned int smb2_buf_len, smb2_neg_size, neg_ctxt_len = 0;
1080 ksmbd_debug(SMB, "Received negotiate request\n");
1081 conn->need_neg = false;
1082 if (ksmbd_conn_good(conn)) {
1083 pr_err("conn->tcp_status is already in CifsGood State\n");
1084 work->send_no_response = 1;
1088 smb2_buf_len = get_rfc1002_len(work->request_buf);
1089 smb2_neg_size = offsetof(struct smb2_negotiate_req, Dialects);
1090 if (smb2_neg_size > smb2_buf_len) {
1091 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1096 if (req->DialectCount == 0) {
1097 pr_err("malformed packet\n");
1098 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1103 if (conn->dialect == SMB311_PROT_ID) {
1104 unsigned int nego_ctxt_off = le32_to_cpu(req->NegotiateContextOffset);
1106 if (smb2_buf_len < nego_ctxt_off) {
1107 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1112 if (smb2_neg_size > nego_ctxt_off) {
1113 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1118 if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
1120 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1125 if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
1127 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1133 conn->cli_cap = le32_to_cpu(req->Capabilities);
1134 switch (conn->dialect) {
1135 case SMB311_PROT_ID:
1136 conn->preauth_info =
1137 kzalloc(sizeof(struct preauth_integrity_info),
1139 if (!conn->preauth_info) {
1141 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1145 status = deassemble_neg_contexts(conn, req,
1146 get_rfc1002_len(work->request_buf));
1147 if (status != STATUS_SUCCESS) {
1148 pr_err("deassemble_neg_contexts error(0x%x)\n",
1150 rsp->hdr.Status = status;
1152 kfree(conn->preauth_info);
1153 conn->preauth_info = NULL;
1157 rc = init_smb3_11_server(conn);
1159 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1160 kfree(conn->preauth_info);
1161 conn->preauth_info = NULL;
1165 ksmbd_gen_preauth_integrity_hash(conn,
1167 conn->preauth_info->Preauth_HashValue);
1168 rsp->NegotiateContextOffset =
1169 cpu_to_le32(OFFSET_OF_NEG_CONTEXT);
1170 neg_ctxt_len = assemble_neg_contexts(conn, rsp);
1172 case SMB302_PROT_ID:
1173 init_smb3_02_server(conn);
1176 init_smb3_0_server(conn);
1179 init_smb2_1_server(conn);
1184 ksmbd_debug(SMB, "Server dialect :0x%x not supported\n",
1186 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
1190 rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
1193 conn->connection_type = conn->dialect;
1195 rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
1196 rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
1197 rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);
1199 memcpy(conn->ClientGUID, req->ClientGUID,
1200 SMB2_CLIENT_GUID_SIZE);
1201 conn->cli_sec_mode = le16_to_cpu(req->SecurityMode);
1203 rsp->StructureSize = cpu_to_le16(65);
1204 rsp->DialectRevision = cpu_to_le16(conn->dialect);
1205 /* Not setting conn guid rsp->ServerGUID, as it
1206 * not used by client for identifying server
1208 memset(rsp->ServerGUID, 0, SMB2_CLIENT_GUID_SIZE);
1210 rsp->SystemTime = cpu_to_le64(ksmbd_systime());
1211 rsp->ServerStartTime = 0;
1212 ksmbd_debug(SMB, "negotiate context offset %d, count %d\n",
1213 le32_to_cpu(rsp->NegotiateContextOffset),
1214 le16_to_cpu(rsp->NegotiateContextCount));
1216 rsp->SecurityBufferOffset = cpu_to_le16(128);
1217 rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
1218 ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) +
1219 le16_to_cpu(rsp->SecurityBufferOffset));
1221 rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
1222 conn->use_spnego = true;
1224 if ((server_conf.signing == KSMBD_CONFIG_OPT_AUTO ||
1225 server_conf.signing == KSMBD_CONFIG_OPT_DISABLED) &&
1226 req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED_LE)
1228 else if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY) {
1229 server_conf.enforced_signing = true;
1230 rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
1234 conn->srv_sec_mode = le16_to_cpu(rsp->SecurityMode);
1235 ksmbd_conn_set_need_negotiate(conn);
1239 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
1242 rc = ksmbd_iov_pin_rsp(work, rsp,
1243 sizeof(struct smb2_negotiate_rsp) +
1244 AUTH_GSS_LENGTH + neg_ctxt_len);
1246 smb2_set_err_rsp(work);
1250 static int alloc_preauth_hash(struct ksmbd_session *sess,
1251 struct ksmbd_conn *conn)
1253 if (sess->Preauth_HashValue)
1256 sess->Preauth_HashValue = kmemdup(conn->preauth_info->Preauth_HashValue,
1257 PREAUTH_HASHVALUE_SIZE, GFP_KERNEL);
1258 if (!sess->Preauth_HashValue)
1264 static int generate_preauth_hash(struct ksmbd_work *work)
1266 struct ksmbd_conn *conn = work->conn;
1267 struct ksmbd_session *sess = work->sess;
1270 if (conn->dialect != SMB311_PROT_ID)
1273 if (conn->binding) {
1274 struct preauth_session *preauth_sess;
1276 preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
1277 if (!preauth_sess) {
1278 preauth_sess = ksmbd_preauth_session_alloc(conn, sess->id);
1283 preauth_hash = preauth_sess->Preauth_HashValue;
1285 if (!sess->Preauth_HashValue)
1286 if (alloc_preauth_hash(sess, conn))
1288 preauth_hash = sess->Preauth_HashValue;
1291 ksmbd_gen_preauth_integrity_hash(conn, work->request_buf, preauth_hash);
1295 static int decode_negotiation_token(struct ksmbd_conn *conn,
1296 struct negotiate_message *negblob,
1299 if (!conn->use_spnego)
1302 if (ksmbd_decode_negTokenInit((char *)negblob, sz, conn)) {
1303 if (ksmbd_decode_negTokenTarg((char *)negblob, sz, conn)) {
1304 conn->auth_mechs |= KSMBD_AUTH_NTLMSSP;
1305 conn->preferred_auth_mech = KSMBD_AUTH_NTLMSSP;
1306 conn->use_spnego = false;
1312 static int ntlm_negotiate(struct ksmbd_work *work,
1313 struct negotiate_message *negblob,
1314 size_t negblob_len, struct smb2_sess_setup_rsp *rsp)
1316 struct challenge_message *chgblob;
1317 unsigned char *spnego_blob = NULL;
1318 u16 spnego_blob_len;
1322 ksmbd_debug(SMB, "negotiate phase\n");
1323 rc = ksmbd_decode_ntlmssp_neg_blob(negblob, negblob_len, work->conn);
1327 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1329 (struct challenge_message *)((char *)&rsp->hdr.ProtocolId + sz);
1330 memset(chgblob, 0, sizeof(struct challenge_message));
1332 if (!work->conn->use_spnego) {
1333 sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
1337 rsp->SecurityBufferLength = cpu_to_le16(sz);
1341 sz = sizeof(struct challenge_message);
1342 sz += (strlen(ksmbd_netbios_name()) * 2 + 1 + 4) * 6;
1344 neg_blob = kzalloc(sz, GFP_KERNEL);
1348 chgblob = (struct challenge_message *)neg_blob;
1349 sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
1355 rc = build_spnego_ntlmssp_neg_blob(&spnego_blob, &spnego_blob_len,
1362 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1363 memcpy((char *)&rsp->hdr.ProtocolId + sz, spnego_blob, spnego_blob_len);
1364 rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
1372 static struct authenticate_message *user_authblob(struct ksmbd_conn *conn,
1373 struct smb2_sess_setup_req *req)
1377 if (conn->use_spnego && conn->mechToken)
1378 return (struct authenticate_message *)conn->mechToken;
1380 sz = le16_to_cpu(req->SecurityBufferOffset);
1381 return (struct authenticate_message *)((char *)&req->hdr.ProtocolId
1385 static struct ksmbd_user *session_user(struct ksmbd_conn *conn,
1386 struct smb2_sess_setup_req *req)
1388 struct authenticate_message *authblob;
1389 struct ksmbd_user *user;
1391 unsigned int name_off, name_len, secbuf_len;
1393 if (conn->use_spnego && conn->mechToken)
1394 secbuf_len = conn->mechTokenLen;
1396 secbuf_len = le16_to_cpu(req->SecurityBufferLength);
1397 if (secbuf_len < sizeof(struct authenticate_message)) {
1398 ksmbd_debug(SMB, "blob len %d too small\n", secbuf_len);
1401 authblob = user_authblob(conn, req);
1402 name_off = le32_to_cpu(authblob->UserName.BufferOffset);
1403 name_len = le16_to_cpu(authblob->UserName.Length);
1405 if (secbuf_len < (u64)name_off + name_len)
1408 name = smb_strndup_from_utf16((const char *)authblob + name_off,
1413 pr_err("cannot allocate memory\n");
1417 ksmbd_debug(SMB, "session setup request for user %s\n", name);
1418 user = ksmbd_login_user(name);
1423 static int ntlm_authenticate(struct ksmbd_work *work,
1424 struct smb2_sess_setup_req *req,
1425 struct smb2_sess_setup_rsp *rsp)
1427 struct ksmbd_conn *conn = work->conn;
1428 struct ksmbd_session *sess = work->sess;
1429 struct channel *chann = NULL;
1430 struct ksmbd_user *user;
1434 ksmbd_debug(SMB, "authenticate phase\n");
1435 if (conn->use_spnego) {
1436 unsigned char *spnego_blob;
1437 u16 spnego_blob_len;
1439 rc = build_spnego_ntlmssp_auth_blob(&spnego_blob,
1445 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1446 memcpy((char *)&rsp->hdr.ProtocolId + sz, spnego_blob, spnego_blob_len);
1447 rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
1451 user = session_user(conn, req);
1453 ksmbd_debug(SMB, "Unknown user name or an error\n");
1457 /* Check for previous session */
1458 prev_id = le64_to_cpu(req->PreviousSessionId);
1459 if (prev_id && prev_id != sess->id)
1460 destroy_previous_session(conn, user, prev_id);
1462 if (sess->state == SMB2_SESSION_VALID) {
1464 * Reuse session if anonymous try to connect
1465 * on reauthetication.
1467 if (conn->binding == false && ksmbd_anonymous_user(user)) {
1468 ksmbd_free_user(user);
1472 if (!ksmbd_compare_user(sess->user, user)) {
1473 ksmbd_free_user(user);
1476 ksmbd_free_user(user);
1481 if (conn->binding == false && user_guest(sess->user)) {
1482 rsp->SessionFlags = SMB2_SESSION_FLAG_IS_GUEST_LE;
1484 struct authenticate_message *authblob;
1486 authblob = user_authblob(conn, req);
1487 if (conn->use_spnego && conn->mechToken)
1488 sz = conn->mechTokenLen;
1490 sz = le16_to_cpu(req->SecurityBufferLength);
1491 rc = ksmbd_decode_ntlmssp_auth_blob(authblob, sz, conn, sess);
1493 set_user_flag(sess->user, KSMBD_USER_FLAG_BAD_PASSWORD);
1494 ksmbd_debug(SMB, "authentication failed\n");
1500 * If session state is SMB2_SESSION_VALID, We can assume
1501 * that it is reauthentication. And the user/password
1502 * has been verified, so return it here.
1504 if (sess->state == SMB2_SESSION_VALID) {
1506 goto binding_session;
1510 if ((rsp->SessionFlags != SMB2_SESSION_FLAG_IS_GUEST_LE &&
1511 (conn->sign || server_conf.enforced_signing)) ||
1512 (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
1515 if (smb3_encryption_negotiated(conn) &&
1516 !(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1517 rc = conn->ops->generate_encryptionkey(conn, sess);
1520 "SMB3 encryption key generation failed\n");
1524 if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION)
1525 rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
1527 * signing is disable if encryption is enable
1534 if (conn->dialect >= SMB30_PROT_ID) {
1535 chann = lookup_chann_list(sess, conn);
1537 chann = kmalloc(sizeof(struct channel), GFP_KERNEL);
1542 xa_store(&sess->ksmbd_chann_list, (long)conn, chann, GFP_KERNEL);
1546 if (conn->ops->generate_signingkey) {
1547 rc = conn->ops->generate_signingkey(sess, conn);
1549 ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
1554 if (!ksmbd_conn_lookup_dialect(conn)) {
1555 pr_err("fail to verify the dialect\n");
1561 #ifdef CONFIG_SMB_SERVER_KERBEROS5
1562 static int krb5_authenticate(struct ksmbd_work *work,
1563 struct smb2_sess_setup_req *req,
1564 struct smb2_sess_setup_rsp *rsp)
1566 struct ksmbd_conn *conn = work->conn;
1567 struct ksmbd_session *sess = work->sess;
1568 char *in_blob, *out_blob;
1569 struct channel *chann = NULL;
1571 int in_len, out_len;
1574 in_blob = (char *)&req->hdr.ProtocolId +
1575 le16_to_cpu(req->SecurityBufferOffset);
1576 in_len = le16_to_cpu(req->SecurityBufferLength);
1577 out_blob = (char *)&rsp->hdr.ProtocolId +
1578 le16_to_cpu(rsp->SecurityBufferOffset);
1579 out_len = work->response_sz -
1580 (le16_to_cpu(rsp->SecurityBufferOffset) + 4);
1582 /* Check previous session */
1583 prev_sess_id = le64_to_cpu(req->PreviousSessionId);
1584 if (prev_sess_id && prev_sess_id != sess->id)
1585 destroy_previous_session(conn, sess->user, prev_sess_id);
1587 if (sess->state == SMB2_SESSION_VALID)
1588 ksmbd_free_user(sess->user);
1590 retval = ksmbd_krb5_authenticate(sess, in_blob, in_len,
1591 out_blob, &out_len);
1593 ksmbd_debug(SMB, "krb5 authentication failed\n");
1596 rsp->SecurityBufferLength = cpu_to_le16(out_len);
1598 if ((conn->sign || server_conf.enforced_signing) ||
1599 (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
1602 if (smb3_encryption_negotiated(conn)) {
1603 retval = conn->ops->generate_encryptionkey(conn, sess);
1606 "SMB3 encryption key generation failed\n");
1610 if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION)
1611 rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
1615 if (conn->dialect >= SMB30_PROT_ID) {
1616 chann = lookup_chann_list(sess, conn);
1618 chann = kmalloc(sizeof(struct channel), GFP_KERNEL);
1623 xa_store(&sess->ksmbd_chann_list, (long)conn, chann, GFP_KERNEL);
1627 if (conn->ops->generate_signingkey) {
1628 retval = conn->ops->generate_signingkey(sess, conn);
1630 ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
1635 if (!ksmbd_conn_lookup_dialect(conn)) {
1636 pr_err("fail to verify the dialect\n");
1642 static int krb5_authenticate(struct ksmbd_work *work,
1643 struct smb2_sess_setup_req *req,
1644 struct smb2_sess_setup_rsp *rsp)
1650 int smb2_sess_setup(struct ksmbd_work *work)
1652 struct ksmbd_conn *conn = work->conn;
1653 struct smb2_sess_setup_req *req;
1654 struct smb2_sess_setup_rsp *rsp;
1655 struct ksmbd_session *sess;
1656 struct negotiate_message *negblob;
1657 unsigned int negblob_len, negblob_off;
1660 ksmbd_debug(SMB, "Received request for session setup\n");
1662 WORK_BUFFERS(work, req, rsp);
1664 rsp->StructureSize = cpu_to_le16(9);
1665 rsp->SessionFlags = 0;
1666 rsp->SecurityBufferOffset = cpu_to_le16(72);
1667 rsp->SecurityBufferLength = 0;
1669 ksmbd_conn_lock(conn);
1670 if (!req->hdr.SessionId) {
1671 sess = ksmbd_smb2_session_create();
1676 rsp->hdr.SessionId = cpu_to_le64(sess->id);
1677 rc = ksmbd_session_register(conn, sess);
1680 } else if (conn->dialect >= SMB30_PROT_ID &&
1681 (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
1682 req->Flags & SMB2_SESSION_REQ_FLAG_BINDING) {
1683 u64 sess_id = le64_to_cpu(req->hdr.SessionId);
1685 sess = ksmbd_session_lookup_slowpath(sess_id);
1691 if (conn->dialect != sess->dialect) {
1696 if (!(req->hdr.Flags & SMB2_FLAGS_SIGNED)) {
1701 if (strncmp(conn->ClientGUID, sess->ClientGUID,
1702 SMB2_CLIENT_GUID_SIZE)) {
1707 if (sess->state == SMB2_SESSION_IN_PROGRESS) {
1712 if (sess->state == SMB2_SESSION_EXPIRED) {
1717 if (ksmbd_conn_need_reconnect(conn)) {
1723 if (ksmbd_session_lookup(conn, sess_id)) {
1728 if (user_guest(sess->user)) {
1733 conn->binding = true;
1734 } else if ((conn->dialect < SMB30_PROT_ID ||
1735 server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
1736 (req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1741 sess = ksmbd_session_lookup(conn,
1742 le64_to_cpu(req->hdr.SessionId));
1748 if (sess->state == SMB2_SESSION_EXPIRED) {
1753 if (ksmbd_conn_need_reconnect(conn)) {
1761 negblob_off = le16_to_cpu(req->SecurityBufferOffset);
1762 negblob_len = le16_to_cpu(req->SecurityBufferLength);
1763 if (negblob_off < offsetof(struct smb2_sess_setup_req, Buffer)) {
1768 negblob = (struct negotiate_message *)((char *)&req->hdr.ProtocolId +
1771 if (decode_negotiation_token(conn, negblob, negblob_len) == 0) {
1772 if (conn->mechToken) {
1773 negblob = (struct negotiate_message *)conn->mechToken;
1774 negblob_len = conn->mechTokenLen;
1778 if (negblob_len < offsetof(struct negotiate_message, NegotiateFlags)) {
1783 if (server_conf.auth_mechs & conn->auth_mechs) {
1784 rc = generate_preauth_hash(work);
1788 if (conn->preferred_auth_mech &
1789 (KSMBD_AUTH_KRB5 | KSMBD_AUTH_MSKRB5)) {
1790 rc = krb5_authenticate(work, req, rsp);
1796 if (!ksmbd_conn_need_reconnect(conn)) {
1797 ksmbd_conn_set_good(conn);
1798 sess->state = SMB2_SESSION_VALID;
1800 kfree(sess->Preauth_HashValue);
1801 sess->Preauth_HashValue = NULL;
1802 } else if (conn->preferred_auth_mech == KSMBD_AUTH_NTLMSSP) {
1803 if (negblob->MessageType == NtLmNegotiate) {
1804 rc = ntlm_negotiate(work, negblob, negblob_len, rsp);
1808 STATUS_MORE_PROCESSING_REQUIRED;
1809 } else if (negblob->MessageType == NtLmAuthenticate) {
1810 rc = ntlm_authenticate(work, req, rsp);
1814 if (!ksmbd_conn_need_reconnect(conn)) {
1815 ksmbd_conn_set_good(conn);
1816 sess->state = SMB2_SESSION_VALID;
1818 if (conn->binding) {
1819 struct preauth_session *preauth_sess;
1822 ksmbd_preauth_session_lookup(conn, sess->id);
1824 list_del(&preauth_sess->preauth_entry);
1825 kfree(preauth_sess);
1828 kfree(sess->Preauth_HashValue);
1829 sess->Preauth_HashValue = NULL;
1831 pr_info_ratelimited("Unknown NTLMSSP message type : 0x%x\n",
1832 le32_to_cpu(negblob->MessageType));
1836 /* TODO: need one more negotiation */
1837 pr_err("Not support the preferred authentication\n");
1841 pr_err("Not support authentication\n");
1847 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1848 else if (rc == -ENOENT)
1849 rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
1850 else if (rc == -EACCES)
1851 rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
1852 else if (rc == -EFAULT)
1853 rsp->hdr.Status = STATUS_NETWORK_SESSION_EXPIRED;
1854 else if (rc == -ENOMEM)
1855 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
1856 else if (rc == -EOPNOTSUPP)
1857 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
1859 rsp->hdr.Status = STATUS_LOGON_FAILURE;
1861 if (conn->use_spnego && conn->mechToken) {
1862 kfree(conn->mechToken);
1863 conn->mechToken = NULL;
1868 * SecurityBufferOffset should be set to zero
1869 * in session setup error response.
1871 rsp->SecurityBufferOffset = 0;
1874 bool try_delay = false;
1877 * To avoid dictionary attacks (repeated session setups rapidly sent) to
1878 * connect to server, ksmbd make a delay of a 5 seconds on session setup
1879 * failure to make it harder to send enough random connection requests
1880 * to break into a server.
1882 if (sess->user && sess->user->flags & KSMBD_USER_FLAG_DELAY_SESSION)
1885 sess->last_active = jiffies;
1886 sess->state = SMB2_SESSION_EXPIRED;
1888 ksmbd_conn_set_need_reconnect(conn);
1890 ksmbd_conn_set_need_negotiate(conn);
1893 smb2_set_err_rsp(work);
1895 unsigned int iov_len;
1897 if (rsp->SecurityBufferLength)
1898 iov_len = offsetof(struct smb2_sess_setup_rsp, Buffer) +
1899 le16_to_cpu(rsp->SecurityBufferLength);
1901 iov_len = sizeof(struct smb2_sess_setup_rsp);
1902 rc = ksmbd_iov_pin_rsp(work, rsp, iov_len);
1904 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
1907 ksmbd_conn_unlock(conn);
1912 * smb2_tree_connect() - handler for smb2 tree connect command
1913 * @work: smb work containing smb request buffer
1915 * Return: 0 on success, otherwise error
1917 int smb2_tree_connect(struct ksmbd_work *work)
1919 struct ksmbd_conn *conn = work->conn;
1920 struct smb2_tree_connect_req *req;
1921 struct smb2_tree_connect_rsp *rsp;
1922 struct ksmbd_session *sess = work->sess;
1923 char *treename = NULL, *name = NULL;
1924 struct ksmbd_tree_conn_status status;
1925 struct ksmbd_share_config *share;
1928 WORK_BUFFERS(work, req, rsp);
1930 treename = smb_strndup_from_utf16((char *)req + le16_to_cpu(req->PathOffset),
1931 le16_to_cpu(req->PathLength), true,
1933 if (IS_ERR(treename)) {
1934 pr_err("treename is NULL\n");
1935 status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
1939 name = ksmbd_extract_sharename(conn->um, treename);
1941 status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
1945 ksmbd_debug(SMB, "tree connect request for tree %s treename %s\n",
1948 status = ksmbd_tree_conn_connect(conn, sess, name);
1949 if (status.ret == KSMBD_TREE_CONN_STATUS_OK)
1950 rsp->hdr.Id.SyncId.TreeId = cpu_to_le32(status.tree_conn->id);
1954 share = status.tree_conn->share_conf;
1955 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
1956 ksmbd_debug(SMB, "IPC share path request\n");
1957 rsp->ShareType = SMB2_SHARE_TYPE_PIPE;
1958 rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
1959 FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE |
1960 FILE_DELETE_LE | FILE_READ_CONTROL_LE |
1961 FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
1962 FILE_SYNCHRONIZE_LE;
1964 rsp->ShareType = SMB2_SHARE_TYPE_DISK;
1965 rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
1966 FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE;
1967 if (test_tree_conn_flag(status.tree_conn,
1968 KSMBD_TREE_CONN_FLAG_WRITABLE)) {
1969 rsp->MaximalAccess |= FILE_WRITE_DATA_LE |
1970 FILE_APPEND_DATA_LE | FILE_WRITE_EA_LE |
1971 FILE_DELETE_LE | FILE_WRITE_ATTRIBUTES_LE |
1972 FILE_DELETE_CHILD_LE | FILE_READ_CONTROL_LE |
1973 FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
1974 FILE_SYNCHRONIZE_LE;
1978 status.tree_conn->maximal_access = le32_to_cpu(rsp->MaximalAccess);
1979 if (conn->posix_ext_supported)
1980 status.tree_conn->posix_extensions = true;
1982 write_lock(&sess->tree_conns_lock);
1983 status.tree_conn->t_state = TREE_CONNECTED;
1984 write_unlock(&sess->tree_conns_lock);
1985 rsp->StructureSize = cpu_to_le16(16);
1987 rsp->Capabilities = 0;
1989 /* default manual caching */
1990 rsp->ShareFlags = SMB2_SHAREFLAG_MANUAL_CACHING;
1992 rc = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_tree_connect_rsp));
1994 status.ret = KSMBD_TREE_CONN_STATUS_NOMEM;
1996 if (!IS_ERR(treename))
2001 switch (status.ret) {
2002 case KSMBD_TREE_CONN_STATUS_OK:
2003 rsp->hdr.Status = STATUS_SUCCESS;
2008 case KSMBD_TREE_CONN_STATUS_NO_SHARE:
2009 rsp->hdr.Status = STATUS_BAD_NETWORK_NAME;
2012 case KSMBD_TREE_CONN_STATUS_NOMEM:
2013 rsp->hdr.Status = STATUS_NO_MEMORY;
2015 case KSMBD_TREE_CONN_STATUS_ERROR:
2016 case KSMBD_TREE_CONN_STATUS_TOO_MANY_CONNS:
2017 case KSMBD_TREE_CONN_STATUS_TOO_MANY_SESSIONS:
2018 rsp->hdr.Status = STATUS_ACCESS_DENIED;
2021 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2024 rsp->hdr.Status = STATUS_ACCESS_DENIED;
2027 if (status.ret != KSMBD_TREE_CONN_STATUS_OK)
2028 smb2_set_err_rsp(work);
2034 * smb2_create_open_flags() - convert smb open flags to unix open flags
2035 * @file_present: is file already present
2036 * @access: file access flags
2037 * @disposition: file disposition flags
2038 * @may_flags: set with MAY_ flags
2040 * Return: file open flags
2042 static int smb2_create_open_flags(bool file_present, __le32 access,
2046 int oflags = O_NONBLOCK | O_LARGEFILE;
2048 if (access & FILE_READ_DESIRED_ACCESS_LE &&
2049 access & FILE_WRITE_DESIRE_ACCESS_LE) {
2051 *may_flags = MAY_OPEN | MAY_READ | MAY_WRITE;
2052 } else if (access & FILE_WRITE_DESIRE_ACCESS_LE) {
2054 *may_flags = MAY_OPEN | MAY_WRITE;
2057 *may_flags = MAY_OPEN | MAY_READ;
2060 if (access == FILE_READ_ATTRIBUTES_LE)
2064 switch (disposition & FILE_CREATE_MASK_LE) {
2066 case FILE_CREATE_LE:
2068 case FILE_SUPERSEDE_LE:
2069 case FILE_OVERWRITE_LE:
2070 case FILE_OVERWRITE_IF_LE:
2077 switch (disposition & FILE_CREATE_MASK_LE) {
2078 case FILE_SUPERSEDE_LE:
2079 case FILE_CREATE_LE:
2080 case FILE_OPEN_IF_LE:
2081 case FILE_OVERWRITE_IF_LE:
2085 case FILE_OVERWRITE_LE:
2097 * smb2_tree_disconnect() - handler for smb tree connect request
2098 * @work: smb work containing request buffer
2102 int smb2_tree_disconnect(struct ksmbd_work *work)
2104 struct smb2_tree_disconnect_rsp *rsp;
2105 struct smb2_tree_disconnect_req *req;
2106 struct ksmbd_session *sess = work->sess;
2107 struct ksmbd_tree_connect *tcon = work->tcon;
2110 WORK_BUFFERS(work, req, rsp);
2112 ksmbd_debug(SMB, "request\n");
2115 ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
2117 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2122 ksmbd_close_tree_conn_fds(work);
2124 write_lock(&sess->tree_conns_lock);
2125 if (tcon->t_state == TREE_DISCONNECTED) {
2126 write_unlock(&sess->tree_conns_lock);
2127 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2132 WARN_ON_ONCE(atomic_dec_and_test(&tcon->refcount));
2133 tcon->t_state = TREE_DISCONNECTED;
2134 write_unlock(&sess->tree_conns_lock);
2136 err = ksmbd_tree_conn_disconnect(sess, tcon);
2138 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2144 rsp->StructureSize = cpu_to_le16(4);
2145 err = ksmbd_iov_pin_rsp(work, rsp,
2146 sizeof(struct smb2_tree_disconnect_rsp));
2148 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
2155 smb2_set_err_rsp(work);
2161 * smb2_session_logoff() - handler for session log off request
2162 * @work: smb work containing request buffer
2166 int smb2_session_logoff(struct ksmbd_work *work)
2168 struct ksmbd_conn *conn = work->conn;
2169 struct smb2_logoff_req *req;
2170 struct smb2_logoff_rsp *rsp;
2171 struct ksmbd_session *sess;
2175 WORK_BUFFERS(work, req, rsp);
2177 ksmbd_debug(SMB, "request\n");
2179 ksmbd_conn_lock(conn);
2180 if (!ksmbd_conn_good(conn)) {
2181 ksmbd_conn_unlock(conn);
2182 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2183 smb2_set_err_rsp(work);
2186 sess_id = le64_to_cpu(req->hdr.SessionId);
2187 ksmbd_all_conn_set_status(sess_id, KSMBD_SESS_NEED_RECONNECT);
2188 ksmbd_conn_unlock(conn);
2190 ksmbd_close_session_fds(work);
2191 ksmbd_conn_wait_idle(conn, sess_id);
2194 * Re-lookup session to validate if session is deleted
2195 * while waiting request complete
2197 sess = ksmbd_session_lookup_all(conn, sess_id);
2198 if (ksmbd_tree_conn_session_logoff(sess)) {
2199 ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
2200 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2201 smb2_set_err_rsp(work);
2205 ksmbd_destroy_file_table(&sess->file_table);
2206 sess->state = SMB2_SESSION_EXPIRED;
2208 ksmbd_free_user(sess->user);
2210 ksmbd_all_conn_set_status(sess_id, KSMBD_SESS_NEED_NEGOTIATE);
2212 rsp->StructureSize = cpu_to_le16(4);
2213 err = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_logoff_rsp));
2215 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
2216 smb2_set_err_rsp(work);
2223 * create_smb2_pipe() - create IPC pipe
2224 * @work: smb work containing request buffer
2226 * Return: 0 on success, otherwise error
2228 static noinline int create_smb2_pipe(struct ksmbd_work *work)
2230 struct smb2_create_rsp *rsp;
2231 struct smb2_create_req *req;
2236 WORK_BUFFERS(work, req, rsp);
2238 name = smb_strndup_from_utf16(req->Buffer, le16_to_cpu(req->NameLength),
2239 1, work->conn->local_nls);
2241 rsp->hdr.Status = STATUS_NO_MEMORY;
2242 err = PTR_ERR(name);
2246 id = ksmbd_session_rpc_open(work->sess, name);
2248 pr_err("Unable to open RPC pipe: %d\n", id);
2253 rsp->hdr.Status = STATUS_SUCCESS;
2254 rsp->StructureSize = cpu_to_le16(89);
2255 rsp->OplockLevel = SMB2_OPLOCK_LEVEL_NONE;
2257 rsp->CreateAction = cpu_to_le32(FILE_OPENED);
2259 rsp->CreationTime = cpu_to_le64(0);
2260 rsp->LastAccessTime = cpu_to_le64(0);
2261 rsp->ChangeTime = cpu_to_le64(0);
2262 rsp->AllocationSize = cpu_to_le64(0);
2263 rsp->EndofFile = cpu_to_le64(0);
2264 rsp->FileAttributes = FILE_ATTRIBUTE_NORMAL_LE;
2266 rsp->VolatileFileId = id;
2267 rsp->PersistentFileId = 0;
2268 rsp->CreateContextsOffset = 0;
2269 rsp->CreateContextsLength = 0;
2271 err = ksmbd_iov_pin_rsp(work, rsp, offsetof(struct smb2_create_rsp, Buffer));
2281 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2285 rsp->hdr.Status = STATUS_NO_MEMORY;
2292 smb2_set_err_rsp(work);
2297 * smb2_set_ea() - handler for setting extended attributes using set
2299 * @eabuf: set info command buffer
2300 * @buf_len: set info command buffer length
2301 * @path: dentry path for get ea
2302 * @get_write: get write access to a mount
2304 * Return: 0 on success, otherwise error
2306 static int smb2_set_ea(struct smb2_ea_info *eabuf, unsigned int buf_len,
2307 const struct path *path, bool get_write)
2309 struct mnt_idmap *idmap = mnt_idmap(path->mnt);
2310 char *attr_name = NULL, *value;
2312 unsigned int next = 0;
2314 if (buf_len < sizeof(struct smb2_ea_info) + eabuf->EaNameLength +
2315 le16_to_cpu(eabuf->EaValueLength))
2318 attr_name = kmalloc(XATTR_NAME_MAX + 1, GFP_KERNEL);
2323 if (!eabuf->EaNameLength)
2327 "name : <%s>, name_len : %u, value_len : %u, next : %u\n",
2328 eabuf->name, eabuf->EaNameLength,
2329 le16_to_cpu(eabuf->EaValueLength),
2330 le32_to_cpu(eabuf->NextEntryOffset));
2332 if (eabuf->EaNameLength >
2333 (XATTR_NAME_MAX - XATTR_USER_PREFIX_LEN)) {
2338 memcpy(attr_name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN);
2339 memcpy(&attr_name[XATTR_USER_PREFIX_LEN], eabuf->name,
2340 eabuf->EaNameLength);
2341 attr_name[XATTR_USER_PREFIX_LEN + eabuf->EaNameLength] = '\0';
2342 value = (char *)&eabuf->name + eabuf->EaNameLength + 1;
2344 if (!eabuf->EaValueLength) {
2345 rc = ksmbd_vfs_casexattr_len(idmap,
2348 XATTR_USER_PREFIX_LEN +
2349 eabuf->EaNameLength);
2351 /* delete the EA only when it exits */
2353 rc = ksmbd_vfs_remove_xattr(idmap,
2359 "remove xattr failed(%d)\n",
2365 /* if the EA doesn't exist, just do nothing. */
2368 rc = ksmbd_vfs_setxattr(idmap, path, attr_name, value,
2369 le16_to_cpu(eabuf->EaValueLength),
2373 "ksmbd_vfs_setxattr is failed(%d)\n",
2380 next = le32_to_cpu(eabuf->NextEntryOffset);
2381 if (next == 0 || buf_len < next)
2384 eabuf = (struct smb2_ea_info *)((char *)eabuf + next);
2385 if (buf_len < sizeof(struct smb2_ea_info)) {
2390 if (buf_len < sizeof(struct smb2_ea_info) + eabuf->EaNameLength +
2391 le16_to_cpu(eabuf->EaValueLength)) {
2395 } while (next != 0);
2401 static noinline int smb2_set_stream_name_xattr(const struct path *path,
2402 struct ksmbd_file *fp,
2403 char *stream_name, int s_type)
2405 struct mnt_idmap *idmap = mnt_idmap(path->mnt);
2406 size_t xattr_stream_size;
2407 char *xattr_stream_name;
2410 rc = ksmbd_vfs_xattr_stream_name(stream_name,
2417 fp->stream.name = xattr_stream_name;
2418 fp->stream.size = xattr_stream_size;
2420 /* Check if there is stream prefix in xattr space */
2421 rc = ksmbd_vfs_casexattr_len(idmap,
2428 if (fp->cdoption == FILE_OPEN_LE) {
2429 ksmbd_debug(SMB, "XATTR stream name lookup failed: %d\n", rc);
2433 rc = ksmbd_vfs_setxattr(idmap, path, xattr_stream_name, NULL, 0, 0, false);
2435 pr_err("Failed to store XATTR stream name :%d\n", rc);
2439 static int smb2_remove_smb_xattrs(const struct path *path)
2441 struct mnt_idmap *idmap = mnt_idmap(path->mnt);
2442 char *name, *xattr_list = NULL;
2443 ssize_t xattr_list_len;
2446 xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
2447 if (xattr_list_len < 0) {
2449 } else if (!xattr_list_len) {
2450 ksmbd_debug(SMB, "empty xattr in the file\n");
2454 for (name = xattr_list; name - xattr_list < xattr_list_len;
2455 name += strlen(name) + 1) {
2456 ksmbd_debug(SMB, "%s, len %zd\n", name, strlen(name));
2458 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN) &&
2459 !strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
2460 STREAM_PREFIX_LEN)) {
2461 err = ksmbd_vfs_remove_xattr(idmap, path,
2464 ksmbd_debug(SMB, "remove xattr failed : %s\n",
2473 static int smb2_create_truncate(const struct path *path)
2475 int rc = vfs_truncate(path, 0);
2478 pr_err("vfs_truncate failed, rc %d\n", rc);
2482 rc = smb2_remove_smb_xattrs(path);
2483 if (rc == -EOPNOTSUPP)
2487 "ksmbd_truncate_stream_name_xattr failed, rc %d\n",
2492 static void smb2_new_xattrs(struct ksmbd_tree_connect *tcon, const struct path *path,
2493 struct ksmbd_file *fp)
2495 struct xattr_dos_attrib da = {0};
2498 if (!test_share_config_flag(tcon->share_conf,
2499 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2503 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
2504 da.itime = da.create_time = fp->create_time;
2505 da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
2506 XATTR_DOSINFO_ITIME;
2508 rc = ksmbd_vfs_set_dos_attrib_xattr(mnt_idmap(path->mnt), path, &da, true);
2510 ksmbd_debug(SMB, "failed to store file attribute into xattr\n");
2513 static void smb2_update_xattrs(struct ksmbd_tree_connect *tcon,
2514 const struct path *path, struct ksmbd_file *fp)
2516 struct xattr_dos_attrib da;
2519 fp->f_ci->m_fattr &= ~(FILE_ATTRIBUTE_HIDDEN_LE | FILE_ATTRIBUTE_SYSTEM_LE);
2521 /* get FileAttributes from XATTR_NAME_DOS_ATTRIBUTE */
2522 if (!test_share_config_flag(tcon->share_conf,
2523 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2526 rc = ksmbd_vfs_get_dos_attrib_xattr(mnt_idmap(path->mnt),
2529 fp->f_ci->m_fattr = cpu_to_le32(da.attr);
2530 fp->create_time = da.create_time;
2531 fp->itime = da.itime;
2535 static int smb2_creat(struct ksmbd_work *work, struct path *parent_path,
2536 struct path *path, char *name, int open_flags,
2537 umode_t posix_mode, bool is_dir)
2539 struct ksmbd_tree_connect *tcon = work->tcon;
2540 struct ksmbd_share_config *share = tcon->share_conf;
2544 if (!(open_flags & O_CREAT))
2547 ksmbd_debug(SMB, "file does not exist, so creating\n");
2548 if (is_dir == true) {
2549 ksmbd_debug(SMB, "creating directory\n");
2551 mode = share_config_directory_mode(share, posix_mode);
2552 rc = ksmbd_vfs_mkdir(work, name, mode);
2556 ksmbd_debug(SMB, "creating regular file\n");
2558 mode = share_config_create_mode(share, posix_mode);
2559 rc = ksmbd_vfs_create(work, name, mode);
2564 rc = ksmbd_vfs_kern_path_locked(work, name, 0, parent_path, path, 0);
2566 pr_err("cannot get linux path (%s), err = %d\n",
2573 static int smb2_create_sd_buffer(struct ksmbd_work *work,
2574 struct smb2_create_req *req,
2575 const struct path *path)
2577 struct create_context *context;
2578 struct create_sd_buf_req *sd_buf;
2580 if (!req->CreateContextsOffset)
2583 /* Parse SD BUFFER create contexts */
2584 context = smb2_find_context_vals(req, SMB2_CREATE_SD_BUFFER, 4);
2587 else if (IS_ERR(context))
2588 return PTR_ERR(context);
2591 "Set ACLs using SMB2_CREATE_SD_BUFFER context\n");
2592 sd_buf = (struct create_sd_buf_req *)context;
2593 if (le16_to_cpu(context->DataOffset) +
2594 le32_to_cpu(context->DataLength) <
2595 sizeof(struct create_sd_buf_req))
2597 return set_info_sec(work->conn, work->tcon, path, &sd_buf->ntsd,
2598 le32_to_cpu(sd_buf->ccontext.DataLength), true, false);
2601 static void ksmbd_acls_fattr(struct smb_fattr *fattr,
2602 struct mnt_idmap *idmap,
2603 struct inode *inode)
2605 vfsuid_t vfsuid = i_uid_into_vfsuid(idmap, inode);
2606 vfsgid_t vfsgid = i_gid_into_vfsgid(idmap, inode);
2608 fattr->cf_uid = vfsuid_into_kuid(vfsuid);
2609 fattr->cf_gid = vfsgid_into_kgid(vfsgid);
2610 fattr->cf_mode = inode->i_mode;
2611 fattr->cf_acls = NULL;
2612 fattr->cf_dacls = NULL;
2614 if (IS_ENABLED(CONFIG_FS_POSIX_ACL)) {
2615 fattr->cf_acls = get_inode_acl(inode, ACL_TYPE_ACCESS);
2616 if (S_ISDIR(inode->i_mode))
2617 fattr->cf_dacls = get_inode_acl(inode, ACL_TYPE_DEFAULT);
2622 DURABLE_RECONN_V2 = 1,
2628 struct durable_info {
2629 struct ksmbd_file *fp;
2630 unsigned short int type;
2633 unsigned int timeout;
2637 static int parse_durable_handle_context(struct ksmbd_work *work,
2638 struct smb2_create_req *req,
2639 struct lease_ctx_info *lc,
2640 struct durable_info *dh_info)
2642 struct ksmbd_conn *conn = work->conn;
2643 struct create_context *context;
2644 int dh_idx, err = 0;
2645 u64 persistent_id = 0;
2647 static const char * const durable_arr[] = {"DH2C", "DHnC", "DH2Q", "DHnQ"};
2649 req_op_level = req->RequestedOplockLevel;
2650 for (dh_idx = DURABLE_RECONN_V2; dh_idx <= ARRAY_SIZE(durable_arr);
2652 context = smb2_find_context_vals(req, durable_arr[dh_idx - 1], 4);
2653 if (IS_ERR(context)) {
2654 err = PTR_ERR(context);
2661 case DURABLE_RECONN_V2:
2663 struct create_durable_reconn_v2_req *recon_v2;
2665 if (dh_info->type == DURABLE_RECONN ||
2666 dh_info->type == DURABLE_REQ_V2) {
2671 recon_v2 = (struct create_durable_reconn_v2_req *)context;
2672 persistent_id = recon_v2->Fid.PersistentFileId;
2673 dh_info->fp = ksmbd_lookup_durable_fd(persistent_id);
2675 ksmbd_debug(SMB, "Failed to get durable handle state\n");
2680 if (memcmp(dh_info->fp->create_guid, recon_v2->CreateGuid,
2681 SMB2_CREATE_GUID_SIZE)) {
2683 ksmbd_put_durable_fd(dh_info->fp);
2687 dh_info->type = dh_idx;
2688 dh_info->reconnected = true;
2690 "reconnect v2 Persistent-id from reconnect = %llu\n",
2694 case DURABLE_RECONN:
2696 struct create_durable_reconn_req *recon;
2698 if (dh_info->type == DURABLE_RECONN_V2 ||
2699 dh_info->type == DURABLE_REQ_V2) {
2704 recon = (struct create_durable_reconn_req *)context;
2705 persistent_id = recon->Data.Fid.PersistentFileId;
2706 dh_info->fp = ksmbd_lookup_durable_fd(persistent_id);
2708 ksmbd_debug(SMB, "Failed to get durable handle state\n");
2713 dh_info->type = dh_idx;
2714 dh_info->reconnected = true;
2715 ksmbd_debug(SMB, "reconnect Persistent-id from reconnect = %llu\n",
2719 case DURABLE_REQ_V2:
2721 struct create_durable_req_v2 *durable_v2_blob;
2723 if (dh_info->type == DURABLE_RECONN ||
2724 dh_info->type == DURABLE_RECONN_V2) {
2730 (struct create_durable_req_v2 *)context;
2731 ksmbd_debug(SMB, "Request for durable v2 open\n");
2732 dh_info->fp = ksmbd_lookup_fd_cguid(durable_v2_blob->CreateGuid);
2734 if (!memcmp(conn->ClientGUID, dh_info->fp->client_guid,
2735 SMB2_CLIENT_GUID_SIZE)) {
2736 if (!(req->hdr.Flags & SMB2_FLAGS_REPLAY_OPERATION)) {
2741 dh_info->fp->conn = conn;
2742 dh_info->reconnected = true;
2747 if (((lc && (lc->req_state & SMB2_LEASE_HANDLE_CACHING_LE)) ||
2748 req_op_level == SMB2_OPLOCK_LEVEL_BATCH)) {
2749 dh_info->CreateGuid =
2750 durable_v2_blob->CreateGuid;
2751 dh_info->persistent =
2752 le32_to_cpu(durable_v2_blob->Flags);
2754 le32_to_cpu(durable_v2_blob->Timeout);
2755 dh_info->type = dh_idx;
2760 if (dh_info->type == DURABLE_RECONN)
2762 if (dh_info->type == DURABLE_RECONN_V2 ||
2763 dh_info->type == DURABLE_REQ_V2) {
2768 if (((lc && (lc->req_state & SMB2_LEASE_HANDLE_CACHING_LE)) ||
2769 req_op_level == SMB2_OPLOCK_LEVEL_BATCH)) {
2770 ksmbd_debug(SMB, "Request for durable open\n");
2771 dh_info->type = dh_idx;
2781 * smb2_open() - handler for smb file open request
2782 * @work: smb work containing request buffer
2784 * Return: 0 on success, otherwise error
2786 int smb2_open(struct ksmbd_work *work)
2788 struct ksmbd_conn *conn = work->conn;
2789 struct ksmbd_session *sess = work->sess;
2790 struct ksmbd_tree_connect *tcon = work->tcon;
2791 struct smb2_create_req *req;
2792 struct smb2_create_rsp *rsp;
2793 struct path path, parent_path;
2794 struct ksmbd_share_config *share = tcon->share_conf;
2795 struct ksmbd_file *fp = NULL;
2796 struct file *filp = NULL;
2797 struct mnt_idmap *idmap = NULL;
2799 struct create_context *context;
2800 struct lease_ctx_info *lc = NULL;
2801 struct create_ea_buf_req *ea_buf = NULL;
2802 struct oplock_info *opinfo;
2803 struct durable_info dh_info = {0};
2804 __le32 *next_ptr = NULL;
2805 int req_op_level = 0, open_flags = 0, may_flags = 0, file_info = 0;
2807 int contxt_cnt = 0, query_disk_id = 0;
2808 int maximal_access_ctxt = 0, posix_ctxt = 0;
2812 char *stream_name = NULL;
2813 bool file_present = false, created = false, already_permitted = false;
2814 int share_ret, need_truncate = 0;
2816 umode_t posix_mode = 0;
2817 __le32 daccess, maximal_access = 0;
2820 WORK_BUFFERS(work, req, rsp);
2822 if (req->hdr.NextCommand && !work->next_smb2_rcv_hdr_off &&
2823 (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
2824 ksmbd_debug(SMB, "invalid flag in chained command\n");
2825 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2826 smb2_set_err_rsp(work);
2830 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
2831 ksmbd_debug(SMB, "IPC pipe create request\n");
2832 return create_smb2_pipe(work);
2835 if (req->NameLength) {
2836 if ((req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
2837 *(char *)req->Buffer == '\\') {
2838 pr_err("not allow directory name included leading slash\n");
2843 name = smb2_get_name((char *)req + le16_to_cpu(req->NameOffset),
2844 le16_to_cpu(req->NameLength),
2845 work->conn->local_nls);
2854 ksmbd_debug(SMB, "converted name = %s\n", name);
2855 if (strchr(name, ':')) {
2856 if (!test_share_config_flag(work->tcon->share_conf,
2857 KSMBD_SHARE_FLAG_STREAMS)) {
2861 rc = parse_stream_name(name, &stream_name, &s_type);
2866 rc = ksmbd_validate_filename(name);
2870 if (ksmbd_share_veto_filename(share, name)) {
2872 ksmbd_debug(SMB, "Reject open(), vetoed file: %s\n",
2877 name = kstrdup("", GFP_KERNEL);
2884 req_op_level = req->RequestedOplockLevel;
2886 if (server_conf.flags & KSMBD_GLOBAL_FLAG_DURABLE_HANDLE &&
2887 req->CreateContextsOffset) {
2888 lc = parse_lease_state(req);
2889 rc = parse_durable_handle_context(work, req, lc, &dh_info);
2891 ksmbd_debug(SMB, "error parsing durable handle context\n");
2895 if (dh_info.reconnected == true) {
2896 rc = smb2_check_durable_oplock(conn, share, dh_info.fp, lc, name);
2898 ksmbd_put_durable_fd(dh_info.fp);
2902 rc = ksmbd_reopen_durable_fd(work, dh_info.fp);
2904 ksmbd_put_durable_fd(dh_info.fp);
2908 if (ksmbd_override_fsids(work)) {
2910 ksmbd_put_durable_fd(dh_info.fp);
2915 file_info = FILE_OPENED;
2917 rc = ksmbd_vfs_getattr(&fp->filp->f_path, &stat);
2921 ksmbd_put_durable_fd(fp);
2922 goto reconnected_fp;
2924 } else if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE)
2925 lc = parse_lease_state(req);
2927 if (le32_to_cpu(req->ImpersonationLevel) > le32_to_cpu(IL_DELEGATE)) {
2928 pr_err("Invalid impersonationlevel : 0x%x\n",
2929 le32_to_cpu(req->ImpersonationLevel));
2931 rsp->hdr.Status = STATUS_BAD_IMPERSONATION_LEVEL;
2935 if (req->CreateOptions && !(req->CreateOptions & CREATE_OPTIONS_MASK_LE)) {
2936 pr_err("Invalid create options : 0x%x\n",
2937 le32_to_cpu(req->CreateOptions));
2941 if (req->CreateOptions & FILE_SEQUENTIAL_ONLY_LE &&
2942 req->CreateOptions & FILE_RANDOM_ACCESS_LE)
2943 req->CreateOptions = ~(FILE_SEQUENTIAL_ONLY_LE);
2945 if (req->CreateOptions &
2946 (FILE_OPEN_BY_FILE_ID_LE | CREATE_TREE_CONNECTION |
2947 FILE_RESERVE_OPFILTER_LE)) {
2952 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
2953 if (req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE) {
2956 } else if (req->CreateOptions & FILE_NO_COMPRESSION_LE) {
2957 req->CreateOptions = ~(FILE_NO_COMPRESSION_LE);
2962 if (le32_to_cpu(req->CreateDisposition) >
2963 le32_to_cpu(FILE_OVERWRITE_IF_LE)) {
2964 pr_err("Invalid create disposition : 0x%x\n",
2965 le32_to_cpu(req->CreateDisposition));
2970 if (!(req->DesiredAccess & DESIRED_ACCESS_MASK)) {
2971 pr_err("Invalid desired access : 0x%x\n",
2972 le32_to_cpu(req->DesiredAccess));
2977 if (req->FileAttributes && !(req->FileAttributes & FILE_ATTRIBUTE_MASK_LE)) {
2978 pr_err("Invalid file attribute : 0x%x\n",
2979 le32_to_cpu(req->FileAttributes));
2984 if (req->CreateContextsOffset) {
2985 /* Parse non-durable handle create contexts */
2986 context = smb2_find_context_vals(req, SMB2_CREATE_EA_BUFFER, 4);
2987 if (IS_ERR(context)) {
2988 rc = PTR_ERR(context);
2990 } else if (context) {
2991 ea_buf = (struct create_ea_buf_req *)context;
2992 if (le16_to_cpu(context->DataOffset) +
2993 le32_to_cpu(context->DataLength) <
2994 sizeof(struct create_ea_buf_req)) {
2998 if (req->CreateOptions & FILE_NO_EA_KNOWLEDGE_LE) {
2999 rsp->hdr.Status = STATUS_ACCESS_DENIED;
3005 context = smb2_find_context_vals(req,
3006 SMB2_CREATE_QUERY_MAXIMAL_ACCESS_REQUEST, 4);
3007 if (IS_ERR(context)) {
3008 rc = PTR_ERR(context);
3010 } else if (context) {
3012 "get query maximal access context\n");
3013 maximal_access_ctxt = 1;
3016 context = smb2_find_context_vals(req,
3017 SMB2_CREATE_TIMEWARP_REQUEST, 4);
3018 if (IS_ERR(context)) {
3019 rc = PTR_ERR(context);
3021 } else if (context) {
3022 ksmbd_debug(SMB, "get timewarp context\n");
3027 if (tcon->posix_extensions) {
3028 context = smb2_find_context_vals(req,
3029 SMB2_CREATE_TAG_POSIX, 16);
3030 if (IS_ERR(context)) {
3031 rc = PTR_ERR(context);
3033 } else if (context) {
3034 struct create_posix *posix =
3035 (struct create_posix *)context;
3036 if (le16_to_cpu(context->DataOffset) +
3037 le32_to_cpu(context->DataLength) <
3038 sizeof(struct create_posix) - 4) {
3042 ksmbd_debug(SMB, "get posix context\n");
3044 posix_mode = le32_to_cpu(posix->Mode);
3050 if (ksmbd_override_fsids(work)) {
3055 rc = ksmbd_vfs_kern_path_locked(work, name, LOOKUP_NO_SYMLINKS,
3056 &parent_path, &path, 1);
3058 file_present = true;
3060 if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE) {
3062 * If file exists with under flags, return access
3065 if (req->CreateDisposition == FILE_OVERWRITE_IF_LE ||
3066 req->CreateDisposition == FILE_OPEN_IF_LE) {
3071 if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
3073 "User does not have write permission\n");
3077 } else if (d_is_symlink(path.dentry)) {
3082 file_present = true;
3083 idmap = mnt_idmap(path.mnt);
3087 ksmbd_debug(SMB, "can not get linux path for %s, rc = %d\n",
3093 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
3094 if (s_type == DATA_STREAM) {
3096 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
3099 if (file_present && S_ISDIR(d_inode(path.dentry)->i_mode) &&
3100 s_type == DATA_STREAM) {
3102 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
3106 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE &&
3107 req->FileAttributes & FILE_ATTRIBUTE_NORMAL_LE) {
3108 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
3116 if (file_present && req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE &&
3117 S_ISDIR(d_inode(path.dentry)->i_mode) &&
3118 !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
3119 ksmbd_debug(SMB, "open() argument is a directory: %s, %x\n",
3120 name, req->CreateOptions);
3121 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
3126 if (file_present && (req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
3127 !(req->CreateDisposition == FILE_CREATE_LE) &&
3128 !S_ISDIR(d_inode(path.dentry)->i_mode)) {
3129 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
3134 if (!stream_name && file_present &&
3135 req->CreateDisposition == FILE_CREATE_LE) {
3140 daccess = smb_map_generic_desired_access(req->DesiredAccess);
3142 if (file_present && !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
3143 rc = smb_check_perm_dacl(conn, &path, &daccess,
3149 if (daccess & FILE_MAXIMAL_ACCESS_LE) {
3150 if (!file_present) {
3151 daccess = cpu_to_le32(GENERIC_ALL_FLAGS);
3153 ksmbd_vfs_query_maximal_access(idmap,
3156 already_permitted = true;
3158 maximal_access = daccess;
3161 open_flags = smb2_create_open_flags(file_present, daccess,
3162 req->CreateDisposition,
3165 if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
3166 if (open_flags & (O_CREAT | O_TRUNC)) {
3168 "User does not have write permission\n");
3174 /*create file if not present */
3175 if (!file_present) {
3176 rc = smb2_creat(work, &parent_path, &path, name, open_flags,
3178 req->CreateOptions & FILE_DIRECTORY_FILE_LE);
3180 if (rc == -ENOENT) {
3182 rsp->hdr.Status = STATUS_OBJECT_PATH_NOT_FOUND;
3188 idmap = mnt_idmap(path.mnt);
3190 if (le32_to_cpu(ea_buf->ccontext.DataLength) <
3191 sizeof(struct smb2_ea_info)) {
3196 rc = smb2_set_ea(&ea_buf->ea,
3197 le32_to_cpu(ea_buf->ccontext.DataLength),
3199 if (rc == -EOPNOTSUPP)
3204 } else if (!already_permitted) {
3205 /* FILE_READ_ATTRIBUTE is allowed without inode_permission,
3206 * because execute(search) permission on a parent directory,
3207 * is already granted.
3209 if (daccess & ~(FILE_READ_ATTRIBUTES_LE | FILE_READ_CONTROL_LE)) {
3210 rc = inode_permission(idmap,
3211 d_inode(path.dentry),
3216 if ((daccess & FILE_DELETE_LE) ||
3217 (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
3218 rc = inode_permission(idmap,
3219 d_inode(path.dentry->d_parent),
3220 MAY_EXEC | MAY_WRITE);
3227 rc = ksmbd_query_inode_status(path.dentry->d_parent);
3228 if (rc == KSMBD_INODE_STATUS_PENDING_DELETE) {
3234 filp = dentry_open(&path, open_flags, current_cred());
3237 pr_err("dentry open for dir failed, rc %d\n", rc);
3242 if (!(open_flags & O_TRUNC))
3243 file_info = FILE_OPENED;
3245 file_info = FILE_OVERWRITTEN;
3247 if ((req->CreateDisposition & FILE_CREATE_MASK_LE) ==
3249 file_info = FILE_SUPERSEDED;
3250 } else if (open_flags & O_CREAT) {
3251 file_info = FILE_CREATED;
3254 ksmbd_vfs_set_fadvise(filp, req->CreateOptions);
3256 /* Obtain Volatile-ID */
3257 fp = ksmbd_open_fd(work, filp);
3265 /* Get Persistent-ID */
3266 ksmbd_open_durable_fd(fp);
3267 if (!has_file_id(fp->persistent_id)) {
3272 fp->cdoption = req->CreateDisposition;
3273 fp->daccess = daccess;
3274 fp->saccess = req->ShareAccess;
3275 fp->coption = req->CreateOptions;
3277 /* Set default windows and posix acls if creating new file */
3280 struct inode *inode = d_inode(path.dentry);
3282 posix_acl_rc = ksmbd_vfs_inherit_posix_acl(idmap,
3284 d_inode(path.dentry->d_parent));
3286 ksmbd_debug(SMB, "inherit posix acl failed : %d\n", posix_acl_rc);
3288 if (test_share_config_flag(work->tcon->share_conf,
3289 KSMBD_SHARE_FLAG_ACL_XATTR)) {
3290 rc = smb_inherit_dacl(conn, &path, sess->user->uid,
3295 rc = smb2_create_sd_buffer(work, req, &path);
3298 ksmbd_vfs_set_init_posix_acl(idmap,
3301 if (test_share_config_flag(work->tcon->share_conf,
3302 KSMBD_SHARE_FLAG_ACL_XATTR)) {
3303 struct smb_fattr fattr;
3304 struct smb_ntsd *pntsd;
3305 int pntsd_size, ace_num = 0;
3307 ksmbd_acls_fattr(&fattr, idmap, inode);
3309 ace_num = fattr.cf_acls->a_count;
3311 ace_num += fattr.cf_dacls->a_count;
3313 pntsd = kmalloc(sizeof(struct smb_ntsd) +
3314 sizeof(struct smb_sid) * 3 +
3315 sizeof(struct smb_acl) +
3316 sizeof(struct smb_ace) * ace_num * 2,
3319 posix_acl_release(fattr.cf_acls);
3320 posix_acl_release(fattr.cf_dacls);
3324 rc = build_sec_desc(idmap,
3329 &pntsd_size, &fattr);
3330 posix_acl_release(fattr.cf_acls);
3331 posix_acl_release(fattr.cf_dacls);
3337 rc = ksmbd_vfs_set_sd_xattr(conn,
3345 pr_err("failed to store ntacl in xattr : %d\n",
3354 rc = smb2_set_stream_name_xattr(&path,
3360 file_info = FILE_CREATED;
3363 fp->attrib_only = !(req->DesiredAccess & ~(FILE_READ_ATTRIBUTES_LE |
3364 FILE_WRITE_ATTRIBUTES_LE | FILE_SYNCHRONIZE_LE));
3366 /* fp should be searchable through ksmbd_inode.m_fp_list
3367 * after daccess, saccess, attrib_only, and stream are
3370 write_lock(&fp->f_ci->m_lock);
3371 list_add(&fp->node, &fp->f_ci->m_fp_list);
3372 write_unlock(&fp->f_ci->m_lock);
3374 /* Check delete pending among previous fp before oplock break */
3375 if (ksmbd_inode_pending_delete(fp)) {
3380 if (file_present || created)
3381 ksmbd_vfs_kern_path_unlock(&parent_path, &path);
3383 if (!S_ISDIR(file_inode(filp)->i_mode) && open_flags & O_TRUNC &&
3384 !fp->attrib_only && !stream_name) {
3385 smb_break_all_oplock(work, fp);
3389 share_ret = ksmbd_smb_check_shared_mode(fp->filp, fp);
3390 if (!test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_OPLOCKS) ||
3391 (req_op_level == SMB2_OPLOCK_LEVEL_LEASE &&
3392 !(conn->vals->capabilities & SMB2_GLOBAL_CAP_LEASING))) {
3393 if (share_ret < 0 && !S_ISDIR(file_inode(fp->filp)->i_mode)) {
3398 if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE) {
3399 if (S_ISDIR(file_inode(filp)->i_mode)) {
3400 lc->req_state &= ~SMB2_LEASE_WRITE_CACHING_LE;
3405 * Compare parent lease using parent key. If there is no
3406 * a lease that has same parent key, Send lease break
3409 smb_send_parent_lease_break_noti(fp, lc);
3411 req_op_level = smb2_map_lease_to_oplock(lc->req_state);
3413 "lease req for(%s) req oplock state 0x%x, lease state 0x%x\n",
3414 name, req_op_level, lc->req_state);
3415 rc = find_same_lease_key(sess, fp->f_ci, lc);
3418 } else if (open_flags == O_RDONLY &&
3419 (req_op_level == SMB2_OPLOCK_LEVEL_BATCH ||
3420 req_op_level == SMB2_OPLOCK_LEVEL_EXCLUSIVE))
3421 req_op_level = SMB2_OPLOCK_LEVEL_II;
3423 rc = smb_grant_oplock(work, req_op_level,
3424 fp->persistent_id, fp,
3425 le32_to_cpu(req->hdr.Id.SyncId.TreeId),
3431 if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)
3432 ksmbd_fd_set_delete_on_close(fp, file_info);
3434 if (need_truncate) {
3435 rc = smb2_create_truncate(&fp->filp->f_path);
3440 if (req->CreateContextsOffset) {
3441 struct create_alloc_size_req *az_req;
3443 az_req = (struct create_alloc_size_req *)smb2_find_context_vals(req,
3444 SMB2_CREATE_ALLOCATION_SIZE, 4);
3445 if (IS_ERR(az_req)) {
3446 rc = PTR_ERR(az_req);
3448 } else if (az_req) {
3452 if (le16_to_cpu(az_req->ccontext.DataOffset) +
3453 le32_to_cpu(az_req->ccontext.DataLength) <
3454 sizeof(struct create_alloc_size_req)) {
3458 alloc_size = le64_to_cpu(az_req->AllocationSize);
3460 "request smb2 create allocate size : %llu\n",
3462 smb_break_all_levII_oplock(work, fp, 1);
3463 err = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
3467 "vfs_fallocate is failed : %d\n",
3471 context = smb2_find_context_vals(req, SMB2_CREATE_QUERY_ON_DISK_ID, 4);
3472 if (IS_ERR(context)) {
3473 rc = PTR_ERR(context);
3475 } else if (context) {
3476 ksmbd_debug(SMB, "get query on disk id context\n");
3481 rc = ksmbd_vfs_getattr(&path, &stat);
3485 if (stat.result_mask & STATX_BTIME)
3486 fp->create_time = ksmbd_UnixTimeToNT(stat.btime);
3488 fp->create_time = ksmbd_UnixTimeToNT(stat.ctime);
3489 if (req->FileAttributes || fp->f_ci->m_fattr == 0)
3491 cpu_to_le32(smb2_get_dos_mode(&stat, le32_to_cpu(req->FileAttributes)));
3494 smb2_update_xattrs(tcon, &path, fp);
3496 smb2_new_xattrs(tcon, &path, fp);
3498 memcpy(fp->client_guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE);
3500 if (dh_info.type == DURABLE_REQ_V2 || dh_info.type == DURABLE_REQ) {
3501 if (dh_info.type == DURABLE_REQ_V2 && dh_info.persistent)
3502 fp->is_persistent = true;
3504 fp->is_durable = true;
3506 if (dh_info.type == DURABLE_REQ_V2) {
3507 memcpy(fp->create_guid, dh_info.CreateGuid,
3508 SMB2_CREATE_GUID_SIZE);
3509 if (dh_info.timeout)
3510 fp->durable_timeout = min(dh_info.timeout,
3513 fp->durable_timeout = 60;
3518 rsp->StructureSize = cpu_to_le16(89);
3520 opinfo = rcu_dereference(fp->f_opinfo);
3521 rsp->OplockLevel = opinfo != NULL ? opinfo->level : 0;
3524 rsp->CreateAction = cpu_to_le32(file_info);
3525 rsp->CreationTime = cpu_to_le64(fp->create_time);
3526 time = ksmbd_UnixTimeToNT(stat.atime);
3527 rsp->LastAccessTime = cpu_to_le64(time);
3528 time = ksmbd_UnixTimeToNT(stat.mtime);
3529 rsp->LastWriteTime = cpu_to_le64(time);
3530 time = ksmbd_UnixTimeToNT(stat.ctime);
3531 rsp->ChangeTime = cpu_to_le64(time);
3532 rsp->AllocationSize = S_ISDIR(stat.mode) ? 0 :
3533 cpu_to_le64(stat.blocks << 9);
3534 rsp->EndofFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
3535 rsp->FileAttributes = fp->f_ci->m_fattr;
3539 rsp->PersistentFileId = fp->persistent_id;
3540 rsp->VolatileFileId = fp->volatile_id;
3542 rsp->CreateContextsOffset = 0;
3543 rsp->CreateContextsLength = 0;
3544 iov_len = offsetof(struct smb2_create_rsp, Buffer);
3546 /* If lease is request send lease context response */
3547 if (opinfo && opinfo->is_lease) {
3548 struct create_context *lease_ccontext;
3550 ksmbd_debug(SMB, "lease granted on(%s) lease state 0x%x\n",
3551 name, opinfo->o_lease->state);
3552 rsp->OplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
3554 lease_ccontext = (struct create_context *)rsp->Buffer;
3556 create_lease_buf(rsp->Buffer, opinfo->o_lease);
3557 le32_add_cpu(&rsp->CreateContextsLength,
3558 conn->vals->create_lease_size);
3559 iov_len += conn->vals->create_lease_size;
3560 next_ptr = &lease_ccontext->Next;
3561 next_off = conn->vals->create_lease_size;
3564 if (maximal_access_ctxt) {
3565 struct create_context *mxac_ccontext;
3567 if (maximal_access == 0)
3568 ksmbd_vfs_query_maximal_access(idmap,
3571 mxac_ccontext = (struct create_context *)(rsp->Buffer +
3572 le32_to_cpu(rsp->CreateContextsLength));
3574 create_mxac_rsp_buf(rsp->Buffer +
3575 le32_to_cpu(rsp->CreateContextsLength),
3576 le32_to_cpu(maximal_access));
3577 le32_add_cpu(&rsp->CreateContextsLength,
3578 conn->vals->create_mxac_size);
3579 iov_len += conn->vals->create_mxac_size;
3581 *next_ptr = cpu_to_le32(next_off);
3582 next_ptr = &mxac_ccontext->Next;
3583 next_off = conn->vals->create_mxac_size;
3586 if (query_disk_id) {
3587 struct create_context *disk_id_ccontext;
3589 disk_id_ccontext = (struct create_context *)(rsp->Buffer +
3590 le32_to_cpu(rsp->CreateContextsLength));
3592 create_disk_id_rsp_buf(rsp->Buffer +
3593 le32_to_cpu(rsp->CreateContextsLength),
3594 stat.ino, tcon->id);
3595 le32_add_cpu(&rsp->CreateContextsLength,
3596 conn->vals->create_disk_id_size);
3597 iov_len += conn->vals->create_disk_id_size;
3599 *next_ptr = cpu_to_le32(next_off);
3600 next_ptr = &disk_id_ccontext->Next;
3601 next_off = conn->vals->create_disk_id_size;
3604 if (dh_info.type == DURABLE_REQ || dh_info.type == DURABLE_REQ_V2) {
3605 struct create_context *durable_ccontext;
3607 durable_ccontext = (struct create_context *)(rsp->Buffer +
3608 le32_to_cpu(rsp->CreateContextsLength));
3610 if (dh_info.type == DURABLE_REQ) {
3611 create_durable_rsp_buf(rsp->Buffer +
3612 le32_to_cpu(rsp->CreateContextsLength));
3613 le32_add_cpu(&rsp->CreateContextsLength,
3614 conn->vals->create_durable_size);
3615 iov_len += conn->vals->create_durable_size;
3617 create_durable_v2_rsp_buf(rsp->Buffer +
3618 le32_to_cpu(rsp->CreateContextsLength),
3620 le32_add_cpu(&rsp->CreateContextsLength,
3621 conn->vals->create_durable_v2_size);
3622 iov_len += conn->vals->create_durable_v2_size;
3626 *next_ptr = cpu_to_le32(next_off);
3627 next_ptr = &durable_ccontext->Next;
3628 next_off = conn->vals->create_durable_size;
3633 create_posix_rsp_buf(rsp->Buffer +
3634 le32_to_cpu(rsp->CreateContextsLength),
3636 le32_add_cpu(&rsp->CreateContextsLength,
3637 conn->vals->create_posix_size);
3638 iov_len += conn->vals->create_posix_size;
3640 *next_ptr = cpu_to_le32(next_off);
3643 if (contxt_cnt > 0) {
3644 rsp->CreateContextsOffset =
3645 cpu_to_le32(offsetof(struct smb2_create_rsp, Buffer));
3649 if (rc && (file_present || created))
3650 ksmbd_vfs_kern_path_unlock(&parent_path, &path);
3653 ksmbd_revert_fsids(work);
3657 ksmbd_update_fstate(&work->sess->file_table, fp, FP_INITED);
3658 rc = ksmbd_iov_pin_rsp(work, (void *)rsp, iov_len);
3662 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
3663 else if (rc == -EOPNOTSUPP)
3664 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
3665 else if (rc == -EACCES || rc == -ESTALE || rc == -EXDEV)
3666 rsp->hdr.Status = STATUS_ACCESS_DENIED;
3667 else if (rc == -ENOENT)
3668 rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
3669 else if (rc == -EPERM)
3670 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
3671 else if (rc == -EBUSY)
3672 rsp->hdr.Status = STATUS_DELETE_PENDING;
3673 else if (rc == -EBADF)
3674 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
3675 else if (rc == -ENOEXEC)
3676 rsp->hdr.Status = STATUS_DUPLICATE_OBJECTID;
3677 else if (rc == -ENXIO)
3678 rsp->hdr.Status = STATUS_NO_SUCH_DEVICE;
3679 else if (rc == -EEXIST)
3680 rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
3681 else if (rc == -EMFILE)
3682 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
3683 if (!rsp->hdr.Status)
3684 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
3687 ksmbd_fd_put(work, fp);
3688 smb2_set_err_rsp(work);
3689 ksmbd_debug(SMB, "Error response: %x\n", rsp->hdr.Status);
3698 static int readdir_info_level_struct_sz(int info_level)
3700 switch (info_level) {
3701 case FILE_FULL_DIRECTORY_INFORMATION:
3702 return sizeof(struct file_full_directory_info);
3703 case FILE_BOTH_DIRECTORY_INFORMATION:
3704 return sizeof(struct file_both_directory_info);
3705 case FILE_DIRECTORY_INFORMATION:
3706 return sizeof(struct file_directory_info);
3707 case FILE_NAMES_INFORMATION:
3708 return sizeof(struct file_names_info);
3709 case FILEID_FULL_DIRECTORY_INFORMATION:
3710 return sizeof(struct file_id_full_dir_info);
3711 case FILEID_BOTH_DIRECTORY_INFORMATION:
3712 return sizeof(struct file_id_both_directory_info);
3713 case SMB_FIND_FILE_POSIX_INFO:
3714 return sizeof(struct smb2_posix_info);
3720 static int dentry_name(struct ksmbd_dir_info *d_info, int info_level)
3722 switch (info_level) {
3723 case FILE_FULL_DIRECTORY_INFORMATION:
3725 struct file_full_directory_info *ffdinfo;
3727 ffdinfo = (struct file_full_directory_info *)d_info->rptr;
3728 d_info->rptr += le32_to_cpu(ffdinfo->NextEntryOffset);
3729 d_info->name = ffdinfo->FileName;
3730 d_info->name_len = le32_to_cpu(ffdinfo->FileNameLength);
3733 case FILE_BOTH_DIRECTORY_INFORMATION:
3735 struct file_both_directory_info *fbdinfo;
3737 fbdinfo = (struct file_both_directory_info *)d_info->rptr;
3738 d_info->rptr += le32_to_cpu(fbdinfo->NextEntryOffset);
3739 d_info->name = fbdinfo->FileName;
3740 d_info->name_len = le32_to_cpu(fbdinfo->FileNameLength);
3743 case FILE_DIRECTORY_INFORMATION:
3745 struct file_directory_info *fdinfo;
3747 fdinfo = (struct file_directory_info *)d_info->rptr;
3748 d_info->rptr += le32_to_cpu(fdinfo->NextEntryOffset);
3749 d_info->name = fdinfo->FileName;
3750 d_info->name_len = le32_to_cpu(fdinfo->FileNameLength);
3753 case FILE_NAMES_INFORMATION:
3755 struct file_names_info *fninfo;
3757 fninfo = (struct file_names_info *)d_info->rptr;
3758 d_info->rptr += le32_to_cpu(fninfo->NextEntryOffset);
3759 d_info->name = fninfo->FileName;
3760 d_info->name_len = le32_to_cpu(fninfo->FileNameLength);
3763 case FILEID_FULL_DIRECTORY_INFORMATION:
3765 struct file_id_full_dir_info *dinfo;
3767 dinfo = (struct file_id_full_dir_info *)d_info->rptr;
3768 d_info->rptr += le32_to_cpu(dinfo->NextEntryOffset);
3769 d_info->name = dinfo->FileName;
3770 d_info->name_len = le32_to_cpu(dinfo->FileNameLength);
3773 case FILEID_BOTH_DIRECTORY_INFORMATION:
3775 struct file_id_both_directory_info *fibdinfo;
3777 fibdinfo = (struct file_id_both_directory_info *)d_info->rptr;
3778 d_info->rptr += le32_to_cpu(fibdinfo->NextEntryOffset);
3779 d_info->name = fibdinfo->FileName;
3780 d_info->name_len = le32_to_cpu(fibdinfo->FileNameLength);
3783 case SMB_FIND_FILE_POSIX_INFO:
3785 struct smb2_posix_info *posix_info;
3787 posix_info = (struct smb2_posix_info *)d_info->rptr;
3788 d_info->rptr += le32_to_cpu(posix_info->NextEntryOffset);
3789 d_info->name = posix_info->name;
3790 d_info->name_len = le32_to_cpu(posix_info->name_len);
3799 * smb2_populate_readdir_entry() - encode directory entry in smb2 response
3801 * @conn: connection instance
3802 * @info_level: smb information level
3803 * @d_info: structure included variables for query dir
3804 * @ksmbd_kstat: ksmbd wrapper of dirent stat information
3806 * if directory has many entries, find first can't read it fully.
3807 * find next might be called multiple times to read remaining dir entries
3809 * Return: 0 on success, otherwise error
3811 static int smb2_populate_readdir_entry(struct ksmbd_conn *conn, int info_level,
3812 struct ksmbd_dir_info *d_info,
3813 struct ksmbd_kstat *ksmbd_kstat)
3815 int next_entry_offset = 0;
3819 int struct_sz, rc = 0;
3821 conv_name = ksmbd_convert_dir_info_name(d_info,
3827 /* Somehow the name has only terminating NULL bytes */
3830 goto free_conv_name;
3833 struct_sz = readdir_info_level_struct_sz(info_level) + conv_len;
3834 next_entry_offset = ALIGN(struct_sz, KSMBD_DIR_INFO_ALIGNMENT);
3835 d_info->last_entry_off_align = next_entry_offset - struct_sz;
3837 if (next_entry_offset > d_info->out_buf_len) {
3838 d_info->out_buf_len = 0;
3840 goto free_conv_name;
3843 kstat = d_info->wptr;
3844 if (info_level != FILE_NAMES_INFORMATION)
3845 kstat = ksmbd_vfs_init_kstat(&d_info->wptr, ksmbd_kstat);
3847 switch (info_level) {
3848 case FILE_FULL_DIRECTORY_INFORMATION:
3850 struct file_full_directory_info *ffdinfo;
3852 ffdinfo = (struct file_full_directory_info *)kstat;
3853 ffdinfo->FileNameLength = cpu_to_le32(conv_len);
3855 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3856 if (ffdinfo->EaSize)
3857 ffdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3858 if (d_info->hide_dot_file && d_info->name[0] == '.')
3859 ffdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3860 memcpy(ffdinfo->FileName, conv_name, conv_len);
3861 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3864 case FILE_BOTH_DIRECTORY_INFORMATION:
3866 struct file_both_directory_info *fbdinfo;
3868 fbdinfo = (struct file_both_directory_info *)kstat;
3869 fbdinfo->FileNameLength = cpu_to_le32(conv_len);
3871 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3872 if (fbdinfo->EaSize)
3873 fbdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3874 fbdinfo->ShortNameLength = 0;
3875 fbdinfo->Reserved = 0;
3876 if (d_info->hide_dot_file && d_info->name[0] == '.')
3877 fbdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3878 memcpy(fbdinfo->FileName, conv_name, conv_len);
3879 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3882 case FILE_DIRECTORY_INFORMATION:
3884 struct file_directory_info *fdinfo;
3886 fdinfo = (struct file_directory_info *)kstat;
3887 fdinfo->FileNameLength = cpu_to_le32(conv_len);
3888 if (d_info->hide_dot_file && d_info->name[0] == '.')
3889 fdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3890 memcpy(fdinfo->FileName, conv_name, conv_len);
3891 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3894 case FILE_NAMES_INFORMATION:
3896 struct file_names_info *fninfo;
3898 fninfo = (struct file_names_info *)kstat;
3899 fninfo->FileNameLength = cpu_to_le32(conv_len);
3900 memcpy(fninfo->FileName, conv_name, conv_len);
3901 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3904 case FILEID_FULL_DIRECTORY_INFORMATION:
3906 struct file_id_full_dir_info *dinfo;
3908 dinfo = (struct file_id_full_dir_info *)kstat;
3909 dinfo->FileNameLength = cpu_to_le32(conv_len);
3911 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3913 dinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3914 dinfo->Reserved = 0;
3915 dinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
3916 if (d_info->hide_dot_file && d_info->name[0] == '.')
3917 dinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3918 memcpy(dinfo->FileName, conv_name, conv_len);
3919 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3922 case FILEID_BOTH_DIRECTORY_INFORMATION:
3924 struct file_id_both_directory_info *fibdinfo;
3926 fibdinfo = (struct file_id_both_directory_info *)kstat;
3927 fibdinfo->FileNameLength = cpu_to_le32(conv_len);
3929 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3930 if (fibdinfo->EaSize)
3931 fibdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3932 fibdinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
3933 fibdinfo->ShortNameLength = 0;
3934 fibdinfo->Reserved = 0;
3935 fibdinfo->Reserved2 = cpu_to_le16(0);
3936 if (d_info->hide_dot_file && d_info->name[0] == '.')
3937 fibdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3938 memcpy(fibdinfo->FileName, conv_name, conv_len);
3939 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3942 case SMB_FIND_FILE_POSIX_INFO:
3944 struct smb2_posix_info *posix_info;
3947 posix_info = (struct smb2_posix_info *)kstat;
3948 posix_info->Ignored = 0;
3949 posix_info->CreationTime = cpu_to_le64(ksmbd_kstat->create_time);
3950 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->ctime);
3951 posix_info->ChangeTime = cpu_to_le64(time);
3952 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->atime);
3953 posix_info->LastAccessTime = cpu_to_le64(time);
3954 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->mtime);
3955 posix_info->LastWriteTime = cpu_to_le64(time);
3956 posix_info->EndOfFile = cpu_to_le64(ksmbd_kstat->kstat->size);
3957 posix_info->AllocationSize = cpu_to_le64(ksmbd_kstat->kstat->blocks << 9);
3958 posix_info->DeviceId = cpu_to_le32(ksmbd_kstat->kstat->rdev);
3959 posix_info->HardLinks = cpu_to_le32(ksmbd_kstat->kstat->nlink);
3960 posix_info->Mode = cpu_to_le32(ksmbd_kstat->kstat->mode & 0777);
3961 posix_info->Inode = cpu_to_le64(ksmbd_kstat->kstat->ino);
3962 posix_info->DosAttributes =
3963 S_ISDIR(ksmbd_kstat->kstat->mode) ?
3964 FILE_ATTRIBUTE_DIRECTORY_LE : FILE_ATTRIBUTE_ARCHIVE_LE;
3965 if (d_info->hide_dot_file && d_info->name[0] == '.')
3966 posix_info->DosAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3968 * SidBuffer(32) contain two sids(Domain sid(16), UNIX group sid(16)).
3969 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) +
3970 * sub_auth(4 * 1(num_subauth)) + RID(4).
3972 id_to_sid(from_kuid_munged(&init_user_ns, ksmbd_kstat->kstat->uid),
3973 SIDUNIX_USER, (struct smb_sid *)&posix_info->SidBuffer[0]);
3974 id_to_sid(from_kgid_munged(&init_user_ns, ksmbd_kstat->kstat->gid),
3975 SIDUNIX_GROUP, (struct smb_sid *)&posix_info->SidBuffer[16]);
3976 memcpy(posix_info->name, conv_name, conv_len);
3977 posix_info->name_len = cpu_to_le32(conv_len);
3978 posix_info->NextEntryOffset = cpu_to_le32(next_entry_offset);
3982 } /* switch (info_level) */
3984 d_info->last_entry_offset = d_info->data_count;
3985 d_info->data_count += next_entry_offset;
3986 d_info->out_buf_len -= next_entry_offset;
3987 d_info->wptr += next_entry_offset;
3990 "info_level : %d, buf_len :%d, next_offset : %d, data_count : %d\n",
3991 info_level, d_info->out_buf_len,
3992 next_entry_offset, d_info->data_count);
3999 struct smb2_query_dir_private {
4000 struct ksmbd_work *work;
4001 char *search_pattern;
4002 struct ksmbd_file *dir_fp;
4004 struct ksmbd_dir_info *d_info;
4008 static void lock_dir(struct ksmbd_file *dir_fp)
4010 struct dentry *dir = dir_fp->filp->f_path.dentry;
4012 inode_lock_nested(d_inode(dir), I_MUTEX_PARENT);
4015 static void unlock_dir(struct ksmbd_file *dir_fp)
4017 struct dentry *dir = dir_fp->filp->f_path.dentry;
4019 inode_unlock(d_inode(dir));
4022 static int process_query_dir_entries(struct smb2_query_dir_private *priv)
4024 struct mnt_idmap *idmap = file_mnt_idmap(priv->dir_fp->filp);
4026 struct ksmbd_kstat ksmbd_kstat;
4030 for (i = 0; i < priv->d_info->num_entry; i++) {
4031 struct dentry *dent;
4033 if (dentry_name(priv->d_info, priv->info_level))
4036 lock_dir(priv->dir_fp);
4037 dent = lookup_one(idmap, priv->d_info->name,
4038 priv->dir_fp->filp->f_path.dentry,
4039 priv->d_info->name_len);
4040 unlock_dir(priv->dir_fp);
4043 ksmbd_debug(SMB, "Cannot lookup `%s' [%ld]\n",
4048 if (unlikely(d_is_negative(dent))) {
4050 ksmbd_debug(SMB, "Negative dentry `%s'\n",
4051 priv->d_info->name);
4055 ksmbd_kstat.kstat = &kstat;
4056 if (priv->info_level != FILE_NAMES_INFORMATION) {
4057 rc = ksmbd_vfs_fill_dentry_attrs(priv->work,
4067 rc = smb2_populate_readdir_entry(priv->work->conn,
4078 static int reserve_populate_dentry(struct ksmbd_dir_info *d_info,
4083 int next_entry_offset;
4085 struct_sz = readdir_info_level_struct_sz(info_level);
4086 if (struct_sz == -EOPNOTSUPP)
4089 conv_len = (d_info->name_len + 1) * 2;
4090 next_entry_offset = ALIGN(struct_sz + conv_len,
4091 KSMBD_DIR_INFO_ALIGNMENT);
4093 if (next_entry_offset > d_info->out_buf_len) {
4094 d_info->out_buf_len = 0;
4098 switch (info_level) {
4099 case FILE_FULL_DIRECTORY_INFORMATION:
4101 struct file_full_directory_info *ffdinfo;
4103 ffdinfo = (struct file_full_directory_info *)d_info->wptr;
4104 memcpy(ffdinfo->FileName, d_info->name, d_info->name_len);
4105 ffdinfo->FileName[d_info->name_len] = 0x00;
4106 ffdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
4107 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4110 case FILE_BOTH_DIRECTORY_INFORMATION:
4112 struct file_both_directory_info *fbdinfo;
4114 fbdinfo = (struct file_both_directory_info *)d_info->wptr;
4115 memcpy(fbdinfo->FileName, d_info->name, d_info->name_len);
4116 fbdinfo->FileName[d_info->name_len] = 0x00;
4117 fbdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
4118 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4121 case FILE_DIRECTORY_INFORMATION:
4123 struct file_directory_info *fdinfo;
4125 fdinfo = (struct file_directory_info *)d_info->wptr;
4126 memcpy(fdinfo->FileName, d_info->name, d_info->name_len);
4127 fdinfo->FileName[d_info->name_len] = 0x00;
4128 fdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
4129 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4132 case FILE_NAMES_INFORMATION:
4134 struct file_names_info *fninfo;
4136 fninfo = (struct file_names_info *)d_info->wptr;
4137 memcpy(fninfo->FileName, d_info->name, d_info->name_len);
4138 fninfo->FileName[d_info->name_len] = 0x00;
4139 fninfo->FileNameLength = cpu_to_le32(d_info->name_len);
4140 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4143 case FILEID_FULL_DIRECTORY_INFORMATION:
4145 struct file_id_full_dir_info *dinfo;
4147 dinfo = (struct file_id_full_dir_info *)d_info->wptr;
4148 memcpy(dinfo->FileName, d_info->name, d_info->name_len);
4149 dinfo->FileName[d_info->name_len] = 0x00;
4150 dinfo->FileNameLength = cpu_to_le32(d_info->name_len);
4151 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4154 case FILEID_BOTH_DIRECTORY_INFORMATION:
4156 struct file_id_both_directory_info *fibdinfo;
4158 fibdinfo = (struct file_id_both_directory_info *)d_info->wptr;
4159 memcpy(fibdinfo->FileName, d_info->name, d_info->name_len);
4160 fibdinfo->FileName[d_info->name_len] = 0x00;
4161 fibdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
4162 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
4165 case SMB_FIND_FILE_POSIX_INFO:
4167 struct smb2_posix_info *posix_info;
4169 posix_info = (struct smb2_posix_info *)d_info->wptr;
4170 memcpy(posix_info->name, d_info->name, d_info->name_len);
4171 posix_info->name[d_info->name_len] = 0x00;
4172 posix_info->name_len = cpu_to_le32(d_info->name_len);
4173 posix_info->NextEntryOffset =
4174 cpu_to_le32(next_entry_offset);
4177 } /* switch (info_level) */
4179 d_info->num_entry++;
4180 d_info->out_buf_len -= next_entry_offset;
4181 d_info->wptr += next_entry_offset;
4185 static bool __query_dir(struct dir_context *ctx, const char *name, int namlen,
4186 loff_t offset, u64 ino, unsigned int d_type)
4188 struct ksmbd_readdir_data *buf;
4189 struct smb2_query_dir_private *priv;
4190 struct ksmbd_dir_info *d_info;
4193 buf = container_of(ctx, struct ksmbd_readdir_data, ctx);
4194 priv = buf->private;
4195 d_info = priv->d_info;
4197 /* dot and dotdot entries are already reserved */
4198 if (!strcmp(".", name) || !strcmp("..", name))
4200 if (ksmbd_share_veto_filename(priv->work->tcon->share_conf, name))
4202 if (!match_pattern(name, namlen, priv->search_pattern))
4205 d_info->name = name;
4206 d_info->name_len = namlen;
4207 rc = reserve_populate_dentry(d_info, priv->info_level);
4210 if (d_info->flags & SMB2_RETURN_SINGLE_ENTRY)
4211 d_info->out_buf_len = 0;
4215 static int verify_info_level(int info_level)
4217 switch (info_level) {
4218 case FILE_FULL_DIRECTORY_INFORMATION:
4219 case FILE_BOTH_DIRECTORY_INFORMATION:
4220 case FILE_DIRECTORY_INFORMATION:
4221 case FILE_NAMES_INFORMATION:
4222 case FILEID_FULL_DIRECTORY_INFORMATION:
4223 case FILEID_BOTH_DIRECTORY_INFORMATION:
4224 case SMB_FIND_FILE_POSIX_INFO:
4233 static int smb2_resp_buf_len(struct ksmbd_work *work, unsigned short hdr2_len)
4237 free_len = (int)(work->response_sz -
4238 (get_rfc1002_len(work->response_buf) + 4)) - hdr2_len;
4242 static int smb2_calc_max_out_buf_len(struct ksmbd_work *work,
4243 unsigned short hdr2_len,
4244 unsigned int out_buf_len)
4248 if (out_buf_len > work->conn->vals->max_trans_size)
4251 free_len = smb2_resp_buf_len(work, hdr2_len);
4255 return min_t(int, out_buf_len, free_len);
4258 int smb2_query_dir(struct ksmbd_work *work)
4260 struct ksmbd_conn *conn = work->conn;
4261 struct smb2_query_directory_req *req;
4262 struct smb2_query_directory_rsp *rsp;
4263 struct ksmbd_share_config *share = work->tcon->share_conf;
4264 struct ksmbd_file *dir_fp = NULL;
4265 struct ksmbd_dir_info d_info;
4267 char *srch_ptr = NULL;
4268 unsigned char srch_flag;
4270 struct smb2_query_dir_private query_dir_private = {NULL, };
4272 WORK_BUFFERS(work, req, rsp);
4274 if (ksmbd_override_fsids(work)) {
4275 rsp->hdr.Status = STATUS_NO_MEMORY;
4276 smb2_set_err_rsp(work);
4280 rc = verify_info_level(req->FileInformationClass);
4286 dir_fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
4292 if (!(dir_fp->daccess & FILE_LIST_DIRECTORY_LE) ||
4293 inode_permission(file_mnt_idmap(dir_fp->filp),
4294 file_inode(dir_fp->filp),
4295 MAY_READ | MAY_EXEC)) {
4296 pr_err("no right to enumerate directory (%pD)\n", dir_fp->filp);
4301 if (!S_ISDIR(file_inode(dir_fp->filp)->i_mode)) {
4302 pr_err("can't do query dir for a file\n");
4307 srch_flag = req->Flags;
4308 srch_ptr = smb_strndup_from_utf16((char *)req + le16_to_cpu(req->FileNameOffset),
4309 le16_to_cpu(req->FileNameLength), 1,
4311 if (IS_ERR(srch_ptr)) {
4312 ksmbd_debug(SMB, "Search Pattern not found\n");
4316 ksmbd_debug(SMB, "Search pattern is %s\n", srch_ptr);
4319 if (srch_flag & SMB2_REOPEN || srch_flag & SMB2_RESTART_SCANS) {
4320 ksmbd_debug(SMB, "Restart directory scan\n");
4321 generic_file_llseek(dir_fp->filp, 0, SEEK_SET);
4324 memset(&d_info, 0, sizeof(struct ksmbd_dir_info));
4325 d_info.wptr = (char *)rsp->Buffer;
4326 d_info.rptr = (char *)rsp->Buffer;
4327 d_info.out_buf_len =
4328 smb2_calc_max_out_buf_len(work, 8,
4329 le32_to_cpu(req->OutputBufferLength));
4330 if (d_info.out_buf_len < 0) {
4334 d_info.flags = srch_flag;
4337 * reserve dot and dotdot entries in head of buffer
4340 rc = ksmbd_populate_dot_dotdot_entries(work, req->FileInformationClass,
4341 dir_fp, &d_info, srch_ptr,
4342 smb2_populate_readdir_entry);
4348 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_HIDE_DOT_FILES))
4349 d_info.hide_dot_file = true;
4351 buffer_sz = d_info.out_buf_len;
4352 d_info.rptr = d_info.wptr;
4353 query_dir_private.work = work;
4354 query_dir_private.search_pattern = srch_ptr;
4355 query_dir_private.dir_fp = dir_fp;
4356 query_dir_private.d_info = &d_info;
4357 query_dir_private.info_level = req->FileInformationClass;
4358 dir_fp->readdir_data.private = &query_dir_private;
4359 set_ctx_actor(&dir_fp->readdir_data.ctx, __query_dir);
4361 rc = iterate_dir(dir_fp->filp, &dir_fp->readdir_data.ctx);
4363 * req->OutputBufferLength is too small to contain even one entry.
4364 * In this case, it immediately returns OutputBufferLength 0 to client.
4366 if (!d_info.out_buf_len && !d_info.num_entry)
4368 if (rc > 0 || rc == -ENOSPC)
4373 d_info.wptr = d_info.rptr;
4374 d_info.out_buf_len = buffer_sz;
4375 rc = process_query_dir_entries(&query_dir_private);
4379 if (!d_info.data_count && d_info.out_buf_len >= 0) {
4380 if (srch_flag & SMB2_RETURN_SINGLE_ENTRY && !is_asterisk(srch_ptr)) {
4381 rsp->hdr.Status = STATUS_NO_SUCH_FILE;
4383 dir_fp->dot_dotdot[0] = dir_fp->dot_dotdot[1] = 0;
4384 rsp->hdr.Status = STATUS_NO_MORE_FILES;
4386 rsp->StructureSize = cpu_to_le16(9);
4387 rsp->OutputBufferOffset = cpu_to_le16(0);
4388 rsp->OutputBufferLength = cpu_to_le32(0);
4390 rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
4391 sizeof(struct smb2_query_directory_rsp));
4396 ((struct file_directory_info *)
4397 ((char *)rsp->Buffer + d_info.last_entry_offset))
4398 ->NextEntryOffset = 0;
4399 if (d_info.data_count >= d_info.last_entry_off_align)
4400 d_info.data_count -= d_info.last_entry_off_align;
4402 rsp->StructureSize = cpu_to_le16(9);
4403 rsp->OutputBufferOffset = cpu_to_le16(72);
4404 rsp->OutputBufferLength = cpu_to_le32(d_info.data_count);
4405 rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
4406 offsetof(struct smb2_query_directory_rsp, Buffer) +
4413 ksmbd_fd_put(work, dir_fp);
4414 ksmbd_revert_fsids(work);
4418 pr_err("error while processing smb2 query dir rc = %d\n", rc);
4423 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
4424 else if (rc == -EACCES)
4425 rsp->hdr.Status = STATUS_ACCESS_DENIED;
4426 else if (rc == -ENOENT)
4427 rsp->hdr.Status = STATUS_NO_SUCH_FILE;
4428 else if (rc == -EBADF)
4429 rsp->hdr.Status = STATUS_FILE_CLOSED;
4430 else if (rc == -ENOMEM)
4431 rsp->hdr.Status = STATUS_NO_MEMORY;
4432 else if (rc == -EFAULT)
4433 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
4434 else if (rc == -EIO)
4435 rsp->hdr.Status = STATUS_FILE_CORRUPT_ERROR;
4436 if (!rsp->hdr.Status)
4437 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
4439 smb2_set_err_rsp(work);
4440 ksmbd_fd_put(work, dir_fp);
4441 ksmbd_revert_fsids(work);
4446 * buffer_check_err() - helper function to check buffer errors
4447 * @reqOutputBufferLength: max buffer length expected in command response
4448 * @rsp: query info response buffer contains output buffer length
4449 * @rsp_org: base response buffer pointer in case of chained response
4451 * Return: 0 on success, otherwise error
4453 static int buffer_check_err(int reqOutputBufferLength,
4454 struct smb2_query_info_rsp *rsp,
4457 if (reqOutputBufferLength < le32_to_cpu(rsp->OutputBufferLength)) {
4458 pr_err("Invalid Buffer Size Requested\n");
4459 rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
4460 *(__be32 *)rsp_org = cpu_to_be32(sizeof(struct smb2_hdr));
4466 static void get_standard_info_pipe(struct smb2_query_info_rsp *rsp,
4469 struct smb2_file_standard_info *sinfo;
4471 sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
4473 sinfo->AllocationSize = cpu_to_le64(4096);
4474 sinfo->EndOfFile = cpu_to_le64(0);
4475 sinfo->NumberOfLinks = cpu_to_le32(1);
4476 sinfo->DeletePending = 1;
4477 sinfo->Directory = 0;
4478 rsp->OutputBufferLength =
4479 cpu_to_le32(sizeof(struct smb2_file_standard_info));
4482 static void get_internal_info_pipe(struct smb2_query_info_rsp *rsp, u64 num,
4485 struct smb2_file_internal_info *file_info;
4487 file_info = (struct smb2_file_internal_info *)rsp->Buffer;
4489 /* any unique number */
4490 file_info->IndexNumber = cpu_to_le64(num | (1ULL << 63));
4491 rsp->OutputBufferLength =
4492 cpu_to_le32(sizeof(struct smb2_file_internal_info));
4495 static int smb2_get_info_file_pipe(struct ksmbd_session *sess,
4496 struct smb2_query_info_req *req,
4497 struct smb2_query_info_rsp *rsp,
4504 * Windows can sometime send query file info request on
4505 * pipe without opening it, checking error condition here
4507 id = req->VolatileFileId;
4508 if (!ksmbd_session_rpc_method(sess, id))
4511 ksmbd_debug(SMB, "FileInfoClass %u, FileId 0x%llx\n",
4512 req->FileInfoClass, req->VolatileFileId);
4514 switch (req->FileInfoClass) {
4515 case FILE_STANDARD_INFORMATION:
4516 get_standard_info_pipe(rsp, rsp_org);
4517 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4520 case FILE_INTERNAL_INFORMATION:
4521 get_internal_info_pipe(rsp, id, rsp_org);
4522 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4526 ksmbd_debug(SMB, "smb2_info_file_pipe for %u not supported\n",
4527 req->FileInfoClass);
4534 * smb2_get_ea() - handler for smb2 get extended attribute command
4535 * @work: smb work containing query info command buffer
4536 * @fp: ksmbd_file pointer
4537 * @req: get extended attribute request
4538 * @rsp: response buffer pointer
4539 * @rsp_org: base response buffer pointer in case of chained response
4541 * Return: 0 on success, otherwise error
4543 static int smb2_get_ea(struct ksmbd_work *work, struct ksmbd_file *fp,
4544 struct smb2_query_info_req *req,
4545 struct smb2_query_info_rsp *rsp, void *rsp_org)
4547 struct smb2_ea_info *eainfo, *prev_eainfo;
4548 char *name, *ptr, *xattr_list = NULL, *buf;
4549 int rc, name_len, value_len, xattr_list_len, idx;
4550 ssize_t buf_free_len, alignment_bytes, next_offset, rsp_data_cnt = 0;
4551 struct smb2_ea_info_req *ea_req = NULL;
4552 const struct path *path;
4553 struct mnt_idmap *idmap = file_mnt_idmap(fp->filp);
4555 if (!(fp->daccess & FILE_READ_EA_LE)) {
4556 pr_err("Not permitted to read ext attr : 0x%x\n",
4561 path = &fp->filp->f_path;
4562 /* single EA entry is requested with given user.* name */
4563 if (req->InputBufferLength) {
4564 if (le32_to_cpu(req->InputBufferLength) <
4565 sizeof(struct smb2_ea_info_req))
4568 ea_req = (struct smb2_ea_info_req *)((char *)req +
4569 le16_to_cpu(req->InputBufferOffset));
4571 /* need to send all EAs, if no specific EA is requested*/
4572 if (le32_to_cpu(req->Flags) & SL_RETURN_SINGLE_ENTRY)
4574 "All EAs are requested but need to send single EA entry in rsp flags 0x%x\n",
4575 le32_to_cpu(req->Flags));
4579 smb2_calc_max_out_buf_len(work, 8,
4580 le32_to_cpu(req->OutputBufferLength));
4581 if (buf_free_len < 0)
4584 rc = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
4586 rsp->hdr.Status = STATUS_INVALID_HANDLE;
4588 } else if (!rc) { /* there is no EA in the file */
4589 ksmbd_debug(SMB, "no ea data in the file\n");
4592 xattr_list_len = rc;
4594 ptr = (char *)rsp->Buffer;
4595 eainfo = (struct smb2_ea_info *)ptr;
4596 prev_eainfo = eainfo;
4599 while (idx < xattr_list_len) {
4600 name = xattr_list + idx;
4601 name_len = strlen(name);
4603 ksmbd_debug(SMB, "%s, len %d\n", name, name_len);
4604 idx += name_len + 1;
4607 * CIFS does not support EA other than user.* namespace,
4608 * still keep the framework generic, to list other attrs
4611 if (strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4614 if (!strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
4618 if (req->InputBufferLength &&
4619 strncmp(&name[XATTR_USER_PREFIX_LEN], ea_req->name,
4620 ea_req->EaNameLength))
4623 if (!strncmp(&name[XATTR_USER_PREFIX_LEN],
4624 DOS_ATTRIBUTE_PREFIX, DOS_ATTRIBUTE_PREFIX_LEN))
4627 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4628 name_len -= XATTR_USER_PREFIX_LEN;
4630 ptr = eainfo->name + name_len + 1;
4631 buf_free_len -= (offsetof(struct smb2_ea_info, name) +
4633 /* bailout if xattr can't fit in buf_free_len */
4634 value_len = ksmbd_vfs_getxattr(idmap, path->dentry,
4636 if (value_len <= 0) {
4638 rsp->hdr.Status = STATUS_INVALID_HANDLE;
4642 buf_free_len -= value_len;
4643 if (buf_free_len < 0) {
4648 memcpy(ptr, buf, value_len);
4653 eainfo->EaNameLength = name_len;
4655 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4656 memcpy(eainfo->name, &name[XATTR_USER_PREFIX_LEN],
4659 memcpy(eainfo->name, name, name_len);
4661 eainfo->name[name_len] = '\0';
4662 eainfo->EaValueLength = cpu_to_le16(value_len);
4663 next_offset = offsetof(struct smb2_ea_info, name) +
4664 name_len + 1 + value_len;
4666 /* align next xattr entry at 4 byte bundary */
4667 alignment_bytes = ((next_offset + 3) & ~3) - next_offset;
4668 if (alignment_bytes) {
4669 memset(ptr, '\0', alignment_bytes);
4670 ptr += alignment_bytes;
4671 next_offset += alignment_bytes;
4672 buf_free_len -= alignment_bytes;
4674 eainfo->NextEntryOffset = cpu_to_le32(next_offset);
4675 prev_eainfo = eainfo;
4676 eainfo = (struct smb2_ea_info *)ptr;
4677 rsp_data_cnt += next_offset;
4679 if (req->InputBufferLength) {
4680 ksmbd_debug(SMB, "single entry requested\n");
4685 /* no more ea entries */
4686 prev_eainfo->NextEntryOffset = 0;
4689 if (rsp_data_cnt == 0)
4690 rsp->hdr.Status = STATUS_NO_EAS_ON_FILE;
4691 rsp->OutputBufferLength = cpu_to_le32(rsp_data_cnt);
4697 static void get_file_access_info(struct smb2_query_info_rsp *rsp,
4698 struct ksmbd_file *fp, void *rsp_org)
4700 struct smb2_file_access_info *file_info;
4702 file_info = (struct smb2_file_access_info *)rsp->Buffer;
4703 file_info->AccessFlags = fp->daccess;
4704 rsp->OutputBufferLength =
4705 cpu_to_le32(sizeof(struct smb2_file_access_info));
4708 static int get_file_basic_info(struct smb2_query_info_rsp *rsp,
4709 struct ksmbd_file *fp, void *rsp_org)
4711 struct smb2_file_basic_info *basic_info;
4716 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4717 pr_err("no right to read the attributes : 0x%x\n",
4722 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
4723 AT_STATX_SYNC_AS_STAT);
4727 basic_info = (struct smb2_file_basic_info *)rsp->Buffer;
4728 basic_info->CreationTime = cpu_to_le64(fp->create_time);
4729 time = ksmbd_UnixTimeToNT(stat.atime);
4730 basic_info->LastAccessTime = cpu_to_le64(time);
4731 time = ksmbd_UnixTimeToNT(stat.mtime);
4732 basic_info->LastWriteTime = cpu_to_le64(time);
4733 time = ksmbd_UnixTimeToNT(stat.ctime);
4734 basic_info->ChangeTime = cpu_to_le64(time);
4735 basic_info->Attributes = fp->f_ci->m_fattr;
4736 basic_info->Pad1 = 0;
4737 rsp->OutputBufferLength =
4738 cpu_to_le32(sizeof(struct smb2_file_basic_info));
4742 static int get_file_standard_info(struct smb2_query_info_rsp *rsp,
4743 struct ksmbd_file *fp, void *rsp_org)
4745 struct smb2_file_standard_info *sinfo;
4746 unsigned int delete_pending;
4750 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
4751 AT_STATX_SYNC_AS_STAT);
4755 sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
4756 delete_pending = ksmbd_inode_pending_delete(fp);
4758 sinfo->AllocationSize = cpu_to_le64(stat.blocks << 9);
4759 sinfo->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4760 sinfo->NumberOfLinks = cpu_to_le32(get_nlink(&stat) - delete_pending);
4761 sinfo->DeletePending = delete_pending;
4762 sinfo->Directory = S_ISDIR(stat.mode) ? 1 : 0;
4763 rsp->OutputBufferLength =
4764 cpu_to_le32(sizeof(struct smb2_file_standard_info));
4769 static void get_file_alignment_info(struct smb2_query_info_rsp *rsp,
4772 struct smb2_file_alignment_info *file_info;
4774 file_info = (struct smb2_file_alignment_info *)rsp->Buffer;
4775 file_info->AlignmentRequirement = 0;
4776 rsp->OutputBufferLength =
4777 cpu_to_le32(sizeof(struct smb2_file_alignment_info));
4780 static int get_file_all_info(struct ksmbd_work *work,
4781 struct smb2_query_info_rsp *rsp,
4782 struct ksmbd_file *fp,
4785 struct ksmbd_conn *conn = work->conn;
4786 struct smb2_file_all_info *file_info;
4787 unsigned int delete_pending;
4794 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4795 ksmbd_debug(SMB, "no right to read the attributes : 0x%x\n",
4800 filename = convert_to_nt_pathname(work->tcon->share_conf, &fp->filp->f_path);
4801 if (IS_ERR(filename))
4802 return PTR_ERR(filename);
4804 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
4805 AT_STATX_SYNC_AS_STAT);
4809 ksmbd_debug(SMB, "filename = %s\n", filename);
4810 delete_pending = ksmbd_inode_pending_delete(fp);
4811 file_info = (struct smb2_file_all_info *)rsp->Buffer;
4813 file_info->CreationTime = cpu_to_le64(fp->create_time);
4814 time = ksmbd_UnixTimeToNT(stat.atime);
4815 file_info->LastAccessTime = cpu_to_le64(time);
4816 time = ksmbd_UnixTimeToNT(stat.mtime);
4817 file_info->LastWriteTime = cpu_to_le64(time);
4818 time = ksmbd_UnixTimeToNT(stat.ctime);
4819 file_info->ChangeTime = cpu_to_le64(time);
4820 file_info->Attributes = fp->f_ci->m_fattr;
4821 file_info->Pad1 = 0;
4822 file_info->AllocationSize =
4823 cpu_to_le64(stat.blocks << 9);
4824 file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4825 file_info->NumberOfLinks =
4826 cpu_to_le32(get_nlink(&stat) - delete_pending);
4827 file_info->DeletePending = delete_pending;
4828 file_info->Directory = S_ISDIR(stat.mode) ? 1 : 0;
4829 file_info->Pad2 = 0;
4830 file_info->IndexNumber = cpu_to_le64(stat.ino);
4831 file_info->EASize = 0;
4832 file_info->AccessFlags = fp->daccess;
4833 file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
4834 file_info->Mode = fp->coption;
4835 file_info->AlignmentRequirement = 0;
4836 conv_len = smbConvertToUTF16((__le16 *)file_info->FileName, filename,
4837 PATH_MAX, conn->local_nls, 0);
4839 file_info->FileNameLength = cpu_to_le32(conv_len);
4840 rsp->OutputBufferLength =
4841 cpu_to_le32(sizeof(struct smb2_file_all_info) + conv_len - 1);
4846 static void get_file_alternate_info(struct ksmbd_work *work,
4847 struct smb2_query_info_rsp *rsp,
4848 struct ksmbd_file *fp,
4851 struct ksmbd_conn *conn = work->conn;
4852 struct smb2_file_alt_name_info *file_info;
4853 struct dentry *dentry = fp->filp->f_path.dentry;
4856 spin_lock(&dentry->d_lock);
4857 file_info = (struct smb2_file_alt_name_info *)rsp->Buffer;
4858 conv_len = ksmbd_extract_shortname(conn,
4859 dentry->d_name.name,
4860 file_info->FileName);
4861 spin_unlock(&dentry->d_lock);
4862 file_info->FileNameLength = cpu_to_le32(conv_len);
4863 rsp->OutputBufferLength =
4864 cpu_to_le32(sizeof(struct smb2_file_alt_name_info) + conv_len);
4867 static int get_file_stream_info(struct ksmbd_work *work,
4868 struct smb2_query_info_rsp *rsp,
4869 struct ksmbd_file *fp,
4872 struct ksmbd_conn *conn = work->conn;
4873 struct smb2_file_stream_info *file_info;
4874 char *stream_name, *xattr_list = NULL, *stream_buf;
4876 const struct path *path = &fp->filp->f_path;
4877 ssize_t xattr_list_len;
4878 int nbytes = 0, streamlen, stream_name_len, next, idx = 0;
4880 struct smb2_query_info_req *req = ksmbd_req_buf_next(work);
4883 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
4884 AT_STATX_SYNC_AS_STAT);
4888 file_info = (struct smb2_file_stream_info *)rsp->Buffer;
4891 smb2_calc_max_out_buf_len(work, 8,
4892 le32_to_cpu(req->OutputBufferLength));
4893 if (buf_free_len < 0)
4896 xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
4897 if (xattr_list_len < 0) {
4899 } else if (!xattr_list_len) {
4900 ksmbd_debug(SMB, "empty xattr in the file\n");
4904 while (idx < xattr_list_len) {
4905 stream_name = xattr_list + idx;
4906 streamlen = strlen(stream_name);
4907 idx += streamlen + 1;
4909 ksmbd_debug(SMB, "%s, len %d\n", stream_name, streamlen);
4911 if (strncmp(&stream_name[XATTR_USER_PREFIX_LEN],
4912 STREAM_PREFIX, STREAM_PREFIX_LEN))
4915 stream_name_len = streamlen - (XATTR_USER_PREFIX_LEN +
4917 streamlen = stream_name_len;
4921 stream_buf = kmalloc(streamlen + 1, GFP_KERNEL);
4925 streamlen = snprintf(stream_buf, streamlen + 1,
4926 ":%s", &stream_name[XATTR_NAME_STREAM_LEN]);
4928 next = sizeof(struct smb2_file_stream_info) + streamlen * 2;
4929 if (next > buf_free_len) {
4934 file_info = (struct smb2_file_stream_info *)&rsp->Buffer[nbytes];
4935 streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
4936 stream_buf, streamlen,
4937 conn->local_nls, 0);
4940 file_info->StreamNameLength = cpu_to_le32(streamlen);
4941 file_info->StreamSize = cpu_to_le64(stream_name_len);
4942 file_info->StreamAllocationSize = cpu_to_le64(stream_name_len);
4945 buf_free_len -= next;
4946 file_info->NextEntryOffset = cpu_to_le32(next);
4950 if (!S_ISDIR(stat.mode) &&
4951 buf_free_len >= sizeof(struct smb2_file_stream_info) + 7 * 2) {
4952 file_info = (struct smb2_file_stream_info *)
4953 &rsp->Buffer[nbytes];
4954 streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
4955 "::$DATA", 7, conn->local_nls, 0);
4957 file_info->StreamNameLength = cpu_to_le32(streamlen);
4958 file_info->StreamSize = cpu_to_le64(stat.size);
4959 file_info->StreamAllocationSize = cpu_to_le64(stat.blocks << 9);
4960 nbytes += sizeof(struct smb2_file_stream_info) + streamlen;
4963 /* last entry offset should be 0 */
4964 file_info->NextEntryOffset = 0;
4967 rsp->OutputBufferLength = cpu_to_le32(nbytes);
4972 static int get_file_internal_info(struct smb2_query_info_rsp *rsp,
4973 struct ksmbd_file *fp, void *rsp_org)
4975 struct smb2_file_internal_info *file_info;
4979 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
4980 AT_STATX_SYNC_AS_STAT);
4984 file_info = (struct smb2_file_internal_info *)rsp->Buffer;
4985 file_info->IndexNumber = cpu_to_le64(stat.ino);
4986 rsp->OutputBufferLength =
4987 cpu_to_le32(sizeof(struct smb2_file_internal_info));
4992 static int get_file_network_open_info(struct smb2_query_info_rsp *rsp,
4993 struct ksmbd_file *fp, void *rsp_org)
4995 struct smb2_file_ntwrk_info *file_info;
5000 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
5001 pr_err("no right to read the attributes : 0x%x\n",
5006 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5007 AT_STATX_SYNC_AS_STAT);
5011 file_info = (struct smb2_file_ntwrk_info *)rsp->Buffer;
5013 file_info->CreationTime = cpu_to_le64(fp->create_time);
5014 time = ksmbd_UnixTimeToNT(stat.atime);
5015 file_info->LastAccessTime = cpu_to_le64(time);
5016 time = ksmbd_UnixTimeToNT(stat.mtime);
5017 file_info->LastWriteTime = cpu_to_le64(time);
5018 time = ksmbd_UnixTimeToNT(stat.ctime);
5019 file_info->ChangeTime = cpu_to_le64(time);
5020 file_info->Attributes = fp->f_ci->m_fattr;
5021 file_info->AllocationSize = cpu_to_le64(stat.blocks << 9);
5022 file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
5023 file_info->Reserved = cpu_to_le32(0);
5024 rsp->OutputBufferLength =
5025 cpu_to_le32(sizeof(struct smb2_file_ntwrk_info));
5029 static void get_file_ea_info(struct smb2_query_info_rsp *rsp, void *rsp_org)
5031 struct smb2_file_ea_info *file_info;
5033 file_info = (struct smb2_file_ea_info *)rsp->Buffer;
5034 file_info->EASize = 0;
5035 rsp->OutputBufferLength =
5036 cpu_to_le32(sizeof(struct smb2_file_ea_info));
5039 static void get_file_position_info(struct smb2_query_info_rsp *rsp,
5040 struct ksmbd_file *fp, void *rsp_org)
5042 struct smb2_file_pos_info *file_info;
5044 file_info = (struct smb2_file_pos_info *)rsp->Buffer;
5045 file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
5046 rsp->OutputBufferLength =
5047 cpu_to_le32(sizeof(struct smb2_file_pos_info));
5050 static void get_file_mode_info(struct smb2_query_info_rsp *rsp,
5051 struct ksmbd_file *fp, void *rsp_org)
5053 struct smb2_file_mode_info *file_info;
5055 file_info = (struct smb2_file_mode_info *)rsp->Buffer;
5056 file_info->Mode = fp->coption & FILE_MODE_INFO_MASK;
5057 rsp->OutputBufferLength =
5058 cpu_to_le32(sizeof(struct smb2_file_mode_info));
5061 static int get_file_compression_info(struct smb2_query_info_rsp *rsp,
5062 struct ksmbd_file *fp, void *rsp_org)
5064 struct smb2_file_comp_info *file_info;
5068 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5069 AT_STATX_SYNC_AS_STAT);
5073 file_info = (struct smb2_file_comp_info *)rsp->Buffer;
5074 file_info->CompressedFileSize = cpu_to_le64(stat.blocks << 9);
5075 file_info->CompressionFormat = COMPRESSION_FORMAT_NONE;
5076 file_info->CompressionUnitShift = 0;
5077 file_info->ChunkShift = 0;
5078 file_info->ClusterShift = 0;
5079 memset(&file_info->Reserved[0], 0, 3);
5081 rsp->OutputBufferLength =
5082 cpu_to_le32(sizeof(struct smb2_file_comp_info));
5087 static int get_file_attribute_tag_info(struct smb2_query_info_rsp *rsp,
5088 struct ksmbd_file *fp, void *rsp_org)
5090 struct smb2_file_attr_tag_info *file_info;
5092 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
5093 pr_err("no right to read the attributes : 0x%x\n",
5098 file_info = (struct smb2_file_attr_tag_info *)rsp->Buffer;
5099 file_info->FileAttributes = fp->f_ci->m_fattr;
5100 file_info->ReparseTag = 0;
5101 rsp->OutputBufferLength =
5102 cpu_to_le32(sizeof(struct smb2_file_attr_tag_info));
5106 static int find_file_posix_info(struct smb2_query_info_rsp *rsp,
5107 struct ksmbd_file *fp, void *rsp_org)
5109 struct smb311_posix_qinfo *file_info;
5110 struct inode *inode = file_inode(fp->filp);
5111 struct mnt_idmap *idmap = file_mnt_idmap(fp->filp);
5112 vfsuid_t vfsuid = i_uid_into_vfsuid(idmap, inode);
5113 vfsgid_t vfsgid = i_gid_into_vfsgid(idmap, inode);
5116 int out_buf_len = sizeof(struct smb311_posix_qinfo) + 32;
5119 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5120 AT_STATX_SYNC_AS_STAT);
5124 file_info = (struct smb311_posix_qinfo *)rsp->Buffer;
5125 file_info->CreationTime = cpu_to_le64(fp->create_time);
5126 time = ksmbd_UnixTimeToNT(stat.atime);
5127 file_info->LastAccessTime = cpu_to_le64(time);
5128 time = ksmbd_UnixTimeToNT(stat.mtime);
5129 file_info->LastWriteTime = cpu_to_le64(time);
5130 time = ksmbd_UnixTimeToNT(stat.ctime);
5131 file_info->ChangeTime = cpu_to_le64(time);
5132 file_info->DosAttributes = fp->f_ci->m_fattr;
5133 file_info->Inode = cpu_to_le64(stat.ino);
5134 file_info->EndOfFile = cpu_to_le64(stat.size);
5135 file_info->AllocationSize = cpu_to_le64(stat.blocks << 9);
5136 file_info->HardLinks = cpu_to_le32(stat.nlink);
5137 file_info->Mode = cpu_to_le32(stat.mode & 0777);
5138 file_info->DeviceId = cpu_to_le32(stat.rdev);
5141 * Sids(32) contain two sids(Domain sid(16), UNIX group sid(16)).
5142 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) +
5143 * sub_auth(4 * 1(num_subauth)) + RID(4).
5145 id_to_sid(from_kuid_munged(&init_user_ns, vfsuid_into_kuid(vfsuid)),
5146 SIDUNIX_USER, (struct smb_sid *)&file_info->Sids[0]);
5147 id_to_sid(from_kgid_munged(&init_user_ns, vfsgid_into_kgid(vfsgid)),
5148 SIDUNIX_GROUP, (struct smb_sid *)&file_info->Sids[16]);
5150 rsp->OutputBufferLength = cpu_to_le32(out_buf_len);
5155 static int smb2_get_info_file(struct ksmbd_work *work,
5156 struct smb2_query_info_req *req,
5157 struct smb2_query_info_rsp *rsp)
5159 struct ksmbd_file *fp;
5160 int fileinfoclass = 0;
5162 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
5164 if (test_share_config_flag(work->tcon->share_conf,
5165 KSMBD_SHARE_FLAG_PIPE)) {
5166 /* smb2 info file called for pipe */
5167 return smb2_get_info_file_pipe(work->sess, req, rsp,
5168 work->response_buf);
5171 if (work->next_smb2_rcv_hdr_off) {
5172 if (!has_file_id(req->VolatileFileId)) {
5173 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
5174 work->compound_fid);
5175 id = work->compound_fid;
5176 pid = work->compound_pfid;
5180 if (!has_file_id(id)) {
5181 id = req->VolatileFileId;
5182 pid = req->PersistentFileId;
5185 fp = ksmbd_lookup_fd_slow(work, id, pid);
5189 fileinfoclass = req->FileInfoClass;
5191 switch (fileinfoclass) {
5192 case FILE_ACCESS_INFORMATION:
5193 get_file_access_info(rsp, fp, work->response_buf);
5196 case FILE_BASIC_INFORMATION:
5197 rc = get_file_basic_info(rsp, fp, work->response_buf);
5200 case FILE_STANDARD_INFORMATION:
5201 rc = get_file_standard_info(rsp, fp, work->response_buf);
5204 case FILE_ALIGNMENT_INFORMATION:
5205 get_file_alignment_info(rsp, work->response_buf);
5208 case FILE_ALL_INFORMATION:
5209 rc = get_file_all_info(work, rsp, fp, work->response_buf);
5212 case FILE_ALTERNATE_NAME_INFORMATION:
5213 get_file_alternate_info(work, rsp, fp, work->response_buf);
5216 case FILE_STREAM_INFORMATION:
5217 rc = get_file_stream_info(work, rsp, fp, work->response_buf);
5220 case FILE_INTERNAL_INFORMATION:
5221 rc = get_file_internal_info(rsp, fp, work->response_buf);
5224 case FILE_NETWORK_OPEN_INFORMATION:
5225 rc = get_file_network_open_info(rsp, fp, work->response_buf);
5228 case FILE_EA_INFORMATION:
5229 get_file_ea_info(rsp, work->response_buf);
5232 case FILE_FULL_EA_INFORMATION:
5233 rc = smb2_get_ea(work, fp, req, rsp, work->response_buf);
5236 case FILE_POSITION_INFORMATION:
5237 get_file_position_info(rsp, fp, work->response_buf);
5240 case FILE_MODE_INFORMATION:
5241 get_file_mode_info(rsp, fp, work->response_buf);
5244 case FILE_COMPRESSION_INFORMATION:
5245 rc = get_file_compression_info(rsp, fp, work->response_buf);
5248 case FILE_ATTRIBUTE_TAG_INFORMATION:
5249 rc = get_file_attribute_tag_info(rsp, fp, work->response_buf);
5251 case SMB_FIND_FILE_POSIX_INFO:
5252 if (!work->tcon->posix_extensions) {
5253 pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
5256 rc = find_file_posix_info(rsp, fp, work->response_buf);
5260 ksmbd_debug(SMB, "fileinfoclass %d not supported yet\n",
5265 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
5266 rsp, work->response_buf);
5267 ksmbd_fd_put(work, fp);
5271 static int smb2_get_info_filesystem(struct ksmbd_work *work,
5272 struct smb2_query_info_req *req,
5273 struct smb2_query_info_rsp *rsp)
5275 struct ksmbd_session *sess = work->sess;
5276 struct ksmbd_conn *conn = work->conn;
5277 struct ksmbd_share_config *share = work->tcon->share_conf;
5278 int fsinfoclass = 0;
5279 struct kstatfs stfs;
5286 rc = kern_path(share->path, LOOKUP_NO_SYMLINKS, &path);
5288 pr_err("cannot create vfs path\n");
5292 rc = vfs_statfs(&path, &stfs);
5294 pr_err("cannot do stat of path %s\n", share->path);
5299 fsinfoclass = req->FileInfoClass;
5301 switch (fsinfoclass) {
5302 case FS_DEVICE_INFORMATION:
5304 struct filesystem_device_info *info;
5306 info = (struct filesystem_device_info *)rsp->Buffer;
5308 info->DeviceType = cpu_to_le32(stfs.f_type);
5309 info->DeviceCharacteristics = cpu_to_le32(0x00000020);
5310 rsp->OutputBufferLength = cpu_to_le32(8);
5313 case FS_ATTRIBUTE_INFORMATION:
5315 struct filesystem_attribute_info *info;
5318 info = (struct filesystem_attribute_info *)rsp->Buffer;
5319 info->Attributes = cpu_to_le32(FILE_SUPPORTS_OBJECT_IDS |
5320 FILE_PERSISTENT_ACLS |
5321 FILE_UNICODE_ON_DISK |
5322 FILE_CASE_PRESERVED_NAMES |
5323 FILE_CASE_SENSITIVE_SEARCH |
5324 FILE_SUPPORTS_BLOCK_REFCOUNTING);
5326 info->Attributes |= cpu_to_le32(server_conf.share_fake_fscaps);
5328 if (test_share_config_flag(work->tcon->share_conf,
5329 KSMBD_SHARE_FLAG_STREAMS))
5330 info->Attributes |= cpu_to_le32(FILE_NAMED_STREAMS);
5332 info->MaxPathNameComponentLength = cpu_to_le32(stfs.f_namelen);
5333 len = smbConvertToUTF16((__le16 *)info->FileSystemName,
5334 "NTFS", PATH_MAX, conn->local_nls, 0);
5336 info->FileSystemNameLen = cpu_to_le32(len);
5337 sz = sizeof(struct filesystem_attribute_info) - 2 + len;
5338 rsp->OutputBufferLength = cpu_to_le32(sz);
5341 case FS_VOLUME_INFORMATION:
5343 struct filesystem_vol_info *info;
5345 unsigned int serial_crc = 0;
5347 info = (struct filesystem_vol_info *)(rsp->Buffer);
5348 info->VolumeCreationTime = 0;
5349 serial_crc = crc32_le(serial_crc, share->name,
5350 strlen(share->name));
5351 serial_crc = crc32_le(serial_crc, share->path,
5352 strlen(share->path));
5353 serial_crc = crc32_le(serial_crc, ksmbd_netbios_name(),
5354 strlen(ksmbd_netbios_name()));
5355 /* Taking dummy value of serial number*/
5356 info->SerialNumber = cpu_to_le32(serial_crc);
5357 len = smbConvertToUTF16((__le16 *)info->VolumeLabel,
5358 share->name, PATH_MAX,
5359 conn->local_nls, 0);
5361 info->VolumeLabelSize = cpu_to_le32(len);
5363 sz = sizeof(struct filesystem_vol_info) - 2 + len;
5364 rsp->OutputBufferLength = cpu_to_le32(sz);
5367 case FS_SIZE_INFORMATION:
5369 struct filesystem_info *info;
5371 info = (struct filesystem_info *)(rsp->Buffer);
5372 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
5373 info->FreeAllocationUnits = cpu_to_le64(stfs.f_bfree);
5374 info->SectorsPerAllocationUnit = cpu_to_le32(1);
5375 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
5376 rsp->OutputBufferLength = cpu_to_le32(24);
5379 case FS_FULL_SIZE_INFORMATION:
5381 struct smb2_fs_full_size_info *info;
5383 info = (struct smb2_fs_full_size_info *)(rsp->Buffer);
5384 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
5385 info->CallerAvailableAllocationUnits =
5386 cpu_to_le64(stfs.f_bavail);
5387 info->ActualAvailableAllocationUnits =
5388 cpu_to_le64(stfs.f_bfree);
5389 info->SectorsPerAllocationUnit = cpu_to_le32(1);
5390 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
5391 rsp->OutputBufferLength = cpu_to_le32(32);
5394 case FS_OBJECT_ID_INFORMATION:
5396 struct object_id_info *info;
5398 info = (struct object_id_info *)(rsp->Buffer);
5400 if (!user_guest(sess->user))
5401 memcpy(info->objid, user_passkey(sess->user), 16);
5403 memset(info->objid, 0, 16);
5405 info->extended_info.magic = cpu_to_le32(EXTENDED_INFO_MAGIC);
5406 info->extended_info.version = cpu_to_le32(1);
5407 info->extended_info.release = cpu_to_le32(1);
5408 info->extended_info.rel_date = 0;
5409 memcpy(info->extended_info.version_string, "1.1.0", strlen("1.1.0"));
5410 rsp->OutputBufferLength = cpu_to_le32(64);
5413 case FS_SECTOR_SIZE_INFORMATION:
5415 struct smb3_fs_ss_info *info;
5416 unsigned int sector_size =
5417 min_t(unsigned int, path.mnt->mnt_sb->s_blocksize, 4096);
5419 info = (struct smb3_fs_ss_info *)(rsp->Buffer);
5421 info->LogicalBytesPerSector = cpu_to_le32(sector_size);
5422 info->PhysicalBytesPerSectorForAtomicity =
5423 cpu_to_le32(sector_size);
5424 info->PhysicalBytesPerSectorForPerf = cpu_to_le32(sector_size);
5425 info->FSEffPhysicalBytesPerSectorForAtomicity =
5426 cpu_to_le32(sector_size);
5427 info->Flags = cpu_to_le32(SSINFO_FLAGS_ALIGNED_DEVICE |
5428 SSINFO_FLAGS_PARTITION_ALIGNED_ON_DEVICE);
5429 info->ByteOffsetForSectorAlignment = 0;
5430 info->ByteOffsetForPartitionAlignment = 0;
5431 rsp->OutputBufferLength = cpu_to_le32(28);
5434 case FS_CONTROL_INFORMATION:
5437 * TODO : The current implementation is based on
5438 * test result with win7(NTFS) server. It's need to
5439 * modify this to get valid Quota values
5442 struct smb2_fs_control_info *info;
5444 info = (struct smb2_fs_control_info *)(rsp->Buffer);
5445 info->FreeSpaceStartFiltering = 0;
5446 info->FreeSpaceThreshold = 0;
5447 info->FreeSpaceStopFiltering = 0;
5448 info->DefaultQuotaThreshold = cpu_to_le64(SMB2_NO_FID);
5449 info->DefaultQuotaLimit = cpu_to_le64(SMB2_NO_FID);
5451 rsp->OutputBufferLength = cpu_to_le32(48);
5454 case FS_POSIX_INFORMATION:
5456 struct filesystem_posix_info *info;
5458 if (!work->tcon->posix_extensions) {
5459 pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
5462 info = (struct filesystem_posix_info *)(rsp->Buffer);
5463 info->OptimalTransferSize = cpu_to_le32(stfs.f_bsize);
5464 info->BlockSize = cpu_to_le32(stfs.f_bsize);
5465 info->TotalBlocks = cpu_to_le64(stfs.f_blocks);
5466 info->BlocksAvail = cpu_to_le64(stfs.f_bfree);
5467 info->UserBlocksAvail = cpu_to_le64(stfs.f_bavail);
5468 info->TotalFileNodes = cpu_to_le64(stfs.f_files);
5469 info->FreeFileNodes = cpu_to_le64(stfs.f_ffree);
5470 rsp->OutputBufferLength = cpu_to_le32(56);
5478 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
5479 rsp, work->response_buf);
5484 static int smb2_get_info_sec(struct ksmbd_work *work,
5485 struct smb2_query_info_req *req,
5486 struct smb2_query_info_rsp *rsp)
5488 struct ksmbd_file *fp;
5489 struct mnt_idmap *idmap;
5490 struct smb_ntsd *pntsd = (struct smb_ntsd *)rsp->Buffer, *ppntsd = NULL;
5491 struct smb_fattr fattr = {{0}};
5492 struct inode *inode;
5493 __u32 secdesclen = 0;
5494 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
5495 int addition_info = le32_to_cpu(req->AdditionalInformation);
5496 int rc = 0, ppntsd_size = 0;
5498 if (addition_info & ~(OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO |
5499 PROTECTED_DACL_SECINFO |
5500 UNPROTECTED_DACL_SECINFO)) {
5501 ksmbd_debug(SMB, "Unsupported addition info: 0x%x)\n",
5504 pntsd->revision = cpu_to_le16(1);
5505 pntsd->type = cpu_to_le16(SELF_RELATIVE | DACL_PROTECTED);
5506 pntsd->osidoffset = 0;
5507 pntsd->gsidoffset = 0;
5508 pntsd->sacloffset = 0;
5509 pntsd->dacloffset = 0;
5511 secdesclen = sizeof(struct smb_ntsd);
5512 rsp->OutputBufferLength = cpu_to_le32(secdesclen);
5517 if (work->next_smb2_rcv_hdr_off) {
5518 if (!has_file_id(req->VolatileFileId)) {
5519 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
5520 work->compound_fid);
5521 id = work->compound_fid;
5522 pid = work->compound_pfid;
5526 if (!has_file_id(id)) {
5527 id = req->VolatileFileId;
5528 pid = req->PersistentFileId;
5531 fp = ksmbd_lookup_fd_slow(work, id, pid);
5535 idmap = file_mnt_idmap(fp->filp);
5536 inode = file_inode(fp->filp);
5537 ksmbd_acls_fattr(&fattr, idmap, inode);
5539 if (test_share_config_flag(work->tcon->share_conf,
5540 KSMBD_SHARE_FLAG_ACL_XATTR))
5541 ppntsd_size = ksmbd_vfs_get_sd_xattr(work->conn, idmap,
5542 fp->filp->f_path.dentry,
5545 /* Check if sd buffer size exceeds response buffer size */
5546 if (smb2_resp_buf_len(work, 8) > ppntsd_size)
5547 rc = build_sec_desc(idmap, pntsd, ppntsd, ppntsd_size,
5548 addition_info, &secdesclen, &fattr);
5549 posix_acl_release(fattr.cf_acls);
5550 posix_acl_release(fattr.cf_dacls);
5552 ksmbd_fd_put(work, fp);
5556 rsp->OutputBufferLength = cpu_to_le32(secdesclen);
5561 * smb2_query_info() - handler for smb2 query info command
5562 * @work: smb work containing query info request buffer
5564 * Return: 0 on success, otherwise error
5566 int smb2_query_info(struct ksmbd_work *work)
5568 struct smb2_query_info_req *req;
5569 struct smb2_query_info_rsp *rsp;
5572 WORK_BUFFERS(work, req, rsp);
5574 ksmbd_debug(SMB, "GOT query info request\n");
5576 switch (req->InfoType) {
5577 case SMB2_O_INFO_FILE:
5578 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
5579 rc = smb2_get_info_file(work, req, rsp);
5581 case SMB2_O_INFO_FILESYSTEM:
5582 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILESYSTEM\n");
5583 rc = smb2_get_info_filesystem(work, req, rsp);
5585 case SMB2_O_INFO_SECURITY:
5586 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
5587 rc = smb2_get_info_sec(work, req, rsp);
5590 ksmbd_debug(SMB, "InfoType %d not supported yet\n",
5596 rsp->StructureSize = cpu_to_le16(9);
5597 rsp->OutputBufferOffset = cpu_to_le16(72);
5598 rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
5599 offsetof(struct smb2_query_info_rsp, Buffer) +
5600 le32_to_cpu(rsp->OutputBufferLength));
5605 rsp->hdr.Status = STATUS_ACCESS_DENIED;
5606 else if (rc == -ENOENT)
5607 rsp->hdr.Status = STATUS_FILE_CLOSED;
5608 else if (rc == -EIO)
5609 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
5610 else if (rc == -ENOMEM)
5611 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
5612 else if (rc == -EOPNOTSUPP || rsp->hdr.Status == 0)
5613 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
5614 smb2_set_err_rsp(work);
5616 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n",
5624 * smb2_close_pipe() - handler for closing IPC pipe
5625 * @work: smb work containing close request buffer
5629 static noinline int smb2_close_pipe(struct ksmbd_work *work)
5632 struct smb2_close_req *req;
5633 struct smb2_close_rsp *rsp;
5635 WORK_BUFFERS(work, req, rsp);
5637 id = req->VolatileFileId;
5638 ksmbd_session_rpc_close(work->sess, id);
5640 rsp->StructureSize = cpu_to_le16(60);
5643 rsp->CreationTime = 0;
5644 rsp->LastAccessTime = 0;
5645 rsp->LastWriteTime = 0;
5646 rsp->ChangeTime = 0;
5647 rsp->AllocationSize = 0;
5649 rsp->Attributes = 0;
5651 return ksmbd_iov_pin_rsp(work, (void *)rsp,
5652 sizeof(struct smb2_close_rsp));
5656 * smb2_close() - handler for smb2 close file command
5657 * @work: smb work containing close request buffer
5661 int smb2_close(struct ksmbd_work *work)
5663 u64 volatile_id = KSMBD_NO_FID;
5665 struct smb2_close_req *req;
5666 struct smb2_close_rsp *rsp;
5667 struct ksmbd_conn *conn = work->conn;
5668 struct ksmbd_file *fp;
5672 WORK_BUFFERS(work, req, rsp);
5674 if (test_share_config_flag(work->tcon->share_conf,
5675 KSMBD_SHARE_FLAG_PIPE)) {
5676 ksmbd_debug(SMB, "IPC pipe close request\n");
5677 return smb2_close_pipe(work);
5680 sess_id = le64_to_cpu(req->hdr.SessionId);
5681 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5682 sess_id = work->compound_sid;
5684 work->compound_sid = 0;
5685 if (check_session_id(conn, sess_id)) {
5686 work->compound_sid = sess_id;
5688 rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
5689 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5690 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
5695 if (work->next_smb2_rcv_hdr_off &&
5696 !has_file_id(req->VolatileFileId)) {
5697 if (!has_file_id(work->compound_fid)) {
5698 /* file already closed, return FILE_CLOSED */
5699 ksmbd_debug(SMB, "file already closed\n");
5700 rsp->hdr.Status = STATUS_FILE_CLOSED;
5705 "Compound request set FID = %llu:%llu\n",
5707 work->compound_pfid);
5708 volatile_id = work->compound_fid;
5710 /* file closed, stored id is not valid anymore */
5711 work->compound_fid = KSMBD_NO_FID;
5712 work->compound_pfid = KSMBD_NO_FID;
5715 volatile_id = req->VolatileFileId;
5717 ksmbd_debug(SMB, "volatile_id = %llu\n", volatile_id);
5719 rsp->StructureSize = cpu_to_le16(60);
5722 if (req->Flags == SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB) {
5726 fp = ksmbd_lookup_fd_fast(work, volatile_id);
5732 ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
5733 AT_STATX_SYNC_AS_STAT);
5735 ksmbd_fd_put(work, fp);
5739 rsp->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB;
5740 rsp->AllocationSize = S_ISDIR(stat.mode) ? 0 :
5741 cpu_to_le64(stat.blocks << 9);
5742 rsp->EndOfFile = cpu_to_le64(stat.size);
5743 rsp->Attributes = fp->f_ci->m_fattr;
5744 rsp->CreationTime = cpu_to_le64(fp->create_time);
5745 time = ksmbd_UnixTimeToNT(stat.atime);
5746 rsp->LastAccessTime = cpu_to_le64(time);
5747 time = ksmbd_UnixTimeToNT(stat.mtime);
5748 rsp->LastWriteTime = cpu_to_le64(time);
5749 time = ksmbd_UnixTimeToNT(stat.ctime);
5750 rsp->ChangeTime = cpu_to_le64(time);
5751 ksmbd_fd_put(work, fp);
5754 rsp->AllocationSize = 0;
5756 rsp->Attributes = 0;
5757 rsp->CreationTime = 0;
5758 rsp->LastAccessTime = 0;
5759 rsp->LastWriteTime = 0;
5760 rsp->ChangeTime = 0;
5763 err = ksmbd_close_fd(work, volatile_id);
5766 err = ksmbd_iov_pin_rsp(work, (void *)rsp,
5767 sizeof(struct smb2_close_rsp));
5770 if (rsp->hdr.Status == 0)
5771 rsp->hdr.Status = STATUS_FILE_CLOSED;
5772 smb2_set_err_rsp(work);
5779 * smb2_echo() - handler for smb2 echo(ping) command
5780 * @work: smb work containing echo request buffer
5784 int smb2_echo(struct ksmbd_work *work)
5786 struct smb2_echo_rsp *rsp = smb2_get_msg(work->response_buf);
5788 if (work->next_smb2_rcv_hdr_off)
5789 rsp = ksmbd_resp_buf_next(work);
5791 rsp->StructureSize = cpu_to_le16(4);
5793 return ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_echo_rsp));
5796 static int smb2_rename(struct ksmbd_work *work,
5797 struct ksmbd_file *fp,
5798 struct smb2_file_rename_info *file_info,
5799 struct nls_table *local_nls)
5801 struct ksmbd_share_config *share = fp->tcon->share_conf;
5802 char *new_name = NULL;
5805 ksmbd_debug(SMB, "setting FILE_RENAME_INFO\n");
5806 new_name = smb2_get_name(file_info->FileName,
5807 le32_to_cpu(file_info->FileNameLength),
5809 if (IS_ERR(new_name))
5810 return PTR_ERR(new_name);
5812 if (strchr(new_name, ':')) {
5814 char *xattr_stream_name, *stream_name = NULL;
5815 size_t xattr_stream_size;
5818 rc = parse_stream_name(new_name, &stream_name, &s_type);
5822 len = strlen(new_name);
5823 if (len > 0 && new_name[len - 1] != '/') {
5824 pr_err("not allow base filename in rename\n");
5829 rc = ksmbd_vfs_xattr_stream_name(stream_name,
5836 rc = ksmbd_vfs_setxattr(file_mnt_idmap(fp->filp),
5841 pr_err("failed to store stream name in xattr: %d\n",
5850 ksmbd_debug(SMB, "new name %s\n", new_name);
5851 if (ksmbd_share_veto_filename(share, new_name)) {
5853 ksmbd_debug(SMB, "Can't rename vetoed file: %s\n", new_name);
5857 if (!file_info->ReplaceIfExists)
5858 flags = RENAME_NOREPLACE;
5860 smb_break_all_levII_oplock(work, fp, 0);
5861 rc = ksmbd_vfs_rename(work, &fp->filp->f_path, new_name, flags);
5867 static int smb2_create_link(struct ksmbd_work *work,
5868 struct ksmbd_share_config *share,
5869 struct smb2_file_link_info *file_info,
5870 unsigned int buf_len, struct file *filp,
5871 struct nls_table *local_nls)
5873 char *link_name = NULL, *target_name = NULL, *pathname = NULL;
5874 struct path path, parent_path;
5875 bool file_present = false;
5878 if (buf_len < (u64)sizeof(struct smb2_file_link_info) +
5879 le32_to_cpu(file_info->FileNameLength))
5882 ksmbd_debug(SMB, "setting FILE_LINK_INFORMATION\n");
5883 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
5887 link_name = smb2_get_name(file_info->FileName,
5888 le32_to_cpu(file_info->FileNameLength),
5890 if (IS_ERR(link_name) || S_ISDIR(file_inode(filp)->i_mode)) {
5895 ksmbd_debug(SMB, "link name is %s\n", link_name);
5896 target_name = file_path(filp, pathname, PATH_MAX);
5897 if (IS_ERR(target_name)) {
5902 ksmbd_debug(SMB, "target name is %s\n", target_name);
5903 rc = ksmbd_vfs_kern_path_locked(work, link_name, LOOKUP_NO_SYMLINKS,
5904 &parent_path, &path, 0);
5909 file_present = true;
5911 if (file_info->ReplaceIfExists) {
5913 rc = ksmbd_vfs_remove_file(work, &path);
5916 ksmbd_debug(SMB, "cannot delete %s\n",
5924 ksmbd_debug(SMB, "link already exists\n");
5929 rc = ksmbd_vfs_link(work, target_name, link_name);
5934 ksmbd_vfs_kern_path_unlock(&parent_path, &path);
5936 if (!IS_ERR(link_name))
5942 static int set_file_basic_info(struct ksmbd_file *fp,
5943 struct smb2_file_basic_info *file_info,
5944 struct ksmbd_share_config *share)
5948 struct inode *inode;
5949 struct mnt_idmap *idmap;
5952 if (!(fp->daccess & FILE_WRITE_ATTRIBUTES_LE))
5957 inode = file_inode(filp);
5958 idmap = file_mnt_idmap(filp);
5960 if (file_info->CreationTime)
5961 fp->create_time = le64_to_cpu(file_info->CreationTime);
5963 if (file_info->LastAccessTime) {
5964 attrs.ia_atime = ksmbd_NTtimeToUnix(file_info->LastAccessTime);
5965 attrs.ia_valid |= (ATTR_ATIME | ATTR_ATIME_SET);
5968 attrs.ia_valid |= ATTR_CTIME;
5969 if (file_info->ChangeTime)
5970 attrs.ia_ctime = ksmbd_NTtimeToUnix(file_info->ChangeTime);
5972 attrs.ia_ctime = inode_get_ctime(inode);
5974 if (file_info->LastWriteTime) {
5975 attrs.ia_mtime = ksmbd_NTtimeToUnix(file_info->LastWriteTime);
5976 attrs.ia_valid |= (ATTR_MTIME | ATTR_MTIME_SET);
5979 if (file_info->Attributes) {
5980 if (!S_ISDIR(inode->i_mode) &&
5981 file_info->Attributes & FILE_ATTRIBUTE_DIRECTORY_LE) {
5982 pr_err("can't change a file to a directory\n");
5986 if (!(S_ISDIR(inode->i_mode) && file_info->Attributes == FILE_ATTRIBUTE_NORMAL_LE))
5987 fp->f_ci->m_fattr = file_info->Attributes |
5988 (fp->f_ci->m_fattr & FILE_ATTRIBUTE_DIRECTORY_LE);
5991 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_STORE_DOS_ATTRS) &&
5992 (file_info->CreationTime || file_info->Attributes)) {
5993 struct xattr_dos_attrib da = {0};
5996 da.itime = fp->itime;
5997 da.create_time = fp->create_time;
5998 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
5999 da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
6000 XATTR_DOSINFO_ITIME;
6002 rc = ksmbd_vfs_set_dos_attrib_xattr(idmap, &filp->f_path, &da,
6006 "failed to restore file attribute in EA\n");
6010 if (attrs.ia_valid) {
6011 struct dentry *dentry = filp->f_path.dentry;
6012 struct inode *inode = d_inode(dentry);
6014 if (IS_IMMUTABLE(inode) || IS_APPEND(inode))
6018 inode_set_ctime_to_ts(inode, attrs.ia_ctime);
6019 attrs.ia_valid &= ~ATTR_CTIME;
6020 rc = notify_change(idmap, dentry, &attrs, NULL);
6021 inode_unlock(inode);
6026 static int set_file_allocation_info(struct ksmbd_work *work,
6027 struct ksmbd_file *fp,
6028 struct smb2_file_alloc_info *file_alloc_info)
6031 * TODO : It's working fine only when store dos attributes
6032 * is not yes. need to implement a logic which works
6033 * properly with any smb.conf option
6037 struct inode *inode;
6041 if (!(fp->daccess & FILE_WRITE_DATA_LE))
6044 rc = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
6045 AT_STATX_SYNC_AS_STAT);
6049 alloc_blks = (le64_to_cpu(file_alloc_info->AllocationSize) + 511) >> 9;
6050 inode = file_inode(fp->filp);
6052 if (alloc_blks > stat.blocks) {
6053 smb_break_all_levII_oplock(work, fp, 1);
6054 rc = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
6056 if (rc && rc != -EOPNOTSUPP) {
6057 pr_err("vfs_fallocate is failed : %d\n", rc);
6060 } else if (alloc_blks < stat.blocks) {
6064 * Allocation size could be smaller than original one
6065 * which means allocated blocks in file should be
6066 * deallocated. use truncate to cut out it, but inode
6067 * size is also updated with truncate offset.
6068 * inode size is retained by backup inode size.
6070 size = i_size_read(inode);
6071 rc = ksmbd_vfs_truncate(work, fp, alloc_blks * 512);
6073 pr_err("truncate failed!, err %d\n", rc);
6076 if (size < alloc_blks * 512)
6077 i_size_write(inode, size);
6082 static int set_end_of_file_info(struct ksmbd_work *work, struct ksmbd_file *fp,
6083 struct smb2_file_eof_info *file_eof_info)
6086 struct inode *inode;
6089 if (!(fp->daccess & FILE_WRITE_DATA_LE))
6092 newsize = le64_to_cpu(file_eof_info->EndOfFile);
6093 inode = file_inode(fp->filp);
6096 * If FILE_END_OF_FILE_INFORMATION of set_info_file is called
6097 * on FAT32 shared device, truncate execution time is too long
6098 * and network error could cause from windows client. because
6099 * truncate of some filesystem like FAT32 fill zero data in
6102 if (inode->i_sb->s_magic != MSDOS_SUPER_MAGIC) {
6103 ksmbd_debug(SMB, "truncated to newsize %lld\n", newsize);
6104 rc = ksmbd_vfs_truncate(work, fp, newsize);
6106 ksmbd_debug(SMB, "truncate failed!, err %d\n", rc);
6115 static int set_rename_info(struct ksmbd_work *work, struct ksmbd_file *fp,
6116 struct smb2_file_rename_info *rename_info,
6117 unsigned int buf_len)
6119 if (!(fp->daccess & FILE_DELETE_LE)) {
6120 pr_err("no right to delete : 0x%x\n", fp->daccess);
6124 if (buf_len < (u64)sizeof(struct smb2_file_rename_info) +
6125 le32_to_cpu(rename_info->FileNameLength))
6128 if (!le32_to_cpu(rename_info->FileNameLength))
6131 return smb2_rename(work, fp, rename_info, work->conn->local_nls);
6134 static int set_file_disposition_info(struct ksmbd_file *fp,
6135 struct smb2_file_disposition_info *file_info)
6137 struct inode *inode;
6139 if (!(fp->daccess & FILE_DELETE_LE)) {
6140 pr_err("no right to delete : 0x%x\n", fp->daccess);
6144 inode = file_inode(fp->filp);
6145 if (file_info->DeletePending) {
6146 if (S_ISDIR(inode->i_mode) &&
6147 ksmbd_vfs_empty_dir(fp) == -ENOTEMPTY)
6149 ksmbd_set_inode_pending_delete(fp);
6151 ksmbd_clear_inode_pending_delete(fp);
6156 static int set_file_position_info(struct ksmbd_file *fp,
6157 struct smb2_file_pos_info *file_info)
6159 loff_t current_byte_offset;
6160 unsigned long sector_size;
6161 struct inode *inode;
6163 inode = file_inode(fp->filp);
6164 current_byte_offset = le64_to_cpu(file_info->CurrentByteOffset);
6165 sector_size = inode->i_sb->s_blocksize;
6167 if (current_byte_offset < 0 ||
6168 (fp->coption == FILE_NO_INTERMEDIATE_BUFFERING_LE &&
6169 current_byte_offset & (sector_size - 1))) {
6170 pr_err("CurrentByteOffset is not valid : %llu\n",
6171 current_byte_offset);
6175 fp->filp->f_pos = current_byte_offset;
6179 static int set_file_mode_info(struct ksmbd_file *fp,
6180 struct smb2_file_mode_info *file_info)
6184 mode = file_info->Mode;
6186 if ((mode & ~FILE_MODE_INFO_MASK)) {
6187 pr_err("Mode is not valid : 0x%x\n", le32_to_cpu(mode));
6192 * TODO : need to implement consideration for
6193 * FILE_SYNCHRONOUS_IO_ALERT and FILE_SYNCHRONOUS_IO_NONALERT
6195 ksmbd_vfs_set_fadvise(fp->filp, mode);
6201 * smb2_set_info_file() - handler for smb2 set info command
6202 * @work: smb work containing set info command buffer
6203 * @fp: ksmbd_file pointer
6204 * @req: request buffer pointer
6205 * @share: ksmbd_share_config pointer
6207 * Return: 0 on success, otherwise error
6208 * TODO: need to implement an error handling for STATUS_INFO_LENGTH_MISMATCH
6210 static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp,
6211 struct smb2_set_info_req *req,
6212 struct ksmbd_share_config *share)
6214 unsigned int buf_len = le32_to_cpu(req->BufferLength);
6215 char *buffer = (char *)req + le16_to_cpu(req->BufferOffset);
6217 switch (req->FileInfoClass) {
6218 case FILE_BASIC_INFORMATION:
6220 if (buf_len < sizeof(struct smb2_file_basic_info))
6223 return set_file_basic_info(fp, (struct smb2_file_basic_info *)buffer, share);
6225 case FILE_ALLOCATION_INFORMATION:
6227 if (buf_len < sizeof(struct smb2_file_alloc_info))
6230 return set_file_allocation_info(work, fp,
6231 (struct smb2_file_alloc_info *)buffer);
6233 case FILE_END_OF_FILE_INFORMATION:
6235 if (buf_len < sizeof(struct smb2_file_eof_info))
6238 return set_end_of_file_info(work, fp,
6239 (struct smb2_file_eof_info *)buffer);
6241 case FILE_RENAME_INFORMATION:
6243 if (buf_len < sizeof(struct smb2_file_rename_info))
6246 return set_rename_info(work, fp,
6247 (struct smb2_file_rename_info *)buffer,
6250 case FILE_LINK_INFORMATION:
6252 if (buf_len < sizeof(struct smb2_file_link_info))
6255 return smb2_create_link(work, work->tcon->share_conf,
6256 (struct smb2_file_link_info *)buffer,
6258 work->conn->local_nls);
6260 case FILE_DISPOSITION_INFORMATION:
6262 if (buf_len < sizeof(struct smb2_file_disposition_info))
6265 return set_file_disposition_info(fp,
6266 (struct smb2_file_disposition_info *)buffer);
6268 case FILE_FULL_EA_INFORMATION:
6270 if (!(fp->daccess & FILE_WRITE_EA_LE)) {
6271 pr_err("Not permitted to write ext attr: 0x%x\n",
6276 if (buf_len < sizeof(struct smb2_ea_info))
6279 return smb2_set_ea((struct smb2_ea_info *)buffer,
6280 buf_len, &fp->filp->f_path, true);
6282 case FILE_POSITION_INFORMATION:
6284 if (buf_len < sizeof(struct smb2_file_pos_info))
6287 return set_file_position_info(fp, (struct smb2_file_pos_info *)buffer);
6289 case FILE_MODE_INFORMATION:
6291 if (buf_len < sizeof(struct smb2_file_mode_info))
6294 return set_file_mode_info(fp, (struct smb2_file_mode_info *)buffer);
6298 pr_err("Unimplemented Fileinfoclass :%d\n", req->FileInfoClass);
6302 static int smb2_set_info_sec(struct ksmbd_file *fp, int addition_info,
6303 char *buffer, int buf_len)
6305 struct smb_ntsd *pntsd = (struct smb_ntsd *)buffer;
6307 fp->saccess |= FILE_SHARE_DELETE_LE;
6309 return set_info_sec(fp->conn, fp->tcon, &fp->filp->f_path, pntsd,
6310 buf_len, false, true);
6314 * smb2_set_info() - handler for smb2 set info command handler
6315 * @work: smb work containing set info request buffer
6317 * Return: 0 on success, otherwise error
6319 int smb2_set_info(struct ksmbd_work *work)
6321 struct smb2_set_info_req *req;
6322 struct smb2_set_info_rsp *rsp;
6323 struct ksmbd_file *fp = NULL;
6325 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
6327 ksmbd_debug(SMB, "Received set info request\n");
6329 if (work->next_smb2_rcv_hdr_off) {
6330 req = ksmbd_req_buf_next(work);
6331 rsp = ksmbd_resp_buf_next(work);
6332 if (!has_file_id(req->VolatileFileId)) {
6333 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
6334 work->compound_fid);
6335 id = work->compound_fid;
6336 pid = work->compound_pfid;
6339 req = smb2_get_msg(work->request_buf);
6340 rsp = smb2_get_msg(work->response_buf);
6343 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
6344 ksmbd_debug(SMB, "User does not have write permission\n");
6345 pr_err("User does not have write permission\n");
6350 if (!has_file_id(id)) {
6351 id = req->VolatileFileId;
6352 pid = req->PersistentFileId;
6355 fp = ksmbd_lookup_fd_slow(work, id, pid);
6357 ksmbd_debug(SMB, "Invalid id for close: %u\n", id);
6362 switch (req->InfoType) {
6363 case SMB2_O_INFO_FILE:
6364 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
6365 rc = smb2_set_info_file(work, fp, req, work->tcon->share_conf);
6367 case SMB2_O_INFO_SECURITY:
6368 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
6369 if (ksmbd_override_fsids(work)) {
6373 rc = smb2_set_info_sec(fp,
6374 le32_to_cpu(req->AdditionalInformation),
6375 (char *)req + le16_to_cpu(req->BufferOffset),
6376 le32_to_cpu(req->BufferLength));
6377 ksmbd_revert_fsids(work);
6386 rsp->StructureSize = cpu_to_le16(2);
6387 rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
6388 sizeof(struct smb2_set_info_rsp));
6391 ksmbd_fd_put(work, fp);
6395 if (rc == -EACCES || rc == -EPERM || rc == -EXDEV)
6396 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6397 else if (rc == -EINVAL)
6398 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6399 else if (rc == -ESHARE)
6400 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6401 else if (rc == -ENOENT)
6402 rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
6403 else if (rc == -EBUSY || rc == -ENOTEMPTY)
6404 rsp->hdr.Status = STATUS_DIRECTORY_NOT_EMPTY;
6405 else if (rc == -EAGAIN)
6406 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6407 else if (rc == -EBADF || rc == -ESTALE)
6408 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6409 else if (rc == -EEXIST)
6410 rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
6411 else if (rsp->hdr.Status == 0 || rc == -EOPNOTSUPP)
6412 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
6413 smb2_set_err_rsp(work);
6414 ksmbd_fd_put(work, fp);
6415 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n", rc);
6420 * smb2_read_pipe() - handler for smb2 read from IPC pipe
6421 * @work: smb work containing read IPC pipe command buffer
6423 * Return: 0 on success, otherwise error
6425 static noinline int smb2_read_pipe(struct ksmbd_work *work)
6427 int nbytes = 0, err;
6429 struct ksmbd_rpc_command *rpc_resp;
6430 struct smb2_read_req *req;
6431 struct smb2_read_rsp *rsp;
6433 WORK_BUFFERS(work, req, rsp);
6435 id = req->VolatileFileId;
6437 rpc_resp = ksmbd_rpc_read(work->sess, id);
6439 void *aux_payload_buf;
6441 if (rpc_resp->flags != KSMBD_RPC_OK) {
6447 kvmalloc(rpc_resp->payload_sz, GFP_KERNEL);
6448 if (!aux_payload_buf) {
6453 memcpy(aux_payload_buf, rpc_resp->payload, rpc_resp->payload_sz);
6455 nbytes = rpc_resp->payload_sz;
6456 err = ksmbd_iov_pin_rsp_read(work, (void *)rsp,
6457 offsetof(struct smb2_read_rsp, Buffer),
6458 aux_payload_buf, nbytes);
6460 kvfree(aux_payload_buf);
6465 err = ksmbd_iov_pin_rsp(work, (void *)rsp,
6466 offsetof(struct smb2_read_rsp, Buffer));
6471 rsp->StructureSize = cpu_to_le16(17);
6472 rsp->DataOffset = 80;
6474 rsp->DataLength = cpu_to_le32(nbytes);
6475 rsp->DataRemaining = 0;
6480 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
6481 smb2_set_err_rsp(work);
6486 static int smb2_set_remote_key_for_rdma(struct ksmbd_work *work,
6487 struct smb2_buffer_desc_v1 *desc,
6489 __le16 ChannelInfoLength)
6491 unsigned int i, ch_count;
6493 if (work->conn->dialect == SMB30_PROT_ID &&
6494 Channel != SMB2_CHANNEL_RDMA_V1)
6497 ch_count = le16_to_cpu(ChannelInfoLength) / sizeof(*desc);
6498 if (ksmbd_debug_types & KSMBD_DEBUG_RDMA) {
6499 for (i = 0; i < ch_count; i++) {
6500 pr_info("RDMA r/w request %#x: token %#x, length %#x\n",
6502 le32_to_cpu(desc[i].token),
6503 le32_to_cpu(desc[i].length));
6509 work->need_invalidate_rkey =
6510 (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE);
6511 if (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE)
6512 work->remote_key = le32_to_cpu(desc->token);
6516 static ssize_t smb2_read_rdma_channel(struct ksmbd_work *work,
6517 struct smb2_read_req *req, void *data_buf,
6522 err = ksmbd_conn_rdma_write(work->conn, data_buf, length,
6523 (struct smb2_buffer_desc_v1 *)
6524 ((char *)req + le16_to_cpu(req->ReadChannelInfoOffset)),
6525 le16_to_cpu(req->ReadChannelInfoLength));
6533 * smb2_read() - handler for smb2 read from file
6534 * @work: smb work containing read command buffer
6536 * Return: 0 on success, otherwise error
6538 int smb2_read(struct ksmbd_work *work)
6540 struct ksmbd_conn *conn = work->conn;
6541 struct smb2_read_req *req;
6542 struct smb2_read_rsp *rsp;
6543 struct ksmbd_file *fp = NULL;
6545 size_t length, mincount;
6546 ssize_t nbytes = 0, remain_bytes = 0;
6548 bool is_rdma_channel = false;
6549 unsigned int max_read_size = conn->vals->max_read_size;
6550 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
6551 void *aux_payload_buf;
6553 if (test_share_config_flag(work->tcon->share_conf,
6554 KSMBD_SHARE_FLAG_PIPE)) {
6555 ksmbd_debug(SMB, "IPC pipe read request\n");
6556 return smb2_read_pipe(work);
6559 if (work->next_smb2_rcv_hdr_off) {
6560 req = ksmbd_req_buf_next(work);
6561 rsp = ksmbd_resp_buf_next(work);
6562 if (!has_file_id(req->VolatileFileId)) {
6563 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
6564 work->compound_fid);
6565 id = work->compound_fid;
6566 pid = work->compound_pfid;
6569 req = smb2_get_msg(work->request_buf);
6570 rsp = smb2_get_msg(work->response_buf);
6573 if (!has_file_id(id)) {
6574 id = req->VolatileFileId;
6575 pid = req->PersistentFileId;
6578 if (req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE ||
6579 req->Channel == SMB2_CHANNEL_RDMA_V1) {
6580 is_rdma_channel = true;
6581 max_read_size = get_smbd_max_read_write_size();
6584 if (is_rdma_channel == true) {
6585 unsigned int ch_offset = le16_to_cpu(req->ReadChannelInfoOffset);
6587 if (ch_offset < offsetof(struct smb2_read_req, Buffer)) {
6591 err = smb2_set_remote_key_for_rdma(work,
6592 (struct smb2_buffer_desc_v1 *)
6593 ((char *)req + ch_offset),
6595 req->ReadChannelInfoLength);
6600 fp = ksmbd_lookup_fd_slow(work, id, pid);
6606 if (!(fp->daccess & (FILE_READ_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
6607 pr_err("Not permitted to read : 0x%x\n", fp->daccess);
6612 offset = le64_to_cpu(req->Offset);
6613 length = le32_to_cpu(req->Length);
6614 mincount = le32_to_cpu(req->MinimumCount);
6616 if (length > max_read_size) {
6617 ksmbd_debug(SMB, "limiting read size to max size(%u)\n",
6623 ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
6624 fp->filp, offset, length);
6626 aux_payload_buf = kvzalloc(length, GFP_KERNEL);
6627 if (!aux_payload_buf) {
6632 nbytes = ksmbd_vfs_read(work, fp, length, &offset, aux_payload_buf);
6638 if ((nbytes == 0 && length != 0) || nbytes < mincount) {
6639 kvfree(aux_payload_buf);
6640 rsp->hdr.Status = STATUS_END_OF_FILE;
6641 smb2_set_err_rsp(work);
6642 ksmbd_fd_put(work, fp);
6646 ksmbd_debug(SMB, "nbytes %zu, offset %lld mincount %zu\n",
6647 nbytes, offset, mincount);
6649 if (is_rdma_channel == true) {
6650 /* write data to the client using rdma channel */
6651 remain_bytes = smb2_read_rdma_channel(work, req,
6654 kvfree(aux_payload_buf);
6655 aux_payload_buf = NULL;
6657 if (remain_bytes < 0) {
6658 err = (int)remain_bytes;
6663 rsp->StructureSize = cpu_to_le16(17);
6664 rsp->DataOffset = 80;
6666 rsp->DataLength = cpu_to_le32(nbytes);
6667 rsp->DataRemaining = cpu_to_le32(remain_bytes);
6669 err = ksmbd_iov_pin_rsp_read(work, (void *)rsp,
6670 offsetof(struct smb2_read_rsp, Buffer),
6671 aux_payload_buf, nbytes);
6673 kvfree(aux_payload_buf);
6676 ksmbd_fd_put(work, fp);
6682 rsp->hdr.Status = STATUS_INVALID_DEVICE_REQUEST;
6683 else if (err == -EAGAIN)
6684 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6685 else if (err == -ENOENT)
6686 rsp->hdr.Status = STATUS_FILE_CLOSED;
6687 else if (err == -EACCES)
6688 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6689 else if (err == -ESHARE)
6690 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6691 else if (err == -EINVAL)
6692 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6694 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6696 smb2_set_err_rsp(work);
6698 ksmbd_fd_put(work, fp);
6703 * smb2_write_pipe() - handler for smb2 write on IPC pipe
6704 * @work: smb work containing write IPC pipe command buffer
6706 * Return: 0 on success, otherwise error
6708 static noinline int smb2_write_pipe(struct ksmbd_work *work)
6710 struct smb2_write_req *req;
6711 struct smb2_write_rsp *rsp;
6712 struct ksmbd_rpc_command *rpc_resp;
6714 int err = 0, ret = 0;
6718 WORK_BUFFERS(work, req, rsp);
6720 length = le32_to_cpu(req->Length);
6721 id = req->VolatileFileId;
6723 if ((u64)le16_to_cpu(req->DataOffset) + length >
6724 get_rfc1002_len(work->request_buf)) {
6725 pr_err("invalid write data offset %u, smb_len %u\n",
6726 le16_to_cpu(req->DataOffset),
6727 get_rfc1002_len(work->request_buf));
6732 data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
6733 le16_to_cpu(req->DataOffset));
6735 rpc_resp = ksmbd_rpc_write(work->sess, id, data_buf, length);
6737 if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
6738 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
6740 smb2_set_err_rsp(work);
6743 if (rpc_resp->flags != KSMBD_RPC_OK) {
6744 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6745 smb2_set_err_rsp(work);
6752 rsp->StructureSize = cpu_to_le16(17);
6753 rsp->DataOffset = 0;
6755 rsp->DataLength = cpu_to_le32(length);
6756 rsp->DataRemaining = 0;
6758 err = ksmbd_iov_pin_rsp(work, (void *)rsp,
6759 offsetof(struct smb2_write_rsp, Buffer));
6762 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6763 smb2_set_err_rsp(work);
6769 static ssize_t smb2_write_rdma_channel(struct ksmbd_work *work,
6770 struct smb2_write_req *req,
6771 struct ksmbd_file *fp,
6772 loff_t offset, size_t length, bool sync)
6778 data_buf = kvzalloc(length, GFP_KERNEL);
6782 ret = ksmbd_conn_rdma_read(work->conn, data_buf, length,
6783 (struct smb2_buffer_desc_v1 *)
6784 ((char *)req + le16_to_cpu(req->WriteChannelInfoOffset)),
6785 le16_to_cpu(req->WriteChannelInfoLength));
6791 ret = ksmbd_vfs_write(work, fp, data_buf, length, &offset, sync, &nbytes);
6800 * smb2_write() - handler for smb2 write from file
6801 * @work: smb work containing write command buffer
6803 * Return: 0 on success, otherwise error
6805 int smb2_write(struct ksmbd_work *work)
6807 struct smb2_write_req *req;
6808 struct smb2_write_rsp *rsp;
6809 struct ksmbd_file *fp = NULL;
6814 bool writethrough = false, is_rdma_channel = false;
6816 unsigned int max_write_size = work->conn->vals->max_write_size;
6818 WORK_BUFFERS(work, req, rsp);
6820 if (test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_PIPE)) {
6821 ksmbd_debug(SMB, "IPC pipe write request\n");
6822 return smb2_write_pipe(work);
6825 offset = le64_to_cpu(req->Offset);
6826 length = le32_to_cpu(req->Length);
6828 if (req->Channel == SMB2_CHANNEL_RDMA_V1 ||
6829 req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE) {
6830 is_rdma_channel = true;
6831 max_write_size = get_smbd_max_read_write_size();
6832 length = le32_to_cpu(req->RemainingBytes);
6835 if (is_rdma_channel == true) {
6836 unsigned int ch_offset = le16_to_cpu(req->WriteChannelInfoOffset);
6838 if (req->Length != 0 || req->DataOffset != 0 ||
6839 ch_offset < offsetof(struct smb2_write_req, Buffer)) {
6843 err = smb2_set_remote_key_for_rdma(work,
6844 (struct smb2_buffer_desc_v1 *)
6845 ((char *)req + ch_offset),
6847 req->WriteChannelInfoLength);
6852 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
6853 ksmbd_debug(SMB, "User does not have write permission\n");
6858 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
6864 if (!(fp->daccess & (FILE_WRITE_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
6865 pr_err("Not permitted to write : 0x%x\n", fp->daccess);
6870 if (length > max_write_size) {
6871 ksmbd_debug(SMB, "limiting write size to max size(%u)\n",
6877 ksmbd_debug(SMB, "flags %u\n", le32_to_cpu(req->Flags));
6878 if (le32_to_cpu(req->Flags) & SMB2_WRITEFLAG_WRITE_THROUGH)
6879 writethrough = true;
6881 if (is_rdma_channel == false) {
6882 if (le16_to_cpu(req->DataOffset) <
6883 offsetof(struct smb2_write_req, Buffer)) {
6888 data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
6889 le16_to_cpu(req->DataOffset));
6891 ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
6892 fp->filp, offset, length);
6893 err = ksmbd_vfs_write(work, fp, data_buf, length, &offset,
6894 writethrough, &nbytes);
6898 /* read data from the client using rdma channel, and
6901 nbytes = smb2_write_rdma_channel(work, req, fp, offset, length,
6909 rsp->StructureSize = cpu_to_le16(17);
6910 rsp->DataOffset = 0;
6912 rsp->DataLength = cpu_to_le32(nbytes);
6913 rsp->DataRemaining = 0;
6915 err = ksmbd_iov_pin_rsp(work, rsp, offsetof(struct smb2_write_rsp, Buffer));
6918 ksmbd_fd_put(work, fp);
6923 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6924 else if (err == -ENOSPC || err == -EFBIG)
6925 rsp->hdr.Status = STATUS_DISK_FULL;
6926 else if (err == -ENOENT)
6927 rsp->hdr.Status = STATUS_FILE_CLOSED;
6928 else if (err == -EACCES)
6929 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6930 else if (err == -ESHARE)
6931 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6932 else if (err == -EINVAL)
6933 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6935 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6937 smb2_set_err_rsp(work);
6938 ksmbd_fd_put(work, fp);
6943 * smb2_flush() - handler for smb2 flush file - fsync
6944 * @work: smb work containing flush command buffer
6946 * Return: 0 on success, otherwise error
6948 int smb2_flush(struct ksmbd_work *work)
6950 struct smb2_flush_req *req;
6951 struct smb2_flush_rsp *rsp;
6954 WORK_BUFFERS(work, req, rsp);
6956 ksmbd_debug(SMB, "SMB2_FLUSH called for fid %llu\n", req->VolatileFileId);
6958 err = ksmbd_vfs_fsync(work, req->VolatileFileId, req->PersistentFileId);
6962 rsp->StructureSize = cpu_to_le16(4);
6964 return ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_flush_rsp));
6967 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6968 smb2_set_err_rsp(work);
6973 * smb2_cancel() - handler for smb2 cancel command
6974 * @work: smb work containing cancel command buffer
6976 * Return: 0 on success, otherwise error
6978 int smb2_cancel(struct ksmbd_work *work)
6980 struct ksmbd_conn *conn = work->conn;
6981 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
6982 struct smb2_hdr *chdr;
6983 struct ksmbd_work *iter;
6984 struct list_head *command_list;
6986 if (work->next_smb2_rcv_hdr_off)
6987 hdr = ksmbd_resp_buf_next(work);
6989 ksmbd_debug(SMB, "smb2 cancel called on mid %llu, async flags 0x%x\n",
6990 hdr->MessageId, hdr->Flags);
6992 if (hdr->Flags & SMB2_FLAGS_ASYNC_COMMAND) {
6993 command_list = &conn->async_requests;
6995 spin_lock(&conn->request_lock);
6996 list_for_each_entry(iter, command_list,
6997 async_request_entry) {
6998 chdr = smb2_get_msg(iter->request_buf);
7000 if (iter->async_id !=
7001 le64_to_cpu(hdr->Id.AsyncId))
7005 "smb2 with AsyncId %llu cancelled command = 0x%x\n",
7006 le64_to_cpu(hdr->Id.AsyncId),
7007 le16_to_cpu(chdr->Command));
7008 iter->state = KSMBD_WORK_CANCELLED;
7009 if (iter->cancel_fn)
7010 iter->cancel_fn(iter->cancel_argv);
7013 spin_unlock(&conn->request_lock);
7015 command_list = &conn->requests;
7017 spin_lock(&conn->request_lock);
7018 list_for_each_entry(iter, command_list, request_entry) {
7019 chdr = smb2_get_msg(iter->request_buf);
7021 if (chdr->MessageId != hdr->MessageId ||
7026 "smb2 with mid %llu cancelled command = 0x%x\n",
7027 le64_to_cpu(hdr->MessageId),
7028 le16_to_cpu(chdr->Command));
7029 iter->state = KSMBD_WORK_CANCELLED;
7032 spin_unlock(&conn->request_lock);
7035 /* For SMB2_CANCEL command itself send no response*/
7036 work->send_no_response = 1;
7040 struct file_lock *smb_flock_init(struct file *f)
7042 struct file_lock *fl;
7044 fl = locks_alloc_lock();
7048 locks_init_lock(fl);
7050 fl->c.flc_owner = f;
7051 fl->c.flc_pid = current->tgid;
7053 fl->c.flc_flags = FL_POSIX;
7055 fl->fl_lmops = NULL;
7061 static int smb2_set_flock_flags(struct file_lock *flock, int flags)
7065 /* Checking for wrong flag combination during lock request*/
7067 case SMB2_LOCKFLAG_SHARED:
7068 ksmbd_debug(SMB, "received shared request\n");
7070 flock->c.flc_type = F_RDLCK;
7071 flock->c.flc_flags |= FL_SLEEP;
7073 case SMB2_LOCKFLAG_EXCLUSIVE:
7074 ksmbd_debug(SMB, "received exclusive request\n");
7076 flock->c.flc_type = F_WRLCK;
7077 flock->c.flc_flags |= FL_SLEEP;
7079 case SMB2_LOCKFLAG_SHARED | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
7081 "received shared & fail immediately request\n");
7083 flock->c.flc_type = F_RDLCK;
7085 case SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
7087 "received exclusive & fail immediately request\n");
7089 flock->c.flc_type = F_WRLCK;
7091 case SMB2_LOCKFLAG_UNLOCK:
7092 ksmbd_debug(SMB, "received unlock request\n");
7093 flock->c.flc_type = F_UNLCK;
7101 static struct ksmbd_lock *smb2_lock_init(struct file_lock *flock,
7102 unsigned int cmd, int flags,
7103 struct list_head *lock_list)
7105 struct ksmbd_lock *lock;
7107 lock = kzalloc(sizeof(struct ksmbd_lock), GFP_KERNEL);
7113 lock->start = flock->fl_start;
7114 lock->end = flock->fl_end;
7115 lock->flags = flags;
7116 if (lock->start == lock->end)
7118 INIT_LIST_HEAD(&lock->clist);
7119 INIT_LIST_HEAD(&lock->flist);
7120 INIT_LIST_HEAD(&lock->llist);
7121 list_add_tail(&lock->llist, lock_list);
7126 static void smb2_remove_blocked_lock(void **argv)
7128 struct file_lock *flock = (struct file_lock *)argv[0];
7130 ksmbd_vfs_posix_lock_unblock(flock);
7131 locks_wake_up(flock);
7134 static inline bool lock_defer_pending(struct file_lock *fl)
7136 /* check pending lock waiters */
7137 return waitqueue_active(&fl->c.flc_wait);
7141 * smb2_lock() - handler for smb2 file lock command
7142 * @work: smb work containing lock command buffer
7144 * Return: 0 on success, otherwise error
7146 int smb2_lock(struct ksmbd_work *work)
7148 struct smb2_lock_req *req;
7149 struct smb2_lock_rsp *rsp;
7150 struct smb2_lock_element *lock_ele;
7151 struct ksmbd_file *fp = NULL;
7152 struct file_lock *flock = NULL;
7153 struct file *filp = NULL;
7157 int err = -EIO, i, rc = 0;
7158 u64 lock_start, lock_length;
7159 struct ksmbd_lock *smb_lock = NULL, *cmp_lock, *tmp, *tmp2;
7160 struct ksmbd_conn *conn;
7162 LIST_HEAD(lock_list);
7163 LIST_HEAD(rollback_list);
7166 WORK_BUFFERS(work, req, rsp);
7168 ksmbd_debug(SMB, "Received lock request\n");
7169 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
7171 ksmbd_debug(SMB, "Invalid file id for lock : %llu\n", req->VolatileFileId);
7177 lock_count = le16_to_cpu(req->LockCount);
7178 lock_ele = req->locks;
7180 ksmbd_debug(SMB, "lock count is %d\n", lock_count);
7186 for (i = 0; i < lock_count; i++) {
7187 flags = le32_to_cpu(lock_ele[i].Flags);
7189 flock = smb_flock_init(filp);
7193 cmd = smb2_set_flock_flags(flock, flags);
7195 lock_start = le64_to_cpu(lock_ele[i].Offset);
7196 lock_length = le64_to_cpu(lock_ele[i].Length);
7197 if (lock_start > U64_MAX - lock_length) {
7198 pr_err("Invalid lock range requested\n");
7199 rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
7200 locks_free_lock(flock);
7204 if (lock_start > OFFSET_MAX)
7205 flock->fl_start = OFFSET_MAX;
7207 flock->fl_start = lock_start;
7209 lock_length = le64_to_cpu(lock_ele[i].Length);
7210 if (lock_length > OFFSET_MAX - flock->fl_start)
7211 lock_length = OFFSET_MAX - flock->fl_start;
7213 flock->fl_end = flock->fl_start + lock_length;
7215 if (flock->fl_end < flock->fl_start) {
7217 "the end offset(%llx) is smaller than the start offset(%llx)\n",
7218 flock->fl_end, flock->fl_start);
7219 rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
7220 locks_free_lock(flock);
7224 /* Check conflict locks in one request */
7225 list_for_each_entry(cmp_lock, &lock_list, llist) {
7226 if (cmp_lock->fl->fl_start <= flock->fl_start &&
7227 cmp_lock->fl->fl_end >= flock->fl_end) {
7228 if (cmp_lock->fl->c.flc_type != F_UNLCK &&
7229 flock->c.flc_type != F_UNLCK) {
7230 pr_err("conflict two locks in one request\n");
7232 locks_free_lock(flock);
7238 smb_lock = smb2_lock_init(flock, cmd, flags, &lock_list);
7241 locks_free_lock(flock);
7246 list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
7247 if (smb_lock->cmd < 0) {
7252 if (!(smb_lock->flags & SMB2_LOCKFLAG_MASK)) {
7257 if ((prior_lock & (SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_SHARED) &&
7258 smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) ||
7259 (prior_lock == SMB2_LOCKFLAG_UNLOCK &&
7260 !(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK))) {
7265 prior_lock = smb_lock->flags;
7267 if (!(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) &&
7268 !(smb_lock->flags & SMB2_LOCKFLAG_FAIL_IMMEDIATELY))
7272 /* check locks in connection list */
7273 down_read(&conn_list_lock);
7274 list_for_each_entry(conn, &conn_list, conns_list) {
7275 spin_lock(&conn->llist_lock);
7276 list_for_each_entry_safe(cmp_lock, tmp2, &conn->lock_list, clist) {
7277 if (file_inode(cmp_lock->fl->c.flc_file) !=
7278 file_inode(smb_lock->fl->c.flc_file))
7281 if (lock_is_unlock(smb_lock->fl)) {
7282 if (cmp_lock->fl->c.flc_file == smb_lock->fl->c.flc_file &&
7283 cmp_lock->start == smb_lock->start &&
7284 cmp_lock->end == smb_lock->end &&
7285 !lock_defer_pending(cmp_lock->fl)) {
7287 list_del(&cmp_lock->flist);
7288 list_del(&cmp_lock->clist);
7289 spin_unlock(&conn->llist_lock);
7290 up_read(&conn_list_lock);
7292 locks_free_lock(cmp_lock->fl);
7299 if (cmp_lock->fl->c.flc_file == smb_lock->fl->c.flc_file) {
7300 if (smb_lock->flags & SMB2_LOCKFLAG_SHARED)
7303 if (cmp_lock->flags & SMB2_LOCKFLAG_SHARED)
7307 /* check zero byte lock range */
7308 if (cmp_lock->zero_len && !smb_lock->zero_len &&
7309 cmp_lock->start > smb_lock->start &&
7310 cmp_lock->start < smb_lock->end) {
7311 spin_unlock(&conn->llist_lock);
7312 up_read(&conn_list_lock);
7313 pr_err("previous lock conflict with zero byte lock range\n");
7317 if (smb_lock->zero_len && !cmp_lock->zero_len &&
7318 smb_lock->start > cmp_lock->start &&
7319 smb_lock->start < cmp_lock->end) {
7320 spin_unlock(&conn->llist_lock);
7321 up_read(&conn_list_lock);
7322 pr_err("current lock conflict with zero byte lock range\n");
7326 if (((cmp_lock->start <= smb_lock->start &&
7327 cmp_lock->end > smb_lock->start) ||
7328 (cmp_lock->start < smb_lock->end &&
7329 cmp_lock->end >= smb_lock->end)) &&
7330 !cmp_lock->zero_len && !smb_lock->zero_len) {
7331 spin_unlock(&conn->llist_lock);
7332 up_read(&conn_list_lock);
7333 pr_err("Not allow lock operation on exclusive lock range\n");
7337 spin_unlock(&conn->llist_lock);
7339 up_read(&conn_list_lock);
7341 if (lock_is_unlock(smb_lock->fl) && nolock) {
7342 pr_err("Try to unlock nolocked range\n");
7343 rsp->hdr.Status = STATUS_RANGE_NOT_LOCKED;
7348 if (smb_lock->zero_len) {
7353 flock = smb_lock->fl;
7354 list_del(&smb_lock->llist);
7356 rc = vfs_lock_file(filp, smb_lock->cmd, flock, NULL);
7358 if (flags & SMB2_LOCKFLAG_UNLOCK) {
7360 ksmbd_debug(SMB, "File unlocked\n");
7361 } else if (rc == -ENOENT) {
7362 rsp->hdr.Status = STATUS_NOT_LOCKED;
7365 locks_free_lock(flock);
7368 if (rc == FILE_LOCK_DEFERRED) {
7372 "would have to wait for getting lock\n");
7373 list_add(&smb_lock->llist, &rollback_list);
7375 argv = kmalloc(sizeof(void *), GFP_KERNEL);
7382 rc = setup_async_work(work,
7383 smb2_remove_blocked_lock,
7390 spin_lock(&fp->f_lock);
7391 list_add(&work->fp_entry, &fp->blocked_works);
7392 spin_unlock(&fp->f_lock);
7394 smb2_send_interim_resp(work, STATUS_PENDING);
7396 ksmbd_vfs_posix_lock_wait(flock);
7398 spin_lock(&fp->f_lock);
7399 list_del(&work->fp_entry);
7400 spin_unlock(&fp->f_lock);
7402 if (work->state != KSMBD_WORK_ACTIVE) {
7403 list_del(&smb_lock->llist);
7404 locks_free_lock(flock);
7406 if (work->state == KSMBD_WORK_CANCELLED) {
7410 smb2_send_interim_resp(work,
7412 work->send_no_response = 1;
7417 STATUS_RANGE_NOT_LOCKED;
7422 list_del(&smb_lock->llist);
7423 release_async_work(work);
7426 list_add(&smb_lock->llist, &rollback_list);
7427 spin_lock(&work->conn->llist_lock);
7428 list_add_tail(&smb_lock->clist,
7429 &work->conn->lock_list);
7430 list_add_tail(&smb_lock->flist,
7432 spin_unlock(&work->conn->llist_lock);
7433 ksmbd_debug(SMB, "successful in taking lock\n");
7440 if (atomic_read(&fp->f_ci->op_count) > 1)
7441 smb_break_all_oplock(work, fp);
7443 rsp->StructureSize = cpu_to_le16(4);
7444 ksmbd_debug(SMB, "successful in taking lock\n");
7445 rsp->hdr.Status = STATUS_SUCCESS;
7447 err = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_lock_rsp));
7451 ksmbd_fd_put(work, fp);
7455 list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
7456 locks_free_lock(smb_lock->fl);
7457 list_del(&smb_lock->llist);
7461 list_for_each_entry_safe(smb_lock, tmp, &rollback_list, llist) {
7462 struct file_lock *rlock = NULL;
7464 rlock = smb_flock_init(filp);
7465 rlock->c.flc_type = F_UNLCK;
7466 rlock->fl_start = smb_lock->start;
7467 rlock->fl_end = smb_lock->end;
7469 rc = vfs_lock_file(filp, F_SETLK, rlock, NULL);
7471 pr_err("rollback unlock fail : %d\n", rc);
7473 list_del(&smb_lock->llist);
7474 spin_lock(&work->conn->llist_lock);
7475 if (!list_empty(&smb_lock->flist))
7476 list_del(&smb_lock->flist);
7477 list_del(&smb_lock->clist);
7478 spin_unlock(&work->conn->llist_lock);
7480 locks_free_lock(smb_lock->fl);
7481 locks_free_lock(rlock);
7485 ksmbd_debug(SMB, "failed in taking lock(flags : %x), err : %d\n", flags, err);
7487 if (!rsp->hdr.Status) {
7489 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7490 else if (err == -ENOMEM)
7491 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
7492 else if (err == -ENOENT)
7493 rsp->hdr.Status = STATUS_FILE_CLOSED;
7495 rsp->hdr.Status = STATUS_LOCK_NOT_GRANTED;
7498 smb2_set_err_rsp(work);
7499 ksmbd_fd_put(work, fp);
7503 static int fsctl_copychunk(struct ksmbd_work *work,
7504 struct copychunk_ioctl_req *ci_req,
7505 unsigned int cnt_code,
7506 unsigned int input_count,
7507 unsigned long long volatile_id,
7508 unsigned long long persistent_id,
7509 struct smb2_ioctl_rsp *rsp)
7511 struct copychunk_ioctl_rsp *ci_rsp;
7512 struct ksmbd_file *src_fp = NULL, *dst_fp = NULL;
7513 struct srv_copychunk *chunks;
7514 unsigned int i, chunk_count, chunk_count_written = 0;
7515 unsigned int chunk_size_written = 0;
7516 loff_t total_size_written = 0;
7519 ci_rsp = (struct copychunk_ioctl_rsp *)&rsp->Buffer[0];
7521 rsp->VolatileFileId = volatile_id;
7522 rsp->PersistentFileId = persistent_id;
7523 ci_rsp->ChunksWritten =
7524 cpu_to_le32(ksmbd_server_side_copy_max_chunk_count());
7525 ci_rsp->ChunkBytesWritten =
7526 cpu_to_le32(ksmbd_server_side_copy_max_chunk_size());
7527 ci_rsp->TotalBytesWritten =
7528 cpu_to_le32(ksmbd_server_side_copy_max_total_size());
7530 chunks = (struct srv_copychunk *)&ci_req->Chunks[0];
7531 chunk_count = le32_to_cpu(ci_req->ChunkCount);
7532 if (chunk_count == 0)
7534 total_size_written = 0;
7536 /* verify the SRV_COPYCHUNK_COPY packet */
7537 if (chunk_count > ksmbd_server_side_copy_max_chunk_count() ||
7538 input_count < offsetof(struct copychunk_ioctl_req, Chunks) +
7539 chunk_count * sizeof(struct srv_copychunk)) {
7540 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7544 for (i = 0; i < chunk_count; i++) {
7545 if (le32_to_cpu(chunks[i].Length) == 0 ||
7546 le32_to_cpu(chunks[i].Length) > ksmbd_server_side_copy_max_chunk_size())
7548 total_size_written += le32_to_cpu(chunks[i].Length);
7551 if (i < chunk_count ||
7552 total_size_written > ksmbd_server_side_copy_max_total_size()) {
7553 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7557 src_fp = ksmbd_lookup_foreign_fd(work,
7558 le64_to_cpu(ci_req->ResumeKey[0]));
7559 dst_fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
7562 src_fp->persistent_id != le64_to_cpu(ci_req->ResumeKey[1])) {
7563 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
7568 rsp->hdr.Status = STATUS_FILE_CLOSED;
7573 * FILE_READ_DATA should only be included in
7574 * the FSCTL_COPYCHUNK case
7576 if (cnt_code == FSCTL_COPYCHUNK &&
7577 !(dst_fp->daccess & (FILE_READ_DATA_LE | FILE_GENERIC_READ_LE))) {
7578 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7582 ret = ksmbd_vfs_copy_file_ranges(work, src_fp, dst_fp,
7583 chunks, chunk_count,
7584 &chunk_count_written,
7585 &chunk_size_written,
7586 &total_size_written);
7589 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7591 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
7592 else if (ret == -EBADF)
7593 rsp->hdr.Status = STATUS_INVALID_HANDLE;
7594 else if (ret == -EFBIG || ret == -ENOSPC)
7595 rsp->hdr.Status = STATUS_DISK_FULL;
7596 else if (ret == -EINVAL)
7597 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7598 else if (ret == -EISDIR)
7599 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
7600 else if (ret == -E2BIG)
7601 rsp->hdr.Status = STATUS_INVALID_VIEW_SIZE;
7603 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
7606 ci_rsp->ChunksWritten = cpu_to_le32(chunk_count_written);
7607 ci_rsp->ChunkBytesWritten = cpu_to_le32(chunk_size_written);
7608 ci_rsp->TotalBytesWritten = cpu_to_le32(total_size_written);
7610 ksmbd_fd_put(work, src_fp);
7611 ksmbd_fd_put(work, dst_fp);
7615 static __be32 idev_ipv4_address(struct in_device *idev)
7619 struct in_ifaddr *ifa;
7622 in_dev_for_each_ifa_rcu(ifa, idev) {
7623 if (ifa->ifa_flags & IFA_F_SECONDARY)
7626 addr = ifa->ifa_address;
7633 static int fsctl_query_iface_info_ioctl(struct ksmbd_conn *conn,
7634 struct smb2_ioctl_rsp *rsp,
7635 unsigned int out_buf_len)
7637 struct network_interface_info_ioctl_rsp *nii_rsp = NULL;
7639 struct net_device *netdev;
7640 struct sockaddr_storage_rsp *sockaddr_storage;
7642 unsigned long long speed;
7645 for_each_netdev(&init_net, netdev) {
7646 bool ipv4_set = false;
7648 if (netdev->type == ARPHRD_LOOPBACK)
7651 flags = dev_get_flags(netdev);
7652 if (!(flags & IFF_RUNNING))
7656 nbytes + sizeof(struct network_interface_info_ioctl_rsp)) {
7661 nii_rsp = (struct network_interface_info_ioctl_rsp *)
7662 &rsp->Buffer[nbytes];
7663 nii_rsp->IfIndex = cpu_to_le32(netdev->ifindex);
7665 nii_rsp->Capability = 0;
7666 if (netdev->real_num_tx_queues > 1)
7667 nii_rsp->Capability |= cpu_to_le32(RSS_CAPABLE);
7668 if (ksmbd_rdma_capable_netdev(netdev))
7669 nii_rsp->Capability |= cpu_to_le32(RDMA_CAPABLE);
7671 nii_rsp->Next = cpu_to_le32(152);
7672 nii_rsp->Reserved = 0;
7674 if (netdev->ethtool_ops->get_link_ksettings) {
7675 struct ethtool_link_ksettings cmd;
7677 netdev->ethtool_ops->get_link_ksettings(netdev, &cmd);
7678 speed = cmd.base.speed;
7680 ksmbd_debug(SMB, "%s %s\n", netdev->name,
7681 "speed is unknown, defaulting to 1Gb/sec");
7686 nii_rsp->LinkSpeed = cpu_to_le64(speed);
7688 sockaddr_storage = (struct sockaddr_storage_rsp *)
7689 nii_rsp->SockAddr_Storage;
7690 memset(sockaddr_storage, 0, 128);
7693 struct in_device *idev;
7695 sockaddr_storage->Family = cpu_to_le16(INTERNETWORK);
7696 sockaddr_storage->addr4.Port = 0;
7698 idev = __in_dev_get_rtnl(netdev);
7701 sockaddr_storage->addr4.IPv4address =
7702 idev_ipv4_address(idev);
7703 nbytes += sizeof(struct network_interface_info_ioctl_rsp);
7707 struct inet6_dev *idev6;
7708 struct inet6_ifaddr *ifa;
7709 __u8 *ipv6_addr = sockaddr_storage->addr6.IPv6address;
7711 sockaddr_storage->Family = cpu_to_le16(INTERNETWORKV6);
7712 sockaddr_storage->addr6.Port = 0;
7713 sockaddr_storage->addr6.FlowInfo = 0;
7715 idev6 = __in6_dev_get(netdev);
7719 list_for_each_entry(ifa, &idev6->addr_list, if_list) {
7720 if (ifa->flags & (IFA_F_TENTATIVE |
7723 memcpy(ipv6_addr, ifa->addr.s6_addr, 16);
7726 sockaddr_storage->addr6.ScopeId = 0;
7727 nbytes += sizeof(struct network_interface_info_ioctl_rsp);
7732 /* zero if this is last one */
7736 rsp->PersistentFileId = SMB2_NO_FID;
7737 rsp->VolatileFileId = SMB2_NO_FID;
7741 static int fsctl_validate_negotiate_info(struct ksmbd_conn *conn,
7742 struct validate_negotiate_info_req *neg_req,
7743 struct validate_negotiate_info_rsp *neg_rsp,
7744 unsigned int in_buf_len)
7749 if (in_buf_len < offsetof(struct validate_negotiate_info_req, Dialects) +
7750 le16_to_cpu(neg_req->DialectCount) * sizeof(__le16))
7753 dialect = ksmbd_lookup_dialect_by_id(neg_req->Dialects,
7754 neg_req->DialectCount);
7755 if (dialect == BAD_PROT_ID || dialect != conn->dialect) {
7760 if (strncmp(neg_req->Guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE)) {
7765 if (le16_to_cpu(neg_req->SecurityMode) != conn->cli_sec_mode) {
7770 if (le32_to_cpu(neg_req->Capabilities) != conn->cli_cap) {
7775 neg_rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
7776 memset(neg_rsp->Guid, 0, SMB2_CLIENT_GUID_SIZE);
7777 neg_rsp->SecurityMode = cpu_to_le16(conn->srv_sec_mode);
7778 neg_rsp->Dialect = cpu_to_le16(conn->dialect);
7783 static int fsctl_query_allocated_ranges(struct ksmbd_work *work, u64 id,
7784 struct file_allocated_range_buffer *qar_req,
7785 struct file_allocated_range_buffer *qar_rsp,
7786 unsigned int in_count, unsigned int *out_count)
7788 struct ksmbd_file *fp;
7789 loff_t start, length;
7796 start = le64_to_cpu(qar_req->file_offset);
7797 length = le64_to_cpu(qar_req->length);
7799 if (start < 0 || length < 0)
7802 fp = ksmbd_lookup_fd_fast(work, id);
7806 ret = ksmbd_vfs_fqar_lseek(fp, start, length,
7807 qar_rsp, in_count, out_count);
7808 if (ret && ret != -E2BIG)
7811 ksmbd_fd_put(work, fp);
7815 static int fsctl_pipe_transceive(struct ksmbd_work *work, u64 id,
7816 unsigned int out_buf_len,
7817 struct smb2_ioctl_req *req,
7818 struct smb2_ioctl_rsp *rsp)
7820 struct ksmbd_rpc_command *rpc_resp;
7821 char *data_buf = (char *)req + le32_to_cpu(req->InputOffset);
7824 rpc_resp = ksmbd_rpc_ioctl(work->sess, id, data_buf,
7825 le32_to_cpu(req->InputCount));
7827 if (rpc_resp->flags == KSMBD_RPC_SOME_NOT_MAPPED) {
7829 * set STATUS_SOME_NOT_MAPPED response
7830 * for unknown domain sid.
7832 rsp->hdr.Status = STATUS_SOME_NOT_MAPPED;
7833 } else if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
7834 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7836 } else if (rpc_resp->flags != KSMBD_RPC_OK) {
7837 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7841 nbytes = rpc_resp->payload_sz;
7842 if (rpc_resp->payload_sz > out_buf_len) {
7843 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
7844 nbytes = out_buf_len;
7847 if (!rpc_resp->payload_sz) {
7849 STATUS_UNEXPECTED_IO_ERROR;
7853 memcpy((char *)rsp->Buffer, rpc_resp->payload, nbytes);
7860 static inline int fsctl_set_sparse(struct ksmbd_work *work, u64 id,
7861 struct file_sparse *sparse)
7863 struct ksmbd_file *fp;
7864 struct mnt_idmap *idmap;
7868 fp = ksmbd_lookup_fd_fast(work, id);
7871 idmap = file_mnt_idmap(fp->filp);
7873 old_fattr = fp->f_ci->m_fattr;
7874 if (sparse->SetSparse)
7875 fp->f_ci->m_fattr |= FILE_ATTRIBUTE_SPARSE_FILE_LE;
7877 fp->f_ci->m_fattr &= ~FILE_ATTRIBUTE_SPARSE_FILE_LE;
7879 if (fp->f_ci->m_fattr != old_fattr &&
7880 test_share_config_flag(work->tcon->share_conf,
7881 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS)) {
7882 struct xattr_dos_attrib da;
7884 ret = ksmbd_vfs_get_dos_attrib_xattr(idmap,
7885 fp->filp->f_path.dentry, &da);
7889 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
7890 ret = ksmbd_vfs_set_dos_attrib_xattr(idmap,
7894 fp->f_ci->m_fattr = old_fattr;
7898 ksmbd_fd_put(work, fp);
7902 static int fsctl_request_resume_key(struct ksmbd_work *work,
7903 struct smb2_ioctl_req *req,
7904 struct resume_key_ioctl_rsp *key_rsp)
7906 struct ksmbd_file *fp;
7908 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
7912 memset(key_rsp, 0, sizeof(*key_rsp));
7913 key_rsp->ResumeKey[0] = req->VolatileFileId;
7914 key_rsp->ResumeKey[1] = req->PersistentFileId;
7915 ksmbd_fd_put(work, fp);
7921 * smb2_ioctl() - handler for smb2 ioctl command
7922 * @work: smb work containing ioctl command buffer
7924 * Return: 0 on success, otherwise error
7926 int smb2_ioctl(struct ksmbd_work *work)
7928 struct smb2_ioctl_req *req;
7929 struct smb2_ioctl_rsp *rsp;
7930 unsigned int cnt_code, nbytes = 0, out_buf_len, in_buf_len;
7931 u64 id = KSMBD_NO_FID;
7932 struct ksmbd_conn *conn = work->conn;
7936 if (work->next_smb2_rcv_hdr_off) {
7937 req = ksmbd_req_buf_next(work);
7938 rsp = ksmbd_resp_buf_next(work);
7939 if (!has_file_id(req->VolatileFileId)) {
7940 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
7941 work->compound_fid);
7942 id = work->compound_fid;
7945 req = smb2_get_msg(work->request_buf);
7946 rsp = smb2_get_msg(work->response_buf);
7949 if (!has_file_id(id))
7950 id = req->VolatileFileId;
7952 if (req->Flags != cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL)) {
7953 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7957 buffer = (char *)req + le32_to_cpu(req->InputOffset);
7959 cnt_code = le32_to_cpu(req->CtlCode);
7960 ret = smb2_calc_max_out_buf_len(work, 48,
7961 le32_to_cpu(req->MaxOutputResponse));
7963 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7966 out_buf_len = (unsigned int)ret;
7967 in_buf_len = le32_to_cpu(req->InputCount);
7970 case FSCTL_DFS_GET_REFERRALS:
7971 case FSCTL_DFS_GET_REFERRALS_EX:
7972 /* Not support DFS yet */
7973 rsp->hdr.Status = STATUS_FS_DRIVER_REQUIRED;
7975 case FSCTL_CREATE_OR_GET_OBJECT_ID:
7977 struct file_object_buf_type1_ioctl_rsp *obj_buf;
7979 nbytes = sizeof(struct file_object_buf_type1_ioctl_rsp);
7980 obj_buf = (struct file_object_buf_type1_ioctl_rsp *)
7984 * TODO: This is dummy implementation to pass smbtorture
7985 * Need to check correct response later
7987 memset(obj_buf->ObjectId, 0x0, 16);
7988 memset(obj_buf->BirthVolumeId, 0x0, 16);
7989 memset(obj_buf->BirthObjectId, 0x0, 16);
7990 memset(obj_buf->DomainId, 0x0, 16);
7994 case FSCTL_PIPE_TRANSCEIVE:
7995 out_buf_len = min_t(u32, KSMBD_IPC_MAX_PAYLOAD, out_buf_len);
7996 nbytes = fsctl_pipe_transceive(work, id, out_buf_len, req, rsp);
7998 case FSCTL_VALIDATE_NEGOTIATE_INFO:
7999 if (conn->dialect < SMB30_PROT_ID) {
8004 if (in_buf_len < offsetof(struct validate_negotiate_info_req,
8010 if (out_buf_len < sizeof(struct validate_negotiate_info_rsp)) {
8015 ret = fsctl_validate_negotiate_info(conn,
8016 (struct validate_negotiate_info_req *)buffer,
8017 (struct validate_negotiate_info_rsp *)&rsp->Buffer[0],
8022 nbytes = sizeof(struct validate_negotiate_info_rsp);
8023 rsp->PersistentFileId = SMB2_NO_FID;
8024 rsp->VolatileFileId = SMB2_NO_FID;
8026 case FSCTL_QUERY_NETWORK_INTERFACE_INFO:
8027 ret = fsctl_query_iface_info_ioctl(conn, rsp, out_buf_len);
8032 case FSCTL_REQUEST_RESUME_KEY:
8033 if (out_buf_len < sizeof(struct resume_key_ioctl_rsp)) {
8038 ret = fsctl_request_resume_key(work, req,
8039 (struct resume_key_ioctl_rsp *)&rsp->Buffer[0]);
8042 rsp->PersistentFileId = req->PersistentFileId;
8043 rsp->VolatileFileId = req->VolatileFileId;
8044 nbytes = sizeof(struct resume_key_ioctl_rsp);
8046 case FSCTL_COPYCHUNK:
8047 case FSCTL_COPYCHUNK_WRITE:
8048 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
8050 "User does not have write permission\n");
8055 if (in_buf_len < sizeof(struct copychunk_ioctl_req)) {
8060 if (out_buf_len < sizeof(struct copychunk_ioctl_rsp)) {
8065 nbytes = sizeof(struct copychunk_ioctl_rsp);
8066 rsp->VolatileFileId = req->VolatileFileId;
8067 rsp->PersistentFileId = req->PersistentFileId;
8068 fsctl_copychunk(work,
8069 (struct copychunk_ioctl_req *)buffer,
8070 le32_to_cpu(req->CtlCode),
8071 le32_to_cpu(req->InputCount),
8072 req->VolatileFileId,
8073 req->PersistentFileId,
8076 case FSCTL_SET_SPARSE:
8077 if (in_buf_len < sizeof(struct file_sparse)) {
8082 ret = fsctl_set_sparse(work, id, (struct file_sparse *)buffer);
8086 case FSCTL_SET_ZERO_DATA:
8088 struct file_zero_data_information *zero_data;
8089 struct ksmbd_file *fp;
8090 loff_t off, len, bfz;
8092 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
8094 "User does not have write permission\n");
8099 if (in_buf_len < sizeof(struct file_zero_data_information)) {
8105 (struct file_zero_data_information *)buffer;
8107 off = le64_to_cpu(zero_data->FileOffset);
8108 bfz = le64_to_cpu(zero_data->BeyondFinalZero);
8109 if (off < 0 || bfz < 0 || off > bfz) {
8116 fp = ksmbd_lookup_fd_fast(work, id);
8122 ret = ksmbd_vfs_zero_data(work, fp, off, len);
8123 ksmbd_fd_put(work, fp);
8129 case FSCTL_QUERY_ALLOCATED_RANGES:
8130 if (in_buf_len < sizeof(struct file_allocated_range_buffer)) {
8135 ret = fsctl_query_allocated_ranges(work, id,
8136 (struct file_allocated_range_buffer *)buffer,
8137 (struct file_allocated_range_buffer *)&rsp->Buffer[0],
8139 sizeof(struct file_allocated_range_buffer), &nbytes);
8140 if (ret == -E2BIG) {
8141 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
8142 } else if (ret < 0) {
8147 nbytes *= sizeof(struct file_allocated_range_buffer);
8149 case FSCTL_GET_REPARSE_POINT:
8151 struct reparse_data_buffer *reparse_ptr;
8152 struct ksmbd_file *fp;
8154 reparse_ptr = (struct reparse_data_buffer *)&rsp->Buffer[0];
8155 fp = ksmbd_lookup_fd_fast(work, id);
8157 pr_err("not found fp!!\n");
8162 reparse_ptr->ReparseTag =
8163 smb2_get_reparse_tag_special_file(file_inode(fp->filp)->i_mode);
8164 reparse_ptr->ReparseDataLength = 0;
8165 ksmbd_fd_put(work, fp);
8166 nbytes = sizeof(struct reparse_data_buffer);
8169 case FSCTL_DUPLICATE_EXTENTS_TO_FILE:
8171 struct ksmbd_file *fp_in, *fp_out = NULL;
8172 struct duplicate_extents_to_file *dup_ext;
8173 loff_t src_off, dst_off, length, cloned;
8175 if (in_buf_len < sizeof(struct duplicate_extents_to_file)) {
8180 dup_ext = (struct duplicate_extents_to_file *)buffer;
8182 fp_in = ksmbd_lookup_fd_slow(work, dup_ext->VolatileFileHandle,
8183 dup_ext->PersistentFileHandle);
8185 pr_err("not found file handle in duplicate extent to file\n");
8190 fp_out = ksmbd_lookup_fd_fast(work, id);
8192 pr_err("not found fp\n");
8197 src_off = le64_to_cpu(dup_ext->SourceFileOffset);
8198 dst_off = le64_to_cpu(dup_ext->TargetFileOffset);
8199 length = le64_to_cpu(dup_ext->ByteCount);
8201 * XXX: It is not clear if FSCTL_DUPLICATE_EXTENTS_TO_FILE
8202 * should fall back to vfs_copy_file_range(). This could be
8203 * beneficial when re-exporting nfs/smb mount, but note that
8204 * this can result in partial copy that returns an error status.
8205 * If/when FSCTL_DUPLICATE_EXTENTS_TO_FILE_EX is implemented,
8206 * fall back to vfs_copy_file_range(), should be avoided when
8207 * the flag DUPLICATE_EXTENTS_DATA_EX_SOURCE_ATOMIC is set.
8209 cloned = vfs_clone_file_range(fp_in->filp, src_off,
8210 fp_out->filp, dst_off, length, 0);
8211 if (cloned == -EXDEV || cloned == -EOPNOTSUPP) {
8214 } else if (cloned != length) {
8215 cloned = vfs_copy_file_range(fp_in->filp, src_off,
8216 fp_out->filp, dst_off,
8218 if (cloned != length) {
8227 ksmbd_fd_put(work, fp_in);
8228 ksmbd_fd_put(work, fp_out);
8234 ksmbd_debug(SMB, "not implemented yet ioctl command 0x%x\n",
8240 rsp->CtlCode = cpu_to_le32(cnt_code);
8241 rsp->InputCount = cpu_to_le32(0);
8242 rsp->InputOffset = cpu_to_le32(112);
8243 rsp->OutputOffset = cpu_to_le32(112);
8244 rsp->OutputCount = cpu_to_le32(nbytes);
8245 rsp->StructureSize = cpu_to_le16(49);
8246 rsp->Reserved = cpu_to_le16(0);
8247 rsp->Flags = cpu_to_le32(0);
8248 rsp->Reserved2 = cpu_to_le32(0);
8249 ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_ioctl_rsp) + nbytes);
8255 rsp->hdr.Status = STATUS_ACCESS_DENIED;
8256 else if (ret == -ENOENT)
8257 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
8258 else if (ret == -EOPNOTSUPP)
8259 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
8260 else if (ret == -ENOSPC)
8261 rsp->hdr.Status = STATUS_BUFFER_TOO_SMALL;
8262 else if (ret < 0 || rsp->hdr.Status == 0)
8263 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8264 smb2_set_err_rsp(work);
8269 * smb20_oplock_break_ack() - handler for smb2.0 oplock break command
8270 * @work: smb work containing oplock break command buffer
8274 static void smb20_oplock_break_ack(struct ksmbd_work *work)
8276 struct smb2_oplock_break *req;
8277 struct smb2_oplock_break *rsp;
8278 struct ksmbd_file *fp;
8279 struct oplock_info *opinfo = NULL;
8282 u64 volatile_id, persistent_id;
8283 char req_oplevel = 0, rsp_oplevel = 0;
8284 unsigned int oplock_change_type;
8286 WORK_BUFFERS(work, req, rsp);
8288 volatile_id = req->VolatileFid;
8289 persistent_id = req->PersistentFid;
8290 req_oplevel = req->OplockLevel;
8291 ksmbd_debug(OPLOCK, "v_id %llu, p_id %llu request oplock level %d\n",
8292 volatile_id, persistent_id, req_oplevel);
8294 fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
8296 rsp->hdr.Status = STATUS_FILE_CLOSED;
8297 smb2_set_err_rsp(work);
8301 opinfo = opinfo_get(fp);
8303 pr_err("unexpected null oplock_info\n");
8304 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
8305 smb2_set_err_rsp(work);
8306 ksmbd_fd_put(work, fp);
8310 if (opinfo->level == SMB2_OPLOCK_LEVEL_NONE) {
8311 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
8315 if (opinfo->op_state == OPLOCK_STATE_NONE) {
8316 ksmbd_debug(SMB, "unexpected oplock state 0x%x\n", opinfo->op_state);
8317 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8321 if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
8322 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
8323 (req_oplevel != SMB2_OPLOCK_LEVEL_II &&
8324 req_oplevel != SMB2_OPLOCK_LEVEL_NONE)) {
8325 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8326 oplock_change_type = OPLOCK_WRITE_TO_NONE;
8327 } else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
8328 req_oplevel != SMB2_OPLOCK_LEVEL_NONE) {
8329 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8330 oplock_change_type = OPLOCK_READ_TO_NONE;
8331 } else if (req_oplevel == SMB2_OPLOCK_LEVEL_II ||
8332 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
8333 err = STATUS_INVALID_DEVICE_STATE;
8334 if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
8335 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
8336 req_oplevel == SMB2_OPLOCK_LEVEL_II) {
8337 oplock_change_type = OPLOCK_WRITE_TO_READ;
8338 } else if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
8339 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
8340 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
8341 oplock_change_type = OPLOCK_WRITE_TO_NONE;
8342 } else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
8343 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
8344 oplock_change_type = OPLOCK_READ_TO_NONE;
8346 oplock_change_type = 0;
8349 oplock_change_type = 0;
8352 switch (oplock_change_type) {
8353 case OPLOCK_WRITE_TO_READ:
8354 ret = opinfo_write_to_read(opinfo);
8355 rsp_oplevel = SMB2_OPLOCK_LEVEL_II;
8357 case OPLOCK_WRITE_TO_NONE:
8358 ret = opinfo_write_to_none(opinfo);
8359 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
8361 case OPLOCK_READ_TO_NONE:
8362 ret = opinfo_read_to_none(opinfo);
8363 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
8366 pr_err("unknown oplock change 0x%x -> 0x%x\n",
8367 opinfo->level, rsp_oplevel);
8371 rsp->hdr.Status = err;
8375 opinfo->op_state = OPLOCK_STATE_NONE;
8376 wake_up_interruptible_all(&opinfo->oplock_q);
8378 ksmbd_fd_put(work, fp);
8380 rsp->StructureSize = cpu_to_le16(24);
8381 rsp->OplockLevel = rsp_oplevel;
8384 rsp->VolatileFid = volatile_id;
8385 rsp->PersistentFid = persistent_id;
8386 ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_oplock_break));
8391 opinfo->op_state = OPLOCK_STATE_NONE;
8392 wake_up_interruptible_all(&opinfo->oplock_q);
8395 ksmbd_fd_put(work, fp);
8396 smb2_set_err_rsp(work);
8399 static int check_lease_state(struct lease *lease, __le32 req_state)
8401 if ((lease->new_state ==
8402 (SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE)) &&
8403 !(req_state & SMB2_LEASE_WRITE_CACHING_LE)) {
8404 lease->new_state = req_state;
8408 if (lease->new_state == req_state)
8415 * smb21_lease_break_ack() - handler for smb2.1 lease break command
8416 * @work: smb work containing lease break command buffer
8420 static void smb21_lease_break_ack(struct ksmbd_work *work)
8422 struct ksmbd_conn *conn = work->conn;
8423 struct smb2_lease_ack *req;
8424 struct smb2_lease_ack *rsp;
8425 struct oplock_info *opinfo;
8428 unsigned int lease_change_type;
8430 struct lease *lease;
8432 WORK_BUFFERS(work, req, rsp);
8434 ksmbd_debug(OPLOCK, "smb21 lease break, lease state(0x%x)\n",
8435 le32_to_cpu(req->LeaseState));
8436 opinfo = lookup_lease_in_table(conn, req->LeaseKey);
8438 ksmbd_debug(OPLOCK, "file not opened\n");
8439 smb2_set_err_rsp(work);
8440 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8443 lease = opinfo->o_lease;
8445 if (opinfo->op_state == OPLOCK_STATE_NONE) {
8446 pr_err("unexpected lease break state 0x%x\n",
8448 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8452 if (check_lease_state(lease, req->LeaseState)) {
8453 rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
8455 "req lease state: 0x%x, expected state: 0x%x\n",
8456 req->LeaseState, lease->new_state);
8460 if (!atomic_read(&opinfo->breaking_cnt)) {
8461 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8465 /* check for bad lease state */
8466 if (req->LeaseState &
8467 (~(SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE))) {
8468 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8469 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8470 lease_change_type = OPLOCK_WRITE_TO_NONE;
8472 lease_change_type = OPLOCK_READ_TO_NONE;
8473 ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8474 le32_to_cpu(lease->state),
8475 le32_to_cpu(req->LeaseState));
8476 } else if (lease->state == SMB2_LEASE_READ_CACHING_LE &&
8477 req->LeaseState != SMB2_LEASE_NONE_LE) {
8478 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8479 lease_change_type = OPLOCK_READ_TO_NONE;
8480 ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8481 le32_to_cpu(lease->state),
8482 le32_to_cpu(req->LeaseState));
8484 /* valid lease state changes */
8485 err = STATUS_INVALID_DEVICE_STATE;
8486 if (req->LeaseState == SMB2_LEASE_NONE_LE) {
8487 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8488 lease_change_type = OPLOCK_WRITE_TO_NONE;
8490 lease_change_type = OPLOCK_READ_TO_NONE;
8491 } else if (req->LeaseState & SMB2_LEASE_READ_CACHING_LE) {
8492 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8493 lease_change_type = OPLOCK_WRITE_TO_READ;
8495 lease_change_type = OPLOCK_READ_HANDLE_TO_READ;
8497 lease_change_type = 0;
8501 switch (lease_change_type) {
8502 case OPLOCK_WRITE_TO_READ:
8503 ret = opinfo_write_to_read(opinfo);
8505 case OPLOCK_READ_HANDLE_TO_READ:
8506 ret = opinfo_read_handle_to_read(opinfo);
8508 case OPLOCK_WRITE_TO_NONE:
8509 ret = opinfo_write_to_none(opinfo);
8511 case OPLOCK_READ_TO_NONE:
8512 ret = opinfo_read_to_none(opinfo);
8515 ksmbd_debug(OPLOCK, "unknown lease change 0x%x -> 0x%x\n",
8516 le32_to_cpu(lease->state),
8517 le32_to_cpu(req->LeaseState));
8521 rsp->hdr.Status = err;
8525 lease_state = lease->state;
8526 opinfo->op_state = OPLOCK_STATE_NONE;
8527 wake_up_interruptible_all(&opinfo->oplock_q);
8528 atomic_dec(&opinfo->breaking_cnt);
8529 wake_up_interruptible_all(&opinfo->oplock_brk);
8532 rsp->StructureSize = cpu_to_le16(36);
8535 memcpy(rsp->LeaseKey, req->LeaseKey, 16);
8536 rsp->LeaseState = lease_state;
8537 rsp->LeaseDuration = 0;
8538 ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_lease_ack));
8543 wake_up_interruptible_all(&opinfo->oplock_q);
8544 atomic_dec(&opinfo->breaking_cnt);
8545 wake_up_interruptible_all(&opinfo->oplock_brk);
8548 smb2_set_err_rsp(work);
8552 * smb2_oplock_break() - dispatcher for smb2.0 and 2.1 oplock/lease break
8553 * @work: smb work containing oplock/lease break command buffer
8557 int smb2_oplock_break(struct ksmbd_work *work)
8559 struct smb2_oplock_break *req;
8560 struct smb2_oplock_break *rsp;
8562 WORK_BUFFERS(work, req, rsp);
8564 switch (le16_to_cpu(req->StructureSize)) {
8565 case OP_BREAK_STRUCT_SIZE_20:
8566 smb20_oplock_break_ack(work);
8568 case OP_BREAK_STRUCT_SIZE_21:
8569 smb21_lease_break_ack(work);
8572 ksmbd_debug(OPLOCK, "invalid break cmd %d\n",
8573 le16_to_cpu(req->StructureSize));
8574 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8575 smb2_set_err_rsp(work);
8582 * smb2_notify() - handler for smb2 notify request
8583 * @work: smb work containing notify command buffer
8587 int smb2_notify(struct ksmbd_work *work)
8589 struct smb2_change_notify_req *req;
8590 struct smb2_change_notify_rsp *rsp;
8592 WORK_BUFFERS(work, req, rsp);
8594 if (work->next_smb2_rcv_hdr_off && req->hdr.NextCommand) {
8595 rsp->hdr.Status = STATUS_INTERNAL_ERROR;
8596 smb2_set_err_rsp(work);
8600 smb2_set_err_rsp(work);
8601 rsp->hdr.Status = STATUS_NOT_IMPLEMENTED;
8606 * smb2_is_sign_req() - handler for checking packet signing status
8607 * @work: smb work containing notify command buffer
8608 * @command: SMB2 command id
8610 * Return: true if packed is signed, false otherwise
8612 bool smb2_is_sign_req(struct ksmbd_work *work, unsigned int command)
8614 struct smb2_hdr *rcv_hdr2 = smb2_get_msg(work->request_buf);
8616 if ((rcv_hdr2->Flags & SMB2_FLAGS_SIGNED) &&
8617 command != SMB2_NEGOTIATE_HE &&
8618 command != SMB2_SESSION_SETUP_HE &&
8619 command != SMB2_OPLOCK_BREAK_HE)
8626 * smb2_check_sign_req() - handler for req packet sign processing
8627 * @work: smb work containing notify command buffer
8629 * Return: 1 on success, 0 otherwise
8631 int smb2_check_sign_req(struct ksmbd_work *work)
8633 struct smb2_hdr *hdr;
8634 char signature_req[SMB2_SIGNATURE_SIZE];
8635 char signature[SMB2_HMACSHA256_SIZE];
8639 hdr = smb2_get_msg(work->request_buf);
8640 if (work->next_smb2_rcv_hdr_off)
8641 hdr = ksmbd_req_buf_next(work);
8643 if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8644 len = get_rfc1002_len(work->request_buf);
8645 else if (hdr->NextCommand)
8646 len = le32_to_cpu(hdr->NextCommand);
8648 len = get_rfc1002_len(work->request_buf) -
8649 work->next_smb2_rcv_hdr_off;
8651 memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8652 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8654 iov[0].iov_base = (char *)&hdr->ProtocolId;
8655 iov[0].iov_len = len;
8657 if (ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, 1,
8661 if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8662 pr_err("bad smb2 signature\n");
8670 * smb2_set_sign_rsp() - handler for rsp packet sign processing
8671 * @work: smb work containing notify command buffer
8674 void smb2_set_sign_rsp(struct ksmbd_work *work)
8676 struct smb2_hdr *hdr;
8677 char signature[SMB2_HMACSHA256_SIZE];
8681 hdr = ksmbd_resp_buf_curr(work);
8682 hdr->Flags |= SMB2_FLAGS_SIGNED;
8683 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8685 if (hdr->Command == SMB2_READ) {
8686 iov = &work->iov[work->iov_idx - 1];
8689 iov = &work->iov[work->iov_idx];
8692 if (!ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, n_vec,
8694 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
8698 * smb3_check_sign_req() - handler for req packet sign processing
8699 * @work: smb work containing notify command buffer
8701 * Return: 1 on success, 0 otherwise
8703 int smb3_check_sign_req(struct ksmbd_work *work)
8705 struct ksmbd_conn *conn = work->conn;
8707 struct smb2_hdr *hdr;
8708 struct channel *chann;
8709 char signature_req[SMB2_SIGNATURE_SIZE];
8710 char signature[SMB2_CMACAES_SIZE];
8714 hdr = smb2_get_msg(work->request_buf);
8715 if (work->next_smb2_rcv_hdr_off)
8716 hdr = ksmbd_req_buf_next(work);
8718 if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8719 len = get_rfc1002_len(work->request_buf);
8720 else if (hdr->NextCommand)
8721 len = le32_to_cpu(hdr->NextCommand);
8723 len = get_rfc1002_len(work->request_buf) -
8724 work->next_smb2_rcv_hdr_off;
8726 if (le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8727 signing_key = work->sess->smb3signingkey;
8729 chann = lookup_chann_list(work->sess, conn);
8733 signing_key = chann->smb3signingkey;
8737 pr_err("SMB3 signing key is not generated\n");
8741 memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8742 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8743 iov[0].iov_base = (char *)&hdr->ProtocolId;
8744 iov[0].iov_len = len;
8746 if (ksmbd_sign_smb3_pdu(conn, signing_key, iov, 1, signature))
8749 if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8750 pr_err("bad smb2 signature\n");
8758 * smb3_set_sign_rsp() - handler for rsp packet sign processing
8759 * @work: smb work containing notify command buffer
8762 void smb3_set_sign_rsp(struct ksmbd_work *work)
8764 struct ksmbd_conn *conn = work->conn;
8765 struct smb2_hdr *hdr;
8766 struct channel *chann;
8767 char signature[SMB2_CMACAES_SIZE];
8772 hdr = ksmbd_resp_buf_curr(work);
8774 if (conn->binding == false &&
8775 le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8776 signing_key = work->sess->smb3signingkey;
8778 chann = lookup_chann_list(work->sess, work->conn);
8782 signing_key = chann->smb3signingkey;
8788 hdr->Flags |= SMB2_FLAGS_SIGNED;
8789 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8791 if (hdr->Command == SMB2_READ) {
8792 iov = &work->iov[work->iov_idx - 1];
8795 iov = &work->iov[work->iov_idx];
8798 if (!ksmbd_sign_smb3_pdu(conn, signing_key, iov, n_vec,
8800 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
8804 * smb3_preauth_hash_rsp() - handler for computing preauth hash on response
8805 * @work: smb work containing response buffer
8808 void smb3_preauth_hash_rsp(struct ksmbd_work *work)
8810 struct ksmbd_conn *conn = work->conn;
8811 struct ksmbd_session *sess = work->sess;
8812 struct smb2_hdr *req, *rsp;
8814 if (conn->dialect != SMB311_PROT_ID)
8817 WORK_BUFFERS(work, req, rsp);
8819 if (le16_to_cpu(req->Command) == SMB2_NEGOTIATE_HE &&
8821 ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
8822 conn->preauth_info->Preauth_HashValue);
8824 if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE && sess) {
8827 if (conn->binding) {
8828 struct preauth_session *preauth_sess;
8830 preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
8833 hash_value = preauth_sess->Preauth_HashValue;
8835 hash_value = sess->Preauth_HashValue;
8839 ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
8844 static void fill_transform_hdr(void *tr_buf, char *old_buf, __le16 cipher_type)
8846 struct smb2_transform_hdr *tr_hdr = tr_buf + 4;
8847 struct smb2_hdr *hdr = smb2_get_msg(old_buf);
8848 unsigned int orig_len = get_rfc1002_len(old_buf);
8850 /* tr_buf must be cleared by the caller */
8851 tr_hdr->ProtocolId = SMB2_TRANSFORM_PROTO_NUM;
8852 tr_hdr->OriginalMessageSize = cpu_to_le32(orig_len);
8853 tr_hdr->Flags = cpu_to_le16(TRANSFORM_FLAG_ENCRYPTED);
8854 if (cipher_type == SMB2_ENCRYPTION_AES128_GCM ||
8855 cipher_type == SMB2_ENCRYPTION_AES256_GCM)
8856 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_GCM_NONCE);
8858 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_CCM_NONCE);
8859 memcpy(&tr_hdr->SessionId, &hdr->SessionId, 8);
8860 inc_rfc1001_len(tr_buf, sizeof(struct smb2_transform_hdr));
8861 inc_rfc1001_len(tr_buf, orig_len);
8864 int smb3_encrypt_resp(struct ksmbd_work *work)
8866 struct kvec *iov = work->iov;
8870 tr_buf = kzalloc(sizeof(struct smb2_transform_hdr) + 4, GFP_KERNEL);
8874 /* fill transform header */
8875 fill_transform_hdr(tr_buf, work->response_buf, work->conn->cipher_type);
8877 iov[0].iov_base = tr_buf;
8878 iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
8879 work->tr_buf = tr_buf;
8881 return ksmbd_crypt_message(work, iov, work->iov_idx + 1, 1);
8884 bool smb3_is_transform_hdr(void *buf)
8886 struct smb2_transform_hdr *trhdr = smb2_get_msg(buf);
8888 return trhdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM;
8891 int smb3_decrypt_req(struct ksmbd_work *work)
8893 struct ksmbd_session *sess;
8894 char *buf = work->request_buf;
8895 unsigned int pdu_length = get_rfc1002_len(buf);
8897 int buf_data_size = pdu_length - sizeof(struct smb2_transform_hdr);
8898 struct smb2_transform_hdr *tr_hdr = smb2_get_msg(buf);
8901 if (pdu_length < sizeof(struct smb2_transform_hdr) ||
8902 buf_data_size < sizeof(struct smb2_hdr)) {
8903 pr_err("Transform message is too small (%u)\n",
8905 return -ECONNABORTED;
8908 if (buf_data_size < le32_to_cpu(tr_hdr->OriginalMessageSize)) {
8909 pr_err("Transform message is broken\n");
8910 return -ECONNABORTED;
8913 sess = ksmbd_session_lookup_all(work->conn, le64_to_cpu(tr_hdr->SessionId));
8915 pr_err("invalid session id(%llx) in transform header\n",
8916 le64_to_cpu(tr_hdr->SessionId));
8917 return -ECONNABORTED;
8920 iov[0].iov_base = buf;
8921 iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
8922 iov[1].iov_base = buf + sizeof(struct smb2_transform_hdr) + 4;
8923 iov[1].iov_len = buf_data_size;
8924 rc = ksmbd_crypt_message(work, iov, 2, 0);
8928 memmove(buf + 4, iov[1].iov_base, buf_data_size);
8929 *(__be32 *)buf = cpu_to_be32(buf_data_size);
8934 bool smb3_11_final_sess_setup_resp(struct ksmbd_work *work)
8936 struct ksmbd_conn *conn = work->conn;
8937 struct ksmbd_session *sess = work->sess;
8938 struct smb2_hdr *rsp = smb2_get_msg(work->response_buf);
8940 if (conn->dialect < SMB30_PROT_ID)
8943 if (work->next_smb2_rcv_hdr_off)
8944 rsp = ksmbd_resp_buf_next(work);
8946 if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE &&
8947 sess->user && !user_guest(sess->user) &&
8948 rsp->Status == STATUS_SUCCESS)