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>
23 #include "connection.h"
24 #include "transport_ipc.h"
25 #include "transport_rdma.h"
27 #include "vfs_cache.h"
31 #include "smb_common.h"
32 #include "smbstatus.h"
33 #include "ksmbd_work.h"
34 #include "mgmt/user_config.h"
35 #include "mgmt/share_config.h"
36 #include "mgmt/tree_connect.h"
37 #include "mgmt/user_session.h"
38 #include "mgmt/ksmbd_ida.h"
41 static void __wbuf(struct ksmbd_work *work, void **req, void **rsp)
43 if (work->next_smb2_rcv_hdr_off) {
44 *req = ksmbd_req_buf_next(work);
45 *rsp = ksmbd_resp_buf_next(work);
47 *req = work->request_buf;
48 *rsp = work->response_buf;
52 #define WORK_BUFFERS(w, rq, rs) __wbuf((w), (void **)&(rq), (void **)&(rs))
55 * check_session_id() - check for valid session id in smb header
56 * @conn: connection instance
57 * @id: session id from smb header
59 * Return: 1 if valid session id, otherwise 0
61 static inline bool check_session_id(struct ksmbd_conn *conn, u64 id)
63 struct ksmbd_session *sess;
65 if (id == 0 || id == -1)
68 sess = ksmbd_session_lookup_all(conn, id);
71 pr_err("Invalid user session id: %llu\n", id);
75 struct channel *lookup_chann_list(struct ksmbd_session *sess, struct ksmbd_conn *conn)
77 struct channel *chann;
79 list_for_each_entry(chann, &sess->ksmbd_chann_list, chann_list) {
80 if (chann->conn == conn)
88 * smb2_get_ksmbd_tcon() - get tree connection information using a tree id.
91 * Return: 0 if there is a tree connection matched or these are
92 * skipable commands, otherwise error
94 int smb2_get_ksmbd_tcon(struct ksmbd_work *work)
96 struct smb2_hdr *req_hdr = work->request_buf;
100 if (work->conn->ops->get_cmd_val(work) == SMB2_TREE_CONNECT_HE ||
101 work->conn->ops->get_cmd_val(work) == SMB2_CANCEL_HE ||
102 work->conn->ops->get_cmd_val(work) == SMB2_LOGOFF_HE) {
103 ksmbd_debug(SMB, "skip to check tree connect request\n");
107 if (xa_empty(&work->sess->tree_conns)) {
108 ksmbd_debug(SMB, "NO tree connected\n");
112 tree_id = le32_to_cpu(req_hdr->Id.SyncId.TreeId);
113 work->tcon = ksmbd_tree_conn_lookup(work->sess, tree_id);
115 pr_err("Invalid tid %d\n", tree_id);
123 * smb2_set_err_rsp() - set error response code on smb response
124 * @work: smb work containing response buffer
126 void smb2_set_err_rsp(struct ksmbd_work *work)
128 struct smb2_err_rsp *err_rsp;
130 if (work->next_smb2_rcv_hdr_off)
131 err_rsp = ksmbd_resp_buf_next(work);
133 err_rsp = work->response_buf;
135 if (err_rsp->hdr.Status != STATUS_STOPPED_ON_SYMLINK) {
136 err_rsp->StructureSize = SMB2_ERROR_STRUCTURE_SIZE2_LE;
137 err_rsp->ErrorContextCount = 0;
138 err_rsp->Reserved = 0;
139 err_rsp->ByteCount = 0;
140 err_rsp->ErrorData[0] = 0;
141 inc_rfc1001_len(work->response_buf, SMB2_ERROR_STRUCTURE_SIZE2);
146 * is_smb2_neg_cmd() - is it smb2 negotiation command
147 * @work: smb work containing smb header
149 * Return: true if smb2 negotiation command, otherwise false
151 bool is_smb2_neg_cmd(struct ksmbd_work *work)
153 struct smb2_hdr *hdr = work->request_buf;
155 /* is it SMB2 header ? */
156 if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
159 /* make sure it is request not response message */
160 if (hdr->Flags & SMB2_FLAGS_SERVER_TO_REDIR)
163 if (hdr->Command != SMB2_NEGOTIATE)
170 * is_smb2_rsp() - is it smb2 response
171 * @work: smb work containing smb response buffer
173 * Return: true if smb2 response, otherwise false
175 bool is_smb2_rsp(struct ksmbd_work *work)
177 struct smb2_hdr *hdr = work->response_buf;
179 /* is it SMB2 header ? */
180 if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
183 /* make sure it is response not request message */
184 if (!(hdr->Flags & SMB2_FLAGS_SERVER_TO_REDIR))
191 * get_smb2_cmd_val() - get smb command code from smb header
192 * @work: smb work containing smb request buffer
194 * Return: smb2 request command value
196 u16 get_smb2_cmd_val(struct ksmbd_work *work)
198 struct smb2_hdr *rcv_hdr;
200 if (work->next_smb2_rcv_hdr_off)
201 rcv_hdr = ksmbd_req_buf_next(work);
203 rcv_hdr = work->request_buf;
204 return le16_to_cpu(rcv_hdr->Command);
208 * set_smb2_rsp_status() - set error response code on smb2 header
209 * @work: smb work containing response buffer
210 * @err: error response code
212 void set_smb2_rsp_status(struct ksmbd_work *work, __le32 err)
214 struct smb2_hdr *rsp_hdr;
216 if (work->next_smb2_rcv_hdr_off)
217 rsp_hdr = ksmbd_resp_buf_next(work);
219 rsp_hdr = work->response_buf;
220 rsp_hdr->Status = err;
221 smb2_set_err_rsp(work);
225 * init_smb2_neg_rsp() - initialize smb2 response for negotiate command
226 * @work: smb work containing smb request buffer
228 * smb2 negotiate response is sent in reply of smb1 negotiate command for
229 * dialect auto-negotiation.
231 int init_smb2_neg_rsp(struct ksmbd_work *work)
233 struct smb2_hdr *rsp_hdr;
234 struct smb2_negotiate_rsp *rsp;
235 struct ksmbd_conn *conn = work->conn;
237 if (conn->need_neg == false)
239 if (!(conn->dialect >= SMB20_PROT_ID &&
240 conn->dialect <= SMB311_PROT_ID))
243 rsp_hdr = work->response_buf;
245 memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
247 rsp_hdr->smb2_buf_length =
248 cpu_to_be32(smb2_hdr_size_no_buflen(conn->vals));
250 rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
251 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
252 rsp_hdr->CreditRequest = cpu_to_le16(2);
253 rsp_hdr->Command = SMB2_NEGOTIATE;
254 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
255 rsp_hdr->NextCommand = 0;
256 rsp_hdr->MessageId = 0;
257 rsp_hdr->Id.SyncId.ProcessId = 0;
258 rsp_hdr->Id.SyncId.TreeId = 0;
259 rsp_hdr->SessionId = 0;
260 memset(rsp_hdr->Signature, 0, 16);
262 rsp = work->response_buf;
264 WARN_ON(ksmbd_conn_good(work));
266 rsp->StructureSize = cpu_to_le16(65);
267 ksmbd_debug(SMB, "conn->dialect 0x%x\n", conn->dialect);
268 rsp->DialectRevision = cpu_to_le16(conn->dialect);
269 /* Not setting conn guid rsp->ServerGUID, as it
270 * not used by client for identifying connection
272 rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
273 /* Default Max Message Size till SMB2.0, 64K*/
274 rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
275 rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
276 rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);
278 rsp->SystemTime = cpu_to_le64(ksmbd_systime());
279 rsp->ServerStartTime = 0;
281 rsp->SecurityBufferOffset = cpu_to_le16(128);
282 rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
283 ksmbd_copy_gss_neg_header(((char *)(&rsp->hdr) +
284 sizeof(rsp->hdr.smb2_buf_length)) +
285 le16_to_cpu(rsp->SecurityBufferOffset));
286 inc_rfc1001_len(rsp, sizeof(struct smb2_negotiate_rsp) -
287 sizeof(struct smb2_hdr) - sizeof(rsp->Buffer) +
289 rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
290 if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY)
291 rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
292 conn->use_spnego = true;
294 ksmbd_conn_set_need_negotiate(work);
298 static int smb2_consume_credit_charge(struct ksmbd_work *work,
299 unsigned short credit_charge)
301 struct ksmbd_conn *conn = work->conn;
302 unsigned int rsp_credits = 1;
304 if (!conn->total_credits)
307 if (credit_charge > 0)
308 rsp_credits = credit_charge;
310 conn->total_credits -= rsp_credits;
315 * smb2_set_rsp_credits() - set number of credits in response buffer
316 * @work: smb work containing smb response buffer
318 int smb2_set_rsp_credits(struct ksmbd_work *work)
320 struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
321 struct smb2_hdr *hdr = ksmbd_resp_buf_next(work);
322 struct ksmbd_conn *conn = work->conn;
323 unsigned short credits_requested = le16_to_cpu(req_hdr->CreditRequest);
324 unsigned short credit_charge = 1, credits_granted = 0;
325 unsigned short aux_max, aux_credits, min_credits;
326 int rsp_credit_charge;
328 if (hdr->Command == SMB2_CANCEL)
331 /* get default minimum credits by shifting maximum credits by 4 */
332 min_credits = conn->max_credits >> 4;
334 if (conn->total_credits >= conn->max_credits) {
335 pr_err("Total credits overflow: %d\n", conn->total_credits);
336 conn->total_credits = min_credits;
340 smb2_consume_credit_charge(work, le16_to_cpu(req_hdr->CreditCharge));
341 if (rsp_credit_charge < 0)
344 hdr->CreditCharge = cpu_to_le16(rsp_credit_charge);
346 if (credits_requested > 0) {
347 aux_credits = credits_requested - 1;
349 if (hdr->Command == SMB2_NEGOTIATE)
351 aux_credits = (aux_credits < aux_max) ? aux_credits : aux_max;
352 credits_granted = aux_credits + credit_charge;
354 /* if credits granted per client is getting bigger than default
355 * minimum credits then we should wrap it up within the limits.
357 if ((conn->total_credits + credits_granted) > min_credits)
358 credits_granted = min_credits - conn->total_credits;
360 * TODO: Need to adjuct CreditRequest value according to
363 } else if (conn->total_credits == 0) {
367 conn->total_credits += credits_granted;
368 work->credits_granted += credits_granted;
370 if (!req_hdr->NextCommand) {
371 /* Update CreditRequest in last request */
372 hdr->CreditRequest = cpu_to_le16(work->credits_granted);
376 "credits: requested[%d] granted[%d] total_granted[%d]\n",
377 credits_requested, credits_granted,
378 conn->total_credits);
383 * init_chained_smb2_rsp() - initialize smb2 chained response
384 * @work: smb work containing smb response buffer
386 static void init_chained_smb2_rsp(struct ksmbd_work *work)
388 struct smb2_hdr *req = ksmbd_req_buf_next(work);
389 struct smb2_hdr *rsp = ksmbd_resp_buf_next(work);
390 struct smb2_hdr *rsp_hdr;
391 struct smb2_hdr *rcv_hdr;
392 int next_hdr_offset = 0;
395 /* Len of this response = updated RFC len - offset of previous cmd
396 * in the compound rsp
399 /* Storing the current local FID which may be needed by subsequent
400 * command in the compound request
402 if (req->Command == SMB2_CREATE && rsp->Status == STATUS_SUCCESS) {
404 le64_to_cpu(((struct smb2_create_rsp *)rsp)->
406 work->compound_pfid =
407 le64_to_cpu(((struct smb2_create_rsp *)rsp)->
409 work->compound_sid = le64_to_cpu(rsp->SessionId);
412 len = get_rfc1002_len(work->response_buf) - work->next_smb2_rsp_hdr_off;
413 next_hdr_offset = le32_to_cpu(req->NextCommand);
415 new_len = ALIGN(len, 8);
416 inc_rfc1001_len(work->response_buf, ((sizeof(struct smb2_hdr) - 4)
418 rsp->NextCommand = cpu_to_le32(new_len);
420 work->next_smb2_rcv_hdr_off += next_hdr_offset;
421 work->next_smb2_rsp_hdr_off += new_len;
423 "Compound req new_len = %d rcv off = %d rsp off = %d\n",
424 new_len, work->next_smb2_rcv_hdr_off,
425 work->next_smb2_rsp_hdr_off);
427 rsp_hdr = ksmbd_resp_buf_next(work);
428 rcv_hdr = ksmbd_req_buf_next(work);
430 if (!(rcv_hdr->Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
431 ksmbd_debug(SMB, "related flag should be set\n");
432 work->compound_fid = KSMBD_NO_FID;
433 work->compound_pfid = KSMBD_NO_FID;
435 memset((char *)rsp_hdr + 4, 0, sizeof(struct smb2_hdr) + 2);
436 rsp_hdr->ProtocolId = rcv_hdr->ProtocolId;
437 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
438 rsp_hdr->Command = rcv_hdr->Command;
441 * Message is response. We don't grant oplock yet.
443 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR |
444 SMB2_FLAGS_RELATED_OPERATIONS);
445 rsp_hdr->NextCommand = 0;
446 rsp_hdr->MessageId = rcv_hdr->MessageId;
447 rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
448 rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
449 rsp_hdr->SessionId = rcv_hdr->SessionId;
450 memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);
454 * is_chained_smb2_message() - check for chained command
455 * @work: smb work containing smb request buffer
457 * Return: true if chained request, otherwise false
459 bool is_chained_smb2_message(struct ksmbd_work *work)
461 struct smb2_hdr *hdr = work->request_buf;
464 if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
467 hdr = ksmbd_req_buf_next(work);
468 if (le32_to_cpu(hdr->NextCommand) > 0) {
469 ksmbd_debug(SMB, "got SMB2 chained command\n");
470 init_chained_smb2_rsp(work);
472 } else if (work->next_smb2_rcv_hdr_off) {
474 * This is last request in chained command,
475 * align response to 8 byte
477 len = ALIGN(get_rfc1002_len(work->response_buf), 8);
478 len = len - get_rfc1002_len(work->response_buf);
480 ksmbd_debug(SMB, "padding len %u\n", len);
481 inc_rfc1001_len(work->response_buf, len);
482 if (work->aux_payload_sz)
483 work->aux_payload_sz += len;
490 * init_smb2_rsp_hdr() - initialize smb2 response
491 * @work: smb work containing smb request buffer
495 int init_smb2_rsp_hdr(struct ksmbd_work *work)
497 struct smb2_hdr *rsp_hdr = work->response_buf;
498 struct smb2_hdr *rcv_hdr = work->request_buf;
499 struct ksmbd_conn *conn = work->conn;
501 memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
502 rsp_hdr->smb2_buf_length =
503 cpu_to_be32(smb2_hdr_size_no_buflen(conn->vals));
504 rsp_hdr->ProtocolId = rcv_hdr->ProtocolId;
505 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
506 rsp_hdr->Command = rcv_hdr->Command;
509 * Message is response. We don't grant oplock yet.
511 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
512 rsp_hdr->NextCommand = 0;
513 rsp_hdr->MessageId = rcv_hdr->MessageId;
514 rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
515 rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
516 rsp_hdr->SessionId = rcv_hdr->SessionId;
517 memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);
519 work->syncronous = true;
520 if (work->async_id) {
521 ksmbd_release_id(&conn->async_ida, work->async_id);
529 * smb2_allocate_rsp_buf() - allocate smb2 response buffer
530 * @work: smb work containing smb request buffer
532 * Return: 0 on success, otherwise -ENOMEM
534 int smb2_allocate_rsp_buf(struct ksmbd_work *work)
536 struct smb2_hdr *hdr = work->request_buf;
537 size_t small_sz = MAX_CIFS_SMALL_BUFFER_SIZE;
538 size_t large_sz = work->conn->vals->max_trans_size + MAX_SMB2_HDR_SIZE;
539 size_t sz = small_sz;
540 int cmd = le16_to_cpu(hdr->Command);
542 if (cmd == SMB2_IOCTL_HE || cmd == SMB2_QUERY_DIRECTORY_HE)
545 if (cmd == SMB2_QUERY_INFO_HE) {
546 struct smb2_query_info_req *req;
548 req = work->request_buf;
549 if (req->InfoType == SMB2_O_INFO_FILE &&
550 (req->FileInfoClass == FILE_FULL_EA_INFORMATION ||
551 req->FileInfoClass == FILE_ALL_INFORMATION))
555 /* allocate large response buf for chained commands */
556 if (le32_to_cpu(hdr->NextCommand) > 0)
559 work->response_buf = kvmalloc(sz, GFP_KERNEL | __GFP_ZERO);
560 if (!work->response_buf)
563 work->response_sz = sz;
568 * smb2_check_user_session() - check for valid session for a user
569 * @work: smb work containing smb request buffer
571 * Return: 0 on success, otherwise error
573 int smb2_check_user_session(struct ksmbd_work *work)
575 struct smb2_hdr *req_hdr = work->request_buf;
576 struct ksmbd_conn *conn = work->conn;
577 unsigned int cmd = conn->ops->get_cmd_val(work);
578 unsigned long long sess_id;
582 * SMB2_ECHO, SMB2_NEGOTIATE, SMB2_SESSION_SETUP command do not
583 * require a session id, so no need to validate user session's for
586 if (cmd == SMB2_ECHO_HE || cmd == SMB2_NEGOTIATE_HE ||
587 cmd == SMB2_SESSION_SETUP_HE)
590 if (!ksmbd_conn_good(work))
593 sess_id = le64_to_cpu(req_hdr->SessionId);
594 /* Check for validity of user session */
595 work->sess = ksmbd_session_lookup_all(conn, sess_id);
598 ksmbd_debug(SMB, "Invalid user session, Uid %llu\n", sess_id);
602 static void destroy_previous_session(struct ksmbd_user *user, u64 id)
604 struct ksmbd_session *prev_sess = ksmbd_session_lookup_slowpath(id);
605 struct ksmbd_user *prev_user;
610 prev_user = prev_sess->user;
613 strcmp(user->name, prev_user->name) ||
614 user->passkey_sz != prev_user->passkey_sz ||
615 memcmp(user->passkey, prev_user->passkey, user->passkey_sz)) {
616 put_session(prev_sess);
620 put_session(prev_sess);
621 ksmbd_session_destroy(prev_sess);
625 * smb2_get_name() - get filename string from on the wire smb format
626 * @share: ksmbd_share_config pointer
627 * @src: source buffer
628 * @maxlen: maxlen of source string
629 * @nls_table: nls_table pointer
631 * Return: matching converted filename on success, otherwise error ptr
634 smb2_get_name(struct ksmbd_share_config *share, const char *src,
635 const int maxlen, struct nls_table *local_nls)
637 char *name, *unixname;
639 name = smb_strndup_from_utf16(src, maxlen, 1, local_nls);
641 pr_err("failed to get name %ld\n", PTR_ERR(name));
645 /* change it to absolute unix name */
646 ksmbd_conv_path_to_unix(name);
647 ksmbd_strip_last_slash(name);
649 unixname = convert_to_unix_name(share, name);
652 pr_err("can not convert absolute name\n");
653 return ERR_PTR(-ENOMEM);
656 ksmbd_debug(SMB, "absolute name = %s\n", unixname);
660 int setup_async_work(struct ksmbd_work *work, void (*fn)(void **), void **arg)
662 struct smb2_hdr *rsp_hdr;
663 struct ksmbd_conn *conn = work->conn;
666 rsp_hdr = work->response_buf;
667 rsp_hdr->Flags |= SMB2_FLAGS_ASYNC_COMMAND;
669 id = ksmbd_acquire_async_msg_id(&conn->async_ida);
671 pr_err("Failed to alloc async message id\n");
674 work->syncronous = false;
676 rsp_hdr->Id.AsyncId = cpu_to_le64(id);
679 "Send interim Response to inform async request id : %d\n",
682 work->cancel_fn = fn;
683 work->cancel_argv = arg;
685 if (list_empty(&work->async_request_entry)) {
686 spin_lock(&conn->request_lock);
687 list_add_tail(&work->async_request_entry, &conn->async_requests);
688 spin_unlock(&conn->request_lock);
694 void smb2_send_interim_resp(struct ksmbd_work *work, __le32 status)
696 struct smb2_hdr *rsp_hdr;
698 rsp_hdr = work->response_buf;
699 smb2_set_err_rsp(work);
700 rsp_hdr->Status = status;
703 ksmbd_conn_write(work);
708 static __le32 smb2_get_reparse_tag_special_file(umode_t mode)
710 if (S_ISDIR(mode) || S_ISREG(mode))
714 return IO_REPARSE_TAG_LX_SYMLINK_LE;
715 else if (S_ISFIFO(mode))
716 return IO_REPARSE_TAG_LX_FIFO_LE;
717 else if (S_ISSOCK(mode))
718 return IO_REPARSE_TAG_AF_UNIX_LE;
719 else if (S_ISCHR(mode))
720 return IO_REPARSE_TAG_LX_CHR_LE;
721 else if (S_ISBLK(mode))
722 return IO_REPARSE_TAG_LX_BLK_LE;
728 * smb2_get_dos_mode() - get file mode in dos format from unix mode
729 * @stat: kstat containing file mode
730 * @attribute: attribute flags
732 * Return: converted dos mode
734 static int smb2_get_dos_mode(struct kstat *stat, int attribute)
738 if (S_ISDIR(stat->mode)) {
739 attr = ATTR_DIRECTORY |
740 (attribute & (ATTR_HIDDEN | ATTR_SYSTEM));
742 attr = (attribute & 0x00005137) | ATTR_ARCHIVE;
743 attr &= ~(ATTR_DIRECTORY);
744 if (S_ISREG(stat->mode) && (server_conf.share_fake_fscaps &
745 FILE_SUPPORTS_SPARSE_FILES))
748 if (smb2_get_reparse_tag_special_file(stat->mode))
749 attr |= ATTR_REPARSE;
755 static void build_preauth_ctxt(struct smb2_preauth_neg_context *pneg_ctxt,
758 pneg_ctxt->ContextType = SMB2_PREAUTH_INTEGRITY_CAPABILITIES;
759 pneg_ctxt->DataLength = cpu_to_le16(38);
760 pneg_ctxt->HashAlgorithmCount = cpu_to_le16(1);
761 pneg_ctxt->Reserved = cpu_to_le32(0);
762 pneg_ctxt->SaltLength = cpu_to_le16(SMB311_SALT_SIZE);
763 get_random_bytes(pneg_ctxt->Salt, SMB311_SALT_SIZE);
764 pneg_ctxt->HashAlgorithms = hash_id;
767 static void build_encrypt_ctxt(struct smb2_encryption_neg_context *pneg_ctxt,
770 pneg_ctxt->ContextType = SMB2_ENCRYPTION_CAPABILITIES;
771 pneg_ctxt->DataLength = cpu_to_le16(4);
772 pneg_ctxt->Reserved = cpu_to_le32(0);
773 pneg_ctxt->CipherCount = cpu_to_le16(1);
774 pneg_ctxt->Ciphers[0] = cipher_type;
777 static void build_compression_ctxt(struct smb2_compression_ctx *pneg_ctxt,
780 pneg_ctxt->ContextType = SMB2_COMPRESSION_CAPABILITIES;
781 pneg_ctxt->DataLength =
782 cpu_to_le16(sizeof(struct smb2_compression_ctx)
783 - sizeof(struct smb2_neg_context));
784 pneg_ctxt->Reserved = cpu_to_le32(0);
785 pneg_ctxt->CompressionAlgorithmCount = cpu_to_le16(1);
786 pneg_ctxt->Reserved1 = cpu_to_le32(0);
787 pneg_ctxt->CompressionAlgorithms[0] = comp_algo;
790 static void build_sign_cap_ctxt(struct smb2_signing_capabilities *pneg_ctxt,
793 pneg_ctxt->ContextType = SMB2_SIGNING_CAPABILITIES;
794 pneg_ctxt->DataLength =
795 cpu_to_le16((sizeof(struct smb2_signing_capabilities) + 2)
796 - sizeof(struct smb2_neg_context));
797 pneg_ctxt->Reserved = cpu_to_le32(0);
798 pneg_ctxt->SigningAlgorithmCount = cpu_to_le16(1);
799 pneg_ctxt->SigningAlgorithms[0] = sign_algo;
802 static void build_posix_ctxt(struct smb2_posix_neg_context *pneg_ctxt)
804 pneg_ctxt->ContextType = SMB2_POSIX_EXTENSIONS_AVAILABLE;
805 pneg_ctxt->DataLength = cpu_to_le16(POSIX_CTXT_DATA_LEN);
806 /* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */
807 pneg_ctxt->Name[0] = 0x93;
808 pneg_ctxt->Name[1] = 0xAD;
809 pneg_ctxt->Name[2] = 0x25;
810 pneg_ctxt->Name[3] = 0x50;
811 pneg_ctxt->Name[4] = 0x9C;
812 pneg_ctxt->Name[5] = 0xB4;
813 pneg_ctxt->Name[6] = 0x11;
814 pneg_ctxt->Name[7] = 0xE7;
815 pneg_ctxt->Name[8] = 0xB4;
816 pneg_ctxt->Name[9] = 0x23;
817 pneg_ctxt->Name[10] = 0x83;
818 pneg_ctxt->Name[11] = 0xDE;
819 pneg_ctxt->Name[12] = 0x96;
820 pneg_ctxt->Name[13] = 0x8B;
821 pneg_ctxt->Name[14] = 0xCD;
822 pneg_ctxt->Name[15] = 0x7C;
825 static void assemble_neg_contexts(struct ksmbd_conn *conn,
826 struct smb2_negotiate_rsp *rsp)
828 /* +4 is to account for the RFC1001 len field */
829 char *pneg_ctxt = (char *)rsp +
830 le32_to_cpu(rsp->NegotiateContextOffset) + 4;
831 int neg_ctxt_cnt = 1;
835 "assemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
836 build_preauth_ctxt((struct smb2_preauth_neg_context *)pneg_ctxt,
837 conn->preauth_info->Preauth_HashId);
838 rsp->NegotiateContextCount = cpu_to_le16(neg_ctxt_cnt);
839 inc_rfc1001_len(rsp, AUTH_GSS_PADDING);
840 ctxt_size = sizeof(struct smb2_preauth_neg_context);
841 /* Round to 8 byte boundary */
842 pneg_ctxt += round_up(sizeof(struct smb2_preauth_neg_context), 8);
844 if (conn->cipher_type) {
845 ctxt_size = round_up(ctxt_size, 8);
847 "assemble SMB2_ENCRYPTION_CAPABILITIES context\n");
848 build_encrypt_ctxt((struct smb2_encryption_neg_context *)pneg_ctxt,
850 rsp->NegotiateContextCount = cpu_to_le16(++neg_ctxt_cnt);
851 ctxt_size += sizeof(struct smb2_encryption_neg_context) + 2;
852 /* Round to 8 byte boundary */
854 round_up(sizeof(struct smb2_encryption_neg_context) + 2,
858 if (conn->compress_algorithm) {
859 ctxt_size = round_up(ctxt_size, 8);
861 "assemble SMB2_COMPRESSION_CAPABILITIES context\n");
862 /* Temporarily set to SMB3_COMPRESS_NONE */
863 build_compression_ctxt((struct smb2_compression_ctx *)pneg_ctxt,
864 conn->compress_algorithm);
865 rsp->NegotiateContextCount = cpu_to_le16(++neg_ctxt_cnt);
866 ctxt_size += sizeof(struct smb2_compression_ctx) + 2;
867 /* Round to 8 byte boundary */
868 pneg_ctxt += round_up(sizeof(struct smb2_compression_ctx) + 2,
872 if (conn->posix_ext_supported) {
873 ctxt_size = round_up(ctxt_size, 8);
875 "assemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
876 build_posix_ctxt((struct smb2_posix_neg_context *)pneg_ctxt);
877 rsp->NegotiateContextCount = cpu_to_le16(++neg_ctxt_cnt);
878 ctxt_size += sizeof(struct smb2_posix_neg_context);
879 /* Round to 8 byte boundary */
880 pneg_ctxt += round_up(sizeof(struct smb2_posix_neg_context), 8);
883 if (conn->signing_negotiated) {
884 ctxt_size = round_up(ctxt_size, 8);
886 "assemble SMB2_SIGNING_CAPABILITIES context\n");
887 build_sign_cap_ctxt((struct smb2_signing_capabilities *)pneg_ctxt,
888 conn->signing_algorithm);
889 rsp->NegotiateContextCount = cpu_to_le16(++neg_ctxt_cnt);
890 ctxt_size += sizeof(struct smb2_signing_capabilities) + 2;
893 inc_rfc1001_len(rsp, ctxt_size);
896 static __le32 decode_preauth_ctxt(struct ksmbd_conn *conn,
897 struct smb2_preauth_neg_context *pneg_ctxt)
899 __le32 err = STATUS_NO_PREAUTH_INTEGRITY_HASH_OVERLAP;
901 if (pneg_ctxt->HashAlgorithms == SMB2_PREAUTH_INTEGRITY_SHA512) {
902 conn->preauth_info->Preauth_HashId =
903 SMB2_PREAUTH_INTEGRITY_SHA512;
904 err = STATUS_SUCCESS;
910 static void decode_encrypt_ctxt(struct ksmbd_conn *conn,
911 struct smb2_encryption_neg_context *pneg_ctxt,
914 int cph_cnt = le16_to_cpu(pneg_ctxt->CipherCount);
915 int i, cphs_size = cph_cnt * sizeof(__le16);
917 conn->cipher_type = 0;
919 if (sizeof(struct smb2_encryption_neg_context) + cphs_size >
921 pr_err("Invalid cipher count(%d)\n", cph_cnt);
925 if (!(server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION))
928 for (i = 0; i < cph_cnt; i++) {
929 if (pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_GCM ||
930 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_CCM ||
931 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_CCM ||
932 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_GCM) {
933 ksmbd_debug(SMB, "Cipher ID = 0x%x\n",
934 pneg_ctxt->Ciphers[i]);
935 conn->cipher_type = pneg_ctxt->Ciphers[i];
941 static void decode_compress_ctxt(struct ksmbd_conn *conn,
942 struct smb2_compression_ctx *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,
951 int sign_algo_cnt = le16_to_cpu(pneg_ctxt->SigningAlgorithmCount);
952 int i, sign_alos_size = sign_algo_cnt * sizeof(__le16);
954 conn->signing_negotiated = false;
956 if (sizeof(struct smb2_signing_capabilities) + sign_alos_size >
958 pr_err("Invalid signing algorithm count(%d)\n", sign_algo_cnt);
962 for (i = 0; i < sign_algo_cnt; i++) {
963 if (pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_HMAC_SHA256 ||
964 pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_AES_CMAC) {
965 ksmbd_debug(SMB, "Signing Algorithm ID = 0x%x\n",
966 pneg_ctxt->SigningAlgorithms[i]);
967 conn->signing_negotiated = true;
968 conn->signing_algorithm =
969 pneg_ctxt->SigningAlgorithms[i];
975 static __le32 deassemble_neg_contexts(struct ksmbd_conn *conn,
976 struct smb2_negotiate_req *req)
978 /* +4 is to account for the RFC1001 len field */
979 struct smb2_neg_context *pctx = (struct smb2_neg_context *)((char *)req + 4);
980 int i = 0, len_of_ctxts;
981 int offset = le32_to_cpu(req->NegotiateContextOffset);
982 int neg_ctxt_cnt = le16_to_cpu(req->NegotiateContextCount);
983 int len_of_smb = be32_to_cpu(req->hdr.smb2_buf_length);
984 __le32 status = STATUS_INVALID_PARAMETER;
986 ksmbd_debug(SMB, "decoding %d negotiate contexts\n", neg_ctxt_cnt);
987 if (len_of_smb <= offset) {
988 ksmbd_debug(SMB, "Invalid response: negotiate context offset\n");
992 len_of_ctxts = len_of_smb - offset;
994 while (i++ < neg_ctxt_cnt) {
997 /* check that offset is not beyond end of SMB */
998 if (len_of_ctxts == 0)
1001 if (len_of_ctxts < sizeof(struct smb2_neg_context))
1004 pctx = (struct smb2_neg_context *)((char *)pctx + offset);
1005 clen = le16_to_cpu(pctx->DataLength);
1006 if (clen + sizeof(struct smb2_neg_context) > len_of_ctxts)
1009 if (pctx->ContextType == SMB2_PREAUTH_INTEGRITY_CAPABILITIES) {
1011 "deassemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
1012 if (conn->preauth_info->Preauth_HashId)
1015 status = decode_preauth_ctxt(conn,
1016 (struct smb2_preauth_neg_context *)pctx);
1017 if (status != STATUS_SUCCESS)
1019 } else if (pctx->ContextType == SMB2_ENCRYPTION_CAPABILITIES) {
1021 "deassemble SMB2_ENCRYPTION_CAPABILITIES context\n");
1022 if (conn->cipher_type)
1025 decode_encrypt_ctxt(conn,
1026 (struct smb2_encryption_neg_context *)pctx,
1028 } else if (pctx->ContextType == SMB2_COMPRESSION_CAPABILITIES) {
1030 "deassemble SMB2_COMPRESSION_CAPABILITIES context\n");
1031 if (conn->compress_algorithm)
1034 decode_compress_ctxt(conn,
1035 (struct smb2_compression_ctx *)pctx);
1036 } else if (pctx->ContextType == SMB2_NETNAME_NEGOTIATE_CONTEXT_ID) {
1038 "deassemble SMB2_NETNAME_NEGOTIATE_CONTEXT_ID context\n");
1039 } else if (pctx->ContextType == SMB2_POSIX_EXTENSIONS_AVAILABLE) {
1041 "deassemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
1042 conn->posix_ext_supported = true;
1043 } else if (pctx->ContextType == SMB2_SIGNING_CAPABILITIES) {
1045 "deassemble SMB2_SIGNING_CAPABILITIES context\n");
1046 decode_sign_cap_ctxt(conn,
1047 (struct smb2_signing_capabilities *)pctx,
1051 /* offsets must be 8 byte aligned */
1052 clen = (clen + 7) & ~0x7;
1053 offset = clen + sizeof(struct smb2_neg_context);
1054 len_of_ctxts -= clen + sizeof(struct smb2_neg_context);
1060 * smb2_handle_negotiate() - handler for smb2 negotiate command
1061 * @work: smb work containing smb request buffer
1065 int smb2_handle_negotiate(struct ksmbd_work *work)
1067 struct ksmbd_conn *conn = work->conn;
1068 struct smb2_negotiate_req *req = work->request_buf;
1069 struct smb2_negotiate_rsp *rsp = work->response_buf;
1073 ksmbd_debug(SMB, "Received negotiate request\n");
1074 conn->need_neg = false;
1075 if (ksmbd_conn_good(work)) {
1076 pr_err("conn->tcp_status is already in CifsGood State\n");
1077 work->send_no_response = 1;
1081 if (req->DialectCount == 0) {
1082 pr_err("malformed packet\n");
1083 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1088 conn->cli_cap = le32_to_cpu(req->Capabilities);
1089 switch (conn->dialect) {
1090 case SMB311_PROT_ID:
1091 conn->preauth_info =
1092 kzalloc(sizeof(struct preauth_integrity_info),
1094 if (!conn->preauth_info) {
1096 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1100 status = deassemble_neg_contexts(conn, req);
1101 if (status != STATUS_SUCCESS) {
1102 pr_err("deassemble_neg_contexts error(0x%x)\n",
1104 rsp->hdr.Status = status;
1109 rc = init_smb3_11_server(conn);
1111 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1115 ksmbd_gen_preauth_integrity_hash(conn,
1117 conn->preauth_info->Preauth_HashValue);
1118 rsp->NegotiateContextOffset =
1119 cpu_to_le32(OFFSET_OF_NEG_CONTEXT);
1120 assemble_neg_contexts(conn, rsp);
1122 case SMB302_PROT_ID:
1123 init_smb3_02_server(conn);
1126 init_smb3_0_server(conn);
1129 init_smb2_1_server(conn);
1132 rc = init_smb2_0_server(conn);
1134 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
1141 ksmbd_debug(SMB, "Server dialect :0x%x not supported\n",
1143 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
1147 rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
1150 conn->connection_type = conn->dialect;
1152 rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
1153 rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
1154 rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);
1156 if (conn->dialect > SMB20_PROT_ID) {
1157 memcpy(conn->ClientGUID, req->ClientGUID,
1158 SMB2_CLIENT_GUID_SIZE);
1159 conn->cli_sec_mode = le16_to_cpu(req->SecurityMode);
1162 rsp->StructureSize = cpu_to_le16(65);
1163 rsp->DialectRevision = cpu_to_le16(conn->dialect);
1164 /* Not setting conn guid rsp->ServerGUID, as it
1165 * not used by client for identifying server
1167 memset(rsp->ServerGUID, 0, SMB2_CLIENT_GUID_SIZE);
1169 rsp->SystemTime = cpu_to_le64(ksmbd_systime());
1170 rsp->ServerStartTime = 0;
1171 ksmbd_debug(SMB, "negotiate context offset %d, count %d\n",
1172 le32_to_cpu(rsp->NegotiateContextOffset),
1173 le16_to_cpu(rsp->NegotiateContextCount));
1175 rsp->SecurityBufferOffset = cpu_to_le16(128);
1176 rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
1177 ksmbd_copy_gss_neg_header(((char *)(&rsp->hdr) +
1178 sizeof(rsp->hdr.smb2_buf_length)) +
1179 le16_to_cpu(rsp->SecurityBufferOffset));
1180 inc_rfc1001_len(rsp, sizeof(struct smb2_negotiate_rsp) -
1181 sizeof(struct smb2_hdr) - sizeof(rsp->Buffer) +
1183 rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
1184 conn->use_spnego = true;
1186 if ((server_conf.signing == KSMBD_CONFIG_OPT_AUTO ||
1187 server_conf.signing == KSMBD_CONFIG_OPT_DISABLED) &&
1188 req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED_LE)
1190 else if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY) {
1191 server_conf.enforced_signing = true;
1192 rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
1196 conn->srv_sec_mode = le16_to_cpu(rsp->SecurityMode);
1197 ksmbd_conn_set_need_negotiate(work);
1201 smb2_set_err_rsp(work);
1206 static int alloc_preauth_hash(struct ksmbd_session *sess,
1207 struct ksmbd_conn *conn)
1209 if (sess->Preauth_HashValue)
1212 sess->Preauth_HashValue = kmemdup(conn->preauth_info->Preauth_HashValue,
1213 PREAUTH_HASHVALUE_SIZE, GFP_KERNEL);
1214 if (!sess->Preauth_HashValue)
1220 static int generate_preauth_hash(struct ksmbd_work *work)
1222 struct ksmbd_conn *conn = work->conn;
1223 struct ksmbd_session *sess = work->sess;
1226 if (conn->dialect != SMB311_PROT_ID)
1229 if (conn->binding) {
1230 struct preauth_session *preauth_sess;
1232 preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
1233 if (!preauth_sess) {
1234 preauth_sess = ksmbd_preauth_session_alloc(conn, sess->id);
1239 preauth_hash = preauth_sess->Preauth_HashValue;
1241 if (!sess->Preauth_HashValue)
1242 if (alloc_preauth_hash(sess, conn))
1244 preauth_hash = sess->Preauth_HashValue;
1247 ksmbd_gen_preauth_integrity_hash(conn, work->request_buf, preauth_hash);
1251 static int decode_negotiation_token(struct ksmbd_work *work,
1252 struct negotiate_message *negblob)
1254 struct ksmbd_conn *conn = work->conn;
1255 struct smb2_sess_setup_req *req;
1258 if (!conn->use_spnego)
1261 req = work->request_buf;
1262 sz = le16_to_cpu(req->SecurityBufferLength);
1264 if (ksmbd_decode_negTokenInit((char *)negblob, sz, conn)) {
1265 if (ksmbd_decode_negTokenTarg((char *)negblob, sz, conn)) {
1266 conn->auth_mechs |= KSMBD_AUTH_NTLMSSP;
1267 conn->preferred_auth_mech = KSMBD_AUTH_NTLMSSP;
1268 conn->use_spnego = false;
1274 static int ntlm_negotiate(struct ksmbd_work *work,
1275 struct negotiate_message *negblob)
1277 struct smb2_sess_setup_req *req = work->request_buf;
1278 struct smb2_sess_setup_rsp *rsp = work->response_buf;
1279 struct challenge_message *chgblob;
1280 unsigned char *spnego_blob = NULL;
1281 u16 spnego_blob_len;
1285 ksmbd_debug(SMB, "negotiate phase\n");
1286 sz = le16_to_cpu(req->SecurityBufferLength);
1287 rc = ksmbd_decode_ntlmssp_neg_blob(negblob, sz, work->sess);
1291 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1293 (struct challenge_message *)((char *)&rsp->hdr.ProtocolId + sz);
1294 memset(chgblob, 0, sizeof(struct challenge_message));
1296 if (!work->conn->use_spnego) {
1297 sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->sess);
1301 rsp->SecurityBufferLength = cpu_to_le16(sz);
1305 sz = sizeof(struct challenge_message);
1306 sz += (strlen(ksmbd_netbios_name()) * 2 + 1 + 4) * 6;
1308 neg_blob = kzalloc(sz, GFP_KERNEL);
1312 chgblob = (struct challenge_message *)neg_blob;
1313 sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->sess);
1319 rc = build_spnego_ntlmssp_neg_blob(&spnego_blob, &spnego_blob_len,
1326 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1327 memcpy((char *)&rsp->hdr.ProtocolId + sz, spnego_blob, spnego_blob_len);
1328 rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
1336 static struct authenticate_message *user_authblob(struct ksmbd_conn *conn,
1337 struct smb2_sess_setup_req *req)
1341 if (conn->use_spnego && conn->mechToken)
1342 return (struct authenticate_message *)conn->mechToken;
1344 sz = le16_to_cpu(req->SecurityBufferOffset);
1345 return (struct authenticate_message *)((char *)&req->hdr.ProtocolId
1349 static struct ksmbd_user *session_user(struct ksmbd_conn *conn,
1350 struct smb2_sess_setup_req *req)
1352 struct authenticate_message *authblob;
1353 struct ksmbd_user *user;
1357 authblob = user_authblob(conn, req);
1358 sz = le32_to_cpu(authblob->UserName.BufferOffset);
1359 name = smb_strndup_from_utf16((const char *)authblob + sz,
1360 le16_to_cpu(authblob->UserName.Length),
1364 pr_err("cannot allocate memory\n");
1368 ksmbd_debug(SMB, "session setup request for user %s\n", name);
1369 user = ksmbd_login_user(name);
1374 static int ntlm_authenticate(struct ksmbd_work *work)
1376 struct smb2_sess_setup_req *req = work->request_buf;
1377 struct smb2_sess_setup_rsp *rsp = work->response_buf;
1378 struct ksmbd_conn *conn = work->conn;
1379 struct ksmbd_session *sess = work->sess;
1380 struct channel *chann = NULL;
1381 struct ksmbd_user *user;
1385 ksmbd_debug(SMB, "authenticate phase\n");
1386 if (conn->use_spnego) {
1387 unsigned char *spnego_blob;
1388 u16 spnego_blob_len;
1390 rc = build_spnego_ntlmssp_auth_blob(&spnego_blob,
1396 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1397 memcpy((char *)&rsp->hdr.ProtocolId + sz, spnego_blob, spnego_blob_len);
1398 rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
1400 inc_rfc1001_len(rsp, spnego_blob_len - 1);
1403 user = session_user(conn, req);
1405 ksmbd_debug(SMB, "Unknown user name or an error\n");
1409 /* Check for previous session */
1410 prev_id = le64_to_cpu(req->PreviousSessionId);
1411 if (prev_id && prev_id != sess->id)
1412 destroy_previous_session(user, prev_id);
1414 if (sess->state == SMB2_SESSION_VALID) {
1416 * Reuse session if anonymous try to connect
1417 * on reauthetication.
1419 if (ksmbd_anonymous_user(user)) {
1420 ksmbd_free_user(user);
1423 ksmbd_free_user(sess->user);
1427 if (user_guest(sess->user)) {
1429 ksmbd_debug(SMB, "Guest login not allowed when signing enabled\n");
1433 rsp->SessionFlags = SMB2_SESSION_FLAG_IS_GUEST_LE;
1435 struct authenticate_message *authblob;
1437 authblob = user_authblob(conn, req);
1438 sz = le16_to_cpu(req->SecurityBufferLength);
1439 rc = ksmbd_decode_ntlmssp_auth_blob(authblob, sz, sess);
1441 set_user_flag(sess->user, KSMBD_USER_FLAG_BAD_PASSWORD);
1442 ksmbd_debug(SMB, "authentication failed\n");
1447 * If session state is SMB2_SESSION_VALID, We can assume
1448 * that it is reauthentication. And the user/password
1449 * has been verified, so return it here.
1451 if (sess->state == SMB2_SESSION_VALID) {
1453 goto binding_session;
1457 if ((conn->sign || server_conf.enforced_signing) ||
1458 (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
1461 if (conn->vals->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION &&
1462 conn->ops->generate_encryptionkey &&
1463 !(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1464 rc = conn->ops->generate_encryptionkey(sess);
1467 "SMB3 encryption key generation failed\n");
1471 rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
1473 * signing is disable if encryption is enable
1481 if (conn->dialect >= SMB30_PROT_ID) {
1482 chann = lookup_chann_list(sess, conn);
1484 chann = kmalloc(sizeof(struct channel), GFP_KERNEL);
1489 INIT_LIST_HEAD(&chann->chann_list);
1490 list_add(&chann->chann_list, &sess->ksmbd_chann_list);
1494 if (conn->ops->generate_signingkey) {
1495 rc = conn->ops->generate_signingkey(sess, conn);
1497 ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
1502 if (conn->dialect > SMB20_PROT_ID) {
1503 if (!ksmbd_conn_lookup_dialect(conn)) {
1504 pr_err("fail to verify the dialect\n");
1511 #ifdef CONFIG_SMB_SERVER_KERBEROS5
1512 static int krb5_authenticate(struct ksmbd_work *work)
1514 struct smb2_sess_setup_req *req = work->request_buf;
1515 struct smb2_sess_setup_rsp *rsp = work->response_buf;
1516 struct ksmbd_conn *conn = work->conn;
1517 struct ksmbd_session *sess = work->sess;
1518 char *in_blob, *out_blob;
1519 struct channel *chann = NULL;
1521 int in_len, out_len;
1524 in_blob = (char *)&req->hdr.ProtocolId +
1525 le16_to_cpu(req->SecurityBufferOffset);
1526 in_len = le16_to_cpu(req->SecurityBufferLength);
1527 out_blob = (char *)&rsp->hdr.ProtocolId +
1528 le16_to_cpu(rsp->SecurityBufferOffset);
1529 out_len = work->response_sz -
1530 offsetof(struct smb2_hdr, smb2_buf_length) -
1531 le16_to_cpu(rsp->SecurityBufferOffset);
1533 /* Check previous session */
1534 prev_sess_id = le64_to_cpu(req->PreviousSessionId);
1535 if (prev_sess_id && prev_sess_id != sess->id)
1536 destroy_previous_session(sess->user, prev_sess_id);
1538 if (sess->state == SMB2_SESSION_VALID)
1539 ksmbd_free_user(sess->user);
1541 retval = ksmbd_krb5_authenticate(sess, in_blob, in_len,
1542 out_blob, &out_len);
1544 ksmbd_debug(SMB, "krb5 authentication failed\n");
1547 rsp->SecurityBufferLength = cpu_to_le16(out_len);
1548 inc_rfc1001_len(rsp, out_len - 1);
1550 if ((conn->sign || server_conf.enforced_signing) ||
1551 (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
1554 if ((conn->vals->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION) &&
1555 conn->ops->generate_encryptionkey) {
1556 retval = conn->ops->generate_encryptionkey(sess);
1559 "SMB3 encryption key generation failed\n");
1563 rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
1567 if (conn->dialect >= SMB30_PROT_ID) {
1568 chann = lookup_chann_list(sess, conn);
1570 chann = kmalloc(sizeof(struct channel), GFP_KERNEL);
1575 INIT_LIST_HEAD(&chann->chann_list);
1576 list_add(&chann->chann_list, &sess->ksmbd_chann_list);
1580 if (conn->ops->generate_signingkey) {
1581 retval = conn->ops->generate_signingkey(sess, conn);
1583 ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
1588 if (conn->dialect > SMB20_PROT_ID) {
1589 if (!ksmbd_conn_lookup_dialect(conn)) {
1590 pr_err("fail to verify the dialect\n");
1597 static int krb5_authenticate(struct ksmbd_work *work)
1603 int smb2_sess_setup(struct ksmbd_work *work)
1605 struct ksmbd_conn *conn = work->conn;
1606 struct smb2_sess_setup_req *req = work->request_buf;
1607 struct smb2_sess_setup_rsp *rsp = work->response_buf;
1608 struct ksmbd_session *sess;
1609 struct negotiate_message *negblob;
1612 ksmbd_debug(SMB, "Received request for session setup\n");
1614 rsp->StructureSize = cpu_to_le16(9);
1615 rsp->SessionFlags = 0;
1616 rsp->SecurityBufferOffset = cpu_to_le16(72);
1617 rsp->SecurityBufferLength = 0;
1618 inc_rfc1001_len(rsp, 9);
1620 if (!req->hdr.SessionId) {
1621 sess = ksmbd_smb2_session_create();
1626 rsp->hdr.SessionId = cpu_to_le64(sess->id);
1627 ksmbd_session_register(conn, sess);
1628 } else if (conn->dialect >= SMB30_PROT_ID &&
1629 (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
1630 req->Flags & SMB2_SESSION_REQ_FLAG_BINDING) {
1631 u64 sess_id = le64_to_cpu(req->hdr.SessionId);
1633 sess = ksmbd_session_lookup_slowpath(sess_id);
1639 if (conn->dialect != sess->conn->dialect) {
1644 if (!(req->hdr.Flags & SMB2_FLAGS_SIGNED)) {
1649 if (strncmp(conn->ClientGUID, sess->conn->ClientGUID,
1650 SMB2_CLIENT_GUID_SIZE)) {
1655 if (sess->state == SMB2_SESSION_IN_PROGRESS) {
1660 if (sess->state == SMB2_SESSION_EXPIRED) {
1665 if (ksmbd_session_lookup(conn, sess_id)) {
1670 conn->binding = true;
1671 } else if ((conn->dialect < SMB30_PROT_ID ||
1672 server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
1673 (req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1678 sess = ksmbd_session_lookup(conn,
1679 le64_to_cpu(req->hdr.SessionId));
1687 if (sess->state == SMB2_SESSION_EXPIRED)
1688 sess->state = SMB2_SESSION_IN_PROGRESS;
1690 negblob = (struct negotiate_message *)((char *)&req->hdr.ProtocolId +
1691 le16_to_cpu(req->SecurityBufferOffset));
1693 if (decode_negotiation_token(work, negblob) == 0) {
1694 if (conn->mechToken)
1695 negblob = (struct negotiate_message *)conn->mechToken;
1698 if (server_conf.auth_mechs & conn->auth_mechs) {
1699 rc = generate_preauth_hash(work);
1703 if (conn->preferred_auth_mech &
1704 (KSMBD_AUTH_KRB5 | KSMBD_AUTH_MSKRB5)) {
1705 rc = krb5_authenticate(work);
1711 ksmbd_conn_set_good(work);
1712 sess->state = SMB2_SESSION_VALID;
1713 kfree(sess->Preauth_HashValue);
1714 sess->Preauth_HashValue = NULL;
1715 } else if (conn->preferred_auth_mech == KSMBD_AUTH_NTLMSSP) {
1716 if (negblob->MessageType == NtLmNegotiate) {
1717 rc = ntlm_negotiate(work, negblob);
1721 STATUS_MORE_PROCESSING_REQUIRED;
1723 * Note: here total size -1 is done as an
1724 * adjustment for 0 size blob
1726 inc_rfc1001_len(rsp, le16_to_cpu(rsp->SecurityBufferLength) - 1);
1728 } else if (negblob->MessageType == NtLmAuthenticate) {
1729 rc = ntlm_authenticate(work);
1733 ksmbd_conn_set_good(work);
1734 sess->state = SMB2_SESSION_VALID;
1735 if (conn->binding) {
1736 struct preauth_session *preauth_sess;
1739 ksmbd_preauth_session_lookup(conn, sess->id);
1741 list_del(&preauth_sess->preauth_entry);
1742 kfree(preauth_sess);
1745 kfree(sess->Preauth_HashValue);
1746 sess->Preauth_HashValue = NULL;
1749 /* TODO: need one more negotiation */
1750 pr_err("Not support the preferred authentication\n");
1754 pr_err("Not support authentication\n");
1760 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1761 else if (rc == -ENOENT)
1762 rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
1763 else if (rc == -EACCES)
1764 rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
1765 else if (rc == -EFAULT)
1766 rsp->hdr.Status = STATUS_NETWORK_SESSION_EXPIRED;
1767 else if (rc == -ENOMEM)
1768 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
1770 rsp->hdr.Status = STATUS_LOGON_FAILURE;
1772 if (conn->use_spnego && conn->mechToken) {
1773 kfree(conn->mechToken);
1774 conn->mechToken = NULL;
1777 if (rc < 0 && sess) {
1778 ksmbd_session_destroy(sess);
1786 * smb2_tree_connect() - handler for smb2 tree connect command
1787 * @work: smb work containing smb request buffer
1789 * Return: 0 on success, otherwise error
1791 int smb2_tree_connect(struct ksmbd_work *work)
1793 struct ksmbd_conn *conn = work->conn;
1794 struct smb2_tree_connect_req *req = work->request_buf;
1795 struct smb2_tree_connect_rsp *rsp = work->response_buf;
1796 struct ksmbd_session *sess = work->sess;
1797 char *treename = NULL, *name = NULL;
1798 struct ksmbd_tree_conn_status status;
1799 struct ksmbd_share_config *share;
1802 treename = smb_strndup_from_utf16(req->Buffer,
1803 le16_to_cpu(req->PathLength), true,
1805 if (IS_ERR(treename)) {
1806 pr_err("treename is NULL\n");
1807 status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
1811 name = ksmbd_extract_sharename(treename);
1813 status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
1817 ksmbd_debug(SMB, "tree connect request for tree %s treename %s\n",
1820 status = ksmbd_tree_conn_connect(sess, name);
1821 if (status.ret == KSMBD_TREE_CONN_STATUS_OK)
1822 rsp->hdr.Id.SyncId.TreeId = cpu_to_le32(status.tree_conn->id);
1826 share = status.tree_conn->share_conf;
1827 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
1828 ksmbd_debug(SMB, "IPC share path request\n");
1829 rsp->ShareType = SMB2_SHARE_TYPE_PIPE;
1830 rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
1831 FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE |
1832 FILE_DELETE_LE | FILE_READ_CONTROL_LE |
1833 FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
1834 FILE_SYNCHRONIZE_LE;
1836 rsp->ShareType = SMB2_SHARE_TYPE_DISK;
1837 rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
1838 FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE;
1839 if (test_tree_conn_flag(status.tree_conn,
1840 KSMBD_TREE_CONN_FLAG_WRITABLE)) {
1841 rsp->MaximalAccess |= FILE_WRITE_DATA_LE |
1842 FILE_APPEND_DATA_LE | FILE_WRITE_EA_LE |
1843 FILE_DELETE_LE | FILE_WRITE_ATTRIBUTES_LE |
1844 FILE_DELETE_CHILD_LE | FILE_READ_CONTROL_LE |
1845 FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
1846 FILE_SYNCHRONIZE_LE;
1850 status.tree_conn->maximal_access = le32_to_cpu(rsp->MaximalAccess);
1851 if (conn->posix_ext_supported)
1852 status.tree_conn->posix_extensions = true;
1855 rsp->StructureSize = cpu_to_le16(16);
1856 rsp->Capabilities = 0;
1858 /* default manual caching */
1859 rsp->ShareFlags = SMB2_SHAREFLAG_MANUAL_CACHING;
1860 inc_rfc1001_len(rsp, 16);
1862 if (!IS_ERR(treename))
1867 switch (status.ret) {
1868 case KSMBD_TREE_CONN_STATUS_OK:
1869 rsp->hdr.Status = STATUS_SUCCESS;
1872 case KSMBD_TREE_CONN_STATUS_NO_SHARE:
1873 rsp->hdr.Status = STATUS_BAD_NETWORK_PATH;
1876 case KSMBD_TREE_CONN_STATUS_NOMEM:
1877 rsp->hdr.Status = STATUS_NO_MEMORY;
1879 case KSMBD_TREE_CONN_STATUS_ERROR:
1880 case KSMBD_TREE_CONN_STATUS_TOO_MANY_CONNS:
1881 case KSMBD_TREE_CONN_STATUS_TOO_MANY_SESSIONS:
1882 rsp->hdr.Status = STATUS_ACCESS_DENIED;
1885 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1888 rsp->hdr.Status = STATUS_ACCESS_DENIED;
1895 * smb2_create_open_flags() - convert smb open flags to unix open flags
1896 * @file_present: is file already present
1897 * @access: file access flags
1898 * @disposition: file disposition flags
1899 * @may_flags: set with MAY_ flags
1901 * Return: file open flags
1903 static int smb2_create_open_flags(bool file_present, __le32 access,
1907 int oflags = O_NONBLOCK | O_LARGEFILE;
1909 if (access & FILE_READ_DESIRED_ACCESS_LE &&
1910 access & FILE_WRITE_DESIRE_ACCESS_LE) {
1912 *may_flags = MAY_OPEN | MAY_READ | MAY_WRITE;
1913 } else if (access & FILE_WRITE_DESIRE_ACCESS_LE) {
1915 *may_flags = MAY_OPEN | MAY_WRITE;
1918 *may_flags = MAY_OPEN | MAY_READ;
1921 if (access == FILE_READ_ATTRIBUTES_LE)
1925 switch (disposition & FILE_CREATE_MASK_LE) {
1927 case FILE_CREATE_LE:
1929 case FILE_SUPERSEDE_LE:
1930 case FILE_OVERWRITE_LE:
1931 case FILE_OVERWRITE_IF_LE:
1938 switch (disposition & FILE_CREATE_MASK_LE) {
1939 case FILE_SUPERSEDE_LE:
1940 case FILE_CREATE_LE:
1941 case FILE_OPEN_IF_LE:
1942 case FILE_OVERWRITE_IF_LE:
1946 case FILE_OVERWRITE_LE:
1958 * smb2_tree_disconnect() - handler for smb tree connect request
1959 * @work: smb work containing request buffer
1963 int smb2_tree_disconnect(struct ksmbd_work *work)
1965 struct smb2_tree_disconnect_rsp *rsp = work->response_buf;
1966 struct ksmbd_session *sess = work->sess;
1967 struct ksmbd_tree_connect *tcon = work->tcon;
1969 rsp->StructureSize = cpu_to_le16(4);
1970 inc_rfc1001_len(rsp, 4);
1972 ksmbd_debug(SMB, "request\n");
1975 struct smb2_tree_disconnect_req *req = work->request_buf;
1977 ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
1978 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
1979 smb2_set_err_rsp(work);
1983 ksmbd_close_tree_conn_fds(work);
1984 ksmbd_tree_conn_disconnect(sess, tcon);
1989 * smb2_session_logoff() - handler for session log off request
1990 * @work: smb work containing request buffer
1994 int smb2_session_logoff(struct ksmbd_work *work)
1996 struct ksmbd_conn *conn = work->conn;
1997 struct smb2_logoff_rsp *rsp = work->response_buf;
1998 struct ksmbd_session *sess = work->sess;
2000 rsp->StructureSize = cpu_to_le16(4);
2001 inc_rfc1001_len(rsp, 4);
2003 ksmbd_debug(SMB, "request\n");
2005 /* Got a valid session, set connection state */
2006 WARN_ON(sess->conn != conn);
2008 /* setting CifsExiting here may race with start_tcp_sess */
2009 ksmbd_conn_set_need_reconnect(work);
2010 ksmbd_close_session_fds(work);
2011 ksmbd_conn_wait_idle(conn);
2013 if (ksmbd_tree_conn_session_logoff(sess)) {
2014 struct smb2_logoff_req *req = work->request_buf;
2016 ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
2017 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2018 smb2_set_err_rsp(work);
2022 ksmbd_destroy_file_table(&sess->file_table);
2023 sess->state = SMB2_SESSION_EXPIRED;
2025 ksmbd_free_user(sess->user);
2028 /* let start_tcp_sess free connection info now */
2029 ksmbd_conn_set_need_negotiate(work);
2034 * create_smb2_pipe() - create IPC pipe
2035 * @work: smb work containing request buffer
2037 * Return: 0 on success, otherwise error
2039 static noinline int create_smb2_pipe(struct ksmbd_work *work)
2041 struct smb2_create_rsp *rsp = work->response_buf;
2042 struct smb2_create_req *req = work->request_buf;
2047 name = smb_strndup_from_utf16(req->Buffer, le16_to_cpu(req->NameLength),
2048 1, work->conn->local_nls);
2050 rsp->hdr.Status = STATUS_NO_MEMORY;
2051 err = PTR_ERR(name);
2055 id = ksmbd_session_rpc_open(work->sess, name);
2057 pr_err("Unable to open RPC pipe: %d\n", id);
2062 rsp->hdr.Status = STATUS_SUCCESS;
2063 rsp->StructureSize = cpu_to_le16(89);
2064 rsp->OplockLevel = SMB2_OPLOCK_LEVEL_NONE;
2066 rsp->CreateAction = cpu_to_le32(FILE_OPENED);
2068 rsp->CreationTime = cpu_to_le64(0);
2069 rsp->LastAccessTime = cpu_to_le64(0);
2070 rsp->ChangeTime = cpu_to_le64(0);
2071 rsp->AllocationSize = cpu_to_le64(0);
2072 rsp->EndofFile = cpu_to_le64(0);
2073 rsp->FileAttributes = ATTR_NORMAL_LE;
2075 rsp->VolatileFileId = cpu_to_le64(id);
2076 rsp->PersistentFileId = 0;
2077 rsp->CreateContextsOffset = 0;
2078 rsp->CreateContextsLength = 0;
2080 inc_rfc1001_len(rsp, 88); /* StructureSize - 1*/
2087 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2091 rsp->hdr.Status = STATUS_NO_MEMORY;
2098 smb2_set_err_rsp(work);
2103 * smb2_set_ea() - handler for setting extended attributes using set
2105 * @eabuf: set info command buffer
2106 * @path: dentry path for get ea
2108 * Return: 0 on success, otherwise error
2110 static int smb2_set_ea(struct smb2_ea_info *eabuf, struct path *path)
2112 struct user_namespace *user_ns = mnt_user_ns(path->mnt);
2113 char *attr_name = NULL, *value;
2117 attr_name = kmalloc(XATTR_NAME_MAX + 1, GFP_KERNEL);
2122 if (!eabuf->EaNameLength)
2126 "name : <%s>, name_len : %u, value_len : %u, next : %u\n",
2127 eabuf->name, eabuf->EaNameLength,
2128 le16_to_cpu(eabuf->EaValueLength),
2129 le32_to_cpu(eabuf->NextEntryOffset));
2131 if (eabuf->EaNameLength >
2132 (XATTR_NAME_MAX - XATTR_USER_PREFIX_LEN)) {
2137 memcpy(attr_name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN);
2138 memcpy(&attr_name[XATTR_USER_PREFIX_LEN], eabuf->name,
2139 eabuf->EaNameLength);
2140 attr_name[XATTR_USER_PREFIX_LEN + eabuf->EaNameLength] = '\0';
2141 value = (char *)&eabuf->name + eabuf->EaNameLength + 1;
2143 if (!eabuf->EaValueLength) {
2144 rc = ksmbd_vfs_casexattr_len(user_ns,
2147 XATTR_USER_PREFIX_LEN +
2148 eabuf->EaNameLength);
2150 /* delete the EA only when it exits */
2152 rc = ksmbd_vfs_remove_xattr(user_ns,
2158 "remove xattr failed(%d)\n",
2164 /* if the EA doesn't exist, just do nothing. */
2167 rc = ksmbd_vfs_setxattr(user_ns,
2168 path->dentry, attr_name, value,
2169 le16_to_cpu(eabuf->EaValueLength), 0);
2172 "ksmbd_vfs_setxattr is failed(%d)\n",
2179 next = le32_to_cpu(eabuf->NextEntryOffset);
2180 eabuf = (struct smb2_ea_info *)((char *)eabuf + next);
2181 } while (next != 0);
2187 static noinline int smb2_set_stream_name_xattr(struct path *path,
2188 struct ksmbd_file *fp,
2189 char *stream_name, int s_type)
2191 struct user_namespace *user_ns = mnt_user_ns(path->mnt);
2192 size_t xattr_stream_size;
2193 char *xattr_stream_name;
2196 rc = ksmbd_vfs_xattr_stream_name(stream_name,
2203 fp->stream.name = xattr_stream_name;
2204 fp->stream.size = xattr_stream_size;
2206 /* Check if there is stream prefix in xattr space */
2207 rc = ksmbd_vfs_casexattr_len(user_ns,
2214 if (fp->cdoption == FILE_OPEN_LE) {
2215 ksmbd_debug(SMB, "XATTR stream name lookup failed: %d\n", rc);
2219 rc = ksmbd_vfs_setxattr(user_ns, path->dentry,
2220 xattr_stream_name, NULL, 0, 0);
2222 pr_err("Failed to store XATTR stream name :%d\n", rc);
2226 static int smb2_remove_smb_xattrs(struct path *path)
2228 struct user_namespace *user_ns = mnt_user_ns(path->mnt);
2229 char *name, *xattr_list = NULL;
2230 ssize_t xattr_list_len;
2233 xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
2234 if (xattr_list_len < 0) {
2236 } else if (!xattr_list_len) {
2237 ksmbd_debug(SMB, "empty xattr in the file\n");
2241 for (name = xattr_list; name - xattr_list < xattr_list_len;
2242 name += strlen(name) + 1) {
2243 ksmbd_debug(SMB, "%s, len %zd\n", name, strlen(name));
2245 if (strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN) &&
2246 strncmp(&name[XATTR_USER_PREFIX_LEN], DOS_ATTRIBUTE_PREFIX,
2247 DOS_ATTRIBUTE_PREFIX_LEN) &&
2248 strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX, STREAM_PREFIX_LEN))
2251 err = ksmbd_vfs_remove_xattr(user_ns, path->dentry, name);
2253 ksmbd_debug(SMB, "remove xattr failed : %s\n", name);
2260 static int smb2_create_truncate(struct path *path)
2262 int rc = vfs_truncate(path, 0);
2265 pr_err("vfs_truncate failed, rc %d\n", rc);
2269 rc = smb2_remove_smb_xattrs(path);
2270 if (rc == -EOPNOTSUPP)
2274 "ksmbd_truncate_stream_name_xattr failed, rc %d\n",
2279 static void smb2_new_xattrs(struct ksmbd_tree_connect *tcon, struct path *path,
2280 struct ksmbd_file *fp)
2282 struct xattr_dos_attrib da = {0};
2285 if (!test_share_config_flag(tcon->share_conf,
2286 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2290 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
2291 da.itime = da.create_time = fp->create_time;
2292 da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
2293 XATTR_DOSINFO_ITIME;
2295 rc = ksmbd_vfs_set_dos_attrib_xattr(mnt_user_ns(path->mnt),
2298 ksmbd_debug(SMB, "failed to store file attribute into xattr\n");
2301 static void smb2_update_xattrs(struct ksmbd_tree_connect *tcon,
2302 struct path *path, struct ksmbd_file *fp)
2304 struct xattr_dos_attrib da;
2307 fp->f_ci->m_fattr &= ~(ATTR_HIDDEN_LE | ATTR_SYSTEM_LE);
2309 /* get FileAttributes from XATTR_NAME_DOS_ATTRIBUTE */
2310 if (!test_share_config_flag(tcon->share_conf,
2311 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2314 rc = ksmbd_vfs_get_dos_attrib_xattr(mnt_user_ns(path->mnt),
2317 fp->f_ci->m_fattr = cpu_to_le32(da.attr);
2318 fp->create_time = da.create_time;
2319 fp->itime = da.itime;
2323 static int smb2_creat(struct ksmbd_work *work, struct path *path, char *name,
2324 int open_flags, umode_t posix_mode, bool is_dir)
2326 struct ksmbd_tree_connect *tcon = work->tcon;
2327 struct ksmbd_share_config *share = tcon->share_conf;
2331 if (!(open_flags & O_CREAT))
2334 ksmbd_debug(SMB, "file does not exist, so creating\n");
2335 if (is_dir == true) {
2336 ksmbd_debug(SMB, "creating directory\n");
2338 mode = share_config_directory_mode(share, posix_mode);
2339 rc = ksmbd_vfs_mkdir(work, name, mode);
2343 ksmbd_debug(SMB, "creating regular file\n");
2345 mode = share_config_create_mode(share, posix_mode);
2346 rc = ksmbd_vfs_create(work, name, mode);
2351 rc = ksmbd_vfs_kern_path(name, 0, path, 0);
2353 pr_err("cannot get linux path (%s), err = %d\n",
2360 static int smb2_create_sd_buffer(struct ksmbd_work *work,
2361 struct smb2_create_req *req,
2364 struct create_context *context;
2365 struct create_sd_buf_req *sd_buf;
2367 if (!req->CreateContextsOffset)
2370 /* Parse SD BUFFER create contexts */
2371 context = smb2_find_context_vals(req, SMB2_CREATE_SD_BUFFER);
2374 else if (IS_ERR(context))
2375 return PTR_ERR(context);
2378 "Set ACLs using SMB2_CREATE_SD_BUFFER context\n");
2379 sd_buf = (struct create_sd_buf_req *)context;
2380 return set_info_sec(work->conn, work->tcon, path, &sd_buf->ntsd,
2381 le32_to_cpu(sd_buf->ccontext.DataLength), true);
2384 static void ksmbd_acls_fattr(struct smb_fattr *fattr,
2385 struct user_namespace *mnt_userns,
2386 struct inode *inode)
2388 fattr->cf_uid = i_uid_into_mnt(mnt_userns, inode);
2389 fattr->cf_gid = i_gid_into_mnt(mnt_userns, inode);
2390 fattr->cf_mode = inode->i_mode;
2391 fattr->cf_acls = NULL;
2392 fattr->cf_dacls = NULL;
2394 if (IS_ENABLED(CONFIG_FS_POSIX_ACL)) {
2395 fattr->cf_acls = get_acl(inode, ACL_TYPE_ACCESS);
2396 if (S_ISDIR(inode->i_mode))
2397 fattr->cf_dacls = get_acl(inode, ACL_TYPE_DEFAULT);
2402 * smb2_open() - handler for smb file open request
2403 * @work: smb work containing request buffer
2405 * Return: 0 on success, otherwise error
2407 int smb2_open(struct ksmbd_work *work)
2409 struct ksmbd_conn *conn = work->conn;
2410 struct ksmbd_session *sess = work->sess;
2411 struct ksmbd_tree_connect *tcon = work->tcon;
2412 struct smb2_create_req *req;
2413 struct smb2_create_rsp *rsp, *rsp_org;
2415 struct ksmbd_share_config *share = tcon->share_conf;
2416 struct ksmbd_file *fp = NULL;
2417 struct file *filp = NULL;
2418 struct user_namespace *user_ns = NULL;
2420 struct create_context *context;
2421 struct lease_ctx_info *lc = NULL;
2422 struct create_ea_buf_req *ea_buf = NULL;
2423 struct oplock_info *opinfo;
2424 __le32 *next_ptr = NULL;
2425 int req_op_level = 0, open_flags = 0, may_flags = 0, file_info = 0;
2426 int rc = 0, len = 0;
2427 int contxt_cnt = 0, query_disk_id = 0;
2428 int maximal_access_ctxt = 0, posix_ctxt = 0;
2432 char *stream_name = NULL;
2433 bool file_present = false, created = false, already_permitted = false;
2434 int share_ret, need_truncate = 0;
2436 umode_t posix_mode = 0;
2437 __le32 daccess, maximal_access = 0;
2439 rsp_org = work->response_buf;
2440 WORK_BUFFERS(work, req, rsp);
2442 if (req->hdr.NextCommand && !work->next_smb2_rcv_hdr_off &&
2443 (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
2444 ksmbd_debug(SMB, "invalid flag in chained command\n");
2445 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2446 smb2_set_err_rsp(work);
2450 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
2451 ksmbd_debug(SMB, "IPC pipe create request\n");
2452 return create_smb2_pipe(work);
2455 if (req->NameLength) {
2456 if ((req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
2457 *(char *)req->Buffer == '\\') {
2458 pr_err("not allow directory name included leading slash\n");
2463 name = smb2_get_name(share,
2465 le16_to_cpu(req->NameLength),
2466 work->conn->local_nls);
2475 ksmbd_debug(SMB, "converted name = %s\n", name);
2476 if (strchr(name, ':')) {
2477 if (!test_share_config_flag(work->tcon->share_conf,
2478 KSMBD_SHARE_FLAG_STREAMS)) {
2482 rc = parse_stream_name(name, &stream_name, &s_type);
2487 rc = ksmbd_validate_filename(name);
2491 if (ksmbd_share_veto_filename(share, name)) {
2493 ksmbd_debug(SMB, "Reject open(), vetoed file: %s\n",
2498 len = strlen(share->path);
2499 ksmbd_debug(SMB, "share path len %d\n", len);
2500 name = kmalloc(len + 1, GFP_KERNEL);
2502 rsp->hdr.Status = STATUS_NO_MEMORY;
2507 memcpy(name, share->path, len);
2508 *(name + len) = '\0';
2511 req_op_level = req->RequestedOplockLevel;
2512 if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE)
2513 lc = parse_lease_state(req);
2515 if (le32_to_cpu(req->ImpersonationLevel) > le32_to_cpu(IL_DELEGATE_LE)) {
2516 pr_err("Invalid impersonationlevel : 0x%x\n",
2517 le32_to_cpu(req->ImpersonationLevel));
2519 rsp->hdr.Status = STATUS_BAD_IMPERSONATION_LEVEL;
2523 if (req->CreateOptions && !(req->CreateOptions & CREATE_OPTIONS_MASK)) {
2524 pr_err("Invalid create options : 0x%x\n",
2525 le32_to_cpu(req->CreateOptions));
2529 if (req->CreateOptions & FILE_SEQUENTIAL_ONLY_LE &&
2530 req->CreateOptions & FILE_RANDOM_ACCESS_LE)
2531 req->CreateOptions = ~(FILE_SEQUENTIAL_ONLY_LE);
2533 if (req->CreateOptions &
2534 (FILE_OPEN_BY_FILE_ID_LE | CREATE_TREE_CONNECTION |
2535 FILE_RESERVE_OPFILTER_LE)) {
2540 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
2541 if (req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE) {
2544 } else if (req->CreateOptions & FILE_NO_COMPRESSION_LE) {
2545 req->CreateOptions = ~(FILE_NO_COMPRESSION_LE);
2550 if (le32_to_cpu(req->CreateDisposition) >
2551 le32_to_cpu(FILE_OVERWRITE_IF_LE)) {
2552 pr_err("Invalid create disposition : 0x%x\n",
2553 le32_to_cpu(req->CreateDisposition));
2558 if (!(req->DesiredAccess & DESIRED_ACCESS_MASK)) {
2559 pr_err("Invalid desired access : 0x%x\n",
2560 le32_to_cpu(req->DesiredAccess));
2565 if (req->FileAttributes && !(req->FileAttributes & ATTR_MASK_LE)) {
2566 pr_err("Invalid file attribute : 0x%x\n",
2567 le32_to_cpu(req->FileAttributes));
2572 if (req->CreateContextsOffset) {
2573 /* Parse non-durable handle create contexts */
2574 context = smb2_find_context_vals(req, SMB2_CREATE_EA_BUFFER);
2575 if (IS_ERR(context)) {
2576 rc = PTR_ERR(context);
2578 } else if (context) {
2579 ea_buf = (struct create_ea_buf_req *)context;
2580 if (req->CreateOptions & FILE_NO_EA_KNOWLEDGE_LE) {
2581 rsp->hdr.Status = STATUS_ACCESS_DENIED;
2587 context = smb2_find_context_vals(req,
2588 SMB2_CREATE_QUERY_MAXIMAL_ACCESS_REQUEST);
2589 if (IS_ERR(context)) {
2590 rc = PTR_ERR(context);
2592 } else if (context) {
2594 "get query maximal access context\n");
2595 maximal_access_ctxt = 1;
2598 context = smb2_find_context_vals(req,
2599 SMB2_CREATE_TIMEWARP_REQUEST);
2600 if (IS_ERR(context)) {
2601 rc = PTR_ERR(context);
2603 } else if (context) {
2604 ksmbd_debug(SMB, "get timewarp context\n");
2609 if (tcon->posix_extensions) {
2610 context = smb2_find_context_vals(req,
2611 SMB2_CREATE_TAG_POSIX);
2612 if (IS_ERR(context)) {
2613 rc = PTR_ERR(context);
2615 } else if (context) {
2616 struct create_posix *posix =
2617 (struct create_posix *)context;
2618 ksmbd_debug(SMB, "get posix context\n");
2620 posix_mode = le32_to_cpu(posix->Mode);
2626 if (ksmbd_override_fsids(work)) {
2631 if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE) {
2633 * On delete request, instead of following up, need to
2634 * look the current entity
2636 rc = ksmbd_vfs_kern_path(name, 0, &path, 1);
2639 * If file exists with under flags, return access
2642 if (req->CreateDisposition == FILE_OVERWRITE_IF_LE ||
2643 req->CreateDisposition == FILE_OPEN_IF_LE) {
2649 if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
2651 "User does not have write permission\n");
2658 if (test_share_config_flag(work->tcon->share_conf,
2659 KSMBD_SHARE_FLAG_FOLLOW_SYMLINKS)) {
2661 * Use LOOKUP_FOLLOW to follow the path of
2662 * symlink in path buildup
2664 rc = ksmbd_vfs_kern_path(name, LOOKUP_FOLLOW, &path, 1);
2665 if (rc) { /* Case for broken link ?*/
2666 rc = ksmbd_vfs_kern_path(name, 0, &path, 1);
2669 rc = ksmbd_vfs_kern_path(name, 0, &path, 1);
2670 if (!rc && d_is_symlink(path.dentry)) {
2679 if (rc == -EACCES) {
2681 "User does not have right permission\n");
2684 ksmbd_debug(SMB, "can not get linux path for %s, rc = %d\n",
2688 file_present = true;
2689 user_ns = mnt_user_ns(path.mnt);
2690 generic_fillattr(user_ns, d_inode(path.dentry), &stat);
2693 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
2694 if (s_type == DATA_STREAM) {
2696 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2699 if (S_ISDIR(stat.mode) && s_type == DATA_STREAM) {
2701 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
2705 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE &&
2706 req->FileAttributes & ATTR_NORMAL_LE) {
2707 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2715 if (file_present && req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE &&
2716 S_ISDIR(stat.mode) && !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2717 ksmbd_debug(SMB, "open() argument is a directory: %s, %x\n",
2718 name, req->CreateOptions);
2719 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
2724 if (file_present && (req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
2725 !(req->CreateDisposition == FILE_CREATE_LE) &&
2726 !S_ISDIR(stat.mode)) {
2727 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2732 if (!stream_name && file_present &&
2733 req->CreateDisposition == FILE_CREATE_LE) {
2738 daccess = smb_map_generic_desired_access(req->DesiredAccess);
2740 if (file_present && !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2741 rc = smb_check_perm_dacl(conn, &path, &daccess,
2747 if (daccess & FILE_MAXIMAL_ACCESS_LE) {
2748 if (!file_present) {
2749 daccess = cpu_to_le32(GENERIC_ALL_FLAGS);
2751 rc = ksmbd_vfs_query_maximal_access(user_ns,
2756 already_permitted = true;
2758 maximal_access = daccess;
2761 open_flags = smb2_create_open_flags(file_present, daccess,
2762 req->CreateDisposition,
2765 if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
2766 if (open_flags & O_CREAT) {
2768 "User does not have write permission\n");
2774 /*create file if not present */
2775 if (!file_present) {
2776 rc = smb2_creat(work, &path, name, open_flags, posix_mode,
2777 req->CreateOptions & FILE_DIRECTORY_FILE_LE);
2779 if (rc == -ENOENT) {
2781 rsp->hdr.Status = STATUS_OBJECT_PATH_NOT_FOUND;
2787 user_ns = mnt_user_ns(path.mnt);
2789 rc = smb2_set_ea(&ea_buf->ea, &path);
2790 if (rc == -EOPNOTSUPP)
2795 } else if (!already_permitted) {
2796 /* FILE_READ_ATTRIBUTE is allowed without inode_permission,
2797 * because execute(search) permission on a parent directory,
2798 * is already granted.
2800 if (daccess & ~(FILE_READ_ATTRIBUTES_LE | FILE_READ_CONTROL_LE)) {
2801 rc = inode_permission(user_ns,
2802 d_inode(path.dentry),
2807 if ((daccess & FILE_DELETE_LE) ||
2808 (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2809 rc = ksmbd_vfs_may_delete(user_ns,
2817 rc = ksmbd_query_inode_status(d_inode(path.dentry->d_parent));
2818 if (rc == KSMBD_INODE_STATUS_PENDING_DELETE) {
2824 filp = dentry_open(&path, open_flags, current_cred());
2827 pr_err("dentry open for dir failed, rc %d\n", rc);
2832 if (!(open_flags & O_TRUNC))
2833 file_info = FILE_OPENED;
2835 file_info = FILE_OVERWRITTEN;
2837 if ((req->CreateDisposition & FILE_CREATE_MASK_LE) ==
2839 file_info = FILE_SUPERSEDED;
2840 } else if (open_flags & O_CREAT) {
2841 file_info = FILE_CREATED;
2844 ksmbd_vfs_set_fadvise(filp, req->CreateOptions);
2846 /* Obtain Volatile-ID */
2847 fp = ksmbd_open_fd(work, filp);
2855 /* Get Persistent-ID */
2856 ksmbd_open_durable_fd(fp);
2857 if (!has_file_id(fp->persistent_id)) {
2862 fp->filename = name;
2863 fp->cdoption = req->CreateDisposition;
2864 fp->daccess = daccess;
2865 fp->saccess = req->ShareAccess;
2866 fp->coption = req->CreateOptions;
2868 /* Set default windows and posix acls if creating new file */
2871 struct inode *inode = d_inode(path.dentry);
2873 posix_acl_rc = ksmbd_vfs_inherit_posix_acl(user_ns,
2875 d_inode(path.dentry->d_parent));
2877 ksmbd_debug(SMB, "inherit posix acl failed : %d\n", posix_acl_rc);
2879 if (test_share_config_flag(work->tcon->share_conf,
2880 KSMBD_SHARE_FLAG_ACL_XATTR)) {
2881 rc = smb_inherit_dacl(conn, &path, sess->user->uid,
2886 rc = smb2_create_sd_buffer(work, req, &path);
2889 ksmbd_vfs_set_init_posix_acl(user_ns,
2892 if (test_share_config_flag(work->tcon->share_conf,
2893 KSMBD_SHARE_FLAG_ACL_XATTR)) {
2894 struct smb_fattr fattr;
2895 struct smb_ntsd *pntsd;
2896 int pntsd_size, ace_num = 0;
2898 ksmbd_acls_fattr(&fattr, user_ns, inode);
2900 ace_num = fattr.cf_acls->a_count;
2902 ace_num += fattr.cf_dacls->a_count;
2904 pntsd = kmalloc(sizeof(struct smb_ntsd) +
2905 sizeof(struct smb_sid) * 3 +
2906 sizeof(struct smb_acl) +
2907 sizeof(struct smb_ace) * ace_num * 2,
2912 rc = build_sec_desc(user_ns,
2917 &pntsd_size, &fattr);
2918 posix_acl_release(fattr.cf_acls);
2919 posix_acl_release(fattr.cf_dacls);
2921 rc = ksmbd_vfs_set_sd_xattr(conn,
2928 pr_err("failed to store ntacl in xattr : %d\n",
2937 rc = smb2_set_stream_name_xattr(&path,
2943 file_info = FILE_CREATED;
2946 fp->attrib_only = !(req->DesiredAccess & ~(FILE_READ_ATTRIBUTES_LE |
2947 FILE_WRITE_ATTRIBUTES_LE | FILE_SYNCHRONIZE_LE));
2948 if (!S_ISDIR(file_inode(filp)->i_mode) && open_flags & O_TRUNC &&
2949 !fp->attrib_only && !stream_name) {
2950 smb_break_all_oplock(work, fp);
2954 /* fp should be searchable through ksmbd_inode.m_fp_list
2955 * after daccess, saccess, attrib_only, and stream are
2958 write_lock(&fp->f_ci->m_lock);
2959 list_add(&fp->node, &fp->f_ci->m_fp_list);
2960 write_unlock(&fp->f_ci->m_lock);
2962 rc = ksmbd_vfs_getattr(&path, &stat);
2964 generic_fillattr(user_ns, d_inode(path.dentry), &stat);
2968 /* Check delete pending among previous fp before oplock break */
2969 if (ksmbd_inode_pending_delete(fp)) {
2974 share_ret = ksmbd_smb_check_shared_mode(fp->filp, fp);
2975 if (!test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_OPLOCKS) ||
2976 (req_op_level == SMB2_OPLOCK_LEVEL_LEASE &&
2977 !(conn->vals->capabilities & SMB2_GLOBAL_CAP_LEASING))) {
2978 if (share_ret < 0 && !S_ISDIR(file_inode(fp->filp)->i_mode)) {
2983 if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE) {
2984 req_op_level = smb2_map_lease_to_oplock(lc->req_state);
2986 "lease req for(%s) req oplock state 0x%x, lease state 0x%x\n",
2987 name, req_op_level, lc->req_state);
2988 rc = find_same_lease_key(sess, fp->f_ci, lc);
2991 } else if (open_flags == O_RDONLY &&
2992 (req_op_level == SMB2_OPLOCK_LEVEL_BATCH ||
2993 req_op_level == SMB2_OPLOCK_LEVEL_EXCLUSIVE))
2994 req_op_level = SMB2_OPLOCK_LEVEL_II;
2996 rc = smb_grant_oplock(work, req_op_level,
2997 fp->persistent_id, fp,
2998 le32_to_cpu(req->hdr.Id.SyncId.TreeId),
3004 if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)
3005 ksmbd_fd_set_delete_on_close(fp, file_info);
3007 if (need_truncate) {
3008 rc = smb2_create_truncate(&path);
3013 if (req->CreateContextsOffset) {
3014 struct create_alloc_size_req *az_req;
3016 az_req = (struct create_alloc_size_req *)smb2_find_context_vals(req,
3017 SMB2_CREATE_ALLOCATION_SIZE);
3018 if (IS_ERR(az_req)) {
3019 rc = PTR_ERR(az_req);
3021 } else if (az_req) {
3022 loff_t alloc_size = le64_to_cpu(az_req->AllocationSize);
3026 "request smb2 create allocate size : %llu\n",
3028 smb_break_all_levII_oplock(work, fp, 1);
3029 err = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
3033 "vfs_fallocate is failed : %d\n",
3037 context = smb2_find_context_vals(req, SMB2_CREATE_QUERY_ON_DISK_ID);
3038 if (IS_ERR(context)) {
3039 rc = PTR_ERR(context);
3041 } else if (context) {
3042 ksmbd_debug(SMB, "get query on disk id context\n");
3047 if (stat.result_mask & STATX_BTIME)
3048 fp->create_time = ksmbd_UnixTimeToNT(stat.btime);
3050 fp->create_time = ksmbd_UnixTimeToNT(stat.ctime);
3051 if (req->FileAttributes || fp->f_ci->m_fattr == 0)
3053 cpu_to_le32(smb2_get_dos_mode(&stat, le32_to_cpu(req->FileAttributes)));
3056 smb2_update_xattrs(tcon, &path, fp);
3058 smb2_new_xattrs(tcon, &path, fp);
3060 memcpy(fp->client_guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE);
3062 generic_fillattr(user_ns, file_inode(fp->filp),
3065 rsp->StructureSize = cpu_to_le16(89);
3067 opinfo = rcu_dereference(fp->f_opinfo);
3068 rsp->OplockLevel = opinfo != NULL ? opinfo->level : 0;
3071 rsp->CreateAction = cpu_to_le32(file_info);
3072 rsp->CreationTime = cpu_to_le64(fp->create_time);
3073 time = ksmbd_UnixTimeToNT(stat.atime);
3074 rsp->LastAccessTime = cpu_to_le64(time);
3075 time = ksmbd_UnixTimeToNT(stat.mtime);
3076 rsp->LastWriteTime = cpu_to_le64(time);
3077 time = ksmbd_UnixTimeToNT(stat.ctime);
3078 rsp->ChangeTime = cpu_to_le64(time);
3079 rsp->AllocationSize = S_ISDIR(stat.mode) ? 0 :
3080 cpu_to_le64(stat.blocks << 9);
3081 rsp->EndofFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
3082 rsp->FileAttributes = fp->f_ci->m_fattr;
3086 rsp->PersistentFileId = cpu_to_le64(fp->persistent_id);
3087 rsp->VolatileFileId = cpu_to_le64(fp->volatile_id);
3089 rsp->CreateContextsOffset = 0;
3090 rsp->CreateContextsLength = 0;
3091 inc_rfc1001_len(rsp_org, 88); /* StructureSize - 1*/
3093 /* If lease is request send lease context response */
3094 if (opinfo && opinfo->is_lease) {
3095 struct create_context *lease_ccontext;
3097 ksmbd_debug(SMB, "lease granted on(%s) lease state 0x%x\n",
3098 name, opinfo->o_lease->state);
3099 rsp->OplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
3101 lease_ccontext = (struct create_context *)rsp->Buffer;
3103 create_lease_buf(rsp->Buffer, opinfo->o_lease);
3104 le32_add_cpu(&rsp->CreateContextsLength,
3105 conn->vals->create_lease_size);
3106 inc_rfc1001_len(rsp_org, conn->vals->create_lease_size);
3107 next_ptr = &lease_ccontext->Next;
3108 next_off = conn->vals->create_lease_size;
3111 if (maximal_access_ctxt) {
3112 struct create_context *mxac_ccontext;
3114 if (maximal_access == 0)
3115 ksmbd_vfs_query_maximal_access(user_ns,
3118 mxac_ccontext = (struct create_context *)(rsp->Buffer +
3119 le32_to_cpu(rsp->CreateContextsLength));
3121 create_mxac_rsp_buf(rsp->Buffer +
3122 le32_to_cpu(rsp->CreateContextsLength),
3123 le32_to_cpu(maximal_access));
3124 le32_add_cpu(&rsp->CreateContextsLength,
3125 conn->vals->create_mxac_size);
3126 inc_rfc1001_len(rsp_org, conn->vals->create_mxac_size);
3128 *next_ptr = cpu_to_le32(next_off);
3129 next_ptr = &mxac_ccontext->Next;
3130 next_off = conn->vals->create_mxac_size;
3133 if (query_disk_id) {
3134 struct create_context *disk_id_ccontext;
3136 disk_id_ccontext = (struct create_context *)(rsp->Buffer +
3137 le32_to_cpu(rsp->CreateContextsLength));
3139 create_disk_id_rsp_buf(rsp->Buffer +
3140 le32_to_cpu(rsp->CreateContextsLength),
3141 stat.ino, tcon->id);
3142 le32_add_cpu(&rsp->CreateContextsLength,
3143 conn->vals->create_disk_id_size);
3144 inc_rfc1001_len(rsp_org, conn->vals->create_disk_id_size);
3146 *next_ptr = cpu_to_le32(next_off);
3147 next_ptr = &disk_id_ccontext->Next;
3148 next_off = conn->vals->create_disk_id_size;
3153 create_posix_rsp_buf(rsp->Buffer +
3154 le32_to_cpu(rsp->CreateContextsLength),
3156 le32_add_cpu(&rsp->CreateContextsLength,
3157 conn->vals->create_posix_size);
3158 inc_rfc1001_len(rsp_org, conn->vals->create_posix_size);
3160 *next_ptr = cpu_to_le32(next_off);
3163 if (contxt_cnt > 0) {
3164 rsp->CreateContextsOffset =
3165 cpu_to_le32(offsetof(struct smb2_create_rsp, Buffer)
3170 if (file_present || created)
3172 ksmbd_revert_fsids(work);
3176 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
3177 else if (rc == -EOPNOTSUPP)
3178 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
3179 else if (rc == -EACCES || rc == -ESTALE)
3180 rsp->hdr.Status = STATUS_ACCESS_DENIED;
3181 else if (rc == -ENOENT)
3182 rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
3183 else if (rc == -EPERM)
3184 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
3185 else if (rc == -EBUSY)
3186 rsp->hdr.Status = STATUS_DELETE_PENDING;
3187 else if (rc == -EBADF)
3188 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
3189 else if (rc == -ENOEXEC)
3190 rsp->hdr.Status = STATUS_DUPLICATE_OBJECTID;
3191 else if (rc == -ENXIO)
3192 rsp->hdr.Status = STATUS_NO_SUCH_DEVICE;
3193 else if (rc == -EEXIST)
3194 rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
3195 else if (rc == -EMFILE)
3196 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
3197 if (!rsp->hdr.Status)
3198 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
3200 if (!fp || !fp->filename)
3203 ksmbd_fd_put(work, fp);
3204 smb2_set_err_rsp(work);
3205 ksmbd_debug(SMB, "Error response: %x\n", rsp->hdr.Status);
3213 static int readdir_info_level_struct_sz(int info_level)
3215 switch (info_level) {
3216 case FILE_FULL_DIRECTORY_INFORMATION:
3217 return sizeof(struct file_full_directory_info);
3218 case FILE_BOTH_DIRECTORY_INFORMATION:
3219 return sizeof(struct file_both_directory_info);
3220 case FILE_DIRECTORY_INFORMATION:
3221 return sizeof(struct file_directory_info);
3222 case FILE_NAMES_INFORMATION:
3223 return sizeof(struct file_names_info);
3224 case FILEID_FULL_DIRECTORY_INFORMATION:
3225 return sizeof(struct file_id_full_dir_info);
3226 case FILEID_BOTH_DIRECTORY_INFORMATION:
3227 return sizeof(struct file_id_both_directory_info);
3228 case SMB_FIND_FILE_POSIX_INFO:
3229 return sizeof(struct smb2_posix_info);
3235 static int dentry_name(struct ksmbd_dir_info *d_info, int info_level)
3237 switch (info_level) {
3238 case FILE_FULL_DIRECTORY_INFORMATION:
3240 struct file_full_directory_info *ffdinfo;
3242 ffdinfo = (struct file_full_directory_info *)d_info->rptr;
3243 d_info->rptr += le32_to_cpu(ffdinfo->NextEntryOffset);
3244 d_info->name = ffdinfo->FileName;
3245 d_info->name_len = le32_to_cpu(ffdinfo->FileNameLength);
3248 case FILE_BOTH_DIRECTORY_INFORMATION:
3250 struct file_both_directory_info *fbdinfo;
3252 fbdinfo = (struct file_both_directory_info *)d_info->rptr;
3253 d_info->rptr += le32_to_cpu(fbdinfo->NextEntryOffset);
3254 d_info->name = fbdinfo->FileName;
3255 d_info->name_len = le32_to_cpu(fbdinfo->FileNameLength);
3258 case FILE_DIRECTORY_INFORMATION:
3260 struct file_directory_info *fdinfo;
3262 fdinfo = (struct file_directory_info *)d_info->rptr;
3263 d_info->rptr += le32_to_cpu(fdinfo->NextEntryOffset);
3264 d_info->name = fdinfo->FileName;
3265 d_info->name_len = le32_to_cpu(fdinfo->FileNameLength);
3268 case FILE_NAMES_INFORMATION:
3270 struct file_names_info *fninfo;
3272 fninfo = (struct file_names_info *)d_info->rptr;
3273 d_info->rptr += le32_to_cpu(fninfo->NextEntryOffset);
3274 d_info->name = fninfo->FileName;
3275 d_info->name_len = le32_to_cpu(fninfo->FileNameLength);
3278 case FILEID_FULL_DIRECTORY_INFORMATION:
3280 struct file_id_full_dir_info *dinfo;
3282 dinfo = (struct file_id_full_dir_info *)d_info->rptr;
3283 d_info->rptr += le32_to_cpu(dinfo->NextEntryOffset);
3284 d_info->name = dinfo->FileName;
3285 d_info->name_len = le32_to_cpu(dinfo->FileNameLength);
3288 case FILEID_BOTH_DIRECTORY_INFORMATION:
3290 struct file_id_both_directory_info *fibdinfo;
3292 fibdinfo = (struct file_id_both_directory_info *)d_info->rptr;
3293 d_info->rptr += le32_to_cpu(fibdinfo->NextEntryOffset);
3294 d_info->name = fibdinfo->FileName;
3295 d_info->name_len = le32_to_cpu(fibdinfo->FileNameLength);
3298 case SMB_FIND_FILE_POSIX_INFO:
3300 struct smb2_posix_info *posix_info;
3302 posix_info = (struct smb2_posix_info *)d_info->rptr;
3303 d_info->rptr += le32_to_cpu(posix_info->NextEntryOffset);
3304 d_info->name = posix_info->name;
3305 d_info->name_len = le32_to_cpu(posix_info->name_len);
3314 * smb2_populate_readdir_entry() - encode directory entry in smb2 response
3316 * @conn: connection instance
3317 * @info_level: smb information level
3318 * @d_info: structure included variables for query dir
3319 * @user_ns: user namespace
3320 * @ksmbd_kstat: ksmbd wrapper of dirent stat information
3322 * if directory has many entries, find first can't read it fully.
3323 * find next might be called multiple times to read remaining dir entries
3325 * Return: 0 on success, otherwise error
3327 static int smb2_populate_readdir_entry(struct ksmbd_conn *conn, int info_level,
3328 struct ksmbd_dir_info *d_info,
3329 struct ksmbd_kstat *ksmbd_kstat)
3331 int next_entry_offset = 0;
3335 int struct_sz, rc = 0;
3337 conv_name = ksmbd_convert_dir_info_name(d_info,
3343 /* Somehow the name has only terminating NULL bytes */
3346 goto free_conv_name;
3349 struct_sz = readdir_info_level_struct_sz(info_level);
3350 next_entry_offset = ALIGN(struct_sz - 1 + conv_len,
3351 KSMBD_DIR_INFO_ALIGNMENT);
3353 if (next_entry_offset > d_info->out_buf_len) {
3354 d_info->out_buf_len = 0;
3356 goto free_conv_name;
3359 kstat = d_info->wptr;
3360 if (info_level != FILE_NAMES_INFORMATION)
3361 kstat = ksmbd_vfs_init_kstat(&d_info->wptr, ksmbd_kstat);
3363 switch (info_level) {
3364 case FILE_FULL_DIRECTORY_INFORMATION:
3366 struct file_full_directory_info *ffdinfo;
3368 ffdinfo = (struct file_full_directory_info *)kstat;
3369 ffdinfo->FileNameLength = cpu_to_le32(conv_len);
3371 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3372 if (ffdinfo->EaSize)
3373 ffdinfo->ExtFileAttributes = ATTR_REPARSE_POINT_LE;
3374 if (d_info->hide_dot_file && d_info->name[0] == '.')
3375 ffdinfo->ExtFileAttributes |= ATTR_HIDDEN_LE;
3376 memcpy(ffdinfo->FileName, conv_name, conv_len);
3377 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3380 case FILE_BOTH_DIRECTORY_INFORMATION:
3382 struct file_both_directory_info *fbdinfo;
3384 fbdinfo = (struct file_both_directory_info *)kstat;
3385 fbdinfo->FileNameLength = cpu_to_le32(conv_len);
3387 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3388 if (fbdinfo->EaSize)
3389 fbdinfo->ExtFileAttributes = ATTR_REPARSE_POINT_LE;
3390 fbdinfo->ShortNameLength = 0;
3391 fbdinfo->Reserved = 0;
3392 if (d_info->hide_dot_file && d_info->name[0] == '.')
3393 fbdinfo->ExtFileAttributes |= ATTR_HIDDEN_LE;
3394 memcpy(fbdinfo->FileName, conv_name, conv_len);
3395 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3398 case FILE_DIRECTORY_INFORMATION:
3400 struct file_directory_info *fdinfo;
3402 fdinfo = (struct file_directory_info *)kstat;
3403 fdinfo->FileNameLength = cpu_to_le32(conv_len);
3404 if (d_info->hide_dot_file && d_info->name[0] == '.')
3405 fdinfo->ExtFileAttributes |= ATTR_HIDDEN_LE;
3406 memcpy(fdinfo->FileName, conv_name, conv_len);
3407 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3410 case FILE_NAMES_INFORMATION:
3412 struct file_names_info *fninfo;
3414 fninfo = (struct file_names_info *)kstat;
3415 fninfo->FileNameLength = cpu_to_le32(conv_len);
3416 memcpy(fninfo->FileName, conv_name, conv_len);
3417 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3420 case FILEID_FULL_DIRECTORY_INFORMATION:
3422 struct file_id_full_dir_info *dinfo;
3424 dinfo = (struct file_id_full_dir_info *)kstat;
3425 dinfo->FileNameLength = cpu_to_le32(conv_len);
3427 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3429 dinfo->ExtFileAttributes = ATTR_REPARSE_POINT_LE;
3430 dinfo->Reserved = 0;
3431 dinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
3432 if (d_info->hide_dot_file && d_info->name[0] == '.')
3433 dinfo->ExtFileAttributes |= ATTR_HIDDEN_LE;
3434 memcpy(dinfo->FileName, conv_name, conv_len);
3435 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3438 case FILEID_BOTH_DIRECTORY_INFORMATION:
3440 struct file_id_both_directory_info *fibdinfo;
3442 fibdinfo = (struct file_id_both_directory_info *)kstat;
3443 fibdinfo->FileNameLength = cpu_to_le32(conv_len);
3445 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3446 if (fibdinfo->EaSize)
3447 fibdinfo->ExtFileAttributes = ATTR_REPARSE_POINT_LE;
3448 fibdinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
3449 fibdinfo->ShortNameLength = 0;
3450 fibdinfo->Reserved = 0;
3451 fibdinfo->Reserved2 = cpu_to_le16(0);
3452 if (d_info->hide_dot_file && d_info->name[0] == '.')
3453 fibdinfo->ExtFileAttributes |= ATTR_HIDDEN_LE;
3454 memcpy(fibdinfo->FileName, conv_name, conv_len);
3455 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3458 case SMB_FIND_FILE_POSIX_INFO:
3460 struct smb2_posix_info *posix_info;
3463 posix_info = (struct smb2_posix_info *)kstat;
3464 posix_info->Ignored = 0;
3465 posix_info->CreationTime = cpu_to_le64(ksmbd_kstat->create_time);
3466 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->ctime);
3467 posix_info->ChangeTime = cpu_to_le64(time);
3468 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->atime);
3469 posix_info->LastAccessTime = cpu_to_le64(time);
3470 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->mtime);
3471 posix_info->LastWriteTime = cpu_to_le64(time);
3472 posix_info->EndOfFile = cpu_to_le64(ksmbd_kstat->kstat->size);
3473 posix_info->AllocationSize = cpu_to_le64(ksmbd_kstat->kstat->blocks << 9);
3474 posix_info->DeviceId = cpu_to_le32(ksmbd_kstat->kstat->rdev);
3475 posix_info->HardLinks = cpu_to_le32(ksmbd_kstat->kstat->nlink);
3476 posix_info->Mode = cpu_to_le32(ksmbd_kstat->kstat->mode);
3477 posix_info->Inode = cpu_to_le64(ksmbd_kstat->kstat->ino);
3478 posix_info->DosAttributes =
3479 S_ISDIR(ksmbd_kstat->kstat->mode) ? ATTR_DIRECTORY_LE : ATTR_ARCHIVE_LE;
3480 if (d_info->hide_dot_file && d_info->name[0] == '.')
3481 posix_info->DosAttributes |= ATTR_HIDDEN_LE;
3482 id_to_sid(from_kuid_munged(&init_user_ns, ksmbd_kstat->kstat->uid),
3483 SIDNFS_USER, (struct smb_sid *)&posix_info->SidBuffer[0]);
3484 id_to_sid(from_kgid_munged(&init_user_ns, ksmbd_kstat->kstat->gid),
3485 SIDNFS_GROUP, (struct smb_sid *)&posix_info->SidBuffer[20]);
3486 memcpy(posix_info->name, conv_name, conv_len);
3487 posix_info->name_len = cpu_to_le32(conv_len);
3488 posix_info->NextEntryOffset = cpu_to_le32(next_entry_offset);
3492 } /* switch (info_level) */
3494 d_info->last_entry_offset = d_info->data_count;
3495 d_info->data_count += next_entry_offset;
3496 d_info->out_buf_len -= next_entry_offset;
3497 d_info->wptr += next_entry_offset;
3500 "info_level : %d, buf_len :%d, next_offset : %d, data_count : %d\n",
3501 info_level, d_info->out_buf_len,
3502 next_entry_offset, d_info->data_count);
3509 struct smb2_query_dir_private {
3510 struct ksmbd_work *work;
3511 char *search_pattern;
3512 struct ksmbd_file *dir_fp;
3514 struct ksmbd_dir_info *d_info;
3518 static void lock_dir(struct ksmbd_file *dir_fp)
3520 struct dentry *dir = dir_fp->filp->f_path.dentry;
3522 inode_lock_nested(d_inode(dir), I_MUTEX_PARENT);
3525 static void unlock_dir(struct ksmbd_file *dir_fp)
3527 struct dentry *dir = dir_fp->filp->f_path.dentry;
3529 inode_unlock(d_inode(dir));
3532 static int process_query_dir_entries(struct smb2_query_dir_private *priv)
3534 struct user_namespace *user_ns = file_mnt_user_ns(priv->dir_fp->filp);
3536 struct ksmbd_kstat ksmbd_kstat;
3540 for (i = 0; i < priv->d_info->num_entry; i++) {
3541 struct dentry *dent;
3543 if (dentry_name(priv->d_info, priv->info_level))
3546 lock_dir(priv->dir_fp);
3547 dent = lookup_one(user_ns, priv->d_info->name,
3548 priv->dir_fp->filp->f_path.dentry,
3549 priv->d_info->name_len);
3550 unlock_dir(priv->dir_fp);
3553 ksmbd_debug(SMB, "Cannot lookup `%s' [%ld]\n",
3558 if (unlikely(d_is_negative(dent))) {
3560 ksmbd_debug(SMB, "Negative dentry `%s'\n",
3561 priv->d_info->name);
3565 ksmbd_kstat.kstat = &kstat;
3566 if (priv->info_level != FILE_NAMES_INFORMATION)
3567 ksmbd_vfs_fill_dentry_attrs(priv->work,
3572 rc = smb2_populate_readdir_entry(priv->work->conn,
3583 static int reserve_populate_dentry(struct ksmbd_dir_info *d_info,
3588 int next_entry_offset;
3590 struct_sz = readdir_info_level_struct_sz(info_level);
3591 if (struct_sz == -EOPNOTSUPP)
3594 conv_len = (d_info->name_len + 1) * 2;
3595 next_entry_offset = ALIGN(struct_sz - 1 + conv_len,
3596 KSMBD_DIR_INFO_ALIGNMENT);
3598 if (next_entry_offset > d_info->out_buf_len) {
3599 d_info->out_buf_len = 0;
3603 switch (info_level) {
3604 case FILE_FULL_DIRECTORY_INFORMATION:
3606 struct file_full_directory_info *ffdinfo;
3608 ffdinfo = (struct file_full_directory_info *)d_info->wptr;
3609 memcpy(ffdinfo->FileName, d_info->name, d_info->name_len);
3610 ffdinfo->FileName[d_info->name_len] = 0x00;
3611 ffdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3612 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3615 case FILE_BOTH_DIRECTORY_INFORMATION:
3617 struct file_both_directory_info *fbdinfo;
3619 fbdinfo = (struct file_both_directory_info *)d_info->wptr;
3620 memcpy(fbdinfo->FileName, d_info->name, d_info->name_len);
3621 fbdinfo->FileName[d_info->name_len] = 0x00;
3622 fbdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3623 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3626 case FILE_DIRECTORY_INFORMATION:
3628 struct file_directory_info *fdinfo;
3630 fdinfo = (struct file_directory_info *)d_info->wptr;
3631 memcpy(fdinfo->FileName, d_info->name, d_info->name_len);
3632 fdinfo->FileName[d_info->name_len] = 0x00;
3633 fdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3634 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3637 case FILE_NAMES_INFORMATION:
3639 struct file_names_info *fninfo;
3641 fninfo = (struct file_names_info *)d_info->wptr;
3642 memcpy(fninfo->FileName, d_info->name, d_info->name_len);
3643 fninfo->FileName[d_info->name_len] = 0x00;
3644 fninfo->FileNameLength = cpu_to_le32(d_info->name_len);
3645 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3648 case FILEID_FULL_DIRECTORY_INFORMATION:
3650 struct file_id_full_dir_info *dinfo;
3652 dinfo = (struct file_id_full_dir_info *)d_info->wptr;
3653 memcpy(dinfo->FileName, d_info->name, d_info->name_len);
3654 dinfo->FileName[d_info->name_len] = 0x00;
3655 dinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3656 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3659 case FILEID_BOTH_DIRECTORY_INFORMATION:
3661 struct file_id_both_directory_info *fibdinfo;
3663 fibdinfo = (struct file_id_both_directory_info *)d_info->wptr;
3664 memcpy(fibdinfo->FileName, d_info->name, d_info->name_len);
3665 fibdinfo->FileName[d_info->name_len] = 0x00;
3666 fibdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3667 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3670 case SMB_FIND_FILE_POSIX_INFO:
3672 struct smb2_posix_info *posix_info;
3674 posix_info = (struct smb2_posix_info *)d_info->wptr;
3675 memcpy(posix_info->name, d_info->name, d_info->name_len);
3676 posix_info->name[d_info->name_len] = 0x00;
3677 posix_info->name_len = cpu_to_le32(d_info->name_len);
3678 posix_info->NextEntryOffset =
3679 cpu_to_le32(next_entry_offset);
3682 } /* switch (info_level) */
3684 d_info->num_entry++;
3685 d_info->out_buf_len -= next_entry_offset;
3686 d_info->wptr += next_entry_offset;
3690 static int __query_dir(struct dir_context *ctx, const char *name, int namlen,
3691 loff_t offset, u64 ino, unsigned int d_type)
3693 struct ksmbd_readdir_data *buf;
3694 struct smb2_query_dir_private *priv;
3695 struct ksmbd_dir_info *d_info;
3698 buf = container_of(ctx, struct ksmbd_readdir_data, ctx);
3699 priv = buf->private;
3700 d_info = priv->d_info;
3702 /* dot and dotdot entries are already reserved */
3703 if (!strcmp(".", name) || !strcmp("..", name))
3705 if (ksmbd_share_veto_filename(priv->work->tcon->share_conf, name))
3707 if (!match_pattern(name, namlen, priv->search_pattern))
3710 d_info->name = name;
3711 d_info->name_len = namlen;
3712 rc = reserve_populate_dentry(d_info, priv->info_level);
3715 if (d_info->flags & SMB2_RETURN_SINGLE_ENTRY) {
3716 d_info->out_buf_len = 0;
3722 static void restart_ctx(struct dir_context *ctx)
3727 static int verify_info_level(int info_level)
3729 switch (info_level) {
3730 case FILE_FULL_DIRECTORY_INFORMATION:
3731 case FILE_BOTH_DIRECTORY_INFORMATION:
3732 case FILE_DIRECTORY_INFORMATION:
3733 case FILE_NAMES_INFORMATION:
3734 case FILEID_FULL_DIRECTORY_INFORMATION:
3735 case FILEID_BOTH_DIRECTORY_INFORMATION:
3736 case SMB_FIND_FILE_POSIX_INFO:
3745 int smb2_query_dir(struct ksmbd_work *work)
3747 struct ksmbd_conn *conn = work->conn;
3748 struct smb2_query_directory_req *req;
3749 struct smb2_query_directory_rsp *rsp, *rsp_org;
3750 struct ksmbd_share_config *share = work->tcon->share_conf;
3751 struct ksmbd_file *dir_fp = NULL;
3752 struct ksmbd_dir_info d_info;
3754 char *srch_ptr = NULL;
3755 unsigned char srch_flag;
3757 struct smb2_query_dir_private query_dir_private = {NULL, };
3759 rsp_org = work->response_buf;
3760 WORK_BUFFERS(work, req, rsp);
3762 if (ksmbd_override_fsids(work)) {
3763 rsp->hdr.Status = STATUS_NO_MEMORY;
3764 smb2_set_err_rsp(work);
3768 rc = verify_info_level(req->FileInformationClass);
3774 dir_fp = ksmbd_lookup_fd_slow(work,
3775 le64_to_cpu(req->VolatileFileId),
3776 le64_to_cpu(req->PersistentFileId));
3782 if (!(dir_fp->daccess & FILE_LIST_DIRECTORY_LE) ||
3783 inode_permission(file_mnt_user_ns(dir_fp->filp),
3784 file_inode(dir_fp->filp),
3785 MAY_READ | MAY_EXEC)) {
3786 pr_err("no right to enumerate directory (%pd)\n",
3787 dir_fp->filp->f_path.dentry);
3792 if (!S_ISDIR(file_inode(dir_fp->filp)->i_mode)) {
3793 pr_err("can't do query dir for a file\n");
3798 srch_flag = req->Flags;
3799 srch_ptr = smb_strndup_from_utf16(req->Buffer,
3800 le16_to_cpu(req->FileNameLength), 1,
3802 if (IS_ERR(srch_ptr)) {
3803 ksmbd_debug(SMB, "Search Pattern not found\n");
3807 ksmbd_debug(SMB, "Search pattern is %s\n", srch_ptr);
3810 ksmbd_debug(SMB, "Directory name is %s\n", dir_fp->filename);
3812 if (srch_flag & SMB2_REOPEN || srch_flag & SMB2_RESTART_SCANS) {
3813 ksmbd_debug(SMB, "Restart directory scan\n");
3814 generic_file_llseek(dir_fp->filp, 0, SEEK_SET);
3815 restart_ctx(&dir_fp->readdir_data.ctx);
3818 memset(&d_info, 0, sizeof(struct ksmbd_dir_info));
3819 d_info.wptr = (char *)rsp->Buffer;
3820 d_info.rptr = (char *)rsp->Buffer;
3821 d_info.out_buf_len = (work->response_sz - (get_rfc1002_len(rsp_org) + 4));
3822 d_info.out_buf_len = min_t(int, d_info.out_buf_len, le32_to_cpu(req->OutputBufferLength)) -
3823 sizeof(struct smb2_query_directory_rsp);
3824 d_info.flags = srch_flag;
3827 * reserve dot and dotdot entries in head of buffer
3830 rc = ksmbd_populate_dot_dotdot_entries(work, req->FileInformationClass,
3831 dir_fp, &d_info, srch_ptr,
3832 smb2_populate_readdir_entry);
3838 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_HIDE_DOT_FILES))
3839 d_info.hide_dot_file = true;
3841 buffer_sz = d_info.out_buf_len;
3842 d_info.rptr = d_info.wptr;
3843 query_dir_private.work = work;
3844 query_dir_private.search_pattern = srch_ptr;
3845 query_dir_private.dir_fp = dir_fp;
3846 query_dir_private.d_info = &d_info;
3847 query_dir_private.info_level = req->FileInformationClass;
3848 dir_fp->readdir_data.private = &query_dir_private;
3849 set_ctx_actor(&dir_fp->readdir_data.ctx, __query_dir);
3851 rc = iterate_dir(dir_fp->filp, &dir_fp->readdir_data.ctx);
3853 restart_ctx(&dir_fp->readdir_data.ctx);
3859 d_info.wptr = d_info.rptr;
3860 d_info.out_buf_len = buffer_sz;
3861 rc = process_query_dir_entries(&query_dir_private);
3865 if (!d_info.data_count && d_info.out_buf_len >= 0) {
3866 if (srch_flag & SMB2_RETURN_SINGLE_ENTRY && !is_asterisk(srch_ptr)) {
3867 rsp->hdr.Status = STATUS_NO_SUCH_FILE;
3869 dir_fp->dot_dotdot[0] = dir_fp->dot_dotdot[1] = 0;
3870 rsp->hdr.Status = STATUS_NO_MORE_FILES;
3872 rsp->StructureSize = cpu_to_le16(9);
3873 rsp->OutputBufferOffset = cpu_to_le16(0);
3874 rsp->OutputBufferLength = cpu_to_le32(0);
3876 inc_rfc1001_len(rsp_org, 9);
3878 ((struct file_directory_info *)
3879 ((char *)rsp->Buffer + d_info.last_entry_offset))
3880 ->NextEntryOffset = 0;
3882 rsp->StructureSize = cpu_to_le16(9);
3883 rsp->OutputBufferOffset = cpu_to_le16(72);
3884 rsp->OutputBufferLength = cpu_to_le32(d_info.data_count);
3885 inc_rfc1001_len(rsp_org, 8 + d_info.data_count);
3889 ksmbd_fd_put(work, dir_fp);
3890 ksmbd_revert_fsids(work);
3894 pr_err("error while processing smb2 query dir rc = %d\n", rc);
3899 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
3900 else if (rc == -EACCES)
3901 rsp->hdr.Status = STATUS_ACCESS_DENIED;
3902 else if (rc == -ENOENT)
3903 rsp->hdr.Status = STATUS_NO_SUCH_FILE;
3904 else if (rc == -EBADF)
3905 rsp->hdr.Status = STATUS_FILE_CLOSED;
3906 else if (rc == -ENOMEM)
3907 rsp->hdr.Status = STATUS_NO_MEMORY;
3908 else if (rc == -EFAULT)
3909 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
3910 if (!rsp->hdr.Status)
3911 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
3913 smb2_set_err_rsp(work);
3914 ksmbd_fd_put(work, dir_fp);
3915 ksmbd_revert_fsids(work);
3920 * buffer_check_err() - helper function to check buffer errors
3921 * @reqOutputBufferLength: max buffer length expected in command response
3922 * @rsp: query info response buffer contains output buffer length
3923 * @infoclass_size: query info class response buffer size
3925 * Return: 0 on success, otherwise error
3927 static int buffer_check_err(int reqOutputBufferLength,
3928 struct smb2_query_info_rsp *rsp, int infoclass_size)
3930 if (reqOutputBufferLength < le32_to_cpu(rsp->OutputBufferLength)) {
3931 if (reqOutputBufferLength < infoclass_size) {
3932 pr_err("Invalid Buffer Size Requested\n");
3933 rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
3934 rsp->hdr.smb2_buf_length = cpu_to_be32(sizeof(struct smb2_hdr) - 4);
3938 ksmbd_debug(SMB, "Buffer Overflow\n");
3939 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
3940 rsp->hdr.smb2_buf_length = cpu_to_be32(sizeof(struct smb2_hdr) - 4 +
3941 reqOutputBufferLength);
3942 rsp->OutputBufferLength = cpu_to_le32(reqOutputBufferLength);
3947 static void get_standard_info_pipe(struct smb2_query_info_rsp *rsp)
3949 struct smb2_file_standard_info *sinfo;
3951 sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
3953 sinfo->AllocationSize = cpu_to_le64(4096);
3954 sinfo->EndOfFile = cpu_to_le64(0);
3955 sinfo->NumberOfLinks = cpu_to_le32(1);
3956 sinfo->DeletePending = 1;
3957 sinfo->Directory = 0;
3958 rsp->OutputBufferLength =
3959 cpu_to_le32(sizeof(struct smb2_file_standard_info));
3960 inc_rfc1001_len(rsp, sizeof(struct smb2_file_standard_info));
3963 static void get_internal_info_pipe(struct smb2_query_info_rsp *rsp, u64 num)
3965 struct smb2_file_internal_info *file_info;
3967 file_info = (struct smb2_file_internal_info *)rsp->Buffer;
3969 /* any unique number */
3970 file_info->IndexNumber = cpu_to_le64(num | (1ULL << 63));
3971 rsp->OutputBufferLength =
3972 cpu_to_le32(sizeof(struct smb2_file_internal_info));
3973 inc_rfc1001_len(rsp, sizeof(struct smb2_file_internal_info));
3976 static int smb2_get_info_file_pipe(struct ksmbd_session *sess,
3977 struct smb2_query_info_req *req,
3978 struct smb2_query_info_rsp *rsp)
3984 * Windows can sometime send query file info request on
3985 * pipe without opening it, checking error condition here
3987 id = le64_to_cpu(req->VolatileFileId);
3988 if (!ksmbd_session_rpc_method(sess, id))
3991 ksmbd_debug(SMB, "FileInfoClass %u, FileId 0x%llx\n",
3992 req->FileInfoClass, le64_to_cpu(req->VolatileFileId));
3994 switch (req->FileInfoClass) {
3995 case FILE_STANDARD_INFORMATION:
3996 get_standard_info_pipe(rsp);
3997 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
3998 rsp, FILE_STANDARD_INFORMATION_SIZE);
4000 case FILE_INTERNAL_INFORMATION:
4001 get_internal_info_pipe(rsp, id);
4002 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4003 rsp, FILE_INTERNAL_INFORMATION_SIZE);
4006 ksmbd_debug(SMB, "smb2_info_file_pipe for %u not supported\n",
4007 req->FileInfoClass);
4014 * smb2_get_ea() - handler for smb2 get extended attribute command
4015 * @work: smb work containing query info command buffer
4016 * @fp: ksmbd_file pointer
4017 * @req: get extended attribute request
4018 * @rsp: response buffer pointer
4019 * @rsp_org: base response buffer pointer in case of chained response
4021 * Return: 0 on success, otherwise error
4023 static int smb2_get_ea(struct ksmbd_work *work, struct ksmbd_file *fp,
4024 struct smb2_query_info_req *req,
4025 struct smb2_query_info_rsp *rsp, void *rsp_org)
4027 struct smb2_ea_info *eainfo, *prev_eainfo;
4028 char *name, *ptr, *xattr_list = NULL, *buf;
4029 int rc, name_len, value_len, xattr_list_len, idx;
4030 ssize_t buf_free_len, alignment_bytes, next_offset, rsp_data_cnt = 0;
4031 struct smb2_ea_info_req *ea_req = NULL;
4033 struct user_namespace *user_ns = file_mnt_user_ns(fp->filp);
4035 if (!(fp->daccess & FILE_READ_EA_LE)) {
4036 pr_err("Not permitted to read ext attr : 0x%x\n",
4041 path = &fp->filp->f_path;
4042 /* single EA entry is requested with given user.* name */
4043 if (req->InputBufferLength) {
4044 ea_req = (struct smb2_ea_info_req *)req->Buffer;
4046 /* need to send all EAs, if no specific EA is requested*/
4047 if (le32_to_cpu(req->Flags) & SL_RETURN_SINGLE_ENTRY)
4049 "All EAs are requested but need to send single EA entry in rsp flags 0x%x\n",
4050 le32_to_cpu(req->Flags));
4053 buf_free_len = work->response_sz -
4054 (get_rfc1002_len(rsp_org) + 4) -
4055 sizeof(struct smb2_query_info_rsp);
4057 if (le32_to_cpu(req->OutputBufferLength) < buf_free_len)
4058 buf_free_len = le32_to_cpu(req->OutputBufferLength);
4060 rc = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
4062 rsp->hdr.Status = STATUS_INVALID_HANDLE;
4064 } else if (!rc) { /* there is no EA in the file */
4065 ksmbd_debug(SMB, "no ea data in the file\n");
4068 xattr_list_len = rc;
4070 ptr = (char *)rsp->Buffer;
4071 eainfo = (struct smb2_ea_info *)ptr;
4072 prev_eainfo = eainfo;
4075 while (idx < xattr_list_len) {
4076 name = xattr_list + idx;
4077 name_len = strlen(name);
4079 ksmbd_debug(SMB, "%s, len %d\n", name, name_len);
4080 idx += name_len + 1;
4083 * CIFS does not support EA other than user.* namespace,
4084 * still keep the framework generic, to list other attrs
4087 if (strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4090 if (!strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
4094 if (req->InputBufferLength &&
4095 strncmp(&name[XATTR_USER_PREFIX_LEN], ea_req->name,
4096 ea_req->EaNameLength))
4099 if (!strncmp(&name[XATTR_USER_PREFIX_LEN],
4100 DOS_ATTRIBUTE_PREFIX, DOS_ATTRIBUTE_PREFIX_LEN))
4103 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4104 name_len -= XATTR_USER_PREFIX_LEN;
4106 ptr = (char *)(&eainfo->name + name_len + 1);
4107 buf_free_len -= (offsetof(struct smb2_ea_info, name) +
4109 /* bailout if xattr can't fit in buf_free_len */
4110 value_len = ksmbd_vfs_getxattr(user_ns, path->dentry,
4112 if (value_len <= 0) {
4114 rsp->hdr.Status = STATUS_INVALID_HANDLE;
4118 buf_free_len -= value_len;
4119 if (buf_free_len < 0) {
4124 memcpy(ptr, buf, value_len);
4129 eainfo->EaNameLength = name_len;
4131 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4132 memcpy(eainfo->name, &name[XATTR_USER_PREFIX_LEN],
4135 memcpy(eainfo->name, name, name_len);
4137 eainfo->name[name_len] = '\0';
4138 eainfo->EaValueLength = cpu_to_le16(value_len);
4139 next_offset = offsetof(struct smb2_ea_info, name) +
4140 name_len + 1 + value_len;
4142 /* align next xattr entry at 4 byte bundary */
4143 alignment_bytes = ((next_offset + 3) & ~3) - next_offset;
4144 if (alignment_bytes) {
4145 memset(ptr, '\0', alignment_bytes);
4146 ptr += alignment_bytes;
4147 next_offset += alignment_bytes;
4148 buf_free_len -= alignment_bytes;
4150 eainfo->NextEntryOffset = cpu_to_le32(next_offset);
4151 prev_eainfo = eainfo;
4152 eainfo = (struct smb2_ea_info *)ptr;
4153 rsp_data_cnt += next_offset;
4155 if (req->InputBufferLength) {
4156 ksmbd_debug(SMB, "single entry requested\n");
4161 /* no more ea entries */
4162 prev_eainfo->NextEntryOffset = 0;
4165 if (rsp_data_cnt == 0)
4166 rsp->hdr.Status = STATUS_NO_EAS_ON_FILE;
4167 rsp->OutputBufferLength = cpu_to_le32(rsp_data_cnt);
4168 inc_rfc1001_len(rsp_org, rsp_data_cnt);
4174 static void get_file_access_info(struct smb2_query_info_rsp *rsp,
4175 struct ksmbd_file *fp, void *rsp_org)
4177 struct smb2_file_access_info *file_info;
4179 file_info = (struct smb2_file_access_info *)rsp->Buffer;
4180 file_info->AccessFlags = fp->daccess;
4181 rsp->OutputBufferLength =
4182 cpu_to_le32(sizeof(struct smb2_file_access_info));
4183 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_access_info));
4186 static int get_file_basic_info(struct smb2_query_info_rsp *rsp,
4187 struct ksmbd_file *fp, void *rsp_org)
4189 struct smb2_file_all_info *basic_info;
4193 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4194 pr_err("no right to read the attributes : 0x%x\n",
4199 basic_info = (struct smb2_file_all_info *)rsp->Buffer;
4200 generic_fillattr(file_mnt_user_ns(fp->filp), file_inode(fp->filp),
4202 basic_info->CreationTime = cpu_to_le64(fp->create_time);
4203 time = ksmbd_UnixTimeToNT(stat.atime);
4204 basic_info->LastAccessTime = cpu_to_le64(time);
4205 time = ksmbd_UnixTimeToNT(stat.mtime);
4206 basic_info->LastWriteTime = cpu_to_le64(time);
4207 time = ksmbd_UnixTimeToNT(stat.ctime);
4208 basic_info->ChangeTime = cpu_to_le64(time);
4209 basic_info->Attributes = fp->f_ci->m_fattr;
4210 basic_info->Pad1 = 0;
4211 rsp->OutputBufferLength =
4212 cpu_to_le32(offsetof(struct smb2_file_all_info, AllocationSize));
4213 inc_rfc1001_len(rsp_org, offsetof(struct smb2_file_all_info,
4218 static unsigned long long get_allocation_size(struct inode *inode,
4221 unsigned long long alloc_size = 0;
4223 if (!S_ISDIR(stat->mode)) {
4224 if ((inode->i_blocks << 9) <= stat->size)
4225 alloc_size = stat->size;
4227 alloc_size = inode->i_blocks << 9;
4233 static void get_file_standard_info(struct smb2_query_info_rsp *rsp,
4234 struct ksmbd_file *fp, void *rsp_org)
4236 struct smb2_file_standard_info *sinfo;
4237 unsigned int delete_pending;
4238 struct inode *inode;
4241 inode = file_inode(fp->filp);
4242 generic_fillattr(file_mnt_user_ns(fp->filp), inode, &stat);
4244 sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
4245 delete_pending = ksmbd_inode_pending_delete(fp);
4247 sinfo->AllocationSize = cpu_to_le64(get_allocation_size(inode, &stat));
4248 sinfo->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4249 sinfo->NumberOfLinks = cpu_to_le32(get_nlink(&stat) - delete_pending);
4250 sinfo->DeletePending = delete_pending;
4251 sinfo->Directory = S_ISDIR(stat.mode) ? 1 : 0;
4252 rsp->OutputBufferLength =
4253 cpu_to_le32(sizeof(struct smb2_file_standard_info));
4254 inc_rfc1001_len(rsp_org,
4255 sizeof(struct smb2_file_standard_info));
4258 static void get_file_alignment_info(struct smb2_query_info_rsp *rsp,
4261 struct smb2_file_alignment_info *file_info;
4263 file_info = (struct smb2_file_alignment_info *)rsp->Buffer;
4264 file_info->AlignmentRequirement = 0;
4265 rsp->OutputBufferLength =
4266 cpu_to_le32(sizeof(struct smb2_file_alignment_info));
4267 inc_rfc1001_len(rsp_org,
4268 sizeof(struct smb2_file_alignment_info));
4271 static int get_file_all_info(struct ksmbd_work *work,
4272 struct smb2_query_info_rsp *rsp,
4273 struct ksmbd_file *fp,
4276 struct ksmbd_conn *conn = work->conn;
4277 struct smb2_file_all_info *file_info;
4278 unsigned int delete_pending;
4279 struct inode *inode;
4285 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4286 ksmbd_debug(SMB, "no right to read the attributes : 0x%x\n",
4291 filename = convert_to_nt_pathname(fp->filename,
4292 work->tcon->share_conf->path);
4296 inode = file_inode(fp->filp);
4297 generic_fillattr(file_mnt_user_ns(fp->filp), inode, &stat);
4299 ksmbd_debug(SMB, "filename = %s\n", filename);
4300 delete_pending = ksmbd_inode_pending_delete(fp);
4301 file_info = (struct smb2_file_all_info *)rsp->Buffer;
4303 file_info->CreationTime = cpu_to_le64(fp->create_time);
4304 time = ksmbd_UnixTimeToNT(stat.atime);
4305 file_info->LastAccessTime = cpu_to_le64(time);
4306 time = ksmbd_UnixTimeToNT(stat.mtime);
4307 file_info->LastWriteTime = cpu_to_le64(time);
4308 time = ksmbd_UnixTimeToNT(stat.ctime);
4309 file_info->ChangeTime = cpu_to_le64(time);
4310 file_info->Attributes = fp->f_ci->m_fattr;
4311 file_info->Pad1 = 0;
4312 file_info->AllocationSize =
4313 cpu_to_le64(get_allocation_size(inode, &stat));
4314 file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4315 file_info->NumberOfLinks =
4316 cpu_to_le32(get_nlink(&stat) - delete_pending);
4317 file_info->DeletePending = delete_pending;
4318 file_info->Directory = S_ISDIR(stat.mode) ? 1 : 0;
4319 file_info->Pad2 = 0;
4320 file_info->IndexNumber = cpu_to_le64(stat.ino);
4321 file_info->EASize = 0;
4322 file_info->AccessFlags = fp->daccess;
4323 file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
4324 file_info->Mode = fp->coption;
4325 file_info->AlignmentRequirement = 0;
4326 conv_len = smbConvertToUTF16((__le16 *)file_info->FileName, filename,
4327 PATH_MAX, conn->local_nls, 0);
4329 file_info->FileNameLength = cpu_to_le32(conv_len);
4330 rsp->OutputBufferLength =
4331 cpu_to_le32(sizeof(struct smb2_file_all_info) + conv_len - 1);
4333 inc_rfc1001_len(rsp_org, le32_to_cpu(rsp->OutputBufferLength));
4337 static void get_file_alternate_info(struct ksmbd_work *work,
4338 struct smb2_query_info_rsp *rsp,
4339 struct ksmbd_file *fp,
4342 struct ksmbd_conn *conn = work->conn;
4343 struct smb2_file_alt_name_info *file_info;
4344 struct dentry *dentry = fp->filp->f_path.dentry;
4347 spin_lock(&dentry->d_lock);
4348 file_info = (struct smb2_file_alt_name_info *)rsp->Buffer;
4349 conv_len = ksmbd_extract_shortname(conn,
4350 dentry->d_name.name,
4351 file_info->FileName);
4352 spin_unlock(&dentry->d_lock);
4353 file_info->FileNameLength = cpu_to_le32(conv_len);
4354 rsp->OutputBufferLength =
4355 cpu_to_le32(sizeof(struct smb2_file_alt_name_info) + conv_len);
4356 inc_rfc1001_len(rsp_org, le32_to_cpu(rsp->OutputBufferLength));
4359 static void get_file_stream_info(struct ksmbd_work *work,
4360 struct smb2_query_info_rsp *rsp,
4361 struct ksmbd_file *fp,
4364 struct ksmbd_conn *conn = work->conn;
4365 struct smb2_file_stream_info *file_info;
4366 char *stream_name, *xattr_list = NULL, *stream_buf;
4368 struct path *path = &fp->filp->f_path;
4369 ssize_t xattr_list_len;
4370 int nbytes = 0, streamlen, stream_name_len, next, idx = 0;
4372 generic_fillattr(file_mnt_user_ns(fp->filp), file_inode(fp->filp),
4374 file_info = (struct smb2_file_stream_info *)rsp->Buffer;
4376 xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
4377 if (xattr_list_len < 0) {
4379 } else if (!xattr_list_len) {
4380 ksmbd_debug(SMB, "empty xattr in the file\n");
4384 while (idx < xattr_list_len) {
4385 stream_name = xattr_list + idx;
4386 streamlen = strlen(stream_name);
4387 idx += streamlen + 1;
4389 ksmbd_debug(SMB, "%s, len %d\n", stream_name, streamlen);
4391 if (strncmp(&stream_name[XATTR_USER_PREFIX_LEN],
4392 STREAM_PREFIX, STREAM_PREFIX_LEN))
4395 stream_name_len = streamlen - (XATTR_USER_PREFIX_LEN +
4397 streamlen = stream_name_len;
4401 stream_buf = kmalloc(streamlen + 1, GFP_KERNEL);
4405 streamlen = snprintf(stream_buf, streamlen + 1,
4406 ":%s", &stream_name[XATTR_NAME_STREAM_LEN]);
4408 file_info = (struct smb2_file_stream_info *)&rsp->Buffer[nbytes];
4409 streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
4410 stream_buf, streamlen,
4411 conn->local_nls, 0);
4414 file_info->StreamNameLength = cpu_to_le32(streamlen);
4415 file_info->StreamSize = cpu_to_le64(stream_name_len);
4416 file_info->StreamAllocationSize = cpu_to_le64(stream_name_len);
4418 next = sizeof(struct smb2_file_stream_info) + streamlen;
4420 file_info->NextEntryOffset = cpu_to_le32(next);
4424 file_info = (struct smb2_file_stream_info *)
4425 &rsp->Buffer[nbytes];
4426 streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
4427 "::$DATA", 7, conn->local_nls, 0);
4429 file_info->StreamNameLength = cpu_to_le32(streamlen);
4430 file_info->StreamSize = S_ISDIR(stat.mode) ? 0 :
4431 cpu_to_le64(stat.size);
4432 file_info->StreamAllocationSize = S_ISDIR(stat.mode) ? 0 :
4433 cpu_to_le64(stat.size);
4434 nbytes += sizeof(struct smb2_file_stream_info) + streamlen;
4437 /* last entry offset should be 0 */
4438 file_info->NextEntryOffset = 0;
4442 rsp->OutputBufferLength = cpu_to_le32(nbytes);
4443 inc_rfc1001_len(rsp_org, nbytes);
4446 static void get_file_internal_info(struct smb2_query_info_rsp *rsp,
4447 struct ksmbd_file *fp, void *rsp_org)
4449 struct smb2_file_internal_info *file_info;
4452 generic_fillattr(file_mnt_user_ns(fp->filp), file_inode(fp->filp),
4454 file_info = (struct smb2_file_internal_info *)rsp->Buffer;
4455 file_info->IndexNumber = cpu_to_le64(stat.ino);
4456 rsp->OutputBufferLength =
4457 cpu_to_le32(sizeof(struct smb2_file_internal_info));
4458 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_internal_info));
4461 static int get_file_network_open_info(struct smb2_query_info_rsp *rsp,
4462 struct ksmbd_file *fp, void *rsp_org)
4464 struct smb2_file_ntwrk_info *file_info;
4465 struct inode *inode;
4469 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4470 pr_err("no right to read the attributes : 0x%x\n",
4475 file_info = (struct smb2_file_ntwrk_info *)rsp->Buffer;
4477 inode = file_inode(fp->filp);
4478 generic_fillattr(file_mnt_user_ns(fp->filp), inode, &stat);
4480 file_info->CreationTime = cpu_to_le64(fp->create_time);
4481 time = ksmbd_UnixTimeToNT(stat.atime);
4482 file_info->LastAccessTime = cpu_to_le64(time);
4483 time = ksmbd_UnixTimeToNT(stat.mtime);
4484 file_info->LastWriteTime = cpu_to_le64(time);
4485 time = ksmbd_UnixTimeToNT(stat.ctime);
4486 file_info->ChangeTime = cpu_to_le64(time);
4487 file_info->Attributes = fp->f_ci->m_fattr;
4488 file_info->AllocationSize =
4489 cpu_to_le64(get_allocation_size(inode, &stat));
4490 file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4491 file_info->Reserved = cpu_to_le32(0);
4492 rsp->OutputBufferLength =
4493 cpu_to_le32(sizeof(struct smb2_file_ntwrk_info));
4494 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_ntwrk_info));
4498 static void get_file_ea_info(struct smb2_query_info_rsp *rsp, void *rsp_org)
4500 struct smb2_file_ea_info *file_info;
4502 file_info = (struct smb2_file_ea_info *)rsp->Buffer;
4503 file_info->EASize = 0;
4504 rsp->OutputBufferLength =
4505 cpu_to_le32(sizeof(struct smb2_file_ea_info));
4506 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_ea_info));
4509 static void get_file_position_info(struct smb2_query_info_rsp *rsp,
4510 struct ksmbd_file *fp, void *rsp_org)
4512 struct smb2_file_pos_info *file_info;
4514 file_info = (struct smb2_file_pos_info *)rsp->Buffer;
4515 file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
4516 rsp->OutputBufferLength =
4517 cpu_to_le32(sizeof(struct smb2_file_pos_info));
4518 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_pos_info));
4521 static void get_file_mode_info(struct smb2_query_info_rsp *rsp,
4522 struct ksmbd_file *fp, void *rsp_org)
4524 struct smb2_file_mode_info *file_info;
4526 file_info = (struct smb2_file_mode_info *)rsp->Buffer;
4527 file_info->Mode = fp->coption & FILE_MODE_INFO_MASK;
4528 rsp->OutputBufferLength =
4529 cpu_to_le32(sizeof(struct smb2_file_mode_info));
4530 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_mode_info));
4533 static void get_file_compression_info(struct smb2_query_info_rsp *rsp,
4534 struct ksmbd_file *fp, void *rsp_org)
4536 struct smb2_file_comp_info *file_info;
4539 generic_fillattr(file_mnt_user_ns(fp->filp), file_inode(fp->filp),
4542 file_info = (struct smb2_file_comp_info *)rsp->Buffer;
4543 file_info->CompressedFileSize = cpu_to_le64(stat.blocks << 9);
4544 file_info->CompressionFormat = COMPRESSION_FORMAT_NONE;
4545 file_info->CompressionUnitShift = 0;
4546 file_info->ChunkShift = 0;
4547 file_info->ClusterShift = 0;
4548 memset(&file_info->Reserved[0], 0, 3);
4550 rsp->OutputBufferLength =
4551 cpu_to_le32(sizeof(struct smb2_file_comp_info));
4552 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_comp_info));
4555 static int get_file_attribute_tag_info(struct smb2_query_info_rsp *rsp,
4556 struct ksmbd_file *fp, void *rsp_org)
4558 struct smb2_file_attr_tag_info *file_info;
4560 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4561 pr_err("no right to read the attributes : 0x%x\n",
4566 file_info = (struct smb2_file_attr_tag_info *)rsp->Buffer;
4567 file_info->FileAttributes = fp->f_ci->m_fattr;
4568 file_info->ReparseTag = 0;
4569 rsp->OutputBufferLength =
4570 cpu_to_le32(sizeof(struct smb2_file_attr_tag_info));
4571 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_attr_tag_info));
4575 static int find_file_posix_info(struct smb2_query_info_rsp *rsp,
4576 struct ksmbd_file *fp, void *rsp_org)
4578 struct smb311_posix_qinfo *file_info;
4579 struct inode *inode = file_inode(fp->filp);
4582 file_info = (struct smb311_posix_qinfo *)rsp->Buffer;
4583 file_info->CreationTime = cpu_to_le64(fp->create_time);
4584 time = ksmbd_UnixTimeToNT(inode->i_atime);
4585 file_info->LastAccessTime = cpu_to_le64(time);
4586 time = ksmbd_UnixTimeToNT(inode->i_mtime);
4587 file_info->LastWriteTime = cpu_to_le64(time);
4588 time = ksmbd_UnixTimeToNT(inode->i_ctime);
4589 file_info->ChangeTime = cpu_to_le64(time);
4590 file_info->DosAttributes = fp->f_ci->m_fattr;
4591 file_info->Inode = cpu_to_le64(inode->i_ino);
4592 file_info->EndOfFile = cpu_to_le64(inode->i_size);
4593 file_info->AllocationSize = cpu_to_le64(inode->i_blocks << 9);
4594 file_info->HardLinks = cpu_to_le32(inode->i_nlink);
4595 file_info->Mode = cpu_to_le32(inode->i_mode);
4596 file_info->DeviceId = cpu_to_le32(inode->i_rdev);
4597 rsp->OutputBufferLength =
4598 cpu_to_le32(sizeof(struct smb311_posix_qinfo));
4599 inc_rfc1001_len(rsp_org, sizeof(struct smb311_posix_qinfo));
4603 static int smb2_get_info_file(struct ksmbd_work *work,
4604 struct smb2_query_info_req *req,
4605 struct smb2_query_info_rsp *rsp, void *rsp_org)
4607 struct ksmbd_file *fp;
4608 int fileinfoclass = 0;
4610 int file_infoclass_size;
4611 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
4613 if (test_share_config_flag(work->tcon->share_conf,
4614 KSMBD_SHARE_FLAG_PIPE)) {
4615 /* smb2 info file called for pipe */
4616 return smb2_get_info_file_pipe(work->sess, req, rsp);
4619 if (work->next_smb2_rcv_hdr_off) {
4620 if (!has_file_id(le64_to_cpu(req->VolatileFileId))) {
4621 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
4622 work->compound_fid);
4623 id = work->compound_fid;
4624 pid = work->compound_pfid;
4628 if (!has_file_id(id)) {
4629 id = le64_to_cpu(req->VolatileFileId);
4630 pid = le64_to_cpu(req->PersistentFileId);
4633 fp = ksmbd_lookup_fd_slow(work, id, pid);
4637 fileinfoclass = req->FileInfoClass;
4639 switch (fileinfoclass) {
4640 case FILE_ACCESS_INFORMATION:
4641 get_file_access_info(rsp, fp, rsp_org);
4642 file_infoclass_size = FILE_ACCESS_INFORMATION_SIZE;
4645 case FILE_BASIC_INFORMATION:
4646 rc = get_file_basic_info(rsp, fp, rsp_org);
4647 file_infoclass_size = FILE_BASIC_INFORMATION_SIZE;
4650 case FILE_STANDARD_INFORMATION:
4651 get_file_standard_info(rsp, fp, rsp_org);
4652 file_infoclass_size = FILE_STANDARD_INFORMATION_SIZE;
4655 case FILE_ALIGNMENT_INFORMATION:
4656 get_file_alignment_info(rsp, rsp_org);
4657 file_infoclass_size = FILE_ALIGNMENT_INFORMATION_SIZE;
4660 case FILE_ALL_INFORMATION:
4661 rc = get_file_all_info(work, rsp, fp, rsp_org);
4662 file_infoclass_size = FILE_ALL_INFORMATION_SIZE;
4665 case FILE_ALTERNATE_NAME_INFORMATION:
4666 get_file_alternate_info(work, rsp, fp, rsp_org);
4667 file_infoclass_size = FILE_ALTERNATE_NAME_INFORMATION_SIZE;
4670 case FILE_STREAM_INFORMATION:
4671 get_file_stream_info(work, rsp, fp, rsp_org);
4672 file_infoclass_size = FILE_STREAM_INFORMATION_SIZE;
4675 case FILE_INTERNAL_INFORMATION:
4676 get_file_internal_info(rsp, fp, rsp_org);
4677 file_infoclass_size = FILE_INTERNAL_INFORMATION_SIZE;
4680 case FILE_NETWORK_OPEN_INFORMATION:
4681 rc = get_file_network_open_info(rsp, fp, rsp_org);
4682 file_infoclass_size = FILE_NETWORK_OPEN_INFORMATION_SIZE;
4685 case FILE_EA_INFORMATION:
4686 get_file_ea_info(rsp, rsp_org);
4687 file_infoclass_size = FILE_EA_INFORMATION_SIZE;
4690 case FILE_FULL_EA_INFORMATION:
4691 rc = smb2_get_ea(work, fp, req, rsp, rsp_org);
4692 file_infoclass_size = FILE_FULL_EA_INFORMATION_SIZE;
4695 case FILE_POSITION_INFORMATION:
4696 get_file_position_info(rsp, fp, rsp_org);
4697 file_infoclass_size = FILE_POSITION_INFORMATION_SIZE;
4700 case FILE_MODE_INFORMATION:
4701 get_file_mode_info(rsp, fp, rsp_org);
4702 file_infoclass_size = FILE_MODE_INFORMATION_SIZE;
4705 case FILE_COMPRESSION_INFORMATION:
4706 get_file_compression_info(rsp, fp, rsp_org);
4707 file_infoclass_size = FILE_COMPRESSION_INFORMATION_SIZE;
4710 case FILE_ATTRIBUTE_TAG_INFORMATION:
4711 rc = get_file_attribute_tag_info(rsp, fp, rsp_org);
4712 file_infoclass_size = FILE_ATTRIBUTE_TAG_INFORMATION_SIZE;
4714 case SMB_FIND_FILE_POSIX_INFO:
4715 if (!work->tcon->posix_extensions) {
4716 pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
4719 rc = find_file_posix_info(rsp, fp, rsp_org);
4720 file_infoclass_size = sizeof(struct smb311_posix_qinfo);
4724 ksmbd_debug(SMB, "fileinfoclass %d not supported yet\n",
4729 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4731 file_infoclass_size);
4732 ksmbd_fd_put(work, fp);
4736 static int smb2_get_info_filesystem(struct ksmbd_work *work,
4737 struct smb2_query_info_req *req,
4738 struct smb2_query_info_rsp *rsp, void *rsp_org)
4740 struct ksmbd_session *sess = work->sess;
4741 struct ksmbd_conn *conn = sess->conn;
4742 struct ksmbd_share_config *share = work->tcon->share_conf;
4743 int fsinfoclass = 0;
4744 struct kstatfs stfs;
4747 int fs_infoclass_size = 0;
4748 int lookup_flags = 0;
4750 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_FOLLOW_SYMLINKS))
4751 lookup_flags = LOOKUP_FOLLOW;
4753 rc = ksmbd_vfs_kern_path(share->path, lookup_flags, &path, 0);
4755 pr_err("cannot create vfs path\n");
4759 rc = vfs_statfs(&path, &stfs);
4761 pr_err("cannot do stat of path %s\n", share->path);
4766 fsinfoclass = req->FileInfoClass;
4768 switch (fsinfoclass) {
4769 case FS_DEVICE_INFORMATION:
4771 struct filesystem_device_info *info;
4773 info = (struct filesystem_device_info *)rsp->Buffer;
4775 info->DeviceType = cpu_to_le32(stfs.f_type);
4776 info->DeviceCharacteristics = cpu_to_le32(0x00000020);
4777 rsp->OutputBufferLength = cpu_to_le32(8);
4778 inc_rfc1001_len(rsp_org, 8);
4779 fs_infoclass_size = FS_DEVICE_INFORMATION_SIZE;
4782 case FS_ATTRIBUTE_INFORMATION:
4784 struct filesystem_attribute_info *info;
4787 info = (struct filesystem_attribute_info *)rsp->Buffer;
4788 info->Attributes = cpu_to_le32(FILE_SUPPORTS_OBJECT_IDS |
4789 FILE_PERSISTENT_ACLS |
4790 FILE_UNICODE_ON_DISK |
4791 FILE_CASE_PRESERVED_NAMES |
4792 FILE_CASE_SENSITIVE_SEARCH |
4793 FILE_SUPPORTS_BLOCK_REFCOUNTING);
4795 info->Attributes |= cpu_to_le32(server_conf.share_fake_fscaps);
4797 info->MaxPathNameComponentLength = cpu_to_le32(stfs.f_namelen);
4798 len = smbConvertToUTF16((__le16 *)info->FileSystemName,
4799 "NTFS", PATH_MAX, conn->local_nls, 0);
4801 info->FileSystemNameLen = cpu_to_le32(len);
4802 sz = sizeof(struct filesystem_attribute_info) - 2 + len;
4803 rsp->OutputBufferLength = cpu_to_le32(sz);
4804 inc_rfc1001_len(rsp_org, sz);
4805 fs_infoclass_size = FS_ATTRIBUTE_INFORMATION_SIZE;
4808 case FS_VOLUME_INFORMATION:
4810 struct filesystem_vol_info *info;
4813 info = (struct filesystem_vol_info *)(rsp->Buffer);
4814 info->VolumeCreationTime = 0;
4815 /* Taking dummy value of serial number*/
4816 info->SerialNumber = cpu_to_le32(0xbc3ac512);
4817 len = smbConvertToUTF16((__le16 *)info->VolumeLabel,
4818 share->name, PATH_MAX,
4819 conn->local_nls, 0);
4821 info->VolumeLabelSize = cpu_to_le32(len);
4823 sz = sizeof(struct filesystem_vol_info) - 2 + len;
4824 rsp->OutputBufferLength = cpu_to_le32(sz);
4825 inc_rfc1001_len(rsp_org, sz);
4826 fs_infoclass_size = FS_VOLUME_INFORMATION_SIZE;
4829 case FS_SIZE_INFORMATION:
4831 struct filesystem_info *info;
4833 info = (struct filesystem_info *)(rsp->Buffer);
4834 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
4835 info->FreeAllocationUnits = cpu_to_le64(stfs.f_bfree);
4836 info->SectorsPerAllocationUnit = cpu_to_le32(1);
4837 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
4838 rsp->OutputBufferLength = cpu_to_le32(24);
4839 inc_rfc1001_len(rsp_org, 24);
4840 fs_infoclass_size = FS_SIZE_INFORMATION_SIZE;
4843 case FS_FULL_SIZE_INFORMATION:
4845 struct smb2_fs_full_size_info *info;
4847 info = (struct smb2_fs_full_size_info *)(rsp->Buffer);
4848 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
4849 info->CallerAvailableAllocationUnits =
4850 cpu_to_le64(stfs.f_bavail);
4851 info->ActualAvailableAllocationUnits =
4852 cpu_to_le64(stfs.f_bfree);
4853 info->SectorsPerAllocationUnit = cpu_to_le32(1);
4854 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
4855 rsp->OutputBufferLength = cpu_to_le32(32);
4856 inc_rfc1001_len(rsp_org, 32);
4857 fs_infoclass_size = FS_FULL_SIZE_INFORMATION_SIZE;
4860 case FS_OBJECT_ID_INFORMATION:
4862 struct object_id_info *info;
4864 info = (struct object_id_info *)(rsp->Buffer);
4866 if (!user_guest(sess->user))
4867 memcpy(info->objid, user_passkey(sess->user), 16);
4869 memset(info->objid, 0, 16);
4871 info->extended_info.magic = cpu_to_le32(EXTENDED_INFO_MAGIC);
4872 info->extended_info.version = cpu_to_le32(1);
4873 info->extended_info.release = cpu_to_le32(1);
4874 info->extended_info.rel_date = 0;
4875 memcpy(info->extended_info.version_string, "1.1.0", strlen("1.1.0"));
4876 rsp->OutputBufferLength = cpu_to_le32(64);
4877 inc_rfc1001_len(rsp_org, 64);
4878 fs_infoclass_size = FS_OBJECT_ID_INFORMATION_SIZE;
4881 case FS_SECTOR_SIZE_INFORMATION:
4883 struct smb3_fs_ss_info *info;
4885 info = (struct smb3_fs_ss_info *)(rsp->Buffer);
4887 info->LogicalBytesPerSector = cpu_to_le32(stfs.f_bsize);
4888 info->PhysicalBytesPerSectorForAtomicity =
4889 cpu_to_le32(stfs.f_bsize);
4890 info->PhysicalBytesPerSectorForPerf = cpu_to_le32(stfs.f_bsize);
4891 info->FSEffPhysicalBytesPerSectorForAtomicity =
4892 cpu_to_le32(stfs.f_bsize);
4893 info->Flags = cpu_to_le32(SSINFO_FLAGS_ALIGNED_DEVICE |
4894 SSINFO_FLAGS_PARTITION_ALIGNED_ON_DEVICE);
4895 info->ByteOffsetForSectorAlignment = 0;
4896 info->ByteOffsetForPartitionAlignment = 0;
4897 rsp->OutputBufferLength = cpu_to_le32(28);
4898 inc_rfc1001_len(rsp_org, 28);
4899 fs_infoclass_size = FS_SECTOR_SIZE_INFORMATION_SIZE;
4902 case FS_CONTROL_INFORMATION:
4905 * TODO : The current implementation is based on
4906 * test result with win7(NTFS) server. It's need to
4907 * modify this to get valid Quota values
4910 struct smb2_fs_control_info *info;
4912 info = (struct smb2_fs_control_info *)(rsp->Buffer);
4913 info->FreeSpaceStartFiltering = 0;
4914 info->FreeSpaceThreshold = 0;
4915 info->FreeSpaceStopFiltering = 0;
4916 info->DefaultQuotaThreshold = cpu_to_le64(SMB2_NO_FID);
4917 info->DefaultQuotaLimit = cpu_to_le64(SMB2_NO_FID);
4919 rsp->OutputBufferLength = cpu_to_le32(48);
4920 inc_rfc1001_len(rsp_org, 48);
4921 fs_infoclass_size = FS_CONTROL_INFORMATION_SIZE;
4924 case FS_POSIX_INFORMATION:
4926 struct filesystem_posix_info *info;
4928 if (!work->tcon->posix_extensions) {
4929 pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
4932 info = (struct filesystem_posix_info *)(rsp->Buffer);
4933 info->OptimalTransferSize = cpu_to_le32(stfs.f_bsize);
4934 info->BlockSize = cpu_to_le32(stfs.f_bsize);
4935 info->TotalBlocks = cpu_to_le64(stfs.f_blocks);
4936 info->BlocksAvail = cpu_to_le64(stfs.f_bfree);
4937 info->UserBlocksAvail = cpu_to_le64(stfs.f_bavail);
4938 info->TotalFileNodes = cpu_to_le64(stfs.f_files);
4939 info->FreeFileNodes = cpu_to_le64(stfs.f_ffree);
4940 rsp->OutputBufferLength = cpu_to_le32(56);
4941 inc_rfc1001_len(rsp_org, 56);
4942 fs_infoclass_size = FS_POSIX_INFORMATION_SIZE;
4950 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4957 static int smb2_get_info_sec(struct ksmbd_work *work,
4958 struct smb2_query_info_req *req,
4959 struct smb2_query_info_rsp *rsp, void *rsp_org)
4961 struct ksmbd_file *fp;
4962 struct user_namespace *user_ns;
4963 struct smb_ntsd *pntsd = (struct smb_ntsd *)rsp->Buffer, *ppntsd = NULL;
4964 struct smb_fattr fattr = {{0}};
4965 struct inode *inode;
4967 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
4968 int addition_info = le32_to_cpu(req->AdditionalInformation);
4971 if (addition_info & ~(OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO |
4972 PROTECTED_DACL_SECINFO |
4973 UNPROTECTED_DACL_SECINFO)) {
4974 pr_err("Unsupported addition info: 0x%x)\n",
4977 pntsd->revision = cpu_to_le16(1);
4978 pntsd->type = cpu_to_le16(SELF_RELATIVE | DACL_PROTECTED);
4979 pntsd->osidoffset = 0;
4980 pntsd->gsidoffset = 0;
4981 pntsd->sacloffset = 0;
4982 pntsd->dacloffset = 0;
4984 secdesclen = sizeof(struct smb_ntsd);
4985 rsp->OutputBufferLength = cpu_to_le32(secdesclen);
4986 inc_rfc1001_len(rsp_org, secdesclen);
4991 if (work->next_smb2_rcv_hdr_off) {
4992 if (!has_file_id(le64_to_cpu(req->VolatileFileId))) {
4993 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
4994 work->compound_fid);
4995 id = work->compound_fid;
4996 pid = work->compound_pfid;
5000 if (!has_file_id(id)) {
5001 id = le64_to_cpu(req->VolatileFileId);
5002 pid = le64_to_cpu(req->PersistentFileId);
5005 fp = ksmbd_lookup_fd_slow(work, id, pid);
5009 user_ns = file_mnt_user_ns(fp->filp);
5010 inode = file_inode(fp->filp);
5011 ksmbd_acls_fattr(&fattr, user_ns, inode);
5013 if (test_share_config_flag(work->tcon->share_conf,
5014 KSMBD_SHARE_FLAG_ACL_XATTR))
5015 ksmbd_vfs_get_sd_xattr(work->conn, user_ns,
5016 fp->filp->f_path.dentry, &ppntsd);
5018 rc = build_sec_desc(user_ns, pntsd, ppntsd, addition_info,
5019 &secdesclen, &fattr);
5020 posix_acl_release(fattr.cf_acls);
5021 posix_acl_release(fattr.cf_dacls);
5023 ksmbd_fd_put(work, fp);
5027 rsp->OutputBufferLength = cpu_to_le32(secdesclen);
5028 inc_rfc1001_len(rsp_org, secdesclen);
5033 * smb2_query_info() - handler for smb2 query info command
5034 * @work: smb work containing query info request buffer
5036 * Return: 0 on success, otherwise error
5038 int smb2_query_info(struct ksmbd_work *work)
5040 struct smb2_query_info_req *req;
5041 struct smb2_query_info_rsp *rsp, *rsp_org;
5044 rsp_org = work->response_buf;
5045 WORK_BUFFERS(work, req, rsp);
5047 ksmbd_debug(SMB, "GOT query info request\n");
5049 switch (req->InfoType) {
5050 case SMB2_O_INFO_FILE:
5051 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
5052 rc = smb2_get_info_file(work, req, rsp, (void *)rsp_org);
5054 case SMB2_O_INFO_FILESYSTEM:
5055 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILESYSTEM\n");
5056 rc = smb2_get_info_filesystem(work, req, rsp, (void *)rsp_org);
5058 case SMB2_O_INFO_SECURITY:
5059 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
5060 rc = smb2_get_info_sec(work, req, rsp, (void *)rsp_org);
5063 ksmbd_debug(SMB, "InfoType %d not supported yet\n",
5070 rsp->hdr.Status = STATUS_ACCESS_DENIED;
5071 else if (rc == -ENOENT)
5072 rsp->hdr.Status = STATUS_FILE_CLOSED;
5073 else if (rc == -EIO)
5074 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
5075 else if (rc == -EOPNOTSUPP || rsp->hdr.Status == 0)
5076 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
5077 smb2_set_err_rsp(work);
5079 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n",
5083 rsp->StructureSize = cpu_to_le16(9);
5084 rsp->OutputBufferOffset = cpu_to_le16(72);
5085 inc_rfc1001_len(rsp_org, 8);
5090 * smb2_close_pipe() - handler for closing IPC pipe
5091 * @work: smb work containing close request buffer
5095 static noinline int smb2_close_pipe(struct ksmbd_work *work)
5098 struct smb2_close_req *req = work->request_buf;
5099 struct smb2_close_rsp *rsp = work->response_buf;
5101 id = le64_to_cpu(req->VolatileFileId);
5102 ksmbd_session_rpc_close(work->sess, id);
5104 rsp->StructureSize = cpu_to_le16(60);
5107 rsp->CreationTime = 0;
5108 rsp->LastAccessTime = 0;
5109 rsp->LastWriteTime = 0;
5110 rsp->ChangeTime = 0;
5111 rsp->AllocationSize = 0;
5113 rsp->Attributes = 0;
5114 inc_rfc1001_len(rsp, 60);
5119 * smb2_close() - handler for smb2 close file command
5120 * @work: smb work containing close request buffer
5124 int smb2_close(struct ksmbd_work *work)
5126 u64 volatile_id = KSMBD_NO_FID;
5128 struct smb2_close_req *req;
5129 struct smb2_close_rsp *rsp;
5130 struct smb2_close_rsp *rsp_org;
5131 struct ksmbd_conn *conn = work->conn;
5132 struct ksmbd_file *fp;
5133 struct inode *inode;
5137 rsp_org = work->response_buf;
5138 WORK_BUFFERS(work, req, rsp);
5140 if (test_share_config_flag(work->tcon->share_conf,
5141 KSMBD_SHARE_FLAG_PIPE)) {
5142 ksmbd_debug(SMB, "IPC pipe close request\n");
5143 return smb2_close_pipe(work);
5146 sess_id = le64_to_cpu(req->hdr.SessionId);
5147 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5148 sess_id = work->compound_sid;
5150 work->compound_sid = 0;
5151 if (check_session_id(conn, sess_id)) {
5152 work->compound_sid = sess_id;
5154 rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
5155 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5156 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
5161 if (work->next_smb2_rcv_hdr_off &&
5162 !has_file_id(le64_to_cpu(req->VolatileFileId))) {
5163 if (!has_file_id(work->compound_fid)) {
5164 /* file already closed, return FILE_CLOSED */
5165 ksmbd_debug(SMB, "file already closed\n");
5166 rsp->hdr.Status = STATUS_FILE_CLOSED;
5171 "Compound request set FID = %llu:%llu\n",
5173 work->compound_pfid);
5174 volatile_id = work->compound_fid;
5176 /* file closed, stored id is not valid anymore */
5177 work->compound_fid = KSMBD_NO_FID;
5178 work->compound_pfid = KSMBD_NO_FID;
5181 volatile_id = le64_to_cpu(req->VolatileFileId);
5183 ksmbd_debug(SMB, "volatile_id = %llu\n", volatile_id);
5185 rsp->StructureSize = cpu_to_le16(60);
5188 if (req->Flags == SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB) {
5189 fp = ksmbd_lookup_fd_fast(work, volatile_id);
5195 inode = file_inode(fp->filp);
5196 rsp->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB;
5197 rsp->AllocationSize = S_ISDIR(inode->i_mode) ? 0 :
5198 cpu_to_le64(inode->i_blocks << 9);
5199 rsp->EndOfFile = cpu_to_le64(inode->i_size);
5200 rsp->Attributes = fp->f_ci->m_fattr;
5201 rsp->CreationTime = cpu_to_le64(fp->create_time);
5202 time = ksmbd_UnixTimeToNT(inode->i_atime);
5203 rsp->LastAccessTime = cpu_to_le64(time);
5204 time = ksmbd_UnixTimeToNT(inode->i_mtime);
5205 rsp->LastWriteTime = cpu_to_le64(time);
5206 time = ksmbd_UnixTimeToNT(inode->i_ctime);
5207 rsp->ChangeTime = cpu_to_le64(time);
5208 ksmbd_fd_put(work, fp);
5211 rsp->AllocationSize = 0;
5213 rsp->Attributes = 0;
5214 rsp->CreationTime = 0;
5215 rsp->LastAccessTime = 0;
5216 rsp->LastWriteTime = 0;
5217 rsp->ChangeTime = 0;
5220 err = ksmbd_close_fd(work, volatile_id);
5223 if (rsp->hdr.Status == 0)
5224 rsp->hdr.Status = STATUS_FILE_CLOSED;
5225 smb2_set_err_rsp(work);
5227 inc_rfc1001_len(rsp_org, 60);
5234 * smb2_echo() - handler for smb2 echo(ping) command
5235 * @work: smb work containing echo request buffer
5239 int smb2_echo(struct ksmbd_work *work)
5241 struct smb2_echo_rsp *rsp = work->response_buf;
5243 rsp->StructureSize = cpu_to_le16(4);
5245 inc_rfc1001_len(rsp, 4);
5249 static int smb2_rename(struct ksmbd_work *work,
5250 struct ksmbd_file *fp,
5251 struct user_namespace *user_ns,
5252 struct smb2_file_rename_info *file_info,
5253 struct nls_table *local_nls)
5255 struct ksmbd_share_config *share = fp->tcon->share_conf;
5256 char *new_name = NULL, *abs_oldname = NULL, *old_name = NULL;
5257 char *pathname = NULL;
5259 bool file_present = true;
5262 ksmbd_debug(SMB, "setting FILE_RENAME_INFO\n");
5263 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
5267 abs_oldname = d_path(&fp->filp->f_path, pathname, PATH_MAX);
5268 if (IS_ERR(abs_oldname)) {
5272 old_name = strrchr(abs_oldname, '/');
5273 if (old_name && old_name[1] != '\0') {
5276 ksmbd_debug(SMB, "can't get last component in path %s\n",
5282 new_name = smb2_get_name(share,
5283 file_info->FileName,
5284 le32_to_cpu(file_info->FileNameLength),
5286 if (IS_ERR(new_name)) {
5287 rc = PTR_ERR(new_name);
5291 if (strchr(new_name, ':')) {
5293 char *xattr_stream_name, *stream_name = NULL;
5294 size_t xattr_stream_size;
5297 rc = parse_stream_name(new_name, &stream_name, &s_type);
5301 len = strlen(new_name);
5302 if (new_name[len - 1] != '/') {
5303 pr_err("not allow base filename in rename\n");
5308 rc = ksmbd_vfs_xattr_stream_name(stream_name,
5315 rc = ksmbd_vfs_setxattr(user_ns,
5316 fp->filp->f_path.dentry,
5320 pr_err("failed to store stream name in xattr: %d\n",
5329 ksmbd_debug(SMB, "new name %s\n", new_name);
5330 rc = ksmbd_vfs_kern_path(new_name, 0, &path, 1);
5332 file_present = false;
5336 if (ksmbd_share_veto_filename(share, new_name)) {
5338 ksmbd_debug(SMB, "Can't rename vetoed file: %s\n", new_name);
5342 if (file_info->ReplaceIfExists) {
5344 rc = ksmbd_vfs_remove_file(work, new_name);
5346 if (rc != -ENOTEMPTY)
5348 ksmbd_debug(SMB, "cannot delete %s, rc %d\n",
5355 strncmp(old_name, path.dentry->d_name.name, strlen(old_name))) {
5358 "cannot rename already existing file\n");
5363 rc = ksmbd_vfs_fp_rename(work, fp, new_name);
5366 if (!IS_ERR(new_name))
5371 static int smb2_create_link(struct ksmbd_work *work,
5372 struct ksmbd_share_config *share,
5373 struct smb2_file_link_info *file_info,
5375 struct nls_table *local_nls)
5377 char *link_name = NULL, *target_name = NULL, *pathname = NULL;
5379 bool file_present = true;
5382 ksmbd_debug(SMB, "setting FILE_LINK_INFORMATION\n");
5383 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
5387 link_name = smb2_get_name(share,
5388 file_info->FileName,
5389 le32_to_cpu(file_info->FileNameLength),
5391 if (IS_ERR(link_name) || S_ISDIR(file_inode(filp)->i_mode)) {
5396 ksmbd_debug(SMB, "link name is %s\n", link_name);
5397 target_name = d_path(&filp->f_path, pathname, PATH_MAX);
5398 if (IS_ERR(target_name)) {
5403 ksmbd_debug(SMB, "target name is %s\n", target_name);
5404 rc = ksmbd_vfs_kern_path(link_name, 0, &path, 0);
5406 file_present = false;
5410 if (file_info->ReplaceIfExists) {
5412 rc = ksmbd_vfs_remove_file(work, link_name);
5415 ksmbd_debug(SMB, "cannot delete %s\n",
5423 ksmbd_debug(SMB, "link already exists\n");
5428 rc = ksmbd_vfs_link(work, target_name, link_name);
5432 if (!IS_ERR(link_name))
5438 static int set_file_basic_info(struct ksmbd_file *fp, char *buf,
5439 struct ksmbd_share_config *share)
5441 struct smb2_file_all_info *file_info;
5443 struct timespec64 ctime;
5445 struct inode *inode;
5446 struct user_namespace *user_ns;
5449 if (!(fp->daccess & FILE_WRITE_ATTRIBUTES_LE))
5452 file_info = (struct smb2_file_all_info *)buf;
5455 inode = file_inode(filp);
5456 user_ns = file_mnt_user_ns(filp);
5458 if (file_info->CreationTime)
5459 fp->create_time = le64_to_cpu(file_info->CreationTime);
5461 if (file_info->LastAccessTime) {
5462 attrs.ia_atime = ksmbd_NTtimeToUnix(file_info->LastAccessTime);
5463 attrs.ia_valid |= (ATTR_ATIME | ATTR_ATIME_SET);
5466 if (file_info->ChangeTime) {
5467 attrs.ia_ctime = ksmbd_NTtimeToUnix(file_info->ChangeTime);
5468 ctime = attrs.ia_ctime;
5469 attrs.ia_valid |= ATTR_CTIME;
5471 ctime = inode->i_ctime;
5474 if (file_info->LastWriteTime) {
5475 attrs.ia_mtime = ksmbd_NTtimeToUnix(file_info->LastWriteTime);
5476 attrs.ia_valid |= (ATTR_MTIME | ATTR_MTIME_SET);
5479 if (file_info->Attributes) {
5480 if (!S_ISDIR(inode->i_mode) &&
5481 file_info->Attributes & ATTR_DIRECTORY_LE) {
5482 pr_err("can't change a file to a directory\n");
5486 if (!(S_ISDIR(inode->i_mode) && file_info->Attributes == ATTR_NORMAL_LE))
5487 fp->f_ci->m_fattr = file_info->Attributes |
5488 (fp->f_ci->m_fattr & ATTR_DIRECTORY_LE);
5491 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_STORE_DOS_ATTRS) &&
5492 (file_info->CreationTime || file_info->Attributes)) {
5493 struct xattr_dos_attrib da = {0};
5496 da.itime = fp->itime;
5497 da.create_time = fp->create_time;
5498 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
5499 da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
5500 XATTR_DOSINFO_ITIME;
5502 rc = ksmbd_vfs_set_dos_attrib_xattr(user_ns,
5503 filp->f_path.dentry, &da);
5506 "failed to restore file attribute in EA\n");
5510 if (attrs.ia_valid) {
5511 struct dentry *dentry = filp->f_path.dentry;
5512 struct inode *inode = d_inode(dentry);
5514 if (IS_IMMUTABLE(inode) || IS_APPEND(inode))
5518 rc = notify_change(user_ns, dentry, &attrs, NULL);
5520 inode->i_ctime = ctime;
5521 mark_inode_dirty(inode);
5523 inode_unlock(inode);
5528 static int set_file_allocation_info(struct ksmbd_work *work,
5529 struct ksmbd_file *fp, char *buf)
5532 * TODO : It's working fine only when store dos attributes
5533 * is not yes. need to implement a logic which works
5534 * properly with any smb.conf option
5537 struct smb2_file_alloc_info *file_alloc_info;
5539 struct inode *inode;
5542 if (!(fp->daccess & FILE_WRITE_DATA_LE))
5545 file_alloc_info = (struct smb2_file_alloc_info *)buf;
5546 alloc_blks = (le64_to_cpu(file_alloc_info->AllocationSize) + 511) >> 9;
5547 inode = file_inode(fp->filp);
5549 if (alloc_blks > inode->i_blocks) {
5550 smb_break_all_levII_oplock(work, fp, 1);
5551 rc = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
5553 if (rc && rc != -EOPNOTSUPP) {
5554 pr_err("vfs_fallocate is failed : %d\n", rc);
5557 } else if (alloc_blks < inode->i_blocks) {
5561 * Allocation size could be smaller than original one
5562 * which means allocated blocks in file should be
5563 * deallocated. use truncate to cut out it, but inode
5564 * size is also updated with truncate offset.
5565 * inode size is retained by backup inode size.
5567 size = i_size_read(inode);
5568 rc = ksmbd_vfs_truncate(work, NULL, fp, alloc_blks * 512);
5570 pr_err("truncate failed! filename : %s, err %d\n",
5574 if (size < alloc_blks * 512)
5575 i_size_write(inode, size);
5580 static int set_end_of_file_info(struct ksmbd_work *work, struct ksmbd_file *fp,
5583 struct smb2_file_eof_info *file_eof_info;
5585 struct inode *inode;
5588 if (!(fp->daccess & FILE_WRITE_DATA_LE))
5591 file_eof_info = (struct smb2_file_eof_info *)buf;
5592 newsize = le64_to_cpu(file_eof_info->EndOfFile);
5593 inode = file_inode(fp->filp);
5596 * If FILE_END_OF_FILE_INFORMATION of set_info_file is called
5597 * on FAT32 shared device, truncate execution time is too long
5598 * and network error could cause from windows client. because
5599 * truncate of some filesystem like FAT32 fill zero data in
5602 if (inode->i_sb->s_magic != MSDOS_SUPER_MAGIC) {
5603 ksmbd_debug(SMB, "filename : %s truncated to newsize %lld\n",
5604 fp->filename, newsize);
5605 rc = ksmbd_vfs_truncate(work, NULL, fp, newsize);
5607 ksmbd_debug(SMB, "truncate failed! filename : %s err %d\n",
5617 static int set_rename_info(struct ksmbd_work *work, struct ksmbd_file *fp,
5620 struct user_namespace *user_ns;
5621 struct ksmbd_file *parent_fp;
5622 struct dentry *parent;
5623 struct dentry *dentry = fp->filp->f_path.dentry;
5626 if (!(fp->daccess & FILE_DELETE_LE)) {
5627 pr_err("no right to delete : 0x%x\n", fp->daccess);
5631 user_ns = file_mnt_user_ns(fp->filp);
5632 if (ksmbd_stream_fd(fp))
5635 parent = dget_parent(dentry);
5636 ret = ksmbd_vfs_lock_parent(user_ns, parent, dentry);
5642 parent_fp = ksmbd_lookup_fd_inode(d_inode(parent));
5643 inode_unlock(d_inode(parent));
5647 if (parent_fp->daccess & FILE_DELETE_LE) {
5648 pr_err("parent dir is opened with delete access\n");
5653 return smb2_rename(work, fp, user_ns,
5654 (struct smb2_file_rename_info *)buf,
5655 work->sess->conn->local_nls);
5658 static int set_file_disposition_info(struct ksmbd_file *fp, char *buf)
5660 struct smb2_file_disposition_info *file_info;
5661 struct inode *inode;
5663 if (!(fp->daccess & FILE_DELETE_LE)) {
5664 pr_err("no right to delete : 0x%x\n", fp->daccess);
5668 inode = file_inode(fp->filp);
5669 file_info = (struct smb2_file_disposition_info *)buf;
5670 if (file_info->DeletePending) {
5671 if (S_ISDIR(inode->i_mode) &&
5672 ksmbd_vfs_empty_dir(fp) == -ENOTEMPTY)
5674 ksmbd_set_inode_pending_delete(fp);
5676 ksmbd_clear_inode_pending_delete(fp);
5681 static int set_file_position_info(struct ksmbd_file *fp, char *buf)
5683 struct smb2_file_pos_info *file_info;
5684 loff_t current_byte_offset;
5685 unsigned long sector_size;
5686 struct inode *inode;
5688 inode = file_inode(fp->filp);
5689 file_info = (struct smb2_file_pos_info *)buf;
5690 current_byte_offset = le64_to_cpu(file_info->CurrentByteOffset);
5691 sector_size = inode->i_sb->s_blocksize;
5693 if (current_byte_offset < 0 ||
5694 (fp->coption == FILE_NO_INTERMEDIATE_BUFFERING_LE &&
5695 current_byte_offset & (sector_size - 1))) {
5696 pr_err("CurrentByteOffset is not valid : %llu\n",
5697 current_byte_offset);
5701 fp->filp->f_pos = current_byte_offset;
5705 static int set_file_mode_info(struct ksmbd_file *fp, char *buf)
5707 struct smb2_file_mode_info *file_info;
5710 file_info = (struct smb2_file_mode_info *)buf;
5711 mode = file_info->Mode;
5713 if ((mode & ~FILE_MODE_INFO_MASK) ||
5714 (mode & FILE_SYNCHRONOUS_IO_ALERT_LE &&
5715 mode & FILE_SYNCHRONOUS_IO_NONALERT_LE)) {
5716 pr_err("Mode is not valid : 0x%x\n", le32_to_cpu(mode));
5721 * TODO : need to implement consideration for
5722 * FILE_SYNCHRONOUS_IO_ALERT and FILE_SYNCHRONOUS_IO_NONALERT
5724 ksmbd_vfs_set_fadvise(fp->filp, mode);
5730 * smb2_set_info_file() - handler for smb2 set info command
5731 * @work: smb work containing set info command buffer
5732 * @fp: ksmbd_file pointer
5733 * @info_class: smb2 set info class
5734 * @share: ksmbd_share_config pointer
5736 * Return: 0 on success, otherwise error
5737 * TODO: need to implement an error handling for STATUS_INFO_LENGTH_MISMATCH
5739 static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp,
5740 int info_class, char *buf,
5741 struct ksmbd_share_config *share)
5743 switch (info_class) {
5744 case FILE_BASIC_INFORMATION:
5745 return set_file_basic_info(fp, buf, share);
5747 case FILE_ALLOCATION_INFORMATION:
5748 return set_file_allocation_info(work, fp, buf);
5750 case FILE_END_OF_FILE_INFORMATION:
5751 return set_end_of_file_info(work, fp, buf);
5753 case FILE_RENAME_INFORMATION:
5754 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
5756 "User does not have write permission\n");
5759 return set_rename_info(work, fp, buf);
5761 case FILE_LINK_INFORMATION:
5762 return smb2_create_link(work, work->tcon->share_conf,
5763 (struct smb2_file_link_info *)buf, fp->filp,
5764 work->sess->conn->local_nls);
5766 case FILE_DISPOSITION_INFORMATION:
5767 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
5769 "User does not have write permission\n");
5772 return set_file_disposition_info(fp, buf);
5774 case FILE_FULL_EA_INFORMATION:
5776 if (!(fp->daccess & FILE_WRITE_EA_LE)) {
5777 pr_err("Not permitted to write ext attr: 0x%x\n",
5782 return smb2_set_ea((struct smb2_ea_info *)buf,
5786 case FILE_POSITION_INFORMATION:
5787 return set_file_position_info(fp, buf);
5789 case FILE_MODE_INFORMATION:
5790 return set_file_mode_info(fp, buf);
5793 pr_err("Unimplemented Fileinfoclass :%d\n", info_class);
5797 static int smb2_set_info_sec(struct ksmbd_file *fp, int addition_info,
5798 char *buffer, int buf_len)
5800 struct smb_ntsd *pntsd = (struct smb_ntsd *)buffer;
5802 fp->saccess |= FILE_SHARE_DELETE_LE;
5804 return set_info_sec(fp->conn, fp->tcon, &fp->filp->f_path, pntsd,
5809 * smb2_set_info() - handler for smb2 set info command handler
5810 * @work: smb work containing set info request buffer
5812 * Return: 0 on success, otherwise error
5814 int smb2_set_info(struct ksmbd_work *work)
5816 struct smb2_set_info_req *req;
5817 struct smb2_set_info_rsp *rsp, *rsp_org;
5818 struct ksmbd_file *fp;
5820 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
5822 ksmbd_debug(SMB, "Received set info request\n");
5824 rsp_org = work->response_buf;
5825 if (work->next_smb2_rcv_hdr_off) {
5826 req = ksmbd_req_buf_next(work);
5827 rsp = ksmbd_resp_buf_next(work);
5828 if (!has_file_id(le64_to_cpu(req->VolatileFileId))) {
5829 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
5830 work->compound_fid);
5831 id = work->compound_fid;
5832 pid = work->compound_pfid;
5835 req = work->request_buf;
5836 rsp = work->response_buf;
5839 if (!has_file_id(id)) {
5840 id = le64_to_cpu(req->VolatileFileId);
5841 pid = le64_to_cpu(req->PersistentFileId);
5844 fp = ksmbd_lookup_fd_slow(work, id, pid);
5846 ksmbd_debug(SMB, "Invalid id for close: %u\n", id);
5851 switch (req->InfoType) {
5852 case SMB2_O_INFO_FILE:
5853 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
5854 rc = smb2_set_info_file(work, fp, req->FileInfoClass,
5855 req->Buffer, work->tcon->share_conf);
5857 case SMB2_O_INFO_SECURITY:
5858 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
5859 if (ksmbd_override_fsids(work)) {
5863 rc = smb2_set_info_sec(fp,
5864 le32_to_cpu(req->AdditionalInformation),
5866 le32_to_cpu(req->BufferLength));
5867 ksmbd_revert_fsids(work);
5876 rsp->StructureSize = cpu_to_le16(2);
5877 inc_rfc1001_len(rsp_org, 2);
5878 ksmbd_fd_put(work, fp);
5882 if (rc == -EACCES || rc == -EPERM)
5883 rsp->hdr.Status = STATUS_ACCESS_DENIED;
5884 else if (rc == -EINVAL)
5885 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
5886 else if (rc == -ESHARE)
5887 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
5888 else if (rc == -ENOENT)
5889 rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
5890 else if (rc == -EBUSY || rc == -ENOTEMPTY)
5891 rsp->hdr.Status = STATUS_DIRECTORY_NOT_EMPTY;
5892 else if (rc == -EAGAIN)
5893 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
5894 else if (rc == -EBADF || rc == -ESTALE)
5895 rsp->hdr.Status = STATUS_INVALID_HANDLE;
5896 else if (rc == -EEXIST)
5897 rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
5898 else if (rsp->hdr.Status == 0 || rc == -EOPNOTSUPP)
5899 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
5900 smb2_set_err_rsp(work);
5901 ksmbd_fd_put(work, fp);
5902 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n", rc);
5907 * smb2_read_pipe() - handler for smb2 read from IPC pipe
5908 * @work: smb work containing read IPC pipe command buffer
5910 * Return: 0 on success, otherwise error
5912 static noinline int smb2_read_pipe(struct ksmbd_work *work)
5914 int nbytes = 0, err;
5916 struct ksmbd_rpc_command *rpc_resp;
5917 struct smb2_read_req *req = work->request_buf;
5918 struct smb2_read_rsp *rsp = work->response_buf;
5920 id = le64_to_cpu(req->VolatileFileId);
5922 inc_rfc1001_len(rsp, 16);
5923 rpc_resp = ksmbd_rpc_read(work->sess, id);
5925 if (rpc_resp->flags != KSMBD_RPC_OK) {
5930 work->aux_payload_buf =
5931 kvmalloc(rpc_resp->payload_sz, GFP_KERNEL | __GFP_ZERO);
5932 if (!work->aux_payload_buf) {
5937 memcpy(work->aux_payload_buf, rpc_resp->payload,
5938 rpc_resp->payload_sz);
5940 nbytes = rpc_resp->payload_sz;
5941 work->resp_hdr_sz = get_rfc1002_len(rsp) + 4;
5942 work->aux_payload_sz = nbytes;
5946 rsp->StructureSize = cpu_to_le16(17);
5947 rsp->DataOffset = 80;
5949 rsp->DataLength = cpu_to_le32(nbytes);
5950 rsp->DataRemaining = 0;
5952 inc_rfc1001_len(rsp, nbytes);
5956 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
5957 smb2_set_err_rsp(work);
5962 static ssize_t smb2_read_rdma_channel(struct ksmbd_work *work,
5963 struct smb2_read_req *req, void *data_buf,
5966 struct smb2_buffer_desc_v1 *desc =
5967 (struct smb2_buffer_desc_v1 *)&req->Buffer[0];
5970 if (work->conn->dialect == SMB30_PROT_ID &&
5971 req->Channel != SMB2_CHANNEL_RDMA_V1)
5974 if (req->ReadChannelInfoOffset == 0 ||
5975 le16_to_cpu(req->ReadChannelInfoLength) < sizeof(*desc))
5978 work->need_invalidate_rkey =
5979 (req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE);
5980 work->remote_key = le32_to_cpu(desc->token);
5982 err = ksmbd_conn_rdma_write(work->conn, data_buf, length,
5983 le32_to_cpu(desc->token),
5984 le64_to_cpu(desc->offset),
5985 le32_to_cpu(desc->length));
5993 * smb2_read() - handler for smb2 read from file
5994 * @work: smb work containing read command buffer
5996 * Return: 0 on success, otherwise error
5998 int smb2_read(struct ksmbd_work *work)
6000 struct ksmbd_conn *conn = work->conn;
6001 struct smb2_read_req *req;
6002 struct smb2_read_rsp *rsp, *rsp_org;
6003 struct ksmbd_file *fp;
6005 size_t length, mincount;
6006 ssize_t nbytes = 0, remain_bytes = 0;
6009 rsp_org = work->response_buf;
6010 WORK_BUFFERS(work, req, rsp);
6012 if (test_share_config_flag(work->tcon->share_conf,
6013 KSMBD_SHARE_FLAG_PIPE)) {
6014 ksmbd_debug(SMB, "IPC pipe read request\n");
6015 return smb2_read_pipe(work);
6018 fp = ksmbd_lookup_fd_slow(work, le64_to_cpu(req->VolatileFileId),
6019 le64_to_cpu(req->PersistentFileId));
6025 if (!(fp->daccess & (FILE_READ_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
6026 pr_err("Not permitted to read : 0x%x\n", fp->daccess);
6031 offset = le64_to_cpu(req->Offset);
6032 length = le32_to_cpu(req->Length);
6033 mincount = le32_to_cpu(req->MinimumCount);
6035 if (length > conn->vals->max_read_size) {
6036 ksmbd_debug(SMB, "limiting read size to max size(%u)\n",
6037 conn->vals->max_read_size);
6042 ksmbd_debug(SMB, "filename %pd, offset %lld, len %zu\n",
6043 fp->filp->f_path.dentry, offset, length);
6045 work->aux_payload_buf = kvmalloc(length, GFP_KERNEL | __GFP_ZERO);
6046 if (!work->aux_payload_buf) {
6051 nbytes = ksmbd_vfs_read(work, fp, length, &offset);
6057 if ((nbytes == 0 && length != 0) || nbytes < mincount) {
6058 kvfree(work->aux_payload_buf);
6059 work->aux_payload_buf = NULL;
6060 rsp->hdr.Status = STATUS_END_OF_FILE;
6061 smb2_set_err_rsp(work);
6062 ksmbd_fd_put(work, fp);
6066 ksmbd_debug(SMB, "nbytes %zu, offset %lld mincount %zu\n",
6067 nbytes, offset, mincount);
6069 if (req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE ||
6070 req->Channel == SMB2_CHANNEL_RDMA_V1) {
6071 /* write data to the client using rdma channel */
6072 remain_bytes = smb2_read_rdma_channel(work, req,
6073 work->aux_payload_buf,
6075 kvfree(work->aux_payload_buf);
6076 work->aux_payload_buf = NULL;
6079 if (remain_bytes < 0) {
6080 err = (int)remain_bytes;
6085 rsp->StructureSize = cpu_to_le16(17);
6086 rsp->DataOffset = 80;
6088 rsp->DataLength = cpu_to_le32(nbytes);
6089 rsp->DataRemaining = cpu_to_le32(remain_bytes);
6091 inc_rfc1001_len(rsp_org, 16);
6092 work->resp_hdr_sz = get_rfc1002_len(rsp_org) + 4;
6093 work->aux_payload_sz = nbytes;
6094 inc_rfc1001_len(rsp_org, nbytes);
6095 ksmbd_fd_put(work, fp);
6101 rsp->hdr.Status = STATUS_INVALID_DEVICE_REQUEST;
6102 else if (err == -EAGAIN)
6103 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6104 else if (err == -ENOENT)
6105 rsp->hdr.Status = STATUS_FILE_CLOSED;
6106 else if (err == -EACCES)
6107 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6108 else if (err == -ESHARE)
6109 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6110 else if (err == -EINVAL)
6111 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6113 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6115 smb2_set_err_rsp(work);
6117 ksmbd_fd_put(work, fp);
6122 * smb2_write_pipe() - handler for smb2 write on IPC pipe
6123 * @work: smb work containing write IPC pipe command buffer
6125 * Return: 0 on success, otherwise error
6127 static noinline int smb2_write_pipe(struct ksmbd_work *work)
6129 struct smb2_write_req *req = work->request_buf;
6130 struct smb2_write_rsp *rsp = work->response_buf;
6131 struct ksmbd_rpc_command *rpc_resp;
6133 int err = 0, ret = 0;
6137 length = le32_to_cpu(req->Length);
6138 id = le64_to_cpu(req->VolatileFileId);
6140 if (le16_to_cpu(req->DataOffset) ==
6141 (offsetof(struct smb2_write_req, Buffer) - 4)) {
6142 data_buf = (char *)&req->Buffer[0];
6144 if ((le16_to_cpu(req->DataOffset) > get_rfc1002_len(req)) ||
6145 (le16_to_cpu(req->DataOffset) + length > get_rfc1002_len(req))) {
6146 pr_err("invalid write data offset %u, smb_len %u\n",
6147 le16_to_cpu(req->DataOffset),
6148 get_rfc1002_len(req));
6153 data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
6154 le16_to_cpu(req->DataOffset));
6157 rpc_resp = ksmbd_rpc_write(work->sess, id, data_buf, length);
6159 if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
6160 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
6162 smb2_set_err_rsp(work);
6165 if (rpc_resp->flags != KSMBD_RPC_OK) {
6166 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6167 smb2_set_err_rsp(work);
6174 rsp->StructureSize = cpu_to_le16(17);
6175 rsp->DataOffset = 0;
6177 rsp->DataLength = cpu_to_le32(length);
6178 rsp->DataRemaining = 0;
6180 inc_rfc1001_len(rsp, 16);
6184 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6185 smb2_set_err_rsp(work);
6191 static ssize_t smb2_write_rdma_channel(struct ksmbd_work *work,
6192 struct smb2_write_req *req,
6193 struct ksmbd_file *fp,
6194 loff_t offset, size_t length, bool sync)
6196 struct smb2_buffer_desc_v1 *desc;
6201 desc = (struct smb2_buffer_desc_v1 *)&req->Buffer[0];
6203 if (work->conn->dialect == SMB30_PROT_ID &&
6204 req->Channel != SMB2_CHANNEL_RDMA_V1)
6207 if (req->Length != 0 || req->DataOffset != 0)
6210 if (req->WriteChannelInfoOffset == 0 ||
6211 le16_to_cpu(req->WriteChannelInfoLength) < sizeof(*desc))
6214 work->need_invalidate_rkey =
6215 (req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE);
6216 work->remote_key = le32_to_cpu(desc->token);
6218 data_buf = kvmalloc(length, GFP_KERNEL | __GFP_ZERO);
6222 ret = ksmbd_conn_rdma_read(work->conn, data_buf, length,
6223 le32_to_cpu(desc->token),
6224 le64_to_cpu(desc->offset),
6225 le32_to_cpu(desc->length));
6231 ret = ksmbd_vfs_write(work, fp, data_buf, length, &offset, sync, &nbytes);
6240 * smb2_write() - handler for smb2 write from file
6241 * @work: smb work containing write command buffer
6243 * Return: 0 on success, otherwise error
6245 int smb2_write(struct ksmbd_work *work)
6247 struct smb2_write_req *req;
6248 struct smb2_write_rsp *rsp, *rsp_org;
6249 struct ksmbd_file *fp = NULL;
6254 bool writethrough = false;
6257 rsp_org = work->response_buf;
6258 WORK_BUFFERS(work, req, rsp);
6260 if (test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_PIPE)) {
6261 ksmbd_debug(SMB, "IPC pipe write request\n");
6262 return smb2_write_pipe(work);
6265 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
6266 ksmbd_debug(SMB, "User does not have write permission\n");
6271 fp = ksmbd_lookup_fd_slow(work, le64_to_cpu(req->VolatileFileId),
6272 le64_to_cpu(req->PersistentFileId));
6278 if (!(fp->daccess & (FILE_WRITE_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
6279 pr_err("Not permitted to write : 0x%x\n", fp->daccess);
6284 offset = le64_to_cpu(req->Offset);
6285 length = le32_to_cpu(req->Length);
6287 if (length > work->conn->vals->max_write_size) {
6288 ksmbd_debug(SMB, "limiting write size to max size(%u)\n",
6289 work->conn->vals->max_write_size);
6294 if (le32_to_cpu(req->Flags) & SMB2_WRITEFLAG_WRITE_THROUGH)
6295 writethrough = true;
6297 if (req->Channel != SMB2_CHANNEL_RDMA_V1 &&
6298 req->Channel != SMB2_CHANNEL_RDMA_V1_INVALIDATE) {
6299 if (le16_to_cpu(req->DataOffset) ==
6300 (offsetof(struct smb2_write_req, Buffer) - 4)) {
6301 data_buf = (char *)&req->Buffer[0];
6303 if ((le16_to_cpu(req->DataOffset) > get_rfc1002_len(req)) ||
6304 (le16_to_cpu(req->DataOffset) + length > get_rfc1002_len(req))) {
6305 pr_err("invalid write data offset %u, smb_len %u\n",
6306 le16_to_cpu(req->DataOffset),
6307 get_rfc1002_len(req));
6312 data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
6313 le16_to_cpu(req->DataOffset));
6316 ksmbd_debug(SMB, "flags %u\n", le32_to_cpu(req->Flags));
6317 if (le32_to_cpu(req->Flags) & SMB2_WRITEFLAG_WRITE_THROUGH)
6318 writethrough = true;
6320 ksmbd_debug(SMB, "filename %pd, offset %lld, len %zu\n",
6321 fp->filp->f_path.dentry, offset, length);
6322 err = ksmbd_vfs_write(work, fp, data_buf, length, &offset,
6323 writethrough, &nbytes);
6327 /* read data from the client using rdma channel, and
6330 nbytes = smb2_write_rdma_channel(work, req, fp, offset,
6331 le32_to_cpu(req->RemainingBytes),
6339 rsp->StructureSize = cpu_to_le16(17);
6340 rsp->DataOffset = 0;
6342 rsp->DataLength = cpu_to_le32(nbytes);
6343 rsp->DataRemaining = 0;
6345 inc_rfc1001_len(rsp_org, 16);
6346 ksmbd_fd_put(work, fp);
6351 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6352 else if (err == -ENOSPC || err == -EFBIG)
6353 rsp->hdr.Status = STATUS_DISK_FULL;
6354 else if (err == -ENOENT)
6355 rsp->hdr.Status = STATUS_FILE_CLOSED;
6356 else if (err == -EACCES)
6357 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6358 else if (err == -ESHARE)
6359 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6360 else if (err == -EINVAL)
6361 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6363 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6365 smb2_set_err_rsp(work);
6366 ksmbd_fd_put(work, fp);
6371 * smb2_flush() - handler for smb2 flush file - fsync
6372 * @work: smb work containing flush command buffer
6374 * Return: 0 on success, otherwise error
6376 int smb2_flush(struct ksmbd_work *work)
6378 struct smb2_flush_req *req;
6379 struct smb2_flush_rsp *rsp, *rsp_org;
6382 rsp_org = work->response_buf;
6383 WORK_BUFFERS(work, req, rsp);
6385 ksmbd_debug(SMB, "SMB2_FLUSH called for fid %llu\n",
6386 le64_to_cpu(req->VolatileFileId));
6388 err = ksmbd_vfs_fsync(work,
6389 le64_to_cpu(req->VolatileFileId),
6390 le64_to_cpu(req->PersistentFileId));
6394 rsp->StructureSize = cpu_to_le16(4);
6396 inc_rfc1001_len(rsp_org, 4);
6401 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6402 smb2_set_err_rsp(work);
6409 * smb2_cancel() - handler for smb2 cancel command
6410 * @work: smb work containing cancel command buffer
6412 * Return: 0 on success, otherwise error
6414 int smb2_cancel(struct ksmbd_work *work)
6416 struct ksmbd_conn *conn = work->conn;
6417 struct smb2_hdr *hdr = work->request_buf;
6418 struct smb2_hdr *chdr;
6419 struct ksmbd_work *cancel_work = NULL;
6421 struct list_head *command_list;
6423 ksmbd_debug(SMB, "smb2 cancel called on mid %llu, async flags 0x%x\n",
6424 hdr->MessageId, hdr->Flags);
6426 if (hdr->Flags & SMB2_FLAGS_ASYNC_COMMAND) {
6427 command_list = &conn->async_requests;
6429 spin_lock(&conn->request_lock);
6430 list_for_each_entry(cancel_work, command_list,
6431 async_request_entry) {
6432 chdr = cancel_work->request_buf;
6434 if (cancel_work->async_id !=
6435 le64_to_cpu(hdr->Id.AsyncId))
6439 "smb2 with AsyncId %llu cancelled command = 0x%x\n",
6440 le64_to_cpu(hdr->Id.AsyncId),
6441 le16_to_cpu(chdr->Command));
6445 spin_unlock(&conn->request_lock);
6447 command_list = &conn->requests;
6449 spin_lock(&conn->request_lock);
6450 list_for_each_entry(cancel_work, command_list, request_entry) {
6451 chdr = cancel_work->request_buf;
6453 if (chdr->MessageId != hdr->MessageId ||
6454 cancel_work == work)
6458 "smb2 with mid %llu cancelled command = 0x%x\n",
6459 le64_to_cpu(hdr->MessageId),
6460 le16_to_cpu(chdr->Command));
6464 spin_unlock(&conn->request_lock);
6468 cancel_work->state = KSMBD_WORK_CANCELLED;
6469 if (cancel_work->cancel_fn)
6470 cancel_work->cancel_fn(cancel_work->cancel_argv);
6473 /* For SMB2_CANCEL command itself send no response*/
6474 work->send_no_response = 1;
6478 struct file_lock *smb_flock_init(struct file *f)
6480 struct file_lock *fl;
6482 fl = locks_alloc_lock();
6486 locks_init_lock(fl);
6489 fl->fl_pid = current->tgid;
6491 fl->fl_flags = FL_POSIX;
6493 fl->fl_lmops = NULL;
6499 static int smb2_set_flock_flags(struct file_lock *flock, int flags)
6503 /* Checking for wrong flag combination during lock request*/
6505 case SMB2_LOCKFLAG_SHARED:
6506 ksmbd_debug(SMB, "received shared request\n");
6508 flock->fl_type = F_RDLCK;
6509 flock->fl_flags |= FL_SLEEP;
6511 case SMB2_LOCKFLAG_EXCLUSIVE:
6512 ksmbd_debug(SMB, "received exclusive request\n");
6514 flock->fl_type = F_WRLCK;
6515 flock->fl_flags |= FL_SLEEP;
6517 case SMB2_LOCKFLAG_SHARED | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
6519 "received shared & fail immediately request\n");
6521 flock->fl_type = F_RDLCK;
6523 case SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
6525 "received exclusive & fail immediately request\n");
6527 flock->fl_type = F_WRLCK;
6529 case SMB2_LOCKFLAG_UNLOCK:
6530 ksmbd_debug(SMB, "received unlock request\n");
6531 flock->fl_type = F_UNLCK;
6539 static struct ksmbd_lock *smb2_lock_init(struct file_lock *flock,
6540 unsigned int cmd, int flags,
6541 struct list_head *lock_list)
6543 struct ksmbd_lock *lock;
6545 lock = kzalloc(sizeof(struct ksmbd_lock), GFP_KERNEL);
6551 lock->start = flock->fl_start;
6552 lock->end = flock->fl_end;
6553 lock->flags = flags;
6554 if (lock->start == lock->end)
6556 INIT_LIST_HEAD(&lock->clist);
6557 INIT_LIST_HEAD(&lock->flist);
6558 INIT_LIST_HEAD(&lock->llist);
6559 list_add_tail(&lock->llist, lock_list);
6564 static void smb2_remove_blocked_lock(void **argv)
6566 struct file_lock *flock = (struct file_lock *)argv[0];
6568 ksmbd_vfs_posix_lock_unblock(flock);
6569 wake_up(&flock->fl_wait);
6572 static inline bool lock_defer_pending(struct file_lock *fl)
6574 /* check pending lock waiters */
6575 return waitqueue_active(&fl->fl_wait);
6579 * smb2_lock() - handler for smb2 file lock command
6580 * @work: smb work containing lock command buffer
6582 * Return: 0 on success, otherwise error
6584 int smb2_lock(struct ksmbd_work *work)
6586 struct smb2_lock_req *req = work->request_buf;
6587 struct smb2_lock_rsp *rsp = work->response_buf;
6588 struct smb2_lock_element *lock_ele;
6589 struct ksmbd_file *fp = NULL;
6590 struct file_lock *flock = NULL;
6591 struct file *filp = NULL;
6595 int err = -EIO, i, rc = 0;
6596 u64 lock_start, lock_length;
6597 struct ksmbd_lock *smb_lock = NULL, *cmp_lock, *tmp, *tmp2;
6598 struct ksmbd_conn *conn;
6600 LIST_HEAD(lock_list);
6601 LIST_HEAD(rollback_list);
6604 ksmbd_debug(SMB, "Received lock request\n");
6605 fp = ksmbd_lookup_fd_slow(work,
6606 le64_to_cpu(req->VolatileFileId),
6607 le64_to_cpu(req->PersistentFileId));
6609 ksmbd_debug(SMB, "Invalid file id for lock : %llu\n",
6610 le64_to_cpu(req->VolatileFileId));
6616 lock_count = le16_to_cpu(req->LockCount);
6617 lock_ele = req->locks;
6619 ksmbd_debug(SMB, "lock count is %d\n", lock_count);
6625 for (i = 0; i < lock_count; i++) {
6626 flags = le32_to_cpu(lock_ele[i].Flags);
6628 flock = smb_flock_init(filp);
6632 cmd = smb2_set_flock_flags(flock, flags);
6634 lock_start = le64_to_cpu(lock_ele[i].Offset);
6635 lock_length = le64_to_cpu(lock_ele[i].Length);
6636 if (lock_start > U64_MAX - lock_length) {
6637 pr_err("Invalid lock range requested\n");
6638 rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
6642 if (lock_start > OFFSET_MAX)
6643 flock->fl_start = OFFSET_MAX;
6645 flock->fl_start = lock_start;
6647 lock_length = le64_to_cpu(lock_ele[i].Length);
6648 if (lock_length > OFFSET_MAX - flock->fl_start)
6649 lock_length = OFFSET_MAX - flock->fl_start;
6651 flock->fl_end = flock->fl_start + lock_length;
6653 if (flock->fl_end < flock->fl_start) {
6655 "the end offset(%llx) is smaller than the start offset(%llx)\n",
6656 flock->fl_end, flock->fl_start);
6657 rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
6661 /* Check conflict locks in one request */
6662 list_for_each_entry(cmp_lock, &lock_list, llist) {
6663 if (cmp_lock->fl->fl_start <= flock->fl_start &&
6664 cmp_lock->fl->fl_end >= flock->fl_end) {
6665 if (cmp_lock->fl->fl_type != F_UNLCK &&
6666 flock->fl_type != F_UNLCK) {
6667 pr_err("conflict two locks in one request\n");
6674 smb_lock = smb2_lock_init(flock, cmd, flags, &lock_list);
6681 list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
6682 if (smb_lock->cmd < 0) {
6687 if (!(smb_lock->flags & SMB2_LOCKFLAG_MASK)) {
6692 if ((prior_lock & (SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_SHARED) &&
6693 smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) ||
6694 (prior_lock == SMB2_LOCKFLAG_UNLOCK &&
6695 !(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK))) {
6700 prior_lock = smb_lock->flags;
6702 if (!(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) &&
6703 !(smb_lock->flags & SMB2_LOCKFLAG_FAIL_IMMEDIATELY))
6707 /* check locks in connection list */
6708 read_lock(&conn_list_lock);
6709 list_for_each_entry(conn, &conn_list, conns_list) {
6710 spin_lock(&conn->llist_lock);
6711 list_for_each_entry_safe(cmp_lock, tmp2, &conn->lock_list, clist) {
6712 if (file_inode(cmp_lock->fl->fl_file) !=
6713 file_inode(smb_lock->fl->fl_file))
6716 if (smb_lock->fl->fl_type == F_UNLCK) {
6717 if (cmp_lock->fl->fl_file == smb_lock->fl->fl_file &&
6718 cmp_lock->start == smb_lock->start &&
6719 cmp_lock->end == smb_lock->end &&
6720 !lock_defer_pending(cmp_lock->fl)) {
6722 list_del(&cmp_lock->flist);
6723 list_del(&cmp_lock->clist);
6724 spin_unlock(&conn->llist_lock);
6725 read_unlock(&conn_list_lock);
6727 locks_free_lock(cmp_lock->fl);
6734 if (cmp_lock->fl->fl_file == smb_lock->fl->fl_file) {
6735 if (smb_lock->flags & SMB2_LOCKFLAG_SHARED)
6738 if (cmp_lock->flags & SMB2_LOCKFLAG_SHARED)
6742 /* check zero byte lock range */
6743 if (cmp_lock->zero_len && !smb_lock->zero_len &&
6744 cmp_lock->start > smb_lock->start &&
6745 cmp_lock->start < smb_lock->end) {
6746 spin_unlock(&conn->llist_lock);
6747 read_unlock(&conn_list_lock);
6748 pr_err("previous lock conflict with zero byte lock range\n");
6752 if (smb_lock->zero_len && !cmp_lock->zero_len &&
6753 smb_lock->start > cmp_lock->start &&
6754 smb_lock->start < cmp_lock->end) {
6755 spin_unlock(&conn->llist_lock);
6756 read_unlock(&conn_list_lock);
6757 pr_err("current lock conflict with zero byte lock range\n");
6761 if (((cmp_lock->start <= smb_lock->start &&
6762 cmp_lock->end > smb_lock->start) ||
6763 (cmp_lock->start < smb_lock->end &&
6764 cmp_lock->end >= smb_lock->end)) &&
6765 !cmp_lock->zero_len && !smb_lock->zero_len) {
6766 spin_unlock(&conn->llist_lock);
6767 read_unlock(&conn_list_lock);
6768 pr_err("Not allow lock operation on exclusive lock range\n");
6772 spin_unlock(&conn->llist_lock);
6774 read_unlock(&conn_list_lock);
6776 if (smb_lock->fl->fl_type == F_UNLCK && nolock) {
6777 pr_err("Try to unlock nolocked range\n");
6778 rsp->hdr.Status = STATUS_RANGE_NOT_LOCKED;
6783 if (smb_lock->zero_len) {
6788 flock = smb_lock->fl;
6789 list_del(&smb_lock->llist);
6791 rc = vfs_lock_file(filp, smb_lock->cmd, flock, NULL);
6793 if (flags & SMB2_LOCKFLAG_UNLOCK) {
6795 ksmbd_debug(SMB, "File unlocked\n");
6796 } else if (rc == -ENOENT) {
6797 rsp->hdr.Status = STATUS_NOT_LOCKED;
6800 locks_free_lock(flock);
6803 if (rc == FILE_LOCK_DEFERRED) {
6807 "would have to wait for getting lock\n");
6808 spin_lock(&work->conn->llist_lock);
6809 list_add_tail(&smb_lock->clist,
6810 &work->conn->lock_list);
6811 spin_unlock(&work->conn->llist_lock);
6812 list_add(&smb_lock->llist, &rollback_list);
6814 argv = kmalloc(sizeof(void *), GFP_KERNEL);
6821 rc = setup_async_work(work,
6822 smb2_remove_blocked_lock,
6828 spin_lock(&fp->f_lock);
6829 list_add(&work->fp_entry, &fp->blocked_works);
6830 spin_unlock(&fp->f_lock);
6832 smb2_send_interim_resp(work, STATUS_PENDING);
6834 ksmbd_vfs_posix_lock_wait(flock);
6836 if (work->state != KSMBD_WORK_ACTIVE) {
6837 list_del(&smb_lock->llist);
6838 spin_lock(&work->conn->llist_lock);
6839 list_del(&smb_lock->clist);
6840 spin_unlock(&work->conn->llist_lock);
6841 locks_free_lock(flock);
6843 if (work->state == KSMBD_WORK_CANCELLED) {
6844 spin_lock(&fp->f_lock);
6845 list_del(&work->fp_entry);
6846 spin_unlock(&fp->f_lock);
6850 smb2_send_interim_resp(work,
6852 work->send_no_response = 1;
6855 init_smb2_rsp_hdr(work);
6856 smb2_set_err_rsp(work);
6858 STATUS_RANGE_NOT_LOCKED;
6863 list_del(&smb_lock->llist);
6864 spin_lock(&work->conn->llist_lock);
6865 list_del(&smb_lock->clist);
6866 spin_unlock(&work->conn->llist_lock);
6868 spin_lock(&fp->f_lock);
6869 list_del(&work->fp_entry);
6870 spin_unlock(&fp->f_lock);
6873 spin_lock(&work->conn->llist_lock);
6874 list_add_tail(&smb_lock->clist,
6875 &work->conn->lock_list);
6876 list_add_tail(&smb_lock->flist,
6878 spin_unlock(&work->conn->llist_lock);
6879 list_add(&smb_lock->llist, &rollback_list);
6880 ksmbd_debug(SMB, "successful in taking lock\n");
6887 if (atomic_read(&fp->f_ci->op_count) > 1)
6888 smb_break_all_oplock(work, fp);
6890 rsp->StructureSize = cpu_to_le16(4);
6891 ksmbd_debug(SMB, "successful in taking lock\n");
6892 rsp->hdr.Status = STATUS_SUCCESS;
6894 inc_rfc1001_len(rsp, 4);
6895 ksmbd_fd_put(work, fp);
6899 list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
6900 locks_free_lock(smb_lock->fl);
6901 list_del(&smb_lock->llist);
6905 list_for_each_entry_safe(smb_lock, tmp, &rollback_list, llist) {
6906 struct file_lock *rlock = NULL;
6908 rlock = smb_flock_init(filp);
6909 rlock->fl_type = F_UNLCK;
6910 rlock->fl_start = smb_lock->start;
6911 rlock->fl_end = smb_lock->end;
6913 rc = vfs_lock_file(filp, 0, rlock, NULL);
6915 pr_err("rollback unlock fail : %d\n", rc);
6917 list_del(&smb_lock->llist);
6918 spin_lock(&work->conn->llist_lock);
6919 if (!list_empty(&smb_lock->flist))
6920 list_del(&smb_lock->flist);
6921 list_del(&smb_lock->clist);
6922 spin_unlock(&work->conn->llist_lock);
6924 locks_free_lock(smb_lock->fl);
6925 locks_free_lock(rlock);
6929 ksmbd_debug(SMB, "failed in taking lock(flags : %x), err : %d\n", flags, err);
6931 if (!rsp->hdr.Status) {
6933 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6934 else if (err == -ENOMEM)
6935 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
6936 else if (err == -ENOENT)
6937 rsp->hdr.Status = STATUS_FILE_CLOSED;
6939 rsp->hdr.Status = STATUS_LOCK_NOT_GRANTED;
6942 smb2_set_err_rsp(work);
6943 ksmbd_fd_put(work, fp);
6947 static int fsctl_copychunk(struct ksmbd_work *work, struct smb2_ioctl_req *req,
6948 struct smb2_ioctl_rsp *rsp)
6950 struct copychunk_ioctl_req *ci_req;
6951 struct copychunk_ioctl_rsp *ci_rsp;
6952 struct ksmbd_file *src_fp = NULL, *dst_fp = NULL;
6953 struct srv_copychunk *chunks;
6954 unsigned int i, chunk_count, chunk_count_written = 0;
6955 unsigned int chunk_size_written = 0;
6956 loff_t total_size_written = 0;
6959 cnt_code = le32_to_cpu(req->CntCode);
6960 ci_req = (struct copychunk_ioctl_req *)&req->Buffer[0];
6961 ci_rsp = (struct copychunk_ioctl_rsp *)&rsp->Buffer[0];
6963 rsp->VolatileFileId = req->VolatileFileId;
6964 rsp->PersistentFileId = req->PersistentFileId;
6965 ci_rsp->ChunksWritten =
6966 cpu_to_le32(ksmbd_server_side_copy_max_chunk_count());
6967 ci_rsp->ChunkBytesWritten =
6968 cpu_to_le32(ksmbd_server_side_copy_max_chunk_size());
6969 ci_rsp->TotalBytesWritten =
6970 cpu_to_le32(ksmbd_server_side_copy_max_total_size());
6972 chunks = (struct srv_copychunk *)&ci_req->Chunks[0];
6973 chunk_count = le32_to_cpu(ci_req->ChunkCount);
6974 total_size_written = 0;
6976 /* verify the SRV_COPYCHUNK_COPY packet */
6977 if (chunk_count > ksmbd_server_side_copy_max_chunk_count() ||
6978 le32_to_cpu(req->InputCount) <
6979 offsetof(struct copychunk_ioctl_req, Chunks) +
6980 chunk_count * sizeof(struct srv_copychunk)) {
6981 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6985 for (i = 0; i < chunk_count; i++) {
6986 if (le32_to_cpu(chunks[i].Length) == 0 ||
6987 le32_to_cpu(chunks[i].Length) > ksmbd_server_side_copy_max_chunk_size())
6989 total_size_written += le32_to_cpu(chunks[i].Length);
6992 if (i < chunk_count ||
6993 total_size_written > ksmbd_server_side_copy_max_total_size()) {
6994 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6998 src_fp = ksmbd_lookup_foreign_fd(work,
6999 le64_to_cpu(ci_req->ResumeKey[0]));
7000 dst_fp = ksmbd_lookup_fd_slow(work,
7001 le64_to_cpu(req->VolatileFileId),
7002 le64_to_cpu(req->PersistentFileId));
7005 src_fp->persistent_id != le64_to_cpu(ci_req->ResumeKey[1])) {
7006 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
7011 rsp->hdr.Status = STATUS_FILE_CLOSED;
7016 * FILE_READ_DATA should only be included in
7017 * the FSCTL_COPYCHUNK case
7019 if (cnt_code == FSCTL_COPYCHUNK &&
7020 !(dst_fp->daccess & (FILE_READ_DATA_LE | FILE_GENERIC_READ_LE))) {
7021 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7025 ret = ksmbd_vfs_copy_file_ranges(work, src_fp, dst_fp,
7026 chunks, chunk_count,
7027 &chunk_count_written,
7028 &chunk_size_written,
7029 &total_size_written);
7032 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7034 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
7035 else if (ret == -EBADF)
7036 rsp->hdr.Status = STATUS_INVALID_HANDLE;
7037 else if (ret == -EFBIG || ret == -ENOSPC)
7038 rsp->hdr.Status = STATUS_DISK_FULL;
7039 else if (ret == -EINVAL)
7040 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7041 else if (ret == -EISDIR)
7042 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
7043 else if (ret == -E2BIG)
7044 rsp->hdr.Status = STATUS_INVALID_VIEW_SIZE;
7046 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
7049 ci_rsp->ChunksWritten = cpu_to_le32(chunk_count_written);
7050 ci_rsp->ChunkBytesWritten = cpu_to_le32(chunk_size_written);
7051 ci_rsp->TotalBytesWritten = cpu_to_le32(total_size_written);
7053 ksmbd_fd_put(work, src_fp);
7054 ksmbd_fd_put(work, dst_fp);
7058 static __be32 idev_ipv4_address(struct in_device *idev)
7062 struct in_ifaddr *ifa;
7065 in_dev_for_each_ifa_rcu(ifa, idev) {
7066 if (ifa->ifa_flags & IFA_F_SECONDARY)
7069 addr = ifa->ifa_address;
7076 static int fsctl_query_iface_info_ioctl(struct ksmbd_conn *conn,
7077 struct smb2_ioctl_req *req,
7078 struct smb2_ioctl_rsp *rsp)
7080 struct network_interface_info_ioctl_rsp *nii_rsp = NULL;
7082 struct net_device *netdev;
7083 struct sockaddr_storage_rsp *sockaddr_storage;
7085 unsigned long long speed;
7086 struct sockaddr_in6 *csin6 = (struct sockaddr_in6 *)&conn->peer_addr;
7089 for_each_netdev(&init_net, netdev) {
7090 if (netdev->type == ARPHRD_LOOPBACK)
7093 flags = dev_get_flags(netdev);
7094 if (!(flags & IFF_RUNNING))
7097 nii_rsp = (struct network_interface_info_ioctl_rsp *)
7098 &rsp->Buffer[nbytes];
7099 nii_rsp->IfIndex = cpu_to_le32(netdev->ifindex);
7101 nii_rsp->Capability = 0;
7102 if (ksmbd_rdma_capable_netdev(netdev))
7103 nii_rsp->Capability |= cpu_to_le32(RDMA_CAPABLE);
7105 nii_rsp->Next = cpu_to_le32(152);
7106 nii_rsp->Reserved = 0;
7108 if (netdev->ethtool_ops->get_link_ksettings) {
7109 struct ethtool_link_ksettings cmd;
7111 netdev->ethtool_ops->get_link_ksettings(netdev, &cmd);
7112 speed = cmd.base.speed;
7114 ksmbd_debug(SMB, "%s %s\n", netdev->name,
7115 "speed is unknown, defaulting to 1Gb/sec");
7120 nii_rsp->LinkSpeed = cpu_to_le64(speed);
7122 sockaddr_storage = (struct sockaddr_storage_rsp *)
7123 nii_rsp->SockAddr_Storage;
7124 memset(sockaddr_storage, 0, 128);
7126 if (conn->peer_addr.ss_family == PF_INET ||
7127 ipv6_addr_v4mapped(&csin6->sin6_addr)) {
7128 struct in_device *idev;
7130 sockaddr_storage->Family = cpu_to_le16(INTERNETWORK);
7131 sockaddr_storage->addr4.Port = 0;
7133 idev = __in_dev_get_rtnl(netdev);
7136 sockaddr_storage->addr4.IPv4address =
7137 idev_ipv4_address(idev);
7139 struct inet6_dev *idev6;
7140 struct inet6_ifaddr *ifa;
7141 __u8 *ipv6_addr = sockaddr_storage->addr6.IPv6address;
7143 sockaddr_storage->Family = cpu_to_le16(INTERNETWORKV6);
7144 sockaddr_storage->addr6.Port = 0;
7145 sockaddr_storage->addr6.FlowInfo = 0;
7147 idev6 = __in6_dev_get(netdev);
7151 list_for_each_entry(ifa, &idev6->addr_list, if_list) {
7152 if (ifa->flags & (IFA_F_TENTATIVE |
7155 memcpy(ipv6_addr, ifa->addr.s6_addr, 16);
7158 sockaddr_storage->addr6.ScopeId = 0;
7161 nbytes += sizeof(struct network_interface_info_ioctl_rsp);
7165 /* zero if this is last one */
7170 rsp->hdr.Status = STATUS_BUFFER_TOO_SMALL;
7174 rsp->PersistentFileId = cpu_to_le64(SMB2_NO_FID);
7175 rsp->VolatileFileId = cpu_to_le64(SMB2_NO_FID);
7179 static int fsctl_validate_negotiate_info(struct ksmbd_conn *conn,
7180 struct validate_negotiate_info_req *neg_req,
7181 struct validate_negotiate_info_rsp *neg_rsp)
7186 dialect = ksmbd_lookup_dialect_by_id(neg_req->Dialects,
7187 neg_req->DialectCount);
7188 if (dialect == BAD_PROT_ID || dialect != conn->dialect) {
7193 if (strncmp(neg_req->Guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE)) {
7198 if (le16_to_cpu(neg_req->SecurityMode) != conn->cli_sec_mode) {
7203 if (le32_to_cpu(neg_req->Capabilities) != conn->cli_cap) {
7208 neg_rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
7209 memset(neg_rsp->Guid, 0, SMB2_CLIENT_GUID_SIZE);
7210 neg_rsp->SecurityMode = cpu_to_le16(conn->srv_sec_mode);
7211 neg_rsp->Dialect = cpu_to_le16(conn->dialect);
7216 static int fsctl_query_allocated_ranges(struct ksmbd_work *work, u64 id,
7217 struct file_allocated_range_buffer *qar_req,
7218 struct file_allocated_range_buffer *qar_rsp,
7219 int in_count, int *out_count)
7221 struct ksmbd_file *fp;
7222 loff_t start, length;
7229 fp = ksmbd_lookup_fd_fast(work, id);
7233 start = le64_to_cpu(qar_req->file_offset);
7234 length = le64_to_cpu(qar_req->length);
7236 ret = ksmbd_vfs_fqar_lseek(fp, start, length,
7237 qar_rsp, in_count, out_count);
7238 if (ret && ret != -E2BIG)
7241 ksmbd_fd_put(work, fp);
7245 static int fsctl_pipe_transceive(struct ksmbd_work *work, u64 id,
7246 int out_buf_len, struct smb2_ioctl_req *req,
7247 struct smb2_ioctl_rsp *rsp)
7249 struct ksmbd_rpc_command *rpc_resp;
7250 char *data_buf = (char *)&req->Buffer[0];
7253 rpc_resp = ksmbd_rpc_ioctl(work->sess, id, data_buf,
7254 le32_to_cpu(req->InputCount));
7256 if (rpc_resp->flags == KSMBD_RPC_SOME_NOT_MAPPED) {
7258 * set STATUS_SOME_NOT_MAPPED response
7259 * for unknown domain sid.
7261 rsp->hdr.Status = STATUS_SOME_NOT_MAPPED;
7262 } else if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
7263 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7265 } else if (rpc_resp->flags != KSMBD_RPC_OK) {
7266 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7270 nbytes = rpc_resp->payload_sz;
7271 if (rpc_resp->payload_sz > out_buf_len) {
7272 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
7273 nbytes = out_buf_len;
7276 if (!rpc_resp->payload_sz) {
7278 STATUS_UNEXPECTED_IO_ERROR;
7282 memcpy((char *)rsp->Buffer, rpc_resp->payload, nbytes);
7289 static inline int fsctl_set_sparse(struct ksmbd_work *work, u64 id,
7290 struct file_sparse *sparse)
7292 struct ksmbd_file *fp;
7293 struct user_namespace *user_ns;
7297 fp = ksmbd_lookup_fd_fast(work, id);
7300 user_ns = file_mnt_user_ns(fp->filp);
7302 old_fattr = fp->f_ci->m_fattr;
7303 if (sparse->SetSparse)
7304 fp->f_ci->m_fattr |= ATTR_SPARSE_FILE_LE;
7306 fp->f_ci->m_fattr &= ~ATTR_SPARSE_FILE_LE;
7308 if (fp->f_ci->m_fattr != old_fattr &&
7309 test_share_config_flag(work->tcon->share_conf,
7310 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS)) {
7311 struct xattr_dos_attrib da;
7313 ret = ksmbd_vfs_get_dos_attrib_xattr(user_ns,
7314 fp->filp->f_path.dentry, &da);
7318 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
7319 ret = ksmbd_vfs_set_dos_attrib_xattr(user_ns,
7320 fp->filp->f_path.dentry, &da);
7322 fp->f_ci->m_fattr = old_fattr;
7326 ksmbd_fd_put(work, fp);
7330 static int fsctl_request_resume_key(struct ksmbd_work *work,
7331 struct smb2_ioctl_req *req,
7332 struct resume_key_ioctl_rsp *key_rsp)
7334 struct ksmbd_file *fp;
7336 fp = ksmbd_lookup_fd_slow(work,
7337 le64_to_cpu(req->VolatileFileId),
7338 le64_to_cpu(req->PersistentFileId));
7342 memset(key_rsp, 0, sizeof(*key_rsp));
7343 key_rsp->ResumeKey[0] = req->VolatileFileId;
7344 key_rsp->ResumeKey[1] = req->PersistentFileId;
7345 ksmbd_fd_put(work, fp);
7351 * smb2_ioctl() - handler for smb2 ioctl command
7352 * @work: smb work containing ioctl command buffer
7354 * Return: 0 on success, otherwise error
7356 int smb2_ioctl(struct ksmbd_work *work)
7358 struct smb2_ioctl_req *req;
7359 struct smb2_ioctl_rsp *rsp, *rsp_org;
7360 int cnt_code, nbytes = 0;
7362 u64 id = KSMBD_NO_FID;
7363 struct ksmbd_conn *conn = work->conn;
7366 rsp_org = work->response_buf;
7367 if (work->next_smb2_rcv_hdr_off) {
7368 req = ksmbd_req_buf_next(work);
7369 rsp = ksmbd_resp_buf_next(work);
7370 if (!has_file_id(le64_to_cpu(req->VolatileFileId))) {
7371 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
7372 work->compound_fid);
7373 id = work->compound_fid;
7376 req = work->request_buf;
7377 rsp = work->response_buf;
7380 if (!has_file_id(id))
7381 id = le64_to_cpu(req->VolatileFileId);
7383 if (req->Flags != cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL)) {
7384 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7388 cnt_code = le32_to_cpu(req->CntCode);
7389 out_buf_len = le32_to_cpu(req->MaxOutputResponse);
7390 out_buf_len = min(KSMBD_IPC_MAX_PAYLOAD, out_buf_len);
7393 case FSCTL_DFS_GET_REFERRALS:
7394 case FSCTL_DFS_GET_REFERRALS_EX:
7395 /* Not support DFS yet */
7396 rsp->hdr.Status = STATUS_FS_DRIVER_REQUIRED;
7398 case FSCTL_CREATE_OR_GET_OBJECT_ID:
7400 struct file_object_buf_type1_ioctl_rsp *obj_buf;
7402 nbytes = sizeof(struct file_object_buf_type1_ioctl_rsp);
7403 obj_buf = (struct file_object_buf_type1_ioctl_rsp *)
7407 * TODO: This is dummy implementation to pass smbtorture
7408 * Need to check correct response later
7410 memset(obj_buf->ObjectId, 0x0, 16);
7411 memset(obj_buf->BirthVolumeId, 0x0, 16);
7412 memset(obj_buf->BirthObjectId, 0x0, 16);
7413 memset(obj_buf->DomainId, 0x0, 16);
7417 case FSCTL_PIPE_TRANSCEIVE:
7418 nbytes = fsctl_pipe_transceive(work, id, out_buf_len, req, rsp);
7420 case FSCTL_VALIDATE_NEGOTIATE_INFO:
7421 if (conn->dialect < SMB30_PROT_ID) {
7426 ret = fsctl_validate_negotiate_info(conn,
7427 (struct validate_negotiate_info_req *)&req->Buffer[0],
7428 (struct validate_negotiate_info_rsp *)&rsp->Buffer[0]);
7432 nbytes = sizeof(struct validate_negotiate_info_rsp);
7433 rsp->PersistentFileId = cpu_to_le64(SMB2_NO_FID);
7434 rsp->VolatileFileId = cpu_to_le64(SMB2_NO_FID);
7436 case FSCTL_QUERY_NETWORK_INTERFACE_INFO:
7437 nbytes = fsctl_query_iface_info_ioctl(conn, req, rsp);
7441 case FSCTL_REQUEST_RESUME_KEY:
7442 if (out_buf_len < sizeof(struct resume_key_ioctl_rsp)) {
7447 ret = fsctl_request_resume_key(work, req,
7448 (struct resume_key_ioctl_rsp *)&rsp->Buffer[0]);
7451 rsp->PersistentFileId = req->PersistentFileId;
7452 rsp->VolatileFileId = req->VolatileFileId;
7453 nbytes = sizeof(struct resume_key_ioctl_rsp);
7455 case FSCTL_COPYCHUNK:
7456 case FSCTL_COPYCHUNK_WRITE:
7457 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7459 "User does not have write permission\n");
7464 if (out_buf_len < sizeof(struct copychunk_ioctl_rsp)) {
7469 nbytes = sizeof(struct copychunk_ioctl_rsp);
7470 fsctl_copychunk(work, req, rsp);
7472 case FSCTL_SET_SPARSE:
7473 ret = fsctl_set_sparse(work, id,
7474 (struct file_sparse *)&req->Buffer[0]);
7478 case FSCTL_SET_ZERO_DATA:
7480 struct file_zero_data_information *zero_data;
7481 struct ksmbd_file *fp;
7484 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7486 "User does not have write permission\n");
7492 (struct file_zero_data_information *)&req->Buffer[0];
7494 fp = ksmbd_lookup_fd_fast(work, id);
7500 off = le64_to_cpu(zero_data->FileOffset);
7501 len = le64_to_cpu(zero_data->BeyondFinalZero) - off;
7503 ret = ksmbd_vfs_zero_data(work, fp, off, len);
7504 ksmbd_fd_put(work, fp);
7509 case FSCTL_QUERY_ALLOCATED_RANGES:
7510 ret = fsctl_query_allocated_ranges(work, id,
7511 (struct file_allocated_range_buffer *)&req->Buffer[0],
7512 (struct file_allocated_range_buffer *)&rsp->Buffer[0],
7514 sizeof(struct file_allocated_range_buffer), &nbytes);
7515 if (ret == -E2BIG) {
7516 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
7517 } else if (ret < 0) {
7522 nbytes *= sizeof(struct file_allocated_range_buffer);
7524 case FSCTL_GET_REPARSE_POINT:
7526 struct reparse_data_buffer *reparse_ptr;
7527 struct ksmbd_file *fp;
7529 reparse_ptr = (struct reparse_data_buffer *)&rsp->Buffer[0];
7530 fp = ksmbd_lookup_fd_fast(work, id);
7532 pr_err("not found fp!!\n");
7537 reparse_ptr->ReparseTag =
7538 smb2_get_reparse_tag_special_file(file_inode(fp->filp)->i_mode);
7539 reparse_ptr->ReparseDataLength = 0;
7540 ksmbd_fd_put(work, fp);
7541 nbytes = sizeof(struct reparse_data_buffer);
7544 case FSCTL_DUPLICATE_EXTENTS_TO_FILE:
7546 struct ksmbd_file *fp_in, *fp_out = NULL;
7547 struct duplicate_extents_to_file *dup_ext;
7548 loff_t src_off, dst_off, length, cloned;
7550 dup_ext = (struct duplicate_extents_to_file *)&req->Buffer[0];
7552 fp_in = ksmbd_lookup_fd_slow(work, dup_ext->VolatileFileHandle,
7553 dup_ext->PersistentFileHandle);
7555 pr_err("not found file handle in duplicate extent to file\n");
7560 fp_out = ksmbd_lookup_fd_fast(work, id);
7562 pr_err("not found fp\n");
7567 src_off = le64_to_cpu(dup_ext->SourceFileOffset);
7568 dst_off = le64_to_cpu(dup_ext->TargetFileOffset);
7569 length = le64_to_cpu(dup_ext->ByteCount);
7570 cloned = vfs_clone_file_range(fp_in->filp, src_off, fp_out->filp,
7571 dst_off, length, 0);
7572 if (cloned == -EXDEV || cloned == -EOPNOTSUPP) {
7575 } else if (cloned != length) {
7576 cloned = vfs_copy_file_range(fp_in->filp, src_off,
7577 fp_out->filp, dst_off, length, 0);
7578 if (cloned != length) {
7587 ksmbd_fd_put(work, fp_in);
7588 ksmbd_fd_put(work, fp_out);
7594 ksmbd_debug(SMB, "not implemented yet ioctl command 0x%x\n",
7600 rsp->CntCode = cpu_to_le32(cnt_code);
7601 rsp->InputCount = cpu_to_le32(0);
7602 rsp->InputOffset = cpu_to_le32(112);
7603 rsp->OutputOffset = cpu_to_le32(112);
7604 rsp->OutputCount = cpu_to_le32(nbytes);
7605 rsp->StructureSize = cpu_to_le16(49);
7606 rsp->Reserved = cpu_to_le16(0);
7607 rsp->Flags = cpu_to_le32(0);
7608 rsp->Reserved2 = cpu_to_le32(0);
7609 inc_rfc1001_len(rsp_org, 48 + nbytes);
7615 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7616 else if (ret == -ENOENT)
7617 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
7618 else if (ret == -EOPNOTSUPP)
7619 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7620 else if (ret < 0 || rsp->hdr.Status == 0)
7621 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7622 smb2_set_err_rsp(work);
7627 * smb20_oplock_break_ack() - handler for smb2.0 oplock break command
7628 * @work: smb work containing oplock break command buffer
7632 static void smb20_oplock_break_ack(struct ksmbd_work *work)
7634 struct smb2_oplock_break *req = work->request_buf;
7635 struct smb2_oplock_break *rsp = work->response_buf;
7636 struct ksmbd_file *fp;
7637 struct oplock_info *opinfo = NULL;
7640 u64 volatile_id, persistent_id;
7641 char req_oplevel = 0, rsp_oplevel = 0;
7642 unsigned int oplock_change_type;
7644 volatile_id = le64_to_cpu(req->VolatileFid);
7645 persistent_id = le64_to_cpu(req->PersistentFid);
7646 req_oplevel = req->OplockLevel;
7647 ksmbd_debug(OPLOCK, "v_id %llu, p_id %llu request oplock level %d\n",
7648 volatile_id, persistent_id, req_oplevel);
7650 fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
7652 rsp->hdr.Status = STATUS_FILE_CLOSED;
7653 smb2_set_err_rsp(work);
7657 opinfo = opinfo_get(fp);
7659 pr_err("unexpected null oplock_info\n");
7660 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
7661 smb2_set_err_rsp(work);
7662 ksmbd_fd_put(work, fp);
7666 if (opinfo->level == SMB2_OPLOCK_LEVEL_NONE) {
7667 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
7671 if (opinfo->op_state == OPLOCK_STATE_NONE) {
7672 ksmbd_debug(SMB, "unexpected oplock state 0x%x\n", opinfo->op_state);
7673 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
7677 if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
7678 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
7679 (req_oplevel != SMB2_OPLOCK_LEVEL_II &&
7680 req_oplevel != SMB2_OPLOCK_LEVEL_NONE)) {
7681 err = STATUS_INVALID_OPLOCK_PROTOCOL;
7682 oplock_change_type = OPLOCK_WRITE_TO_NONE;
7683 } else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
7684 req_oplevel != SMB2_OPLOCK_LEVEL_NONE) {
7685 err = STATUS_INVALID_OPLOCK_PROTOCOL;
7686 oplock_change_type = OPLOCK_READ_TO_NONE;
7687 } else if (req_oplevel == SMB2_OPLOCK_LEVEL_II ||
7688 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
7689 err = STATUS_INVALID_DEVICE_STATE;
7690 if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
7691 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
7692 req_oplevel == SMB2_OPLOCK_LEVEL_II) {
7693 oplock_change_type = OPLOCK_WRITE_TO_READ;
7694 } else if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
7695 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
7696 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
7697 oplock_change_type = OPLOCK_WRITE_TO_NONE;
7698 } else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
7699 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
7700 oplock_change_type = OPLOCK_READ_TO_NONE;
7702 oplock_change_type = 0;
7705 oplock_change_type = 0;
7708 switch (oplock_change_type) {
7709 case OPLOCK_WRITE_TO_READ:
7710 ret = opinfo_write_to_read(opinfo);
7711 rsp_oplevel = SMB2_OPLOCK_LEVEL_II;
7713 case OPLOCK_WRITE_TO_NONE:
7714 ret = opinfo_write_to_none(opinfo);
7715 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
7717 case OPLOCK_READ_TO_NONE:
7718 ret = opinfo_read_to_none(opinfo);
7719 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
7722 pr_err("unknown oplock change 0x%x -> 0x%x\n",
7723 opinfo->level, rsp_oplevel);
7727 rsp->hdr.Status = err;
7732 ksmbd_fd_put(work, fp);
7733 opinfo->op_state = OPLOCK_STATE_NONE;
7734 wake_up_interruptible_all(&opinfo->oplock_q);
7736 rsp->StructureSize = cpu_to_le16(24);
7737 rsp->OplockLevel = rsp_oplevel;
7740 rsp->VolatileFid = cpu_to_le64(volatile_id);
7741 rsp->PersistentFid = cpu_to_le64(persistent_id);
7742 inc_rfc1001_len(rsp, 24);
7746 opinfo->op_state = OPLOCK_STATE_NONE;
7747 wake_up_interruptible_all(&opinfo->oplock_q);
7750 ksmbd_fd_put(work, fp);
7751 smb2_set_err_rsp(work);
7754 static int check_lease_state(struct lease *lease, __le32 req_state)
7756 if ((lease->new_state ==
7757 (SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE)) &&
7758 !(req_state & SMB2_LEASE_WRITE_CACHING_LE)) {
7759 lease->new_state = req_state;
7763 if (lease->new_state == req_state)
7770 * smb21_lease_break_ack() - handler for smb2.1 lease break command
7771 * @work: smb work containing lease break command buffer
7775 static void smb21_lease_break_ack(struct ksmbd_work *work)
7777 struct ksmbd_conn *conn = work->conn;
7778 struct smb2_lease_ack *req = work->request_buf;
7779 struct smb2_lease_ack *rsp = work->response_buf;
7780 struct oplock_info *opinfo;
7783 unsigned int lease_change_type;
7785 struct lease *lease;
7787 ksmbd_debug(OPLOCK, "smb21 lease break, lease state(0x%x)\n",
7788 le32_to_cpu(req->LeaseState));
7789 opinfo = lookup_lease_in_table(conn, req->LeaseKey);
7791 ksmbd_debug(OPLOCK, "file not opened\n");
7792 smb2_set_err_rsp(work);
7793 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
7796 lease = opinfo->o_lease;
7798 if (opinfo->op_state == OPLOCK_STATE_NONE) {
7799 pr_err("unexpected lease break state 0x%x\n",
7801 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
7805 if (check_lease_state(lease, req->LeaseState)) {
7806 rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
7808 "req lease state: 0x%x, expected state: 0x%x\n",
7809 req->LeaseState, lease->new_state);
7813 if (!atomic_read(&opinfo->breaking_cnt)) {
7814 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
7818 /* check for bad lease state */
7819 if (req->LeaseState &
7820 (~(SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE))) {
7821 err = STATUS_INVALID_OPLOCK_PROTOCOL;
7822 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
7823 lease_change_type = OPLOCK_WRITE_TO_NONE;
7825 lease_change_type = OPLOCK_READ_TO_NONE;
7826 ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
7827 le32_to_cpu(lease->state),
7828 le32_to_cpu(req->LeaseState));
7829 } else if (lease->state == SMB2_LEASE_READ_CACHING_LE &&
7830 req->LeaseState != SMB2_LEASE_NONE_LE) {
7831 err = STATUS_INVALID_OPLOCK_PROTOCOL;
7832 lease_change_type = OPLOCK_READ_TO_NONE;
7833 ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
7834 le32_to_cpu(lease->state),
7835 le32_to_cpu(req->LeaseState));
7837 /* valid lease state changes */
7838 err = STATUS_INVALID_DEVICE_STATE;
7839 if (req->LeaseState == SMB2_LEASE_NONE_LE) {
7840 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
7841 lease_change_type = OPLOCK_WRITE_TO_NONE;
7843 lease_change_type = OPLOCK_READ_TO_NONE;
7844 } else if (req->LeaseState & SMB2_LEASE_READ_CACHING_LE) {
7845 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
7846 lease_change_type = OPLOCK_WRITE_TO_READ;
7848 lease_change_type = OPLOCK_READ_HANDLE_TO_READ;
7850 lease_change_type = 0;
7854 switch (lease_change_type) {
7855 case OPLOCK_WRITE_TO_READ:
7856 ret = opinfo_write_to_read(opinfo);
7858 case OPLOCK_READ_HANDLE_TO_READ:
7859 ret = opinfo_read_handle_to_read(opinfo);
7861 case OPLOCK_WRITE_TO_NONE:
7862 ret = opinfo_write_to_none(opinfo);
7864 case OPLOCK_READ_TO_NONE:
7865 ret = opinfo_read_to_none(opinfo);
7868 ksmbd_debug(OPLOCK, "unknown lease change 0x%x -> 0x%x\n",
7869 le32_to_cpu(lease->state),
7870 le32_to_cpu(req->LeaseState));
7873 lease_state = lease->state;
7874 opinfo->op_state = OPLOCK_STATE_NONE;
7875 wake_up_interruptible_all(&opinfo->oplock_q);
7876 atomic_dec(&opinfo->breaking_cnt);
7877 wake_up_interruptible_all(&opinfo->oplock_brk);
7881 rsp->hdr.Status = err;
7885 rsp->StructureSize = cpu_to_le16(36);
7888 memcpy(rsp->LeaseKey, req->LeaseKey, 16);
7889 rsp->LeaseState = lease_state;
7890 rsp->LeaseDuration = 0;
7891 inc_rfc1001_len(rsp, 36);
7895 opinfo->op_state = OPLOCK_STATE_NONE;
7896 wake_up_interruptible_all(&opinfo->oplock_q);
7897 atomic_dec(&opinfo->breaking_cnt);
7898 wake_up_interruptible_all(&opinfo->oplock_brk);
7901 smb2_set_err_rsp(work);
7905 * smb2_oplock_break() - dispatcher for smb2.0 and 2.1 oplock/lease break
7906 * @work: smb work containing oplock/lease break command buffer
7910 int smb2_oplock_break(struct ksmbd_work *work)
7912 struct smb2_oplock_break *req = work->request_buf;
7913 struct smb2_oplock_break *rsp = work->response_buf;
7915 switch (le16_to_cpu(req->StructureSize)) {
7916 case OP_BREAK_STRUCT_SIZE_20:
7917 smb20_oplock_break_ack(work);
7919 case OP_BREAK_STRUCT_SIZE_21:
7920 smb21_lease_break_ack(work);
7923 ksmbd_debug(OPLOCK, "invalid break cmd %d\n",
7924 le16_to_cpu(req->StructureSize));
7925 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7926 smb2_set_err_rsp(work);
7933 * smb2_notify() - handler for smb2 notify request
7934 * @work: smb work containing notify command buffer
7938 int smb2_notify(struct ksmbd_work *work)
7940 struct smb2_notify_req *req;
7941 struct smb2_notify_rsp *rsp;
7943 WORK_BUFFERS(work, req, rsp);
7945 if (work->next_smb2_rcv_hdr_off && req->hdr.NextCommand) {
7946 rsp->hdr.Status = STATUS_INTERNAL_ERROR;
7947 smb2_set_err_rsp(work);
7951 smb2_set_err_rsp(work);
7952 rsp->hdr.Status = STATUS_NOT_IMPLEMENTED;
7957 * smb2_is_sign_req() - handler for checking packet signing status
7958 * @work: smb work containing notify command buffer
7959 * @command: SMB2 command id
7961 * Return: true if packed is signed, false otherwise
7963 bool smb2_is_sign_req(struct ksmbd_work *work, unsigned int command)
7965 struct smb2_hdr *rcv_hdr2 = work->request_buf;
7967 if ((rcv_hdr2->Flags & SMB2_FLAGS_SIGNED) &&
7968 command != SMB2_NEGOTIATE_HE &&
7969 command != SMB2_SESSION_SETUP_HE &&
7970 command != SMB2_OPLOCK_BREAK_HE)
7977 * smb2_check_sign_req() - handler for req packet sign processing
7978 * @work: smb work containing notify command buffer
7980 * Return: 1 on success, 0 otherwise
7982 int smb2_check_sign_req(struct ksmbd_work *work)
7984 struct smb2_hdr *hdr, *hdr_org;
7985 char signature_req[SMB2_SIGNATURE_SIZE];
7986 char signature[SMB2_HMACSHA256_SIZE];
7990 hdr_org = hdr = work->request_buf;
7991 if (work->next_smb2_rcv_hdr_off)
7992 hdr = ksmbd_req_buf_next(work);
7994 if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
7995 len = be32_to_cpu(hdr_org->smb2_buf_length);
7996 else if (hdr->NextCommand)
7997 len = le32_to_cpu(hdr->NextCommand);
7999 len = be32_to_cpu(hdr_org->smb2_buf_length) -
8000 work->next_smb2_rcv_hdr_off;
8002 memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8003 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8005 iov[0].iov_base = (char *)&hdr->ProtocolId;
8006 iov[0].iov_len = len;
8008 if (ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, 1,
8012 if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8013 pr_err("bad smb2 signature\n");
8021 * smb2_set_sign_rsp() - handler for rsp packet sign processing
8022 * @work: smb work containing notify command buffer
8025 void smb2_set_sign_rsp(struct ksmbd_work *work)
8027 struct smb2_hdr *hdr, *hdr_org;
8028 struct smb2_hdr *req_hdr;
8029 char signature[SMB2_HMACSHA256_SIZE];
8034 hdr_org = hdr = work->response_buf;
8035 if (work->next_smb2_rsp_hdr_off)
8036 hdr = ksmbd_resp_buf_next(work);
8038 req_hdr = ksmbd_req_buf_next(work);
8040 if (!work->next_smb2_rsp_hdr_off) {
8041 len = get_rfc1002_len(hdr_org);
8042 if (req_hdr->NextCommand)
8043 len = ALIGN(len, 8);
8045 len = get_rfc1002_len(hdr_org) - work->next_smb2_rsp_hdr_off;
8046 len = ALIGN(len, 8);
8049 if (req_hdr->NextCommand)
8050 hdr->NextCommand = cpu_to_le32(len);
8052 hdr->Flags |= SMB2_FLAGS_SIGNED;
8053 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8055 iov[0].iov_base = (char *)&hdr->ProtocolId;
8056 iov[0].iov_len = len;
8058 if (work->aux_payload_sz) {
8059 iov[0].iov_len -= work->aux_payload_sz;
8061 iov[1].iov_base = work->aux_payload_buf;
8062 iov[1].iov_len = work->aux_payload_sz;
8066 if (!ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, n_vec,
8068 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
8072 * smb3_check_sign_req() - handler for req packet sign processing
8073 * @work: smb work containing notify command buffer
8075 * Return: 1 on success, 0 otherwise
8077 int smb3_check_sign_req(struct ksmbd_work *work)
8079 struct ksmbd_conn *conn = work->conn;
8081 struct smb2_hdr *hdr, *hdr_org;
8082 struct channel *chann;
8083 char signature_req[SMB2_SIGNATURE_SIZE];
8084 char signature[SMB2_CMACAES_SIZE];
8088 hdr_org = hdr = work->request_buf;
8089 if (work->next_smb2_rcv_hdr_off)
8090 hdr = ksmbd_req_buf_next(work);
8092 if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8093 len = be32_to_cpu(hdr_org->smb2_buf_length);
8094 else if (hdr->NextCommand)
8095 len = le32_to_cpu(hdr->NextCommand);
8097 len = be32_to_cpu(hdr_org->smb2_buf_length) -
8098 work->next_smb2_rcv_hdr_off;
8100 if (le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8101 signing_key = work->sess->smb3signingkey;
8103 chann = lookup_chann_list(work->sess, conn);
8106 signing_key = chann->smb3signingkey;
8110 pr_err("SMB3 signing key is not generated\n");
8114 memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8115 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8116 iov[0].iov_base = (char *)&hdr->ProtocolId;
8117 iov[0].iov_len = len;
8119 if (ksmbd_sign_smb3_pdu(conn, signing_key, iov, 1, signature))
8122 if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8123 pr_err("bad smb2 signature\n");
8131 * smb3_set_sign_rsp() - handler for rsp packet sign processing
8132 * @work: smb work containing notify command buffer
8135 void smb3_set_sign_rsp(struct ksmbd_work *work)
8137 struct ksmbd_conn *conn = work->conn;
8138 struct smb2_hdr *req_hdr;
8139 struct smb2_hdr *hdr, *hdr_org;
8140 struct channel *chann;
8141 char signature[SMB2_CMACAES_SIZE];
8147 hdr_org = hdr = work->response_buf;
8148 if (work->next_smb2_rsp_hdr_off)
8149 hdr = ksmbd_resp_buf_next(work);
8151 req_hdr = ksmbd_req_buf_next(work);
8153 if (!work->next_smb2_rsp_hdr_off) {
8154 len = get_rfc1002_len(hdr_org);
8155 if (req_hdr->NextCommand)
8156 len = ALIGN(len, 8);
8158 len = get_rfc1002_len(hdr_org) - work->next_smb2_rsp_hdr_off;
8159 len = ALIGN(len, 8);
8162 if (conn->binding == false &&
8163 le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8164 signing_key = work->sess->smb3signingkey;
8166 chann = lookup_chann_list(work->sess, work->conn);
8169 signing_key = chann->smb3signingkey;
8175 if (req_hdr->NextCommand)
8176 hdr->NextCommand = cpu_to_le32(len);
8178 hdr->Flags |= SMB2_FLAGS_SIGNED;
8179 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8180 iov[0].iov_base = (char *)&hdr->ProtocolId;
8181 iov[0].iov_len = len;
8182 if (work->aux_payload_sz) {
8183 iov[0].iov_len -= work->aux_payload_sz;
8184 iov[1].iov_base = work->aux_payload_buf;
8185 iov[1].iov_len = work->aux_payload_sz;
8189 if (!ksmbd_sign_smb3_pdu(conn, signing_key, iov, n_vec, signature))
8190 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
8194 * smb3_preauth_hash_rsp() - handler for computing preauth hash on response
8195 * @work: smb work containing response buffer
8198 void smb3_preauth_hash_rsp(struct ksmbd_work *work)
8200 struct ksmbd_conn *conn = work->conn;
8201 struct ksmbd_session *sess = work->sess;
8202 struct smb2_hdr *req, *rsp;
8204 if (conn->dialect != SMB311_PROT_ID)
8207 WORK_BUFFERS(work, req, rsp);
8209 if (le16_to_cpu(req->Command) == SMB2_NEGOTIATE_HE)
8210 ksmbd_gen_preauth_integrity_hash(conn, (char *)rsp,
8211 conn->preauth_info->Preauth_HashValue);
8213 if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE && sess) {
8216 if (conn->binding) {
8217 struct preauth_session *preauth_sess;
8219 preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
8222 hash_value = preauth_sess->Preauth_HashValue;
8224 hash_value = sess->Preauth_HashValue;
8228 ksmbd_gen_preauth_integrity_hash(conn, (char *)rsp,
8233 static void fill_transform_hdr(struct smb2_transform_hdr *tr_hdr, char *old_buf,
8236 struct smb2_hdr *hdr = (struct smb2_hdr *)old_buf;
8237 unsigned int orig_len = get_rfc1002_len(old_buf);
8239 memset(tr_hdr, 0, sizeof(struct smb2_transform_hdr));
8240 tr_hdr->ProtocolId = SMB2_TRANSFORM_PROTO_NUM;
8241 tr_hdr->OriginalMessageSize = cpu_to_le32(orig_len);
8242 tr_hdr->Flags = cpu_to_le16(0x01);
8243 if (cipher_type == SMB2_ENCRYPTION_AES128_GCM ||
8244 cipher_type == SMB2_ENCRYPTION_AES256_GCM)
8245 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_GCM_NONCE);
8247 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_CCM_NONCE);
8248 memcpy(&tr_hdr->SessionId, &hdr->SessionId, 8);
8249 inc_rfc1001_len(tr_hdr, sizeof(struct smb2_transform_hdr) - 4);
8250 inc_rfc1001_len(tr_hdr, orig_len);
8253 int smb3_encrypt_resp(struct ksmbd_work *work)
8255 char *buf = work->response_buf;
8256 struct smb2_transform_hdr *tr_hdr;
8259 int buf_size = 0, rq_nvec = 2 + (work->aux_payload_sz ? 1 : 0);
8261 if (ARRAY_SIZE(iov) < rq_nvec)
8264 tr_hdr = kzalloc(sizeof(struct smb2_transform_hdr), GFP_KERNEL);
8268 /* fill transform header */
8269 fill_transform_hdr(tr_hdr, buf, work->conn->cipher_type);
8271 iov[0].iov_base = tr_hdr;
8272 iov[0].iov_len = sizeof(struct smb2_transform_hdr);
8273 buf_size += iov[0].iov_len - 4;
8275 iov[1].iov_base = buf + 4;
8276 iov[1].iov_len = get_rfc1002_len(buf);
8277 if (work->aux_payload_sz) {
8278 iov[1].iov_len = work->resp_hdr_sz - 4;
8280 iov[2].iov_base = work->aux_payload_buf;
8281 iov[2].iov_len = work->aux_payload_sz;
8282 buf_size += iov[2].iov_len;
8284 buf_size += iov[1].iov_len;
8285 work->resp_hdr_sz = iov[1].iov_len;
8287 rc = ksmbd_crypt_message(work->conn, iov, rq_nvec, 1);
8291 memmove(buf, iov[1].iov_base, iov[1].iov_len);
8292 tr_hdr->smb2_buf_length = cpu_to_be32(buf_size);
8293 work->tr_buf = tr_hdr;
8298 bool smb3_is_transform_hdr(void *buf)
8300 struct smb2_transform_hdr *trhdr = buf;
8302 return trhdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM;
8305 int smb3_decrypt_req(struct ksmbd_work *work)
8307 struct ksmbd_conn *conn = work->conn;
8308 struct ksmbd_session *sess;
8309 char *buf = work->request_buf;
8310 struct smb2_hdr *hdr;
8311 unsigned int pdu_length = get_rfc1002_len(buf);
8313 unsigned int buf_data_size = pdu_length + 4 -
8314 sizeof(struct smb2_transform_hdr);
8315 struct smb2_transform_hdr *tr_hdr = (struct smb2_transform_hdr *)buf;
8316 unsigned int orig_len = le32_to_cpu(tr_hdr->OriginalMessageSize);
8319 sess = ksmbd_session_lookup_all(conn, le64_to_cpu(tr_hdr->SessionId));
8321 pr_err("invalid session id(%llx) in transform header\n",
8322 le64_to_cpu(tr_hdr->SessionId));
8323 return -ECONNABORTED;
8326 if (pdu_length + 4 <
8327 sizeof(struct smb2_transform_hdr) + sizeof(struct smb2_hdr)) {
8328 pr_err("Transform message is too small (%u)\n",
8330 return -ECONNABORTED;
8333 if (pdu_length + 4 < orig_len + sizeof(struct smb2_transform_hdr)) {
8334 pr_err("Transform message is broken\n");
8335 return -ECONNABORTED;
8338 iov[0].iov_base = buf;
8339 iov[0].iov_len = sizeof(struct smb2_transform_hdr);
8340 iov[1].iov_base = buf + sizeof(struct smb2_transform_hdr);
8341 iov[1].iov_len = buf_data_size;
8342 rc = ksmbd_crypt_message(conn, iov, 2, 0);
8346 memmove(buf + 4, iov[1].iov_base, buf_data_size);
8347 hdr = (struct smb2_hdr *)buf;
8348 hdr->smb2_buf_length = cpu_to_be32(buf_data_size);
8353 bool smb3_11_final_sess_setup_resp(struct ksmbd_work *work)
8355 struct ksmbd_conn *conn = work->conn;
8356 struct smb2_hdr *rsp = work->response_buf;
8358 if (conn->dialect < SMB30_PROT_ID)
8361 if (work->next_smb2_rcv_hdr_off)
8362 rsp = ksmbd_resp_buf_next(work);
8364 if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE &&
8365 rsp->Status == STATUS_SUCCESS)