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>
22 #include "connection.h"
23 #include "transport_ipc.h"
24 #include "transport_rdma.h"
26 #include "vfs_cache.h"
30 #include "smb_common.h"
31 #include "smbstatus.h"
32 #include "ksmbd_work.h"
33 #include "mgmt/user_config.h"
34 #include "mgmt/share_config.h"
35 #include "mgmt/tree_connect.h"
36 #include "mgmt/user_session.h"
37 #include "mgmt/ksmbd_ida.h"
40 static void __wbuf(struct ksmbd_work *work, void **req, void **rsp)
42 if (work->next_smb2_rcv_hdr_off) {
43 *req = ksmbd_req_buf_next(work);
44 *rsp = ksmbd_resp_buf_next(work);
46 *req = smb2_get_msg(work->request_buf);
47 *rsp = smb2_get_msg(work->response_buf);
51 #define WORK_BUFFERS(w, rq, rs) __wbuf((w), (void **)&(rq), (void **)&(rs))
54 * check_session_id() - check for valid session id in smb header
55 * @conn: connection instance
56 * @id: session id from smb header
58 * Return: 1 if valid session id, otherwise 0
60 static inline bool check_session_id(struct ksmbd_conn *conn, u64 id)
62 struct ksmbd_session *sess;
64 if (id == 0 || id == -1)
67 sess = ksmbd_session_lookup_all(conn, id);
70 pr_err("Invalid user session id: %llu\n", id);
74 struct channel *lookup_chann_list(struct ksmbd_session *sess, struct ksmbd_conn *conn)
76 struct channel *chann;
78 list_for_each_entry(chann, &sess->ksmbd_chann_list, chann_list) {
79 if (chann->conn == conn)
87 * smb2_get_ksmbd_tcon() - get tree connection information using a tree id.
90 * Return: 0 if there is a tree connection matched or these are
91 * skipable commands, otherwise error
93 int smb2_get_ksmbd_tcon(struct ksmbd_work *work)
95 struct smb2_hdr *req_hdr = smb2_get_msg(work->request_buf);
96 unsigned int cmd = le16_to_cpu(req_hdr->Command);
100 if (cmd == SMB2_TREE_CONNECT_HE ||
101 cmd == SMB2_CANCEL_HE ||
102 cmd == 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 = smb2_get_msg(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 = smb2_get_msg(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 = smb2_get_msg(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 = smb2_get_msg(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 = smb2_get_msg(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)
240 *(__be32 *)work->response_buf =
241 cpu_to_be32(conn->vals->header_size);
243 rsp_hdr = smb2_get_msg(work->response_buf);
244 memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
245 rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
246 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
247 rsp_hdr->CreditRequest = cpu_to_le16(2);
248 rsp_hdr->Command = SMB2_NEGOTIATE;
249 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
250 rsp_hdr->NextCommand = 0;
251 rsp_hdr->MessageId = 0;
252 rsp_hdr->Id.SyncId.ProcessId = 0;
253 rsp_hdr->Id.SyncId.TreeId = 0;
254 rsp_hdr->SessionId = 0;
255 memset(rsp_hdr->Signature, 0, 16);
257 rsp = smb2_get_msg(work->response_buf);
259 WARN_ON(ksmbd_conn_good(work));
261 rsp->StructureSize = cpu_to_le16(65);
262 ksmbd_debug(SMB, "conn->dialect 0x%x\n", conn->dialect);
263 rsp->DialectRevision = cpu_to_le16(conn->dialect);
264 /* Not setting conn guid rsp->ServerGUID, as it
265 * not used by client for identifying connection
267 rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
268 /* Default Max Message Size till SMB2.0, 64K*/
269 rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
270 rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
271 rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);
273 rsp->SystemTime = cpu_to_le64(ksmbd_systime());
274 rsp->ServerStartTime = 0;
276 rsp->SecurityBufferOffset = cpu_to_le16(128);
277 rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
278 ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) +
279 le16_to_cpu(rsp->SecurityBufferOffset));
280 inc_rfc1001_len(work->response_buf,
281 sizeof(struct smb2_negotiate_rsp) -
282 sizeof(struct smb2_hdr) - sizeof(rsp->Buffer) +
284 rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
285 if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY)
286 rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
287 conn->use_spnego = true;
289 ksmbd_conn_set_need_negotiate(work);
294 * smb2_set_rsp_credits() - set number of credits in response buffer
295 * @work: smb work containing smb response buffer
297 int smb2_set_rsp_credits(struct ksmbd_work *work)
299 struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
300 struct smb2_hdr *hdr = ksmbd_resp_buf_next(work);
301 struct ksmbd_conn *conn = work->conn;
302 unsigned short credits_requested, aux_max;
303 unsigned short credit_charge, credits_granted = 0;
305 if (work->send_no_response)
308 hdr->CreditCharge = req_hdr->CreditCharge;
310 if (conn->total_credits > conn->vals->max_credits) {
311 hdr->CreditRequest = 0;
312 pr_err("Total credits overflow: %d\n", conn->total_credits);
316 credit_charge = max_t(unsigned short,
317 le16_to_cpu(req_hdr->CreditCharge), 1);
318 if (credit_charge > conn->total_credits) {
319 ksmbd_debug(SMB, "Insufficient credits granted, given: %u, granted: %u\n",
320 credit_charge, conn->total_credits);
324 conn->total_credits -= credit_charge;
325 conn->outstanding_credits -= credit_charge;
326 credits_requested = max_t(unsigned short,
327 le16_to_cpu(req_hdr->CreditRequest), 1);
329 /* according to smb2.credits smbtorture, Windows server
330 * 2016 or later grant up to 8192 credits at once.
332 * TODO: Need to adjuct CreditRequest value according to
335 if (hdr->Command == SMB2_NEGOTIATE)
338 aux_max = conn->vals->max_credits - credit_charge;
339 credits_granted = min_t(unsigned short, credits_requested, aux_max);
341 if (conn->vals->max_credits - conn->total_credits < credits_granted)
342 credits_granted = conn->vals->max_credits -
345 conn->total_credits += credits_granted;
346 work->credits_granted += credits_granted;
348 if (!req_hdr->NextCommand) {
349 /* Update CreditRequest in last request */
350 hdr->CreditRequest = cpu_to_le16(work->credits_granted);
353 "credits: requested[%d] granted[%d] total_granted[%d]\n",
354 credits_requested, credits_granted,
355 conn->total_credits);
360 * init_chained_smb2_rsp() - initialize smb2 chained response
361 * @work: smb work containing smb response buffer
363 static void init_chained_smb2_rsp(struct ksmbd_work *work)
365 struct smb2_hdr *req = ksmbd_req_buf_next(work);
366 struct smb2_hdr *rsp = ksmbd_resp_buf_next(work);
367 struct smb2_hdr *rsp_hdr;
368 struct smb2_hdr *rcv_hdr;
369 int next_hdr_offset = 0;
372 /* Len of this response = updated RFC len - offset of previous cmd
373 * in the compound rsp
376 /* Storing the current local FID which may be needed by subsequent
377 * command in the compound request
379 if (req->Command == SMB2_CREATE && rsp->Status == STATUS_SUCCESS) {
381 le64_to_cpu(((struct smb2_create_rsp *)rsp)->
383 work->compound_pfid =
384 le64_to_cpu(((struct smb2_create_rsp *)rsp)->
386 work->compound_sid = le64_to_cpu(rsp->SessionId);
389 len = get_rfc1002_len(work->response_buf) - work->next_smb2_rsp_hdr_off;
390 next_hdr_offset = le32_to_cpu(req->NextCommand);
392 new_len = ALIGN(len, 8);
393 inc_rfc1001_len(work->response_buf,
394 sizeof(struct smb2_hdr) + new_len - len);
395 rsp->NextCommand = cpu_to_le32(new_len);
397 work->next_smb2_rcv_hdr_off += next_hdr_offset;
398 work->next_smb2_rsp_hdr_off += new_len;
400 "Compound req new_len = %d rcv off = %d rsp off = %d\n",
401 new_len, work->next_smb2_rcv_hdr_off,
402 work->next_smb2_rsp_hdr_off);
404 rsp_hdr = ksmbd_resp_buf_next(work);
405 rcv_hdr = ksmbd_req_buf_next(work);
407 if (!(rcv_hdr->Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
408 ksmbd_debug(SMB, "related flag should be set\n");
409 work->compound_fid = KSMBD_NO_FID;
410 work->compound_pfid = KSMBD_NO_FID;
412 memset((char *)rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
413 rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
414 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
415 rsp_hdr->Command = rcv_hdr->Command;
418 * Message is response. We don't grant oplock yet.
420 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR |
421 SMB2_FLAGS_RELATED_OPERATIONS);
422 rsp_hdr->NextCommand = 0;
423 rsp_hdr->MessageId = rcv_hdr->MessageId;
424 rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
425 rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
426 rsp_hdr->SessionId = rcv_hdr->SessionId;
427 memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);
431 * is_chained_smb2_message() - check for chained command
432 * @work: smb work containing smb request buffer
434 * Return: true if chained request, otherwise false
436 bool is_chained_smb2_message(struct ksmbd_work *work)
438 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
439 unsigned int len, next_cmd;
441 if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
444 hdr = ksmbd_req_buf_next(work);
445 next_cmd = le32_to_cpu(hdr->NextCommand);
447 if ((u64)work->next_smb2_rcv_hdr_off + next_cmd +
448 __SMB2_HEADER_STRUCTURE_SIZE >
449 get_rfc1002_len(work->request_buf)) {
450 pr_err("next command(%u) offset exceeds smb msg size\n",
455 if ((u64)get_rfc1002_len(work->response_buf) + MAX_CIFS_SMALL_BUFFER_SIZE >
457 pr_err("next response offset exceeds response buffer size\n");
461 ksmbd_debug(SMB, "got SMB2 chained command\n");
462 init_chained_smb2_rsp(work);
464 } else if (work->next_smb2_rcv_hdr_off) {
466 * This is last request in chained command,
467 * align response to 8 byte
469 len = ALIGN(get_rfc1002_len(work->response_buf), 8);
470 len = len - get_rfc1002_len(work->response_buf);
472 ksmbd_debug(SMB, "padding len %u\n", len);
473 inc_rfc1001_len(work->response_buf, len);
474 if (work->aux_payload_sz)
475 work->aux_payload_sz += len;
482 * init_smb2_rsp_hdr() - initialize smb2 response
483 * @work: smb work containing smb request buffer
487 int init_smb2_rsp_hdr(struct ksmbd_work *work)
489 struct smb2_hdr *rsp_hdr = smb2_get_msg(work->response_buf);
490 struct smb2_hdr *rcv_hdr = smb2_get_msg(work->request_buf);
491 struct ksmbd_conn *conn = work->conn;
493 memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
494 *(__be32 *)work->response_buf =
495 cpu_to_be32(conn->vals->header_size);
496 rsp_hdr->ProtocolId = rcv_hdr->ProtocolId;
497 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
498 rsp_hdr->Command = rcv_hdr->Command;
501 * Message is response. We don't grant oplock yet.
503 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
504 rsp_hdr->NextCommand = 0;
505 rsp_hdr->MessageId = rcv_hdr->MessageId;
506 rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
507 rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
508 rsp_hdr->SessionId = rcv_hdr->SessionId;
509 memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);
511 work->syncronous = true;
512 if (work->async_id) {
513 ksmbd_release_id(&conn->async_ida, work->async_id);
521 * smb2_allocate_rsp_buf() - allocate smb2 response buffer
522 * @work: smb work containing smb request buffer
524 * Return: 0 on success, otherwise -ENOMEM
526 int smb2_allocate_rsp_buf(struct ksmbd_work *work)
528 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
529 size_t small_sz = MAX_CIFS_SMALL_BUFFER_SIZE;
530 size_t large_sz = small_sz + work->conn->vals->max_trans_size;
531 size_t sz = small_sz;
532 int cmd = le16_to_cpu(hdr->Command);
534 if (cmd == SMB2_IOCTL_HE || cmd == SMB2_QUERY_DIRECTORY_HE)
537 if (cmd == SMB2_QUERY_INFO_HE) {
538 struct smb2_query_info_req *req;
540 req = smb2_get_msg(work->request_buf);
541 if (req->InfoType == SMB2_O_INFO_FILE &&
542 (req->FileInfoClass == FILE_FULL_EA_INFORMATION ||
543 req->FileInfoClass == FILE_ALL_INFORMATION))
547 /* allocate large response buf for chained commands */
548 if (le32_to_cpu(hdr->NextCommand) > 0)
551 work->response_buf = kvmalloc(sz, GFP_KERNEL | __GFP_ZERO);
552 if (!work->response_buf)
555 work->response_sz = sz;
560 * smb2_check_user_session() - check for valid session for a user
561 * @work: smb work containing smb request buffer
563 * Return: 0 on success, otherwise error
565 int smb2_check_user_session(struct ksmbd_work *work)
567 struct smb2_hdr *req_hdr = smb2_get_msg(work->request_buf);
568 struct ksmbd_conn *conn = work->conn;
569 unsigned int cmd = conn->ops->get_cmd_val(work);
570 unsigned long long sess_id;
574 * SMB2_ECHO, SMB2_NEGOTIATE, SMB2_SESSION_SETUP command do not
575 * require a session id, so no need to validate user session's for
578 if (cmd == SMB2_ECHO_HE || cmd == SMB2_NEGOTIATE_HE ||
579 cmd == SMB2_SESSION_SETUP_HE)
582 if (!ksmbd_conn_good(work))
585 sess_id = le64_to_cpu(req_hdr->SessionId);
586 /* Check for validity of user session */
587 work->sess = ksmbd_session_lookup_all(conn, sess_id);
590 ksmbd_debug(SMB, "Invalid user session, Uid %llu\n", sess_id);
594 static void destroy_previous_session(struct ksmbd_user *user, u64 id)
596 struct ksmbd_session *prev_sess = ksmbd_session_lookup_slowpath(id);
597 struct ksmbd_user *prev_user;
602 prev_user = prev_sess->user;
605 strcmp(user->name, prev_user->name) ||
606 user->passkey_sz != prev_user->passkey_sz ||
607 memcmp(user->passkey, prev_user->passkey, user->passkey_sz)) {
608 put_session(prev_sess);
612 put_session(prev_sess);
613 ksmbd_session_destroy(prev_sess);
617 * smb2_get_name() - get filename string from on the wire smb format
618 * @src: source buffer
619 * @maxlen: maxlen of source string
620 * @local_nls: nls_table pointer
622 * Return: matching converted filename on success, otherwise error ptr
625 smb2_get_name(const char *src, const int maxlen, struct nls_table *local_nls)
629 name = smb_strndup_from_utf16(src, maxlen, 1, local_nls);
631 pr_err("failed to get name %ld\n", PTR_ERR(name));
635 ksmbd_conv_path_to_unix(name);
636 ksmbd_strip_last_slash(name);
640 int setup_async_work(struct ksmbd_work *work, void (*fn)(void **), void **arg)
642 struct smb2_hdr *rsp_hdr;
643 struct ksmbd_conn *conn = work->conn;
646 rsp_hdr = smb2_get_msg(work->response_buf);
647 rsp_hdr->Flags |= SMB2_FLAGS_ASYNC_COMMAND;
649 id = ksmbd_acquire_async_msg_id(&conn->async_ida);
651 pr_err("Failed to alloc async message id\n");
654 work->syncronous = false;
656 rsp_hdr->Id.AsyncId = cpu_to_le64(id);
659 "Send interim Response to inform async request id : %d\n",
662 work->cancel_fn = fn;
663 work->cancel_argv = arg;
665 if (list_empty(&work->async_request_entry)) {
666 spin_lock(&conn->request_lock);
667 list_add_tail(&work->async_request_entry, &conn->async_requests);
668 spin_unlock(&conn->request_lock);
674 void smb2_send_interim_resp(struct ksmbd_work *work, __le32 status)
676 struct smb2_hdr *rsp_hdr;
678 rsp_hdr = smb2_get_msg(work->response_buf);
679 smb2_set_err_rsp(work);
680 rsp_hdr->Status = status;
683 ksmbd_conn_write(work);
688 static __le32 smb2_get_reparse_tag_special_file(umode_t mode)
690 if (S_ISDIR(mode) || S_ISREG(mode))
694 return IO_REPARSE_TAG_LX_SYMLINK_LE;
695 else if (S_ISFIFO(mode))
696 return IO_REPARSE_TAG_LX_FIFO_LE;
697 else if (S_ISSOCK(mode))
698 return IO_REPARSE_TAG_AF_UNIX_LE;
699 else if (S_ISCHR(mode))
700 return IO_REPARSE_TAG_LX_CHR_LE;
701 else if (S_ISBLK(mode))
702 return IO_REPARSE_TAG_LX_BLK_LE;
708 * smb2_get_dos_mode() - get file mode in dos format from unix mode
709 * @stat: kstat containing file mode
710 * @attribute: attribute flags
712 * Return: converted dos mode
714 static int smb2_get_dos_mode(struct kstat *stat, int attribute)
718 if (S_ISDIR(stat->mode)) {
719 attr = FILE_ATTRIBUTE_DIRECTORY |
720 (attribute & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM));
722 attr = (attribute & 0x00005137) | FILE_ATTRIBUTE_ARCHIVE;
723 attr &= ~(FILE_ATTRIBUTE_DIRECTORY);
724 if (S_ISREG(stat->mode) && (server_conf.share_fake_fscaps &
725 FILE_SUPPORTS_SPARSE_FILES))
726 attr |= FILE_ATTRIBUTE_SPARSE_FILE;
728 if (smb2_get_reparse_tag_special_file(stat->mode))
729 attr |= FILE_ATTRIBUTE_REPARSE_POINT;
735 static void build_preauth_ctxt(struct smb2_preauth_neg_context *pneg_ctxt,
738 pneg_ctxt->ContextType = SMB2_PREAUTH_INTEGRITY_CAPABILITIES;
739 pneg_ctxt->DataLength = cpu_to_le16(38);
740 pneg_ctxt->HashAlgorithmCount = cpu_to_le16(1);
741 pneg_ctxt->Reserved = cpu_to_le32(0);
742 pneg_ctxt->SaltLength = cpu_to_le16(SMB311_SALT_SIZE);
743 get_random_bytes(pneg_ctxt->Salt, SMB311_SALT_SIZE);
744 pneg_ctxt->HashAlgorithms = hash_id;
747 static void build_encrypt_ctxt(struct smb2_encryption_neg_context *pneg_ctxt,
750 pneg_ctxt->ContextType = SMB2_ENCRYPTION_CAPABILITIES;
751 pneg_ctxt->DataLength = cpu_to_le16(4);
752 pneg_ctxt->Reserved = cpu_to_le32(0);
753 pneg_ctxt->CipherCount = cpu_to_le16(1);
754 pneg_ctxt->Ciphers[0] = cipher_type;
757 static void build_compression_ctxt(struct smb2_compression_capabilities_context *pneg_ctxt,
760 pneg_ctxt->ContextType = SMB2_COMPRESSION_CAPABILITIES;
761 pneg_ctxt->DataLength =
762 cpu_to_le16(sizeof(struct smb2_compression_capabilities_context)
763 - sizeof(struct smb2_neg_context));
764 pneg_ctxt->Reserved = cpu_to_le32(0);
765 pneg_ctxt->CompressionAlgorithmCount = cpu_to_le16(1);
766 pneg_ctxt->Flags = cpu_to_le32(0);
767 pneg_ctxt->CompressionAlgorithms[0] = comp_algo;
770 static void build_sign_cap_ctxt(struct smb2_signing_capabilities *pneg_ctxt,
773 pneg_ctxt->ContextType = SMB2_SIGNING_CAPABILITIES;
774 pneg_ctxt->DataLength =
775 cpu_to_le16((sizeof(struct smb2_signing_capabilities) + 2)
776 - sizeof(struct smb2_neg_context));
777 pneg_ctxt->Reserved = cpu_to_le32(0);
778 pneg_ctxt->SigningAlgorithmCount = cpu_to_le16(1);
779 pneg_ctxt->SigningAlgorithms[0] = sign_algo;
782 static void build_posix_ctxt(struct smb2_posix_neg_context *pneg_ctxt)
784 pneg_ctxt->ContextType = SMB2_POSIX_EXTENSIONS_AVAILABLE;
785 pneg_ctxt->DataLength = cpu_to_le16(POSIX_CTXT_DATA_LEN);
786 /* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */
787 pneg_ctxt->Name[0] = 0x93;
788 pneg_ctxt->Name[1] = 0xAD;
789 pneg_ctxt->Name[2] = 0x25;
790 pneg_ctxt->Name[3] = 0x50;
791 pneg_ctxt->Name[4] = 0x9C;
792 pneg_ctxt->Name[5] = 0xB4;
793 pneg_ctxt->Name[6] = 0x11;
794 pneg_ctxt->Name[7] = 0xE7;
795 pneg_ctxt->Name[8] = 0xB4;
796 pneg_ctxt->Name[9] = 0x23;
797 pneg_ctxt->Name[10] = 0x83;
798 pneg_ctxt->Name[11] = 0xDE;
799 pneg_ctxt->Name[12] = 0x96;
800 pneg_ctxt->Name[13] = 0x8B;
801 pneg_ctxt->Name[14] = 0xCD;
802 pneg_ctxt->Name[15] = 0x7C;
805 static void assemble_neg_contexts(struct ksmbd_conn *conn,
806 struct smb2_negotiate_rsp *rsp,
809 char *pneg_ctxt = (char *)rsp +
810 le32_to_cpu(rsp->NegotiateContextOffset);
811 int neg_ctxt_cnt = 1;
815 "assemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
816 build_preauth_ctxt((struct smb2_preauth_neg_context *)pneg_ctxt,
817 conn->preauth_info->Preauth_HashId);
818 rsp->NegotiateContextCount = cpu_to_le16(neg_ctxt_cnt);
819 inc_rfc1001_len(smb2_buf_len, AUTH_GSS_PADDING);
820 ctxt_size = sizeof(struct smb2_preauth_neg_context);
821 /* Round to 8 byte boundary */
822 pneg_ctxt += round_up(sizeof(struct smb2_preauth_neg_context), 8);
824 if (conn->cipher_type) {
825 ctxt_size = round_up(ctxt_size, 8);
827 "assemble SMB2_ENCRYPTION_CAPABILITIES context\n");
828 build_encrypt_ctxt((struct smb2_encryption_neg_context *)pneg_ctxt,
830 rsp->NegotiateContextCount = cpu_to_le16(++neg_ctxt_cnt);
831 ctxt_size += sizeof(struct smb2_encryption_neg_context) + 2;
832 /* Round to 8 byte boundary */
834 round_up(sizeof(struct smb2_encryption_neg_context) + 2,
838 if (conn->compress_algorithm) {
839 ctxt_size = round_up(ctxt_size, 8);
841 "assemble SMB2_COMPRESSION_CAPABILITIES context\n");
842 /* Temporarily set to SMB3_COMPRESS_NONE */
843 build_compression_ctxt((struct smb2_compression_capabilities_context *)pneg_ctxt,
844 conn->compress_algorithm);
845 rsp->NegotiateContextCount = cpu_to_le16(++neg_ctxt_cnt);
846 ctxt_size += sizeof(struct smb2_compression_capabilities_context) + 2;
847 /* Round to 8 byte boundary */
848 pneg_ctxt += round_up(sizeof(struct smb2_compression_capabilities_context) + 2,
852 if (conn->posix_ext_supported) {
853 ctxt_size = round_up(ctxt_size, 8);
855 "assemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
856 build_posix_ctxt((struct smb2_posix_neg_context *)pneg_ctxt);
857 rsp->NegotiateContextCount = cpu_to_le16(++neg_ctxt_cnt);
858 ctxt_size += sizeof(struct smb2_posix_neg_context);
859 /* Round to 8 byte boundary */
860 pneg_ctxt += round_up(sizeof(struct smb2_posix_neg_context), 8);
863 if (conn->signing_negotiated) {
864 ctxt_size = round_up(ctxt_size, 8);
866 "assemble SMB2_SIGNING_CAPABILITIES context\n");
867 build_sign_cap_ctxt((struct smb2_signing_capabilities *)pneg_ctxt,
868 conn->signing_algorithm);
869 rsp->NegotiateContextCount = cpu_to_le16(++neg_ctxt_cnt);
870 ctxt_size += sizeof(struct smb2_signing_capabilities) + 2;
873 inc_rfc1001_len(smb2_buf_len, ctxt_size);
876 static __le32 decode_preauth_ctxt(struct ksmbd_conn *conn,
877 struct smb2_preauth_neg_context *pneg_ctxt)
879 __le32 err = STATUS_NO_PREAUTH_INTEGRITY_HASH_OVERLAP;
881 if (pneg_ctxt->HashAlgorithms == SMB2_PREAUTH_INTEGRITY_SHA512) {
882 conn->preauth_info->Preauth_HashId =
883 SMB2_PREAUTH_INTEGRITY_SHA512;
884 err = STATUS_SUCCESS;
890 static void decode_encrypt_ctxt(struct ksmbd_conn *conn,
891 struct smb2_encryption_neg_context *pneg_ctxt,
894 int cph_cnt = le16_to_cpu(pneg_ctxt->CipherCount);
895 int i, cphs_size = cph_cnt * sizeof(__le16);
897 conn->cipher_type = 0;
899 if (sizeof(struct smb2_encryption_neg_context) + cphs_size >
901 pr_err("Invalid cipher count(%d)\n", cph_cnt);
905 if (!(server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION))
908 for (i = 0; i < cph_cnt; i++) {
909 if (pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_GCM ||
910 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_CCM ||
911 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_CCM ||
912 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_GCM) {
913 ksmbd_debug(SMB, "Cipher ID = 0x%x\n",
914 pneg_ctxt->Ciphers[i]);
915 conn->cipher_type = pneg_ctxt->Ciphers[i];
922 * smb3_encryption_negotiated() - checks if server and client agreed on enabling encryption
923 * @conn: smb connection
925 * Return: true if connection should be encrypted, else false
927 static bool smb3_encryption_negotiated(struct ksmbd_conn *conn)
929 if (!conn->ops->generate_encryptionkey)
933 * SMB 3.0 and 3.0.2 dialects use the SMB2_GLOBAL_CAP_ENCRYPTION flag.
934 * SMB 3.1.1 uses the cipher_type field.
936 return (conn->vals->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION) ||
940 static void decode_compress_ctxt(struct ksmbd_conn *conn,
941 struct smb2_compression_capabilities_context *pneg_ctxt)
943 conn->compress_algorithm = SMB3_COMPRESS_NONE;
946 static void decode_sign_cap_ctxt(struct ksmbd_conn *conn,
947 struct smb2_signing_capabilities *pneg_ctxt,
950 int sign_algo_cnt = le16_to_cpu(pneg_ctxt->SigningAlgorithmCount);
951 int i, sign_alos_size = sign_algo_cnt * sizeof(__le16);
953 conn->signing_negotiated = false;
955 if (sizeof(struct smb2_signing_capabilities) + sign_alos_size >
957 pr_err("Invalid signing algorithm count(%d)\n", sign_algo_cnt);
961 for (i = 0; i < sign_algo_cnt; i++) {
962 if (pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_HMAC_SHA256_LE ||
963 pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_AES_CMAC_LE) {
964 ksmbd_debug(SMB, "Signing Algorithm ID = 0x%x\n",
965 pneg_ctxt->SigningAlgorithms[i]);
966 conn->signing_negotiated = true;
967 conn->signing_algorithm =
968 pneg_ctxt->SigningAlgorithms[i];
974 static __le32 deassemble_neg_contexts(struct ksmbd_conn *conn,
975 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 *)req;
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 __le32 status = STATUS_INVALID_PARAMETER;
985 ksmbd_debug(SMB, "decoding %d negotiate contexts\n", neg_ctxt_cnt);
986 if (len_of_smb <= offset) {
987 ksmbd_debug(SMB, "Invalid response: negotiate context offset\n");
991 len_of_ctxts = len_of_smb - offset;
993 while (i++ < neg_ctxt_cnt) {
996 /* check that offset is not beyond end of SMB */
997 if (len_of_ctxts == 0)
1000 if (len_of_ctxts < sizeof(struct smb2_neg_context))
1003 pctx = (struct smb2_neg_context *)((char *)pctx + offset);
1004 clen = le16_to_cpu(pctx->DataLength);
1005 if (clen + sizeof(struct smb2_neg_context) > len_of_ctxts)
1008 if (pctx->ContextType == SMB2_PREAUTH_INTEGRITY_CAPABILITIES) {
1010 "deassemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
1011 if (conn->preauth_info->Preauth_HashId)
1014 status = decode_preauth_ctxt(conn,
1015 (struct smb2_preauth_neg_context *)pctx);
1016 if (status != STATUS_SUCCESS)
1018 } else if (pctx->ContextType == SMB2_ENCRYPTION_CAPABILITIES) {
1020 "deassemble SMB2_ENCRYPTION_CAPABILITIES context\n");
1021 if (conn->cipher_type)
1024 decode_encrypt_ctxt(conn,
1025 (struct smb2_encryption_neg_context *)pctx,
1027 } else if (pctx->ContextType == SMB2_COMPRESSION_CAPABILITIES) {
1029 "deassemble SMB2_COMPRESSION_CAPABILITIES context\n");
1030 if (conn->compress_algorithm)
1033 decode_compress_ctxt(conn,
1034 (struct smb2_compression_capabilities_context *)pctx);
1035 } else if (pctx->ContextType == SMB2_NETNAME_NEGOTIATE_CONTEXT_ID) {
1037 "deassemble SMB2_NETNAME_NEGOTIATE_CONTEXT_ID context\n");
1038 } else if (pctx->ContextType == SMB2_POSIX_EXTENSIONS_AVAILABLE) {
1040 "deassemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
1041 conn->posix_ext_supported = true;
1042 } else if (pctx->ContextType == SMB2_SIGNING_CAPABILITIES) {
1044 "deassemble SMB2_SIGNING_CAPABILITIES context\n");
1045 decode_sign_cap_ctxt(conn,
1046 (struct smb2_signing_capabilities *)pctx,
1050 /* offsets must be 8 byte aligned */
1051 clen = (clen + 7) & ~0x7;
1052 offset = clen + sizeof(struct smb2_neg_context);
1053 len_of_ctxts -= clen + sizeof(struct smb2_neg_context);
1059 * smb2_handle_negotiate() - handler for smb2 negotiate command
1060 * @work: smb work containing smb request buffer
1064 int smb2_handle_negotiate(struct ksmbd_work *work)
1066 struct ksmbd_conn *conn = work->conn;
1067 struct smb2_negotiate_req *req = smb2_get_msg(work->request_buf);
1068 struct smb2_negotiate_rsp *rsp = smb2_get_msg(work->response_buf);
1070 unsigned int smb2_buf_len, smb2_neg_size;
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 smb2_buf_len = get_rfc1002_len(work->request_buf);
1089 smb2_neg_size = offsetof(struct smb2_negotiate_req, Dialects);
1090 if (smb2_neg_size > smb2_buf_len) {
1091 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1096 if (conn->dialect == SMB311_PROT_ID) {
1097 unsigned int nego_ctxt_off = le32_to_cpu(req->NegotiateContextOffset);
1099 if (smb2_buf_len < nego_ctxt_off) {
1100 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1105 if (smb2_neg_size > nego_ctxt_off) {
1106 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1111 if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
1113 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1118 if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
1120 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1126 conn->cli_cap = le32_to_cpu(req->Capabilities);
1127 switch (conn->dialect) {
1128 case SMB311_PROT_ID:
1129 conn->preauth_info =
1130 kzalloc(sizeof(struct preauth_integrity_info),
1132 if (!conn->preauth_info) {
1134 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1138 status = deassemble_neg_contexts(conn, req,
1139 get_rfc1002_len(work->request_buf));
1140 if (status != STATUS_SUCCESS) {
1141 pr_err("deassemble_neg_contexts error(0x%x)\n",
1143 rsp->hdr.Status = status;
1148 rc = init_smb3_11_server(conn);
1150 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1154 ksmbd_gen_preauth_integrity_hash(conn,
1156 conn->preauth_info->Preauth_HashValue);
1157 rsp->NegotiateContextOffset =
1158 cpu_to_le32(OFFSET_OF_NEG_CONTEXT);
1159 assemble_neg_contexts(conn, rsp, work->response_buf);
1161 case SMB302_PROT_ID:
1162 init_smb3_02_server(conn);
1165 init_smb3_0_server(conn);
1168 init_smb2_1_server(conn);
1173 ksmbd_debug(SMB, "Server dialect :0x%x not supported\n",
1175 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
1179 rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
1182 conn->connection_type = conn->dialect;
1184 rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
1185 rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
1186 rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);
1188 memcpy(conn->ClientGUID, req->ClientGUID,
1189 SMB2_CLIENT_GUID_SIZE);
1190 conn->cli_sec_mode = le16_to_cpu(req->SecurityMode);
1192 rsp->StructureSize = cpu_to_le16(65);
1193 rsp->DialectRevision = cpu_to_le16(conn->dialect);
1194 /* Not setting conn guid rsp->ServerGUID, as it
1195 * not used by client for identifying server
1197 memset(rsp->ServerGUID, 0, SMB2_CLIENT_GUID_SIZE);
1199 rsp->SystemTime = cpu_to_le64(ksmbd_systime());
1200 rsp->ServerStartTime = 0;
1201 ksmbd_debug(SMB, "negotiate context offset %d, count %d\n",
1202 le32_to_cpu(rsp->NegotiateContextOffset),
1203 le16_to_cpu(rsp->NegotiateContextCount));
1205 rsp->SecurityBufferOffset = cpu_to_le16(128);
1206 rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
1207 ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) +
1208 le16_to_cpu(rsp->SecurityBufferOffset));
1209 inc_rfc1001_len(work->response_buf, sizeof(struct smb2_negotiate_rsp) -
1210 sizeof(struct smb2_hdr) - sizeof(rsp->Buffer) +
1212 rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
1213 conn->use_spnego = true;
1215 if ((server_conf.signing == KSMBD_CONFIG_OPT_AUTO ||
1216 server_conf.signing == KSMBD_CONFIG_OPT_DISABLED) &&
1217 req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED_LE)
1219 else if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY) {
1220 server_conf.enforced_signing = true;
1221 rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
1225 conn->srv_sec_mode = le16_to_cpu(rsp->SecurityMode);
1226 ksmbd_conn_set_need_negotiate(work);
1230 smb2_set_err_rsp(work);
1235 static int alloc_preauth_hash(struct ksmbd_session *sess,
1236 struct ksmbd_conn *conn)
1238 if (sess->Preauth_HashValue)
1241 sess->Preauth_HashValue = kmemdup(conn->preauth_info->Preauth_HashValue,
1242 PREAUTH_HASHVALUE_SIZE, GFP_KERNEL);
1243 if (!sess->Preauth_HashValue)
1249 static int generate_preauth_hash(struct ksmbd_work *work)
1251 struct ksmbd_conn *conn = work->conn;
1252 struct ksmbd_session *sess = work->sess;
1255 if (conn->dialect != SMB311_PROT_ID)
1258 if (conn->binding) {
1259 struct preauth_session *preauth_sess;
1261 preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
1262 if (!preauth_sess) {
1263 preauth_sess = ksmbd_preauth_session_alloc(conn, sess->id);
1268 preauth_hash = preauth_sess->Preauth_HashValue;
1270 if (!sess->Preauth_HashValue)
1271 if (alloc_preauth_hash(sess, conn))
1273 preauth_hash = sess->Preauth_HashValue;
1276 ksmbd_gen_preauth_integrity_hash(conn, work->request_buf, preauth_hash);
1280 static int decode_negotiation_token(struct ksmbd_conn *conn,
1281 struct negotiate_message *negblob,
1284 if (!conn->use_spnego)
1287 if (ksmbd_decode_negTokenInit((char *)negblob, sz, conn)) {
1288 if (ksmbd_decode_negTokenTarg((char *)negblob, sz, conn)) {
1289 conn->auth_mechs |= KSMBD_AUTH_NTLMSSP;
1290 conn->preferred_auth_mech = KSMBD_AUTH_NTLMSSP;
1291 conn->use_spnego = false;
1297 static int ntlm_negotiate(struct ksmbd_work *work,
1298 struct negotiate_message *negblob,
1301 struct smb2_sess_setup_rsp *rsp = smb2_get_msg(work->response_buf);
1302 struct challenge_message *chgblob;
1303 unsigned char *spnego_blob = NULL;
1304 u16 spnego_blob_len;
1308 ksmbd_debug(SMB, "negotiate phase\n");
1309 rc = ksmbd_decode_ntlmssp_neg_blob(negblob, negblob_len, work->conn);
1313 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1315 (struct challenge_message *)((char *)&rsp->hdr.ProtocolId + sz);
1316 memset(chgblob, 0, sizeof(struct challenge_message));
1318 if (!work->conn->use_spnego) {
1319 sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
1323 rsp->SecurityBufferLength = cpu_to_le16(sz);
1327 sz = sizeof(struct challenge_message);
1328 sz += (strlen(ksmbd_netbios_name()) * 2 + 1 + 4) * 6;
1330 neg_blob = kzalloc(sz, GFP_KERNEL);
1334 chgblob = (struct challenge_message *)neg_blob;
1335 sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
1341 rc = build_spnego_ntlmssp_neg_blob(&spnego_blob, &spnego_blob_len,
1348 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1349 memcpy((char *)&rsp->hdr.ProtocolId + sz, spnego_blob, spnego_blob_len);
1350 rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
1358 static struct authenticate_message *user_authblob(struct ksmbd_conn *conn,
1359 struct smb2_sess_setup_req *req)
1363 if (conn->use_spnego && conn->mechToken)
1364 return (struct authenticate_message *)conn->mechToken;
1366 sz = le16_to_cpu(req->SecurityBufferOffset);
1367 return (struct authenticate_message *)((char *)&req->hdr.ProtocolId
1371 static struct ksmbd_user *session_user(struct ksmbd_conn *conn,
1372 struct smb2_sess_setup_req *req)
1374 struct authenticate_message *authblob;
1375 struct ksmbd_user *user;
1377 unsigned int auth_msg_len, name_off, name_len, secbuf_len;
1379 secbuf_len = le16_to_cpu(req->SecurityBufferLength);
1380 if (secbuf_len < sizeof(struct authenticate_message)) {
1381 ksmbd_debug(SMB, "blob len %d too small\n", secbuf_len);
1384 authblob = user_authblob(conn, req);
1385 name_off = le32_to_cpu(authblob->UserName.BufferOffset);
1386 name_len = le16_to_cpu(authblob->UserName.Length);
1387 auth_msg_len = le16_to_cpu(req->SecurityBufferOffset) + secbuf_len;
1389 if (auth_msg_len < (u64)name_off + name_len)
1392 name = smb_strndup_from_utf16((const char *)authblob + name_off,
1397 pr_err("cannot allocate memory\n");
1401 ksmbd_debug(SMB, "session setup request for user %s\n", name);
1402 user = ksmbd_login_user(name);
1407 static int ntlm_authenticate(struct ksmbd_work *work)
1409 struct smb2_sess_setup_req *req = smb2_get_msg(work->request_buf);
1410 struct smb2_sess_setup_rsp *rsp = smb2_get_msg(work->response_buf);
1411 struct ksmbd_conn *conn = work->conn;
1412 struct ksmbd_session *sess = work->sess;
1413 struct channel *chann = NULL;
1414 struct ksmbd_user *user;
1418 ksmbd_debug(SMB, "authenticate phase\n");
1419 if (conn->use_spnego) {
1420 unsigned char *spnego_blob;
1421 u16 spnego_blob_len;
1423 rc = build_spnego_ntlmssp_auth_blob(&spnego_blob,
1429 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1430 memcpy((char *)&rsp->hdr.ProtocolId + sz, spnego_blob, spnego_blob_len);
1431 rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
1433 inc_rfc1001_len(work->response_buf, spnego_blob_len - 1);
1436 user = session_user(conn, req);
1438 ksmbd_debug(SMB, "Unknown user name or an error\n");
1442 /* Check for previous session */
1443 prev_id = le64_to_cpu(req->PreviousSessionId);
1444 if (prev_id && prev_id != sess->id)
1445 destroy_previous_session(user, prev_id);
1447 if (sess->state == SMB2_SESSION_VALID) {
1449 * Reuse session if anonymous try to connect
1450 * on reauthetication.
1452 if (ksmbd_anonymous_user(user)) {
1453 ksmbd_free_user(user);
1457 if (!ksmbd_compare_user(sess->user, user)) {
1458 ksmbd_free_user(user);
1461 ksmbd_free_user(user);
1466 if (user_guest(sess->user)) {
1467 rsp->SessionFlags = SMB2_SESSION_FLAG_IS_GUEST_LE;
1469 struct authenticate_message *authblob;
1471 authblob = user_authblob(conn, req);
1472 sz = le16_to_cpu(req->SecurityBufferLength);
1473 rc = ksmbd_decode_ntlmssp_auth_blob(authblob, sz, conn, sess);
1475 set_user_flag(sess->user, KSMBD_USER_FLAG_BAD_PASSWORD);
1476 ksmbd_debug(SMB, "authentication failed\n");
1482 * If session state is SMB2_SESSION_VALID, We can assume
1483 * that it is reauthentication. And the user/password
1484 * has been verified, so return it here.
1486 if (sess->state == SMB2_SESSION_VALID) {
1488 goto binding_session;
1492 if ((rsp->SessionFlags != SMB2_SESSION_FLAG_IS_GUEST_LE &&
1493 (conn->sign || server_conf.enforced_signing)) ||
1494 (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
1497 if (smb3_encryption_negotiated(conn) &&
1498 !(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1499 rc = conn->ops->generate_encryptionkey(sess);
1502 "SMB3 encryption key generation failed\n");
1506 rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
1508 * signing is disable if encryption is enable
1515 if (conn->dialect >= SMB30_PROT_ID) {
1516 chann = lookup_chann_list(sess, conn);
1518 chann = kmalloc(sizeof(struct channel), GFP_KERNEL);
1523 INIT_LIST_HEAD(&chann->chann_list);
1524 list_add(&chann->chann_list, &sess->ksmbd_chann_list);
1528 if (conn->ops->generate_signingkey) {
1529 rc = conn->ops->generate_signingkey(sess, conn);
1531 ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
1536 if (!ksmbd_conn_lookup_dialect(conn)) {
1537 pr_err("fail to verify the dialect\n");
1543 #ifdef CONFIG_SMB_SERVER_KERBEROS5
1544 static int krb5_authenticate(struct ksmbd_work *work)
1546 struct smb2_sess_setup_req *req = smb2_get_msg(work->request_buf);
1547 struct smb2_sess_setup_rsp *rsp = smb2_get_msg(work->response_buf);
1548 struct ksmbd_conn *conn = work->conn;
1549 struct ksmbd_session *sess = work->sess;
1550 char *in_blob, *out_blob;
1551 struct channel *chann = NULL;
1553 int in_len, out_len;
1556 in_blob = (char *)&req->hdr.ProtocolId +
1557 le16_to_cpu(req->SecurityBufferOffset);
1558 in_len = le16_to_cpu(req->SecurityBufferLength);
1559 out_blob = (char *)&rsp->hdr.ProtocolId +
1560 le16_to_cpu(rsp->SecurityBufferOffset);
1561 out_len = work->response_sz -
1562 (le16_to_cpu(rsp->SecurityBufferOffset) + 4);
1564 /* Check previous session */
1565 prev_sess_id = le64_to_cpu(req->PreviousSessionId);
1566 if (prev_sess_id && prev_sess_id != sess->id)
1567 destroy_previous_session(sess->user, prev_sess_id);
1569 if (sess->state == SMB2_SESSION_VALID)
1570 ksmbd_free_user(sess->user);
1572 retval = ksmbd_krb5_authenticate(sess, in_blob, in_len,
1573 out_blob, &out_len);
1575 ksmbd_debug(SMB, "krb5 authentication failed\n");
1578 rsp->SecurityBufferLength = cpu_to_le16(out_len);
1579 inc_rfc1001_len(work->response_buf, out_len - 1);
1581 if ((conn->sign || server_conf.enforced_signing) ||
1582 (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
1585 if (smb3_encryption_negotiated(conn)) {
1586 retval = conn->ops->generate_encryptionkey(sess);
1589 "SMB3 encryption key generation failed\n");
1593 rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
1597 if (conn->dialect >= SMB30_PROT_ID) {
1598 chann = lookup_chann_list(sess, conn);
1600 chann = kmalloc(sizeof(struct channel), GFP_KERNEL);
1605 INIT_LIST_HEAD(&chann->chann_list);
1606 list_add(&chann->chann_list, &sess->ksmbd_chann_list);
1610 if (conn->ops->generate_signingkey) {
1611 retval = conn->ops->generate_signingkey(sess, conn);
1613 ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
1618 if (!ksmbd_conn_lookup_dialect(conn)) {
1619 pr_err("fail to verify the dialect\n");
1625 static int krb5_authenticate(struct ksmbd_work *work)
1631 int smb2_sess_setup(struct ksmbd_work *work)
1633 struct ksmbd_conn *conn = work->conn;
1634 struct smb2_sess_setup_req *req = smb2_get_msg(work->request_buf);
1635 struct smb2_sess_setup_rsp *rsp = smb2_get_msg(work->response_buf);
1636 struct ksmbd_session *sess;
1637 struct negotiate_message *negblob;
1638 unsigned int negblob_len, negblob_off;
1641 ksmbd_debug(SMB, "Received request for session setup\n");
1643 rsp->StructureSize = cpu_to_le16(9);
1644 rsp->SessionFlags = 0;
1645 rsp->SecurityBufferOffset = cpu_to_le16(72);
1646 rsp->SecurityBufferLength = 0;
1647 inc_rfc1001_len(work->response_buf, 9);
1649 if (!req->hdr.SessionId) {
1650 sess = ksmbd_smb2_session_create();
1655 rsp->hdr.SessionId = cpu_to_le64(sess->id);
1656 ksmbd_session_register(conn, sess);
1657 } else if (conn->dialect >= SMB30_PROT_ID &&
1658 (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
1659 req->Flags & SMB2_SESSION_REQ_FLAG_BINDING) {
1660 u64 sess_id = le64_to_cpu(req->hdr.SessionId);
1662 sess = ksmbd_session_lookup_slowpath(sess_id);
1668 if (conn->dialect != sess->conn->dialect) {
1673 if (!(req->hdr.Flags & SMB2_FLAGS_SIGNED)) {
1678 if (strncmp(conn->ClientGUID, sess->conn->ClientGUID,
1679 SMB2_CLIENT_GUID_SIZE)) {
1684 if (sess->state == SMB2_SESSION_IN_PROGRESS) {
1689 if (sess->state == SMB2_SESSION_EXPIRED) {
1694 if (ksmbd_session_lookup(conn, sess_id)) {
1699 conn->binding = true;
1700 } else if ((conn->dialect < SMB30_PROT_ID ||
1701 server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
1702 (req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1707 sess = ksmbd_session_lookup(conn,
1708 le64_to_cpu(req->hdr.SessionId));
1716 if (sess->state == SMB2_SESSION_EXPIRED)
1717 sess->state = SMB2_SESSION_IN_PROGRESS;
1719 negblob_off = le16_to_cpu(req->SecurityBufferOffset);
1720 negblob_len = le16_to_cpu(req->SecurityBufferLength);
1721 if (negblob_off < offsetof(struct smb2_sess_setup_req, Buffer) ||
1722 negblob_len < offsetof(struct negotiate_message, NegotiateFlags)) {
1727 negblob = (struct negotiate_message *)((char *)&req->hdr.ProtocolId +
1730 if (decode_negotiation_token(conn, negblob, negblob_len) == 0) {
1731 if (conn->mechToken)
1732 negblob = (struct negotiate_message *)conn->mechToken;
1735 if (server_conf.auth_mechs & conn->auth_mechs) {
1736 rc = generate_preauth_hash(work);
1740 if (conn->preferred_auth_mech &
1741 (KSMBD_AUTH_KRB5 | KSMBD_AUTH_MSKRB5)) {
1742 rc = krb5_authenticate(work);
1748 ksmbd_conn_set_good(work);
1749 sess->state = SMB2_SESSION_VALID;
1750 kfree(sess->Preauth_HashValue);
1751 sess->Preauth_HashValue = NULL;
1752 } else if (conn->preferred_auth_mech == KSMBD_AUTH_NTLMSSP) {
1753 if (negblob->MessageType == NtLmNegotiate) {
1754 rc = ntlm_negotiate(work, negblob, negblob_len);
1758 STATUS_MORE_PROCESSING_REQUIRED;
1760 * Note: here total size -1 is done as an
1761 * adjustment for 0 size blob
1763 inc_rfc1001_len(work->response_buf,
1764 le16_to_cpu(rsp->SecurityBufferLength) - 1);
1766 } else if (negblob->MessageType == NtLmAuthenticate) {
1767 rc = ntlm_authenticate(work);
1771 ksmbd_conn_set_good(work);
1772 sess->state = SMB2_SESSION_VALID;
1773 if (conn->binding) {
1774 struct preauth_session *preauth_sess;
1777 ksmbd_preauth_session_lookup(conn, sess->id);
1779 list_del(&preauth_sess->preauth_entry);
1780 kfree(preauth_sess);
1783 kfree(sess->Preauth_HashValue);
1784 sess->Preauth_HashValue = NULL;
1787 /* TODO: need one more negotiation */
1788 pr_err("Not support the preferred authentication\n");
1792 pr_err("Not support authentication\n");
1798 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1799 else if (rc == -ENOENT)
1800 rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
1801 else if (rc == -EACCES)
1802 rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
1803 else if (rc == -EFAULT)
1804 rsp->hdr.Status = STATUS_NETWORK_SESSION_EXPIRED;
1805 else if (rc == -ENOMEM)
1806 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
1808 rsp->hdr.Status = STATUS_LOGON_FAILURE;
1810 if (conn->use_spnego && conn->mechToken) {
1811 kfree(conn->mechToken);
1812 conn->mechToken = NULL;
1817 * SecurityBufferOffset should be set to zero
1818 * in session setup error response.
1820 rsp->SecurityBufferOffset = 0;
1823 bool try_delay = false;
1826 * To avoid dictionary attacks (repeated session setups rapidly sent) to
1827 * connect to server, ksmbd make a delay of a 5 seconds on session setup
1828 * failure to make it harder to send enough random connection requests
1829 * to break into a server.
1831 if (sess->user && sess->user->flags & KSMBD_USER_FLAG_DELAY_SESSION)
1834 ksmbd_session_destroy(sess);
1845 * smb2_tree_connect() - handler for smb2 tree connect command
1846 * @work: smb work containing smb request buffer
1848 * Return: 0 on success, otherwise error
1850 int smb2_tree_connect(struct ksmbd_work *work)
1852 struct ksmbd_conn *conn = work->conn;
1853 struct smb2_tree_connect_req *req = smb2_get_msg(work->request_buf);
1854 struct smb2_tree_connect_rsp *rsp = smb2_get_msg(work->response_buf);
1855 struct ksmbd_session *sess = work->sess;
1856 char *treename = NULL, *name = NULL;
1857 struct ksmbd_tree_conn_status status;
1858 struct ksmbd_share_config *share;
1861 treename = smb_strndup_from_utf16(req->Buffer,
1862 le16_to_cpu(req->PathLength), true,
1864 if (IS_ERR(treename)) {
1865 pr_err("treename is NULL\n");
1866 status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
1870 name = ksmbd_extract_sharename(treename);
1872 status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
1876 ksmbd_debug(SMB, "tree connect request for tree %s treename %s\n",
1879 status = ksmbd_tree_conn_connect(sess, name);
1880 if (status.ret == KSMBD_TREE_CONN_STATUS_OK)
1881 rsp->hdr.Id.SyncId.TreeId = cpu_to_le32(status.tree_conn->id);
1885 share = status.tree_conn->share_conf;
1886 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
1887 ksmbd_debug(SMB, "IPC share path request\n");
1888 rsp->ShareType = SMB2_SHARE_TYPE_PIPE;
1889 rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
1890 FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE |
1891 FILE_DELETE_LE | FILE_READ_CONTROL_LE |
1892 FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
1893 FILE_SYNCHRONIZE_LE;
1895 rsp->ShareType = SMB2_SHARE_TYPE_DISK;
1896 rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
1897 FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE;
1898 if (test_tree_conn_flag(status.tree_conn,
1899 KSMBD_TREE_CONN_FLAG_WRITABLE)) {
1900 rsp->MaximalAccess |= FILE_WRITE_DATA_LE |
1901 FILE_APPEND_DATA_LE | FILE_WRITE_EA_LE |
1902 FILE_DELETE_LE | FILE_WRITE_ATTRIBUTES_LE |
1903 FILE_DELETE_CHILD_LE | FILE_READ_CONTROL_LE |
1904 FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
1905 FILE_SYNCHRONIZE_LE;
1909 status.tree_conn->maximal_access = le32_to_cpu(rsp->MaximalAccess);
1910 if (conn->posix_ext_supported)
1911 status.tree_conn->posix_extensions = true;
1914 rsp->StructureSize = cpu_to_le16(16);
1915 rsp->Capabilities = 0;
1917 /* default manual caching */
1918 rsp->ShareFlags = SMB2_SHAREFLAG_MANUAL_CACHING;
1919 inc_rfc1001_len(work->response_buf, 16);
1921 if (!IS_ERR(treename))
1926 switch (status.ret) {
1927 case KSMBD_TREE_CONN_STATUS_OK:
1928 rsp->hdr.Status = STATUS_SUCCESS;
1931 case KSMBD_TREE_CONN_STATUS_NO_SHARE:
1932 rsp->hdr.Status = STATUS_BAD_NETWORK_PATH;
1935 case KSMBD_TREE_CONN_STATUS_NOMEM:
1936 rsp->hdr.Status = STATUS_NO_MEMORY;
1938 case KSMBD_TREE_CONN_STATUS_ERROR:
1939 case KSMBD_TREE_CONN_STATUS_TOO_MANY_CONNS:
1940 case KSMBD_TREE_CONN_STATUS_TOO_MANY_SESSIONS:
1941 rsp->hdr.Status = STATUS_ACCESS_DENIED;
1944 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1947 rsp->hdr.Status = STATUS_ACCESS_DENIED;
1954 * smb2_create_open_flags() - convert smb open flags to unix open flags
1955 * @file_present: is file already present
1956 * @access: file access flags
1957 * @disposition: file disposition flags
1958 * @may_flags: set with MAY_ flags
1960 * Return: file open flags
1962 static int smb2_create_open_flags(bool file_present, __le32 access,
1966 int oflags = O_NONBLOCK | O_LARGEFILE;
1968 if (access & FILE_READ_DESIRED_ACCESS_LE &&
1969 access & FILE_WRITE_DESIRE_ACCESS_LE) {
1971 *may_flags = MAY_OPEN | MAY_READ | MAY_WRITE;
1972 } else if (access & FILE_WRITE_DESIRE_ACCESS_LE) {
1974 *may_flags = MAY_OPEN | MAY_WRITE;
1977 *may_flags = MAY_OPEN | MAY_READ;
1980 if (access == FILE_READ_ATTRIBUTES_LE)
1984 switch (disposition & FILE_CREATE_MASK_LE) {
1986 case FILE_CREATE_LE:
1988 case FILE_SUPERSEDE_LE:
1989 case FILE_OVERWRITE_LE:
1990 case FILE_OVERWRITE_IF_LE:
1997 switch (disposition & FILE_CREATE_MASK_LE) {
1998 case FILE_SUPERSEDE_LE:
1999 case FILE_CREATE_LE:
2000 case FILE_OPEN_IF_LE:
2001 case FILE_OVERWRITE_IF_LE:
2005 case FILE_OVERWRITE_LE:
2017 * smb2_tree_disconnect() - handler for smb tree connect request
2018 * @work: smb work containing request buffer
2022 int smb2_tree_disconnect(struct ksmbd_work *work)
2024 struct smb2_tree_disconnect_rsp *rsp = smb2_get_msg(work->response_buf);
2025 struct ksmbd_session *sess = work->sess;
2026 struct ksmbd_tree_connect *tcon = work->tcon;
2028 rsp->StructureSize = cpu_to_le16(4);
2029 inc_rfc1001_len(work->response_buf, 4);
2031 ksmbd_debug(SMB, "request\n");
2034 struct smb2_tree_disconnect_req *req =
2035 smb2_get_msg(work->request_buf);
2037 ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
2038 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2039 smb2_set_err_rsp(work);
2043 ksmbd_close_tree_conn_fds(work);
2044 ksmbd_tree_conn_disconnect(sess, tcon);
2049 * smb2_session_logoff() - handler for session log off request
2050 * @work: smb work containing request buffer
2054 int smb2_session_logoff(struct ksmbd_work *work)
2056 struct ksmbd_conn *conn = work->conn;
2057 struct smb2_logoff_rsp *rsp = smb2_get_msg(work->response_buf);
2058 struct ksmbd_session *sess = work->sess;
2060 rsp->StructureSize = cpu_to_le16(4);
2061 inc_rfc1001_len(work->response_buf, 4);
2063 ksmbd_debug(SMB, "request\n");
2065 /* setting CifsExiting here may race with start_tcp_sess */
2066 ksmbd_conn_set_need_reconnect(work);
2067 ksmbd_close_session_fds(work);
2068 ksmbd_conn_wait_idle(conn);
2070 if (ksmbd_tree_conn_session_logoff(sess)) {
2071 struct smb2_logoff_req *req = smb2_get_msg(work->request_buf);
2073 ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
2074 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2075 smb2_set_err_rsp(work);
2079 ksmbd_destroy_file_table(&sess->file_table);
2080 sess->state = SMB2_SESSION_EXPIRED;
2082 ksmbd_free_user(sess->user);
2085 /* let start_tcp_sess free connection info now */
2086 ksmbd_conn_set_need_negotiate(work);
2091 * create_smb2_pipe() - create IPC pipe
2092 * @work: smb work containing request buffer
2094 * Return: 0 on success, otherwise error
2096 static noinline int create_smb2_pipe(struct ksmbd_work *work)
2098 struct smb2_create_rsp *rsp = smb2_get_msg(work->response_buf);
2099 struct smb2_create_req *req = smb2_get_msg(work->request_buf);
2104 name = smb_strndup_from_utf16(req->Buffer, le16_to_cpu(req->NameLength),
2105 1, work->conn->local_nls);
2107 rsp->hdr.Status = STATUS_NO_MEMORY;
2108 err = PTR_ERR(name);
2112 id = ksmbd_session_rpc_open(work->sess, name);
2114 pr_err("Unable to open RPC pipe: %d\n", id);
2119 rsp->hdr.Status = STATUS_SUCCESS;
2120 rsp->StructureSize = cpu_to_le16(89);
2121 rsp->OplockLevel = SMB2_OPLOCK_LEVEL_NONE;
2123 rsp->CreateAction = cpu_to_le32(FILE_OPENED);
2125 rsp->CreationTime = cpu_to_le64(0);
2126 rsp->LastAccessTime = cpu_to_le64(0);
2127 rsp->ChangeTime = cpu_to_le64(0);
2128 rsp->AllocationSize = cpu_to_le64(0);
2129 rsp->EndofFile = cpu_to_le64(0);
2130 rsp->FileAttributes = FILE_ATTRIBUTE_NORMAL_LE;
2132 rsp->VolatileFileId = cpu_to_le64(id);
2133 rsp->PersistentFileId = 0;
2134 rsp->CreateContextsOffset = 0;
2135 rsp->CreateContextsLength = 0;
2137 inc_rfc1001_len(work->response_buf, 88); /* StructureSize - 1*/
2144 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2148 rsp->hdr.Status = STATUS_NO_MEMORY;
2155 smb2_set_err_rsp(work);
2160 * smb2_set_ea() - handler for setting extended attributes using set
2162 * @eabuf: set info command buffer
2163 * @buf_len: set info command buffer length
2164 * @path: dentry path for get ea
2166 * Return: 0 on success, otherwise error
2168 static int smb2_set_ea(struct smb2_ea_info *eabuf, unsigned int buf_len,
2171 struct user_namespace *user_ns = mnt_user_ns(path->mnt);
2172 char *attr_name = NULL, *value;
2174 unsigned int next = 0;
2176 if (buf_len < sizeof(struct smb2_ea_info) + eabuf->EaNameLength +
2177 le16_to_cpu(eabuf->EaValueLength))
2180 attr_name = kmalloc(XATTR_NAME_MAX + 1, GFP_KERNEL);
2185 if (!eabuf->EaNameLength)
2189 "name : <%s>, name_len : %u, value_len : %u, next : %u\n",
2190 eabuf->name, eabuf->EaNameLength,
2191 le16_to_cpu(eabuf->EaValueLength),
2192 le32_to_cpu(eabuf->NextEntryOffset));
2194 if (eabuf->EaNameLength >
2195 (XATTR_NAME_MAX - XATTR_USER_PREFIX_LEN)) {
2200 memcpy(attr_name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN);
2201 memcpy(&attr_name[XATTR_USER_PREFIX_LEN], eabuf->name,
2202 eabuf->EaNameLength);
2203 attr_name[XATTR_USER_PREFIX_LEN + eabuf->EaNameLength] = '\0';
2204 value = (char *)&eabuf->name + eabuf->EaNameLength + 1;
2206 if (!eabuf->EaValueLength) {
2207 rc = ksmbd_vfs_casexattr_len(user_ns,
2210 XATTR_USER_PREFIX_LEN +
2211 eabuf->EaNameLength);
2213 /* delete the EA only when it exits */
2215 rc = ksmbd_vfs_remove_xattr(user_ns,
2221 "remove xattr failed(%d)\n",
2227 /* if the EA doesn't exist, just do nothing. */
2230 rc = ksmbd_vfs_setxattr(user_ns,
2231 path->dentry, attr_name, value,
2232 le16_to_cpu(eabuf->EaValueLength), 0);
2235 "ksmbd_vfs_setxattr is failed(%d)\n",
2242 next = le32_to_cpu(eabuf->NextEntryOffset);
2243 if (next == 0 || buf_len < next)
2246 eabuf = (struct smb2_ea_info *)((char *)eabuf + next);
2247 if (next < (u32)eabuf->EaNameLength + le16_to_cpu(eabuf->EaValueLength))
2250 } while (next != 0);
2256 static noinline int smb2_set_stream_name_xattr(struct path *path,
2257 struct ksmbd_file *fp,
2258 char *stream_name, int s_type)
2260 struct user_namespace *user_ns = mnt_user_ns(path->mnt);
2261 size_t xattr_stream_size;
2262 char *xattr_stream_name;
2265 rc = ksmbd_vfs_xattr_stream_name(stream_name,
2272 fp->stream.name = xattr_stream_name;
2273 fp->stream.size = xattr_stream_size;
2275 /* Check if there is stream prefix in xattr space */
2276 rc = ksmbd_vfs_casexattr_len(user_ns,
2283 if (fp->cdoption == FILE_OPEN_LE) {
2284 ksmbd_debug(SMB, "XATTR stream name lookup failed: %d\n", rc);
2288 rc = ksmbd_vfs_setxattr(user_ns, path->dentry,
2289 xattr_stream_name, NULL, 0, 0);
2291 pr_err("Failed to store XATTR stream name :%d\n", rc);
2295 static int smb2_remove_smb_xattrs(struct path *path)
2297 struct user_namespace *user_ns = mnt_user_ns(path->mnt);
2298 char *name, *xattr_list = NULL;
2299 ssize_t xattr_list_len;
2302 xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
2303 if (xattr_list_len < 0) {
2305 } else if (!xattr_list_len) {
2306 ksmbd_debug(SMB, "empty xattr in the file\n");
2310 for (name = xattr_list; name - xattr_list < xattr_list_len;
2311 name += strlen(name) + 1) {
2312 ksmbd_debug(SMB, "%s, len %zd\n", name, strlen(name));
2314 if (strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN) &&
2315 strncmp(&name[XATTR_USER_PREFIX_LEN], DOS_ATTRIBUTE_PREFIX,
2316 DOS_ATTRIBUTE_PREFIX_LEN) &&
2317 strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX, STREAM_PREFIX_LEN))
2320 err = ksmbd_vfs_remove_xattr(user_ns, path->dentry, name);
2322 ksmbd_debug(SMB, "remove xattr failed : %s\n", name);
2329 static int smb2_create_truncate(struct path *path)
2331 int rc = vfs_truncate(path, 0);
2334 pr_err("vfs_truncate failed, rc %d\n", rc);
2338 rc = smb2_remove_smb_xattrs(path);
2339 if (rc == -EOPNOTSUPP)
2343 "ksmbd_truncate_stream_name_xattr failed, rc %d\n",
2348 static void smb2_new_xattrs(struct ksmbd_tree_connect *tcon, struct path *path,
2349 struct ksmbd_file *fp)
2351 struct xattr_dos_attrib da = {0};
2354 if (!test_share_config_flag(tcon->share_conf,
2355 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2359 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
2360 da.itime = da.create_time = fp->create_time;
2361 da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
2362 XATTR_DOSINFO_ITIME;
2364 rc = ksmbd_vfs_set_dos_attrib_xattr(mnt_user_ns(path->mnt),
2367 ksmbd_debug(SMB, "failed to store file attribute into xattr\n");
2370 static void smb2_update_xattrs(struct ksmbd_tree_connect *tcon,
2371 struct path *path, struct ksmbd_file *fp)
2373 struct xattr_dos_attrib da;
2376 fp->f_ci->m_fattr &= ~(FILE_ATTRIBUTE_HIDDEN_LE | FILE_ATTRIBUTE_SYSTEM_LE);
2378 /* get FileAttributes from XATTR_NAME_DOS_ATTRIBUTE */
2379 if (!test_share_config_flag(tcon->share_conf,
2380 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2383 rc = ksmbd_vfs_get_dos_attrib_xattr(mnt_user_ns(path->mnt),
2386 fp->f_ci->m_fattr = cpu_to_le32(da.attr);
2387 fp->create_time = da.create_time;
2388 fp->itime = da.itime;
2392 static int smb2_creat(struct ksmbd_work *work, struct path *path, char *name,
2393 int open_flags, umode_t posix_mode, bool is_dir)
2395 struct ksmbd_tree_connect *tcon = work->tcon;
2396 struct ksmbd_share_config *share = tcon->share_conf;
2400 if (!(open_flags & O_CREAT))
2403 ksmbd_debug(SMB, "file does not exist, so creating\n");
2404 if (is_dir == true) {
2405 ksmbd_debug(SMB, "creating directory\n");
2407 mode = share_config_directory_mode(share, posix_mode);
2408 rc = ksmbd_vfs_mkdir(work, name, mode);
2412 ksmbd_debug(SMB, "creating regular file\n");
2414 mode = share_config_create_mode(share, posix_mode);
2415 rc = ksmbd_vfs_create(work, name, mode);
2420 rc = ksmbd_vfs_kern_path(work, name, 0, path, 0);
2422 pr_err("cannot get linux path (%s), err = %d\n",
2429 static int smb2_create_sd_buffer(struct ksmbd_work *work,
2430 struct smb2_create_req *req,
2433 struct create_context *context;
2434 struct create_sd_buf_req *sd_buf;
2436 if (!req->CreateContextsOffset)
2439 /* Parse SD BUFFER create contexts */
2440 context = smb2_find_context_vals(req, SMB2_CREATE_SD_BUFFER);
2443 else if (IS_ERR(context))
2444 return PTR_ERR(context);
2447 "Set ACLs using SMB2_CREATE_SD_BUFFER context\n");
2448 sd_buf = (struct create_sd_buf_req *)context;
2449 if (le16_to_cpu(context->DataOffset) +
2450 le32_to_cpu(context->DataLength) <
2451 sizeof(struct create_sd_buf_req))
2453 return set_info_sec(work->conn, work->tcon, path, &sd_buf->ntsd,
2454 le32_to_cpu(sd_buf->ccontext.DataLength), true);
2457 static void ksmbd_acls_fattr(struct smb_fattr *fattr,
2458 struct user_namespace *mnt_userns,
2459 struct inode *inode)
2461 fattr->cf_uid = i_uid_into_mnt(mnt_userns, inode);
2462 fattr->cf_gid = i_gid_into_mnt(mnt_userns, inode);
2463 fattr->cf_mode = inode->i_mode;
2464 fattr->cf_acls = NULL;
2465 fattr->cf_dacls = NULL;
2467 if (IS_ENABLED(CONFIG_FS_POSIX_ACL)) {
2468 fattr->cf_acls = get_acl(inode, ACL_TYPE_ACCESS);
2469 if (S_ISDIR(inode->i_mode))
2470 fattr->cf_dacls = get_acl(inode, ACL_TYPE_DEFAULT);
2475 * smb2_open() - handler for smb file open request
2476 * @work: smb work containing request buffer
2478 * Return: 0 on success, otherwise error
2480 int smb2_open(struct ksmbd_work *work)
2482 struct ksmbd_conn *conn = work->conn;
2483 struct ksmbd_session *sess = work->sess;
2484 struct ksmbd_tree_connect *tcon = work->tcon;
2485 struct smb2_create_req *req;
2486 struct smb2_create_rsp *rsp;
2488 struct ksmbd_share_config *share = tcon->share_conf;
2489 struct ksmbd_file *fp = NULL;
2490 struct file *filp = NULL;
2491 struct user_namespace *user_ns = NULL;
2493 struct create_context *context;
2494 struct lease_ctx_info *lc = NULL;
2495 struct create_ea_buf_req *ea_buf = NULL;
2496 struct oplock_info *opinfo;
2497 __le32 *next_ptr = NULL;
2498 int req_op_level = 0, open_flags = 0, may_flags = 0, file_info = 0;
2500 int contxt_cnt = 0, query_disk_id = 0;
2501 int maximal_access_ctxt = 0, posix_ctxt = 0;
2505 char *stream_name = NULL;
2506 bool file_present = false, created = false, already_permitted = false;
2507 int share_ret, need_truncate = 0;
2509 umode_t posix_mode = 0;
2510 __le32 daccess, maximal_access = 0;
2512 WORK_BUFFERS(work, req, rsp);
2514 if (req->hdr.NextCommand && !work->next_smb2_rcv_hdr_off &&
2515 (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
2516 ksmbd_debug(SMB, "invalid flag in chained command\n");
2517 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2518 smb2_set_err_rsp(work);
2522 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
2523 ksmbd_debug(SMB, "IPC pipe create request\n");
2524 return create_smb2_pipe(work);
2527 if (req->NameLength) {
2528 if ((req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
2529 *(char *)req->Buffer == '\\') {
2530 pr_err("not allow directory name included leading slash\n");
2535 name = smb2_get_name(req->Buffer,
2536 le16_to_cpu(req->NameLength),
2537 work->conn->local_nls);
2546 ksmbd_debug(SMB, "converted name = %s\n", name);
2547 if (strchr(name, ':')) {
2548 if (!test_share_config_flag(work->tcon->share_conf,
2549 KSMBD_SHARE_FLAG_STREAMS)) {
2553 rc = parse_stream_name(name, &stream_name, &s_type);
2558 rc = ksmbd_validate_filename(name);
2562 if (ksmbd_share_veto_filename(share, name)) {
2564 ksmbd_debug(SMB, "Reject open(), vetoed file: %s\n",
2569 name = kstrdup("", GFP_KERNEL);
2576 req_op_level = req->RequestedOplockLevel;
2577 if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE)
2578 lc = parse_lease_state(req);
2580 if (le32_to_cpu(req->ImpersonationLevel) > le32_to_cpu(IL_DELEGATE)) {
2581 pr_err("Invalid impersonationlevel : 0x%x\n",
2582 le32_to_cpu(req->ImpersonationLevel));
2584 rsp->hdr.Status = STATUS_BAD_IMPERSONATION_LEVEL;
2588 if (req->CreateOptions && !(req->CreateOptions & CREATE_OPTIONS_MASK_LE)) {
2589 pr_err("Invalid create options : 0x%x\n",
2590 le32_to_cpu(req->CreateOptions));
2594 if (req->CreateOptions & FILE_SEQUENTIAL_ONLY_LE &&
2595 req->CreateOptions & FILE_RANDOM_ACCESS_LE)
2596 req->CreateOptions = ~(FILE_SEQUENTIAL_ONLY_LE);
2598 if (req->CreateOptions &
2599 (FILE_OPEN_BY_FILE_ID_LE | CREATE_TREE_CONNECTION |
2600 FILE_RESERVE_OPFILTER_LE)) {
2605 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
2606 if (req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE) {
2609 } else if (req->CreateOptions & FILE_NO_COMPRESSION_LE) {
2610 req->CreateOptions = ~(FILE_NO_COMPRESSION_LE);
2615 if (le32_to_cpu(req->CreateDisposition) >
2616 le32_to_cpu(FILE_OVERWRITE_IF_LE)) {
2617 pr_err("Invalid create disposition : 0x%x\n",
2618 le32_to_cpu(req->CreateDisposition));
2623 if (!(req->DesiredAccess & DESIRED_ACCESS_MASK)) {
2624 pr_err("Invalid desired access : 0x%x\n",
2625 le32_to_cpu(req->DesiredAccess));
2630 if (req->FileAttributes && !(req->FileAttributes & FILE_ATTRIBUTE_MASK_LE)) {
2631 pr_err("Invalid file attribute : 0x%x\n",
2632 le32_to_cpu(req->FileAttributes));
2637 if (req->CreateContextsOffset) {
2638 /* Parse non-durable handle create contexts */
2639 context = smb2_find_context_vals(req, SMB2_CREATE_EA_BUFFER);
2640 if (IS_ERR(context)) {
2641 rc = PTR_ERR(context);
2643 } else if (context) {
2644 ea_buf = (struct create_ea_buf_req *)context;
2645 if (le16_to_cpu(context->DataOffset) +
2646 le32_to_cpu(context->DataLength) <
2647 sizeof(struct create_ea_buf_req)) {
2651 if (req->CreateOptions & FILE_NO_EA_KNOWLEDGE_LE) {
2652 rsp->hdr.Status = STATUS_ACCESS_DENIED;
2658 context = smb2_find_context_vals(req,
2659 SMB2_CREATE_QUERY_MAXIMAL_ACCESS_REQUEST);
2660 if (IS_ERR(context)) {
2661 rc = PTR_ERR(context);
2663 } else if (context) {
2665 "get query maximal access context\n");
2666 maximal_access_ctxt = 1;
2669 context = smb2_find_context_vals(req,
2670 SMB2_CREATE_TIMEWARP_REQUEST);
2671 if (IS_ERR(context)) {
2672 rc = PTR_ERR(context);
2674 } else if (context) {
2675 ksmbd_debug(SMB, "get timewarp context\n");
2680 if (tcon->posix_extensions) {
2681 context = smb2_find_context_vals(req,
2682 SMB2_CREATE_TAG_POSIX);
2683 if (IS_ERR(context)) {
2684 rc = PTR_ERR(context);
2686 } else if (context) {
2687 struct create_posix *posix =
2688 (struct create_posix *)context;
2689 if (le16_to_cpu(context->DataOffset) +
2690 le32_to_cpu(context->DataLength) <
2691 sizeof(struct create_posix) - 4) {
2695 ksmbd_debug(SMB, "get posix context\n");
2697 posix_mode = le32_to_cpu(posix->Mode);
2703 if (ksmbd_override_fsids(work)) {
2708 rc = ksmbd_vfs_kern_path(work, name, LOOKUP_NO_SYMLINKS, &path, 1);
2710 if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE) {
2712 * If file exists with under flags, return access
2715 if (req->CreateDisposition == FILE_OVERWRITE_IF_LE ||
2716 req->CreateDisposition == FILE_OPEN_IF_LE) {
2722 if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
2724 "User does not have write permission\n");
2729 } else if (d_is_symlink(path.dentry)) {
2739 ksmbd_debug(SMB, "can not get linux path for %s, rc = %d\n",
2743 file_present = true;
2744 user_ns = mnt_user_ns(path.mnt);
2745 generic_fillattr(user_ns, d_inode(path.dentry), &stat);
2748 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
2749 if (s_type == DATA_STREAM) {
2751 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2754 if (S_ISDIR(stat.mode) && s_type == DATA_STREAM) {
2756 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
2760 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE &&
2761 req->FileAttributes & FILE_ATTRIBUTE_NORMAL_LE) {
2762 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2770 if (file_present && req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE &&
2771 S_ISDIR(stat.mode) && !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2772 ksmbd_debug(SMB, "open() argument is a directory: %s, %x\n",
2773 name, req->CreateOptions);
2774 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
2779 if (file_present && (req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
2780 !(req->CreateDisposition == FILE_CREATE_LE) &&
2781 !S_ISDIR(stat.mode)) {
2782 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2787 if (!stream_name && file_present &&
2788 req->CreateDisposition == FILE_CREATE_LE) {
2793 daccess = smb_map_generic_desired_access(req->DesiredAccess);
2795 if (file_present && !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2796 rc = smb_check_perm_dacl(conn, &path, &daccess,
2802 if (daccess & FILE_MAXIMAL_ACCESS_LE) {
2803 if (!file_present) {
2804 daccess = cpu_to_le32(GENERIC_ALL_FLAGS);
2806 rc = ksmbd_vfs_query_maximal_access(user_ns,
2811 already_permitted = true;
2813 maximal_access = daccess;
2816 open_flags = smb2_create_open_flags(file_present, daccess,
2817 req->CreateDisposition,
2820 if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
2821 if (open_flags & O_CREAT) {
2823 "User does not have write permission\n");
2829 /*create file if not present */
2830 if (!file_present) {
2831 rc = smb2_creat(work, &path, name, open_flags, posix_mode,
2832 req->CreateOptions & FILE_DIRECTORY_FILE_LE);
2834 if (rc == -ENOENT) {
2836 rsp->hdr.Status = STATUS_OBJECT_PATH_NOT_FOUND;
2842 user_ns = mnt_user_ns(path.mnt);
2844 if (le32_to_cpu(ea_buf->ccontext.DataLength) <
2845 sizeof(struct smb2_ea_info)) {
2850 rc = smb2_set_ea(&ea_buf->ea,
2851 le32_to_cpu(ea_buf->ccontext.DataLength),
2853 if (rc == -EOPNOTSUPP)
2858 } else if (!already_permitted) {
2859 /* FILE_READ_ATTRIBUTE is allowed without inode_permission,
2860 * because execute(search) permission on a parent directory,
2861 * is already granted.
2863 if (daccess & ~(FILE_READ_ATTRIBUTES_LE | FILE_READ_CONTROL_LE)) {
2864 rc = inode_permission(user_ns,
2865 d_inode(path.dentry),
2870 if ((daccess & FILE_DELETE_LE) ||
2871 (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2872 rc = ksmbd_vfs_may_delete(user_ns,
2880 rc = ksmbd_query_inode_status(d_inode(path.dentry->d_parent));
2881 if (rc == KSMBD_INODE_STATUS_PENDING_DELETE) {
2887 filp = dentry_open(&path, open_flags, current_cred());
2890 pr_err("dentry open for dir failed, rc %d\n", rc);
2895 if (!(open_flags & O_TRUNC))
2896 file_info = FILE_OPENED;
2898 file_info = FILE_OVERWRITTEN;
2900 if ((req->CreateDisposition & FILE_CREATE_MASK_LE) ==
2902 file_info = FILE_SUPERSEDED;
2903 } else if (open_flags & O_CREAT) {
2904 file_info = FILE_CREATED;
2907 ksmbd_vfs_set_fadvise(filp, req->CreateOptions);
2909 /* Obtain Volatile-ID */
2910 fp = ksmbd_open_fd(work, filp);
2918 /* Get Persistent-ID */
2919 ksmbd_open_durable_fd(fp);
2920 if (!has_file_id(fp->persistent_id)) {
2925 fp->filename = name;
2926 fp->cdoption = req->CreateDisposition;
2927 fp->daccess = daccess;
2928 fp->saccess = req->ShareAccess;
2929 fp->coption = req->CreateOptions;
2931 /* Set default windows and posix acls if creating new file */
2934 struct inode *inode = d_inode(path.dentry);
2936 posix_acl_rc = ksmbd_vfs_inherit_posix_acl(user_ns,
2938 d_inode(path.dentry->d_parent));
2940 ksmbd_debug(SMB, "inherit posix acl failed : %d\n", posix_acl_rc);
2942 if (test_share_config_flag(work->tcon->share_conf,
2943 KSMBD_SHARE_FLAG_ACL_XATTR)) {
2944 rc = smb_inherit_dacl(conn, &path, sess->user->uid,
2949 rc = smb2_create_sd_buffer(work, req, &path);
2952 ksmbd_vfs_set_init_posix_acl(user_ns,
2955 if (test_share_config_flag(work->tcon->share_conf,
2956 KSMBD_SHARE_FLAG_ACL_XATTR)) {
2957 struct smb_fattr fattr;
2958 struct smb_ntsd *pntsd;
2959 int pntsd_size, ace_num = 0;
2961 ksmbd_acls_fattr(&fattr, user_ns, inode);
2963 ace_num = fattr.cf_acls->a_count;
2965 ace_num += fattr.cf_dacls->a_count;
2967 pntsd = kmalloc(sizeof(struct smb_ntsd) +
2968 sizeof(struct smb_sid) * 3 +
2969 sizeof(struct smb_acl) +
2970 sizeof(struct smb_ace) * ace_num * 2,
2975 rc = build_sec_desc(user_ns,
2980 &pntsd_size, &fattr);
2981 posix_acl_release(fattr.cf_acls);
2982 posix_acl_release(fattr.cf_dacls);
2988 rc = ksmbd_vfs_set_sd_xattr(conn,
2995 pr_err("failed to store ntacl in xattr : %d\n",
3004 rc = smb2_set_stream_name_xattr(&path,
3010 file_info = FILE_CREATED;
3013 fp->attrib_only = !(req->DesiredAccess & ~(FILE_READ_ATTRIBUTES_LE |
3014 FILE_WRITE_ATTRIBUTES_LE | FILE_SYNCHRONIZE_LE));
3015 if (!S_ISDIR(file_inode(filp)->i_mode) && open_flags & O_TRUNC &&
3016 !fp->attrib_only && !stream_name) {
3017 smb_break_all_oplock(work, fp);
3021 /* fp should be searchable through ksmbd_inode.m_fp_list
3022 * after daccess, saccess, attrib_only, and stream are
3025 write_lock(&fp->f_ci->m_lock);
3026 list_add(&fp->node, &fp->f_ci->m_fp_list);
3027 write_unlock(&fp->f_ci->m_lock);
3029 rc = ksmbd_vfs_getattr(&path, &stat);
3031 generic_fillattr(user_ns, d_inode(path.dentry), &stat);
3035 /* Check delete pending among previous fp before oplock break */
3036 if (ksmbd_inode_pending_delete(fp)) {
3041 share_ret = ksmbd_smb_check_shared_mode(fp->filp, fp);
3042 if (!test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_OPLOCKS) ||
3043 (req_op_level == SMB2_OPLOCK_LEVEL_LEASE &&
3044 !(conn->vals->capabilities & SMB2_GLOBAL_CAP_LEASING))) {
3045 if (share_ret < 0 && !S_ISDIR(file_inode(fp->filp)->i_mode)) {
3050 if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE) {
3051 req_op_level = smb2_map_lease_to_oplock(lc->req_state);
3053 "lease req for(%s) req oplock state 0x%x, lease state 0x%x\n",
3054 name, req_op_level, lc->req_state);
3055 rc = find_same_lease_key(sess, fp->f_ci, lc);
3058 } else if (open_flags == O_RDONLY &&
3059 (req_op_level == SMB2_OPLOCK_LEVEL_BATCH ||
3060 req_op_level == SMB2_OPLOCK_LEVEL_EXCLUSIVE))
3061 req_op_level = SMB2_OPLOCK_LEVEL_II;
3063 rc = smb_grant_oplock(work, req_op_level,
3064 fp->persistent_id, fp,
3065 le32_to_cpu(req->hdr.Id.SyncId.TreeId),
3071 if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)
3072 ksmbd_fd_set_delete_on_close(fp, file_info);
3074 if (need_truncate) {
3075 rc = smb2_create_truncate(&path);
3080 if (req->CreateContextsOffset) {
3081 struct create_alloc_size_req *az_req;
3083 az_req = (struct create_alloc_size_req *)smb2_find_context_vals(req,
3084 SMB2_CREATE_ALLOCATION_SIZE);
3085 if (IS_ERR(az_req)) {
3086 rc = PTR_ERR(az_req);
3088 } else if (az_req) {
3092 if (le16_to_cpu(az_req->ccontext.DataOffset) +
3093 le32_to_cpu(az_req->ccontext.DataLength) <
3094 sizeof(struct create_alloc_size_req)) {
3098 alloc_size = le64_to_cpu(az_req->AllocationSize);
3100 "request smb2 create allocate size : %llu\n",
3102 smb_break_all_levII_oplock(work, fp, 1);
3103 err = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
3107 "vfs_fallocate is failed : %d\n",
3111 context = smb2_find_context_vals(req, SMB2_CREATE_QUERY_ON_DISK_ID);
3112 if (IS_ERR(context)) {
3113 rc = PTR_ERR(context);
3115 } else if (context) {
3116 ksmbd_debug(SMB, "get query on disk id context\n");
3121 if (stat.result_mask & STATX_BTIME)
3122 fp->create_time = ksmbd_UnixTimeToNT(stat.btime);
3124 fp->create_time = ksmbd_UnixTimeToNT(stat.ctime);
3125 if (req->FileAttributes || fp->f_ci->m_fattr == 0)
3127 cpu_to_le32(smb2_get_dos_mode(&stat, le32_to_cpu(req->FileAttributes)));
3130 smb2_update_xattrs(tcon, &path, fp);
3132 smb2_new_xattrs(tcon, &path, fp);
3134 memcpy(fp->client_guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE);
3136 generic_fillattr(user_ns, file_inode(fp->filp),
3139 rsp->StructureSize = cpu_to_le16(89);
3141 opinfo = rcu_dereference(fp->f_opinfo);
3142 rsp->OplockLevel = opinfo != NULL ? opinfo->level : 0;
3145 rsp->CreateAction = cpu_to_le32(file_info);
3146 rsp->CreationTime = cpu_to_le64(fp->create_time);
3147 time = ksmbd_UnixTimeToNT(stat.atime);
3148 rsp->LastAccessTime = cpu_to_le64(time);
3149 time = ksmbd_UnixTimeToNT(stat.mtime);
3150 rsp->LastWriteTime = cpu_to_le64(time);
3151 time = ksmbd_UnixTimeToNT(stat.ctime);
3152 rsp->ChangeTime = cpu_to_le64(time);
3153 rsp->AllocationSize = S_ISDIR(stat.mode) ? 0 :
3154 cpu_to_le64(stat.blocks << 9);
3155 rsp->EndofFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
3156 rsp->FileAttributes = fp->f_ci->m_fattr;
3160 rsp->PersistentFileId = cpu_to_le64(fp->persistent_id);
3161 rsp->VolatileFileId = cpu_to_le64(fp->volatile_id);
3163 rsp->CreateContextsOffset = 0;
3164 rsp->CreateContextsLength = 0;
3165 inc_rfc1001_len(work->response_buf, 88); /* StructureSize - 1*/
3167 /* If lease is request send lease context response */
3168 if (opinfo && opinfo->is_lease) {
3169 struct create_context *lease_ccontext;
3171 ksmbd_debug(SMB, "lease granted on(%s) lease state 0x%x\n",
3172 name, opinfo->o_lease->state);
3173 rsp->OplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
3175 lease_ccontext = (struct create_context *)rsp->Buffer;
3177 create_lease_buf(rsp->Buffer, opinfo->o_lease);
3178 le32_add_cpu(&rsp->CreateContextsLength,
3179 conn->vals->create_lease_size);
3180 inc_rfc1001_len(work->response_buf,
3181 conn->vals->create_lease_size);
3182 next_ptr = &lease_ccontext->Next;
3183 next_off = conn->vals->create_lease_size;
3186 if (maximal_access_ctxt) {
3187 struct create_context *mxac_ccontext;
3189 if (maximal_access == 0)
3190 ksmbd_vfs_query_maximal_access(user_ns,
3193 mxac_ccontext = (struct create_context *)(rsp->Buffer +
3194 le32_to_cpu(rsp->CreateContextsLength));
3196 create_mxac_rsp_buf(rsp->Buffer +
3197 le32_to_cpu(rsp->CreateContextsLength),
3198 le32_to_cpu(maximal_access));
3199 le32_add_cpu(&rsp->CreateContextsLength,
3200 conn->vals->create_mxac_size);
3201 inc_rfc1001_len(work->response_buf,
3202 conn->vals->create_mxac_size);
3204 *next_ptr = cpu_to_le32(next_off);
3205 next_ptr = &mxac_ccontext->Next;
3206 next_off = conn->vals->create_mxac_size;
3209 if (query_disk_id) {
3210 struct create_context *disk_id_ccontext;
3212 disk_id_ccontext = (struct create_context *)(rsp->Buffer +
3213 le32_to_cpu(rsp->CreateContextsLength));
3215 create_disk_id_rsp_buf(rsp->Buffer +
3216 le32_to_cpu(rsp->CreateContextsLength),
3217 stat.ino, tcon->id);
3218 le32_add_cpu(&rsp->CreateContextsLength,
3219 conn->vals->create_disk_id_size);
3220 inc_rfc1001_len(work->response_buf,
3221 conn->vals->create_disk_id_size);
3223 *next_ptr = cpu_to_le32(next_off);
3224 next_ptr = &disk_id_ccontext->Next;
3225 next_off = conn->vals->create_disk_id_size;
3230 create_posix_rsp_buf(rsp->Buffer +
3231 le32_to_cpu(rsp->CreateContextsLength),
3233 le32_add_cpu(&rsp->CreateContextsLength,
3234 conn->vals->create_posix_size);
3235 inc_rfc1001_len(work->response_buf,
3236 conn->vals->create_posix_size);
3238 *next_ptr = cpu_to_le32(next_off);
3241 if (contxt_cnt > 0) {
3242 rsp->CreateContextsOffset =
3243 cpu_to_le32(offsetof(struct smb2_create_rsp, Buffer));
3247 if (file_present || created)
3249 ksmbd_revert_fsids(work);
3253 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
3254 else if (rc == -EOPNOTSUPP)
3255 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
3256 else if (rc == -EACCES || rc == -ESTALE || rc == -EXDEV)
3257 rsp->hdr.Status = STATUS_ACCESS_DENIED;
3258 else if (rc == -ENOENT)
3259 rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
3260 else if (rc == -EPERM)
3261 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
3262 else if (rc == -EBUSY)
3263 rsp->hdr.Status = STATUS_DELETE_PENDING;
3264 else if (rc == -EBADF)
3265 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
3266 else if (rc == -ENOEXEC)
3267 rsp->hdr.Status = STATUS_DUPLICATE_OBJECTID;
3268 else if (rc == -ENXIO)
3269 rsp->hdr.Status = STATUS_NO_SUCH_DEVICE;
3270 else if (rc == -EEXIST)
3271 rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
3272 else if (rc == -EMFILE)
3273 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
3274 if (!rsp->hdr.Status)
3275 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
3277 if (!fp || !fp->filename)
3280 ksmbd_fd_put(work, fp);
3281 smb2_set_err_rsp(work);
3282 ksmbd_debug(SMB, "Error response: %x\n", rsp->hdr.Status);
3290 static int readdir_info_level_struct_sz(int info_level)
3292 switch (info_level) {
3293 case FILE_FULL_DIRECTORY_INFORMATION:
3294 return sizeof(struct file_full_directory_info);
3295 case FILE_BOTH_DIRECTORY_INFORMATION:
3296 return sizeof(struct file_both_directory_info);
3297 case FILE_DIRECTORY_INFORMATION:
3298 return sizeof(struct file_directory_info);
3299 case FILE_NAMES_INFORMATION:
3300 return sizeof(struct file_names_info);
3301 case FILEID_FULL_DIRECTORY_INFORMATION:
3302 return sizeof(struct file_id_full_dir_info);
3303 case FILEID_BOTH_DIRECTORY_INFORMATION:
3304 return sizeof(struct file_id_both_directory_info);
3305 case SMB_FIND_FILE_POSIX_INFO:
3306 return sizeof(struct smb2_posix_info);
3312 static int dentry_name(struct ksmbd_dir_info *d_info, int info_level)
3314 switch (info_level) {
3315 case FILE_FULL_DIRECTORY_INFORMATION:
3317 struct file_full_directory_info *ffdinfo;
3319 ffdinfo = (struct file_full_directory_info *)d_info->rptr;
3320 d_info->rptr += le32_to_cpu(ffdinfo->NextEntryOffset);
3321 d_info->name = ffdinfo->FileName;
3322 d_info->name_len = le32_to_cpu(ffdinfo->FileNameLength);
3325 case FILE_BOTH_DIRECTORY_INFORMATION:
3327 struct file_both_directory_info *fbdinfo;
3329 fbdinfo = (struct file_both_directory_info *)d_info->rptr;
3330 d_info->rptr += le32_to_cpu(fbdinfo->NextEntryOffset);
3331 d_info->name = fbdinfo->FileName;
3332 d_info->name_len = le32_to_cpu(fbdinfo->FileNameLength);
3335 case FILE_DIRECTORY_INFORMATION:
3337 struct file_directory_info *fdinfo;
3339 fdinfo = (struct file_directory_info *)d_info->rptr;
3340 d_info->rptr += le32_to_cpu(fdinfo->NextEntryOffset);
3341 d_info->name = fdinfo->FileName;
3342 d_info->name_len = le32_to_cpu(fdinfo->FileNameLength);
3345 case FILE_NAMES_INFORMATION:
3347 struct file_names_info *fninfo;
3349 fninfo = (struct file_names_info *)d_info->rptr;
3350 d_info->rptr += le32_to_cpu(fninfo->NextEntryOffset);
3351 d_info->name = fninfo->FileName;
3352 d_info->name_len = le32_to_cpu(fninfo->FileNameLength);
3355 case FILEID_FULL_DIRECTORY_INFORMATION:
3357 struct file_id_full_dir_info *dinfo;
3359 dinfo = (struct file_id_full_dir_info *)d_info->rptr;
3360 d_info->rptr += le32_to_cpu(dinfo->NextEntryOffset);
3361 d_info->name = dinfo->FileName;
3362 d_info->name_len = le32_to_cpu(dinfo->FileNameLength);
3365 case FILEID_BOTH_DIRECTORY_INFORMATION:
3367 struct file_id_both_directory_info *fibdinfo;
3369 fibdinfo = (struct file_id_both_directory_info *)d_info->rptr;
3370 d_info->rptr += le32_to_cpu(fibdinfo->NextEntryOffset);
3371 d_info->name = fibdinfo->FileName;
3372 d_info->name_len = le32_to_cpu(fibdinfo->FileNameLength);
3375 case SMB_FIND_FILE_POSIX_INFO:
3377 struct smb2_posix_info *posix_info;
3379 posix_info = (struct smb2_posix_info *)d_info->rptr;
3380 d_info->rptr += le32_to_cpu(posix_info->NextEntryOffset);
3381 d_info->name = posix_info->name;
3382 d_info->name_len = le32_to_cpu(posix_info->name_len);
3391 * smb2_populate_readdir_entry() - encode directory entry in smb2 response
3393 * @conn: connection instance
3394 * @info_level: smb information level
3395 * @d_info: structure included variables for query dir
3396 * @ksmbd_kstat: ksmbd wrapper of dirent stat information
3398 * if directory has many entries, find first can't read it fully.
3399 * find next might be called multiple times to read remaining dir entries
3401 * Return: 0 on success, otherwise error
3403 static int smb2_populate_readdir_entry(struct ksmbd_conn *conn, int info_level,
3404 struct ksmbd_dir_info *d_info,
3405 struct ksmbd_kstat *ksmbd_kstat)
3407 int next_entry_offset = 0;
3411 int struct_sz, rc = 0;
3413 conv_name = ksmbd_convert_dir_info_name(d_info,
3419 /* Somehow the name has only terminating NULL bytes */
3422 goto free_conv_name;
3425 struct_sz = readdir_info_level_struct_sz(info_level) - 1 + conv_len;
3426 next_entry_offset = ALIGN(struct_sz, KSMBD_DIR_INFO_ALIGNMENT);
3427 d_info->last_entry_off_align = next_entry_offset - struct_sz;
3429 if (next_entry_offset > d_info->out_buf_len) {
3430 d_info->out_buf_len = 0;
3432 goto free_conv_name;
3435 kstat = d_info->wptr;
3436 if (info_level != FILE_NAMES_INFORMATION)
3437 kstat = ksmbd_vfs_init_kstat(&d_info->wptr, ksmbd_kstat);
3439 switch (info_level) {
3440 case FILE_FULL_DIRECTORY_INFORMATION:
3442 struct file_full_directory_info *ffdinfo;
3444 ffdinfo = (struct file_full_directory_info *)kstat;
3445 ffdinfo->FileNameLength = cpu_to_le32(conv_len);
3447 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3448 if (ffdinfo->EaSize)
3449 ffdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3450 if (d_info->hide_dot_file && d_info->name[0] == '.')
3451 ffdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3452 memcpy(ffdinfo->FileName, conv_name, conv_len);
3453 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3456 case FILE_BOTH_DIRECTORY_INFORMATION:
3458 struct file_both_directory_info *fbdinfo;
3460 fbdinfo = (struct file_both_directory_info *)kstat;
3461 fbdinfo->FileNameLength = cpu_to_le32(conv_len);
3463 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3464 if (fbdinfo->EaSize)
3465 fbdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3466 fbdinfo->ShortNameLength = 0;
3467 fbdinfo->Reserved = 0;
3468 if (d_info->hide_dot_file && d_info->name[0] == '.')
3469 fbdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3470 memcpy(fbdinfo->FileName, conv_name, conv_len);
3471 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3474 case FILE_DIRECTORY_INFORMATION:
3476 struct file_directory_info *fdinfo;
3478 fdinfo = (struct file_directory_info *)kstat;
3479 fdinfo->FileNameLength = cpu_to_le32(conv_len);
3480 if (d_info->hide_dot_file && d_info->name[0] == '.')
3481 fdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3482 memcpy(fdinfo->FileName, conv_name, conv_len);
3483 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3486 case FILE_NAMES_INFORMATION:
3488 struct file_names_info *fninfo;
3490 fninfo = (struct file_names_info *)kstat;
3491 fninfo->FileNameLength = cpu_to_le32(conv_len);
3492 memcpy(fninfo->FileName, conv_name, conv_len);
3493 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3496 case FILEID_FULL_DIRECTORY_INFORMATION:
3498 struct file_id_full_dir_info *dinfo;
3500 dinfo = (struct file_id_full_dir_info *)kstat;
3501 dinfo->FileNameLength = cpu_to_le32(conv_len);
3503 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3505 dinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3506 dinfo->Reserved = 0;
3507 dinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
3508 if (d_info->hide_dot_file && d_info->name[0] == '.')
3509 dinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3510 memcpy(dinfo->FileName, conv_name, conv_len);
3511 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3514 case FILEID_BOTH_DIRECTORY_INFORMATION:
3516 struct file_id_both_directory_info *fibdinfo;
3518 fibdinfo = (struct file_id_both_directory_info *)kstat;
3519 fibdinfo->FileNameLength = cpu_to_le32(conv_len);
3521 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3522 if (fibdinfo->EaSize)
3523 fibdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3524 fibdinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
3525 fibdinfo->ShortNameLength = 0;
3526 fibdinfo->Reserved = 0;
3527 fibdinfo->Reserved2 = cpu_to_le16(0);
3528 if (d_info->hide_dot_file && d_info->name[0] == '.')
3529 fibdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3530 memcpy(fibdinfo->FileName, conv_name, conv_len);
3531 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3534 case SMB_FIND_FILE_POSIX_INFO:
3536 struct smb2_posix_info *posix_info;
3539 posix_info = (struct smb2_posix_info *)kstat;
3540 posix_info->Ignored = 0;
3541 posix_info->CreationTime = cpu_to_le64(ksmbd_kstat->create_time);
3542 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->ctime);
3543 posix_info->ChangeTime = cpu_to_le64(time);
3544 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->atime);
3545 posix_info->LastAccessTime = cpu_to_le64(time);
3546 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->mtime);
3547 posix_info->LastWriteTime = cpu_to_le64(time);
3548 posix_info->EndOfFile = cpu_to_le64(ksmbd_kstat->kstat->size);
3549 posix_info->AllocationSize = cpu_to_le64(ksmbd_kstat->kstat->blocks << 9);
3550 posix_info->DeviceId = cpu_to_le32(ksmbd_kstat->kstat->rdev);
3551 posix_info->HardLinks = cpu_to_le32(ksmbd_kstat->kstat->nlink);
3552 posix_info->Mode = cpu_to_le32(ksmbd_kstat->kstat->mode);
3553 posix_info->Inode = cpu_to_le64(ksmbd_kstat->kstat->ino);
3554 posix_info->DosAttributes =
3555 S_ISDIR(ksmbd_kstat->kstat->mode) ?
3556 FILE_ATTRIBUTE_DIRECTORY_LE : FILE_ATTRIBUTE_ARCHIVE_LE;
3557 if (d_info->hide_dot_file && d_info->name[0] == '.')
3558 posix_info->DosAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3559 id_to_sid(from_kuid_munged(&init_user_ns, ksmbd_kstat->kstat->uid),
3560 SIDNFS_USER, (struct smb_sid *)&posix_info->SidBuffer[0]);
3561 id_to_sid(from_kgid_munged(&init_user_ns, ksmbd_kstat->kstat->gid),
3562 SIDNFS_GROUP, (struct smb_sid *)&posix_info->SidBuffer[20]);
3563 memcpy(posix_info->name, conv_name, conv_len);
3564 posix_info->name_len = cpu_to_le32(conv_len);
3565 posix_info->NextEntryOffset = cpu_to_le32(next_entry_offset);
3569 } /* switch (info_level) */
3571 d_info->last_entry_offset = d_info->data_count;
3572 d_info->data_count += next_entry_offset;
3573 d_info->out_buf_len -= next_entry_offset;
3574 d_info->wptr += next_entry_offset;
3577 "info_level : %d, buf_len :%d, next_offset : %d, data_count : %d\n",
3578 info_level, d_info->out_buf_len,
3579 next_entry_offset, d_info->data_count);
3586 struct smb2_query_dir_private {
3587 struct ksmbd_work *work;
3588 char *search_pattern;
3589 struct ksmbd_file *dir_fp;
3591 struct ksmbd_dir_info *d_info;
3595 static void lock_dir(struct ksmbd_file *dir_fp)
3597 struct dentry *dir = dir_fp->filp->f_path.dentry;
3599 inode_lock_nested(d_inode(dir), I_MUTEX_PARENT);
3602 static void unlock_dir(struct ksmbd_file *dir_fp)
3604 struct dentry *dir = dir_fp->filp->f_path.dentry;
3606 inode_unlock(d_inode(dir));
3609 static int process_query_dir_entries(struct smb2_query_dir_private *priv)
3611 struct user_namespace *user_ns = file_mnt_user_ns(priv->dir_fp->filp);
3613 struct ksmbd_kstat ksmbd_kstat;
3617 for (i = 0; i < priv->d_info->num_entry; i++) {
3618 struct dentry *dent;
3620 if (dentry_name(priv->d_info, priv->info_level))
3623 lock_dir(priv->dir_fp);
3624 dent = lookup_one(user_ns, priv->d_info->name,
3625 priv->dir_fp->filp->f_path.dentry,
3626 priv->d_info->name_len);
3627 unlock_dir(priv->dir_fp);
3630 ksmbd_debug(SMB, "Cannot lookup `%s' [%ld]\n",
3635 if (unlikely(d_is_negative(dent))) {
3637 ksmbd_debug(SMB, "Negative dentry `%s'\n",
3638 priv->d_info->name);
3642 ksmbd_kstat.kstat = &kstat;
3643 if (priv->info_level != FILE_NAMES_INFORMATION)
3644 ksmbd_vfs_fill_dentry_attrs(priv->work,
3649 rc = smb2_populate_readdir_entry(priv->work->conn,
3660 static int reserve_populate_dentry(struct ksmbd_dir_info *d_info,
3665 int next_entry_offset;
3667 struct_sz = readdir_info_level_struct_sz(info_level);
3668 if (struct_sz == -EOPNOTSUPP)
3671 conv_len = (d_info->name_len + 1) * 2;
3672 next_entry_offset = ALIGN(struct_sz - 1 + conv_len,
3673 KSMBD_DIR_INFO_ALIGNMENT);
3675 if (next_entry_offset > d_info->out_buf_len) {
3676 d_info->out_buf_len = 0;
3680 switch (info_level) {
3681 case FILE_FULL_DIRECTORY_INFORMATION:
3683 struct file_full_directory_info *ffdinfo;
3685 ffdinfo = (struct file_full_directory_info *)d_info->wptr;
3686 memcpy(ffdinfo->FileName, d_info->name, d_info->name_len);
3687 ffdinfo->FileName[d_info->name_len] = 0x00;
3688 ffdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3689 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3692 case FILE_BOTH_DIRECTORY_INFORMATION:
3694 struct file_both_directory_info *fbdinfo;
3696 fbdinfo = (struct file_both_directory_info *)d_info->wptr;
3697 memcpy(fbdinfo->FileName, d_info->name, d_info->name_len);
3698 fbdinfo->FileName[d_info->name_len] = 0x00;
3699 fbdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3700 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3703 case FILE_DIRECTORY_INFORMATION:
3705 struct file_directory_info *fdinfo;
3707 fdinfo = (struct file_directory_info *)d_info->wptr;
3708 memcpy(fdinfo->FileName, d_info->name, d_info->name_len);
3709 fdinfo->FileName[d_info->name_len] = 0x00;
3710 fdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3711 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3714 case FILE_NAMES_INFORMATION:
3716 struct file_names_info *fninfo;
3718 fninfo = (struct file_names_info *)d_info->wptr;
3719 memcpy(fninfo->FileName, d_info->name, d_info->name_len);
3720 fninfo->FileName[d_info->name_len] = 0x00;
3721 fninfo->FileNameLength = cpu_to_le32(d_info->name_len);
3722 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3725 case FILEID_FULL_DIRECTORY_INFORMATION:
3727 struct file_id_full_dir_info *dinfo;
3729 dinfo = (struct file_id_full_dir_info *)d_info->wptr;
3730 memcpy(dinfo->FileName, d_info->name, d_info->name_len);
3731 dinfo->FileName[d_info->name_len] = 0x00;
3732 dinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3733 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3736 case FILEID_BOTH_DIRECTORY_INFORMATION:
3738 struct file_id_both_directory_info *fibdinfo;
3740 fibdinfo = (struct file_id_both_directory_info *)d_info->wptr;
3741 memcpy(fibdinfo->FileName, d_info->name, d_info->name_len);
3742 fibdinfo->FileName[d_info->name_len] = 0x00;
3743 fibdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3744 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3747 case SMB_FIND_FILE_POSIX_INFO:
3749 struct smb2_posix_info *posix_info;
3751 posix_info = (struct smb2_posix_info *)d_info->wptr;
3752 memcpy(posix_info->name, d_info->name, d_info->name_len);
3753 posix_info->name[d_info->name_len] = 0x00;
3754 posix_info->name_len = cpu_to_le32(d_info->name_len);
3755 posix_info->NextEntryOffset =
3756 cpu_to_le32(next_entry_offset);
3759 } /* switch (info_level) */
3761 d_info->num_entry++;
3762 d_info->out_buf_len -= next_entry_offset;
3763 d_info->wptr += next_entry_offset;
3767 static int __query_dir(struct dir_context *ctx, const char *name, int namlen,
3768 loff_t offset, u64 ino, unsigned int d_type)
3770 struct ksmbd_readdir_data *buf;
3771 struct smb2_query_dir_private *priv;
3772 struct ksmbd_dir_info *d_info;
3775 buf = container_of(ctx, struct ksmbd_readdir_data, ctx);
3776 priv = buf->private;
3777 d_info = priv->d_info;
3779 /* dot and dotdot entries are already reserved */
3780 if (!strcmp(".", name) || !strcmp("..", name))
3782 if (ksmbd_share_veto_filename(priv->work->tcon->share_conf, name))
3784 if (!match_pattern(name, namlen, priv->search_pattern))
3787 d_info->name = name;
3788 d_info->name_len = namlen;
3789 rc = reserve_populate_dentry(d_info, priv->info_level);
3792 if (d_info->flags & SMB2_RETURN_SINGLE_ENTRY) {
3793 d_info->out_buf_len = 0;
3799 static void restart_ctx(struct dir_context *ctx)
3804 static int verify_info_level(int info_level)
3806 switch (info_level) {
3807 case FILE_FULL_DIRECTORY_INFORMATION:
3808 case FILE_BOTH_DIRECTORY_INFORMATION:
3809 case FILE_DIRECTORY_INFORMATION:
3810 case FILE_NAMES_INFORMATION:
3811 case FILEID_FULL_DIRECTORY_INFORMATION:
3812 case FILEID_BOTH_DIRECTORY_INFORMATION:
3813 case SMB_FIND_FILE_POSIX_INFO:
3822 static int smb2_calc_max_out_buf_len(struct ksmbd_work *work,
3823 unsigned short hdr2_len,
3824 unsigned int out_buf_len)
3828 if (out_buf_len > work->conn->vals->max_trans_size)
3831 free_len = (int)(work->response_sz -
3832 (get_rfc1002_len(work->response_buf) + 4)) -
3837 return min_t(int, out_buf_len, free_len);
3840 int smb2_query_dir(struct ksmbd_work *work)
3842 struct ksmbd_conn *conn = work->conn;
3843 struct smb2_query_directory_req *req;
3844 struct smb2_query_directory_rsp *rsp;
3845 struct ksmbd_share_config *share = work->tcon->share_conf;
3846 struct ksmbd_file *dir_fp = NULL;
3847 struct ksmbd_dir_info d_info;
3849 char *srch_ptr = NULL;
3850 unsigned char srch_flag;
3852 struct smb2_query_dir_private query_dir_private = {NULL, };
3854 WORK_BUFFERS(work, req, rsp);
3856 if (ksmbd_override_fsids(work)) {
3857 rsp->hdr.Status = STATUS_NO_MEMORY;
3858 smb2_set_err_rsp(work);
3862 rc = verify_info_level(req->FileInformationClass);
3868 dir_fp = ksmbd_lookup_fd_slow(work,
3869 le64_to_cpu(req->VolatileFileId),
3870 le64_to_cpu(req->PersistentFileId));
3876 if (!(dir_fp->daccess & FILE_LIST_DIRECTORY_LE) ||
3877 inode_permission(file_mnt_user_ns(dir_fp->filp),
3878 file_inode(dir_fp->filp),
3879 MAY_READ | MAY_EXEC)) {
3880 pr_err("no right to enumerate directory (%pd)\n",
3881 dir_fp->filp->f_path.dentry);
3886 if (!S_ISDIR(file_inode(dir_fp->filp)->i_mode)) {
3887 pr_err("can't do query dir for a file\n");
3892 srch_flag = req->Flags;
3893 srch_ptr = smb_strndup_from_utf16(req->Buffer,
3894 le16_to_cpu(req->FileNameLength), 1,
3896 if (IS_ERR(srch_ptr)) {
3897 ksmbd_debug(SMB, "Search Pattern not found\n");
3901 ksmbd_debug(SMB, "Search pattern is %s\n", srch_ptr);
3904 ksmbd_debug(SMB, "Directory name is %s\n", dir_fp->filename);
3906 if (srch_flag & SMB2_REOPEN || srch_flag & SMB2_RESTART_SCANS) {
3907 ksmbd_debug(SMB, "Restart directory scan\n");
3908 generic_file_llseek(dir_fp->filp, 0, SEEK_SET);
3909 restart_ctx(&dir_fp->readdir_data.ctx);
3912 memset(&d_info, 0, sizeof(struct ksmbd_dir_info));
3913 d_info.wptr = (char *)rsp->Buffer;
3914 d_info.rptr = (char *)rsp->Buffer;
3915 d_info.out_buf_len =
3916 smb2_calc_max_out_buf_len(work, 8,
3917 le32_to_cpu(req->OutputBufferLength));
3918 if (d_info.out_buf_len < 0) {
3922 d_info.flags = srch_flag;
3925 * reserve dot and dotdot entries in head of buffer
3928 rc = ksmbd_populate_dot_dotdot_entries(work, req->FileInformationClass,
3929 dir_fp, &d_info, srch_ptr,
3930 smb2_populate_readdir_entry);
3936 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_HIDE_DOT_FILES))
3937 d_info.hide_dot_file = true;
3939 buffer_sz = d_info.out_buf_len;
3940 d_info.rptr = d_info.wptr;
3941 query_dir_private.work = work;
3942 query_dir_private.search_pattern = srch_ptr;
3943 query_dir_private.dir_fp = dir_fp;
3944 query_dir_private.d_info = &d_info;
3945 query_dir_private.info_level = req->FileInformationClass;
3946 dir_fp->readdir_data.private = &query_dir_private;
3947 set_ctx_actor(&dir_fp->readdir_data.ctx, __query_dir);
3949 rc = iterate_dir(dir_fp->filp, &dir_fp->readdir_data.ctx);
3951 restart_ctx(&dir_fp->readdir_data.ctx);
3957 d_info.wptr = d_info.rptr;
3958 d_info.out_buf_len = buffer_sz;
3959 rc = process_query_dir_entries(&query_dir_private);
3963 if (!d_info.data_count && d_info.out_buf_len >= 0) {
3964 if (srch_flag & SMB2_RETURN_SINGLE_ENTRY && !is_asterisk(srch_ptr)) {
3965 rsp->hdr.Status = STATUS_NO_SUCH_FILE;
3967 dir_fp->dot_dotdot[0] = dir_fp->dot_dotdot[1] = 0;
3968 rsp->hdr.Status = STATUS_NO_MORE_FILES;
3970 rsp->StructureSize = cpu_to_le16(9);
3971 rsp->OutputBufferOffset = cpu_to_le16(0);
3972 rsp->OutputBufferLength = cpu_to_le32(0);
3974 inc_rfc1001_len(work->response_buf, 9);
3976 ((struct file_directory_info *)
3977 ((char *)rsp->Buffer + d_info.last_entry_offset))
3978 ->NextEntryOffset = 0;
3979 d_info.data_count -= d_info.last_entry_off_align;
3981 rsp->StructureSize = cpu_to_le16(9);
3982 rsp->OutputBufferOffset = cpu_to_le16(72);
3983 rsp->OutputBufferLength = cpu_to_le32(d_info.data_count);
3984 inc_rfc1001_len(work->response_buf, 8 + d_info.data_count);
3988 ksmbd_fd_put(work, dir_fp);
3989 ksmbd_revert_fsids(work);
3993 pr_err("error while processing smb2 query dir rc = %d\n", rc);
3998 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
3999 else if (rc == -EACCES)
4000 rsp->hdr.Status = STATUS_ACCESS_DENIED;
4001 else if (rc == -ENOENT)
4002 rsp->hdr.Status = STATUS_NO_SUCH_FILE;
4003 else if (rc == -EBADF)
4004 rsp->hdr.Status = STATUS_FILE_CLOSED;
4005 else if (rc == -ENOMEM)
4006 rsp->hdr.Status = STATUS_NO_MEMORY;
4007 else if (rc == -EFAULT)
4008 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
4009 if (!rsp->hdr.Status)
4010 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
4012 smb2_set_err_rsp(work);
4013 ksmbd_fd_put(work, dir_fp);
4014 ksmbd_revert_fsids(work);
4019 * buffer_check_err() - helper function to check buffer errors
4020 * @reqOutputBufferLength: max buffer length expected in command response
4021 * @rsp: query info response buffer contains output buffer length
4022 * @rsp_org: base response buffer pointer in case of chained response
4023 * @infoclass_size: query info class response buffer size
4025 * Return: 0 on success, otherwise error
4027 static int buffer_check_err(int reqOutputBufferLength,
4028 struct smb2_query_info_rsp *rsp,
4029 void *rsp_org, int infoclass_size)
4031 if (reqOutputBufferLength < le32_to_cpu(rsp->OutputBufferLength)) {
4032 if (reqOutputBufferLength < infoclass_size) {
4033 pr_err("Invalid Buffer Size Requested\n");
4034 rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
4035 *(__be32 *)rsp_org = cpu_to_be32(sizeof(struct smb2_hdr));
4039 ksmbd_debug(SMB, "Buffer Overflow\n");
4040 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
4041 *(__be32 *)rsp_org = cpu_to_be32(sizeof(struct smb2_hdr) +
4042 reqOutputBufferLength);
4043 rsp->OutputBufferLength = cpu_to_le32(reqOutputBufferLength);
4048 static void get_standard_info_pipe(struct smb2_query_info_rsp *rsp,
4051 struct smb2_file_standard_info *sinfo;
4053 sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
4055 sinfo->AllocationSize = cpu_to_le64(4096);
4056 sinfo->EndOfFile = cpu_to_le64(0);
4057 sinfo->NumberOfLinks = cpu_to_le32(1);
4058 sinfo->DeletePending = 1;
4059 sinfo->Directory = 0;
4060 rsp->OutputBufferLength =
4061 cpu_to_le32(sizeof(struct smb2_file_standard_info));
4062 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_standard_info));
4065 static void get_internal_info_pipe(struct smb2_query_info_rsp *rsp, u64 num,
4068 struct smb2_file_internal_info *file_info;
4070 file_info = (struct smb2_file_internal_info *)rsp->Buffer;
4072 /* any unique number */
4073 file_info->IndexNumber = cpu_to_le64(num | (1ULL << 63));
4074 rsp->OutputBufferLength =
4075 cpu_to_le32(sizeof(struct smb2_file_internal_info));
4076 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_internal_info));
4079 static int smb2_get_info_file_pipe(struct ksmbd_session *sess,
4080 struct smb2_query_info_req *req,
4081 struct smb2_query_info_rsp *rsp,
4088 * Windows can sometime send query file info request on
4089 * pipe without opening it, checking error condition here
4091 id = le64_to_cpu(req->VolatileFileId);
4092 if (!ksmbd_session_rpc_method(sess, id))
4095 ksmbd_debug(SMB, "FileInfoClass %u, FileId 0x%llx\n",
4096 req->FileInfoClass, le64_to_cpu(req->VolatileFileId));
4098 switch (req->FileInfoClass) {
4099 case FILE_STANDARD_INFORMATION:
4100 get_standard_info_pipe(rsp, rsp_org);
4101 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4103 FILE_STANDARD_INFORMATION_SIZE);
4105 case FILE_INTERNAL_INFORMATION:
4106 get_internal_info_pipe(rsp, id, rsp_org);
4107 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4109 FILE_INTERNAL_INFORMATION_SIZE);
4112 ksmbd_debug(SMB, "smb2_info_file_pipe for %u not supported\n",
4113 req->FileInfoClass);
4120 * smb2_get_ea() - handler for smb2 get extended attribute command
4121 * @work: smb work containing query info command buffer
4122 * @fp: ksmbd_file pointer
4123 * @req: get extended attribute request
4124 * @rsp: response buffer pointer
4125 * @rsp_org: base response buffer pointer in case of chained response
4127 * Return: 0 on success, otherwise error
4129 static int smb2_get_ea(struct ksmbd_work *work, struct ksmbd_file *fp,
4130 struct smb2_query_info_req *req,
4131 struct smb2_query_info_rsp *rsp, void *rsp_org)
4133 struct smb2_ea_info *eainfo, *prev_eainfo;
4134 char *name, *ptr, *xattr_list = NULL, *buf;
4135 int rc, name_len, value_len, xattr_list_len, idx;
4136 ssize_t buf_free_len, alignment_bytes, next_offset, rsp_data_cnt = 0;
4137 struct smb2_ea_info_req *ea_req = NULL;
4139 struct user_namespace *user_ns = file_mnt_user_ns(fp->filp);
4141 if (!(fp->daccess & FILE_READ_EA_LE)) {
4142 pr_err("Not permitted to read ext attr : 0x%x\n",
4147 path = &fp->filp->f_path;
4148 /* single EA entry is requested with given user.* name */
4149 if (req->InputBufferLength) {
4150 if (le32_to_cpu(req->InputBufferLength) <
4151 sizeof(struct smb2_ea_info_req))
4154 ea_req = (struct smb2_ea_info_req *)req->Buffer;
4156 /* need to send all EAs, if no specific EA is requested*/
4157 if (le32_to_cpu(req->Flags) & SL_RETURN_SINGLE_ENTRY)
4159 "All EAs are requested but need to send single EA entry in rsp flags 0x%x\n",
4160 le32_to_cpu(req->Flags));
4164 smb2_calc_max_out_buf_len(work, 8,
4165 le32_to_cpu(req->OutputBufferLength));
4166 if (buf_free_len < 0)
4169 rc = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
4171 rsp->hdr.Status = STATUS_INVALID_HANDLE;
4173 } else if (!rc) { /* there is no EA in the file */
4174 ksmbd_debug(SMB, "no ea data in the file\n");
4177 xattr_list_len = rc;
4179 ptr = (char *)rsp->Buffer;
4180 eainfo = (struct smb2_ea_info *)ptr;
4181 prev_eainfo = eainfo;
4184 while (idx < xattr_list_len) {
4185 name = xattr_list + idx;
4186 name_len = strlen(name);
4188 ksmbd_debug(SMB, "%s, len %d\n", name, name_len);
4189 idx += name_len + 1;
4192 * CIFS does not support EA other than user.* namespace,
4193 * still keep the framework generic, to list other attrs
4196 if (strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4199 if (!strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
4203 if (req->InputBufferLength &&
4204 strncmp(&name[XATTR_USER_PREFIX_LEN], ea_req->name,
4205 ea_req->EaNameLength))
4208 if (!strncmp(&name[XATTR_USER_PREFIX_LEN],
4209 DOS_ATTRIBUTE_PREFIX, DOS_ATTRIBUTE_PREFIX_LEN))
4212 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4213 name_len -= XATTR_USER_PREFIX_LEN;
4215 ptr = (char *)(&eainfo->name + name_len + 1);
4216 buf_free_len -= (offsetof(struct smb2_ea_info, name) +
4218 /* bailout if xattr can't fit in buf_free_len */
4219 value_len = ksmbd_vfs_getxattr(user_ns, path->dentry,
4221 if (value_len <= 0) {
4223 rsp->hdr.Status = STATUS_INVALID_HANDLE;
4227 buf_free_len -= value_len;
4228 if (buf_free_len < 0) {
4233 memcpy(ptr, buf, value_len);
4238 eainfo->EaNameLength = name_len;
4240 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4241 memcpy(eainfo->name, &name[XATTR_USER_PREFIX_LEN],
4244 memcpy(eainfo->name, name, name_len);
4246 eainfo->name[name_len] = '\0';
4247 eainfo->EaValueLength = cpu_to_le16(value_len);
4248 next_offset = offsetof(struct smb2_ea_info, name) +
4249 name_len + 1 + value_len;
4251 /* align next xattr entry at 4 byte bundary */
4252 alignment_bytes = ((next_offset + 3) & ~3) - next_offset;
4253 if (alignment_bytes) {
4254 memset(ptr, '\0', alignment_bytes);
4255 ptr += alignment_bytes;
4256 next_offset += alignment_bytes;
4257 buf_free_len -= alignment_bytes;
4259 eainfo->NextEntryOffset = cpu_to_le32(next_offset);
4260 prev_eainfo = eainfo;
4261 eainfo = (struct smb2_ea_info *)ptr;
4262 rsp_data_cnt += next_offset;
4264 if (req->InputBufferLength) {
4265 ksmbd_debug(SMB, "single entry requested\n");
4270 /* no more ea entries */
4271 prev_eainfo->NextEntryOffset = 0;
4274 if (rsp_data_cnt == 0)
4275 rsp->hdr.Status = STATUS_NO_EAS_ON_FILE;
4276 rsp->OutputBufferLength = cpu_to_le32(rsp_data_cnt);
4277 inc_rfc1001_len(rsp_org, rsp_data_cnt);
4283 static void get_file_access_info(struct smb2_query_info_rsp *rsp,
4284 struct ksmbd_file *fp, void *rsp_org)
4286 struct smb2_file_access_info *file_info;
4288 file_info = (struct smb2_file_access_info *)rsp->Buffer;
4289 file_info->AccessFlags = fp->daccess;
4290 rsp->OutputBufferLength =
4291 cpu_to_le32(sizeof(struct smb2_file_access_info));
4292 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_access_info));
4295 static int get_file_basic_info(struct smb2_query_info_rsp *rsp,
4296 struct ksmbd_file *fp, void *rsp_org)
4298 struct smb2_file_basic_info *basic_info;
4302 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4303 pr_err("no right to read the attributes : 0x%x\n",
4308 basic_info = (struct smb2_file_basic_info *)rsp->Buffer;
4309 generic_fillattr(file_mnt_user_ns(fp->filp), file_inode(fp->filp),
4311 basic_info->CreationTime = cpu_to_le64(fp->create_time);
4312 time = ksmbd_UnixTimeToNT(stat.atime);
4313 basic_info->LastAccessTime = cpu_to_le64(time);
4314 time = ksmbd_UnixTimeToNT(stat.mtime);
4315 basic_info->LastWriteTime = cpu_to_le64(time);
4316 time = ksmbd_UnixTimeToNT(stat.ctime);
4317 basic_info->ChangeTime = cpu_to_le64(time);
4318 basic_info->Attributes = fp->f_ci->m_fattr;
4319 basic_info->Pad1 = 0;
4320 rsp->OutputBufferLength =
4321 cpu_to_le32(sizeof(struct smb2_file_basic_info));
4322 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_basic_info));
4326 static unsigned long long get_allocation_size(struct inode *inode,
4329 unsigned long long alloc_size = 0;
4331 if (!S_ISDIR(stat->mode)) {
4332 if ((inode->i_blocks << 9) <= stat->size)
4333 alloc_size = stat->size;
4335 alloc_size = inode->i_blocks << 9;
4341 static void get_file_standard_info(struct smb2_query_info_rsp *rsp,
4342 struct ksmbd_file *fp, void *rsp_org)
4344 struct smb2_file_standard_info *sinfo;
4345 unsigned int delete_pending;
4346 struct inode *inode;
4349 inode = file_inode(fp->filp);
4350 generic_fillattr(file_mnt_user_ns(fp->filp), inode, &stat);
4352 sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
4353 delete_pending = ksmbd_inode_pending_delete(fp);
4355 sinfo->AllocationSize = cpu_to_le64(get_allocation_size(inode, &stat));
4356 sinfo->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4357 sinfo->NumberOfLinks = cpu_to_le32(get_nlink(&stat) - delete_pending);
4358 sinfo->DeletePending = delete_pending;
4359 sinfo->Directory = S_ISDIR(stat.mode) ? 1 : 0;
4360 rsp->OutputBufferLength =
4361 cpu_to_le32(sizeof(struct smb2_file_standard_info));
4362 inc_rfc1001_len(rsp_org,
4363 sizeof(struct smb2_file_standard_info));
4366 static void get_file_alignment_info(struct smb2_query_info_rsp *rsp,
4369 struct smb2_file_alignment_info *file_info;
4371 file_info = (struct smb2_file_alignment_info *)rsp->Buffer;
4372 file_info->AlignmentRequirement = 0;
4373 rsp->OutputBufferLength =
4374 cpu_to_le32(sizeof(struct smb2_file_alignment_info));
4375 inc_rfc1001_len(rsp_org,
4376 sizeof(struct smb2_file_alignment_info));
4379 static int get_file_all_info(struct ksmbd_work *work,
4380 struct smb2_query_info_rsp *rsp,
4381 struct ksmbd_file *fp,
4384 struct ksmbd_conn *conn = work->conn;
4385 struct smb2_file_all_info *file_info;
4386 unsigned int delete_pending;
4387 struct inode *inode;
4393 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4394 ksmbd_debug(SMB, "no right to read the attributes : 0x%x\n",
4399 filename = convert_to_nt_pathname(fp->filename);
4403 inode = file_inode(fp->filp);
4404 generic_fillattr(file_mnt_user_ns(fp->filp), inode, &stat);
4406 ksmbd_debug(SMB, "filename = %s\n", filename);
4407 delete_pending = ksmbd_inode_pending_delete(fp);
4408 file_info = (struct smb2_file_all_info *)rsp->Buffer;
4410 file_info->CreationTime = cpu_to_le64(fp->create_time);
4411 time = ksmbd_UnixTimeToNT(stat.atime);
4412 file_info->LastAccessTime = cpu_to_le64(time);
4413 time = ksmbd_UnixTimeToNT(stat.mtime);
4414 file_info->LastWriteTime = cpu_to_le64(time);
4415 time = ksmbd_UnixTimeToNT(stat.ctime);
4416 file_info->ChangeTime = cpu_to_le64(time);
4417 file_info->Attributes = fp->f_ci->m_fattr;
4418 file_info->Pad1 = 0;
4419 file_info->AllocationSize =
4420 cpu_to_le64(get_allocation_size(inode, &stat));
4421 file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4422 file_info->NumberOfLinks =
4423 cpu_to_le32(get_nlink(&stat) - delete_pending);
4424 file_info->DeletePending = delete_pending;
4425 file_info->Directory = S_ISDIR(stat.mode) ? 1 : 0;
4426 file_info->Pad2 = 0;
4427 file_info->IndexNumber = cpu_to_le64(stat.ino);
4428 file_info->EASize = 0;
4429 file_info->AccessFlags = fp->daccess;
4430 file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
4431 file_info->Mode = fp->coption;
4432 file_info->AlignmentRequirement = 0;
4433 conv_len = smbConvertToUTF16((__le16 *)file_info->FileName, filename,
4434 PATH_MAX, conn->local_nls, 0);
4436 file_info->FileNameLength = cpu_to_le32(conv_len);
4437 rsp->OutputBufferLength =
4438 cpu_to_le32(sizeof(struct smb2_file_all_info) + conv_len - 1);
4440 inc_rfc1001_len(rsp_org, le32_to_cpu(rsp->OutputBufferLength));
4444 static void get_file_alternate_info(struct ksmbd_work *work,
4445 struct smb2_query_info_rsp *rsp,
4446 struct ksmbd_file *fp,
4449 struct ksmbd_conn *conn = work->conn;
4450 struct smb2_file_alt_name_info *file_info;
4451 struct dentry *dentry = fp->filp->f_path.dentry;
4454 spin_lock(&dentry->d_lock);
4455 file_info = (struct smb2_file_alt_name_info *)rsp->Buffer;
4456 conv_len = ksmbd_extract_shortname(conn,
4457 dentry->d_name.name,
4458 file_info->FileName);
4459 spin_unlock(&dentry->d_lock);
4460 file_info->FileNameLength = cpu_to_le32(conv_len);
4461 rsp->OutputBufferLength =
4462 cpu_to_le32(sizeof(struct smb2_file_alt_name_info) + conv_len);
4463 inc_rfc1001_len(rsp_org, le32_to_cpu(rsp->OutputBufferLength));
4466 static void get_file_stream_info(struct ksmbd_work *work,
4467 struct smb2_query_info_rsp *rsp,
4468 struct ksmbd_file *fp,
4471 struct ksmbd_conn *conn = work->conn;
4472 struct smb2_file_stream_info *file_info;
4473 char *stream_name, *xattr_list = NULL, *stream_buf;
4475 struct path *path = &fp->filp->f_path;
4476 ssize_t xattr_list_len;
4477 int nbytes = 0, streamlen, stream_name_len, next, idx = 0;
4479 struct smb2_query_info_req *req = ksmbd_req_buf_next(work);
4481 generic_fillattr(file_mnt_user_ns(fp->filp), file_inode(fp->filp),
4483 file_info = (struct smb2_file_stream_info *)rsp->Buffer;
4486 smb2_calc_max_out_buf_len(work, 8,
4487 le32_to_cpu(req->OutputBufferLength));
4488 if (buf_free_len < 0)
4491 xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
4492 if (xattr_list_len < 0) {
4494 } else if (!xattr_list_len) {
4495 ksmbd_debug(SMB, "empty xattr in the file\n");
4499 while (idx < xattr_list_len) {
4500 stream_name = xattr_list + idx;
4501 streamlen = strlen(stream_name);
4502 idx += streamlen + 1;
4504 ksmbd_debug(SMB, "%s, len %d\n", stream_name, streamlen);
4506 if (strncmp(&stream_name[XATTR_USER_PREFIX_LEN],
4507 STREAM_PREFIX, STREAM_PREFIX_LEN))
4510 stream_name_len = streamlen - (XATTR_USER_PREFIX_LEN +
4512 streamlen = stream_name_len;
4516 stream_buf = kmalloc(streamlen + 1, GFP_KERNEL);
4520 streamlen = snprintf(stream_buf, streamlen + 1,
4521 ":%s", &stream_name[XATTR_NAME_STREAM_LEN]);
4523 next = sizeof(struct smb2_file_stream_info) + streamlen * 2;
4524 if (next > buf_free_len) {
4529 file_info = (struct smb2_file_stream_info *)&rsp->Buffer[nbytes];
4530 streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
4531 stream_buf, streamlen,
4532 conn->local_nls, 0);
4535 file_info->StreamNameLength = cpu_to_le32(streamlen);
4536 file_info->StreamSize = cpu_to_le64(stream_name_len);
4537 file_info->StreamAllocationSize = cpu_to_le64(stream_name_len);
4540 buf_free_len -= next;
4541 file_info->NextEntryOffset = cpu_to_le32(next);
4545 if (!S_ISDIR(stat.mode) &&
4546 buf_free_len >= sizeof(struct smb2_file_stream_info) + 7 * 2) {
4547 file_info = (struct smb2_file_stream_info *)
4548 &rsp->Buffer[nbytes];
4549 streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
4550 "::$DATA", 7, conn->local_nls, 0);
4552 file_info->StreamNameLength = cpu_to_le32(streamlen);
4553 file_info->StreamSize = cpu_to_le64(stat.size);
4554 file_info->StreamAllocationSize = cpu_to_le64(stat.blocks << 9);
4555 nbytes += sizeof(struct smb2_file_stream_info) + streamlen;
4558 /* last entry offset should be 0 */
4559 file_info->NextEntryOffset = 0;
4562 rsp->OutputBufferLength = cpu_to_le32(nbytes);
4563 inc_rfc1001_len(rsp_org, nbytes);
4566 static void get_file_internal_info(struct smb2_query_info_rsp *rsp,
4567 struct ksmbd_file *fp, void *rsp_org)
4569 struct smb2_file_internal_info *file_info;
4572 generic_fillattr(file_mnt_user_ns(fp->filp), file_inode(fp->filp),
4574 file_info = (struct smb2_file_internal_info *)rsp->Buffer;
4575 file_info->IndexNumber = cpu_to_le64(stat.ino);
4576 rsp->OutputBufferLength =
4577 cpu_to_le32(sizeof(struct smb2_file_internal_info));
4578 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_internal_info));
4581 static int get_file_network_open_info(struct smb2_query_info_rsp *rsp,
4582 struct ksmbd_file *fp, void *rsp_org)
4584 struct smb2_file_ntwrk_info *file_info;
4585 struct inode *inode;
4589 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4590 pr_err("no right to read the attributes : 0x%x\n",
4595 file_info = (struct smb2_file_ntwrk_info *)rsp->Buffer;
4597 inode = file_inode(fp->filp);
4598 generic_fillattr(file_mnt_user_ns(fp->filp), inode, &stat);
4600 file_info->CreationTime = cpu_to_le64(fp->create_time);
4601 time = ksmbd_UnixTimeToNT(stat.atime);
4602 file_info->LastAccessTime = cpu_to_le64(time);
4603 time = ksmbd_UnixTimeToNT(stat.mtime);
4604 file_info->LastWriteTime = cpu_to_le64(time);
4605 time = ksmbd_UnixTimeToNT(stat.ctime);
4606 file_info->ChangeTime = cpu_to_le64(time);
4607 file_info->Attributes = fp->f_ci->m_fattr;
4608 file_info->AllocationSize =
4609 cpu_to_le64(get_allocation_size(inode, &stat));
4610 file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4611 file_info->Reserved = cpu_to_le32(0);
4612 rsp->OutputBufferLength =
4613 cpu_to_le32(sizeof(struct smb2_file_ntwrk_info));
4614 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_ntwrk_info));
4618 static void get_file_ea_info(struct smb2_query_info_rsp *rsp, void *rsp_org)
4620 struct smb2_file_ea_info *file_info;
4622 file_info = (struct smb2_file_ea_info *)rsp->Buffer;
4623 file_info->EASize = 0;
4624 rsp->OutputBufferLength =
4625 cpu_to_le32(sizeof(struct smb2_file_ea_info));
4626 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_ea_info));
4629 static void get_file_position_info(struct smb2_query_info_rsp *rsp,
4630 struct ksmbd_file *fp, void *rsp_org)
4632 struct smb2_file_pos_info *file_info;
4634 file_info = (struct smb2_file_pos_info *)rsp->Buffer;
4635 file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
4636 rsp->OutputBufferLength =
4637 cpu_to_le32(sizeof(struct smb2_file_pos_info));
4638 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_pos_info));
4641 static void get_file_mode_info(struct smb2_query_info_rsp *rsp,
4642 struct ksmbd_file *fp, void *rsp_org)
4644 struct smb2_file_mode_info *file_info;
4646 file_info = (struct smb2_file_mode_info *)rsp->Buffer;
4647 file_info->Mode = fp->coption & FILE_MODE_INFO_MASK;
4648 rsp->OutputBufferLength =
4649 cpu_to_le32(sizeof(struct smb2_file_mode_info));
4650 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_mode_info));
4653 static void get_file_compression_info(struct smb2_query_info_rsp *rsp,
4654 struct ksmbd_file *fp, void *rsp_org)
4656 struct smb2_file_comp_info *file_info;
4659 generic_fillattr(file_mnt_user_ns(fp->filp), file_inode(fp->filp),
4662 file_info = (struct smb2_file_comp_info *)rsp->Buffer;
4663 file_info->CompressedFileSize = cpu_to_le64(stat.blocks << 9);
4664 file_info->CompressionFormat = COMPRESSION_FORMAT_NONE;
4665 file_info->CompressionUnitShift = 0;
4666 file_info->ChunkShift = 0;
4667 file_info->ClusterShift = 0;
4668 memset(&file_info->Reserved[0], 0, 3);
4670 rsp->OutputBufferLength =
4671 cpu_to_le32(sizeof(struct smb2_file_comp_info));
4672 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_comp_info));
4675 static int get_file_attribute_tag_info(struct smb2_query_info_rsp *rsp,
4676 struct ksmbd_file *fp, void *rsp_org)
4678 struct smb2_file_attr_tag_info *file_info;
4680 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4681 pr_err("no right to read the attributes : 0x%x\n",
4686 file_info = (struct smb2_file_attr_tag_info *)rsp->Buffer;
4687 file_info->FileAttributes = fp->f_ci->m_fattr;
4688 file_info->ReparseTag = 0;
4689 rsp->OutputBufferLength =
4690 cpu_to_le32(sizeof(struct smb2_file_attr_tag_info));
4691 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_attr_tag_info));
4695 static int find_file_posix_info(struct smb2_query_info_rsp *rsp,
4696 struct ksmbd_file *fp, void *rsp_org)
4698 struct smb311_posix_qinfo *file_info;
4699 struct inode *inode = file_inode(fp->filp);
4702 file_info = (struct smb311_posix_qinfo *)rsp->Buffer;
4703 file_info->CreationTime = cpu_to_le64(fp->create_time);
4704 time = ksmbd_UnixTimeToNT(inode->i_atime);
4705 file_info->LastAccessTime = cpu_to_le64(time);
4706 time = ksmbd_UnixTimeToNT(inode->i_mtime);
4707 file_info->LastWriteTime = cpu_to_le64(time);
4708 time = ksmbd_UnixTimeToNT(inode->i_ctime);
4709 file_info->ChangeTime = cpu_to_le64(time);
4710 file_info->DosAttributes = fp->f_ci->m_fattr;
4711 file_info->Inode = cpu_to_le64(inode->i_ino);
4712 file_info->EndOfFile = cpu_to_le64(inode->i_size);
4713 file_info->AllocationSize = cpu_to_le64(inode->i_blocks << 9);
4714 file_info->HardLinks = cpu_to_le32(inode->i_nlink);
4715 file_info->Mode = cpu_to_le32(inode->i_mode);
4716 file_info->DeviceId = cpu_to_le32(inode->i_rdev);
4717 rsp->OutputBufferLength =
4718 cpu_to_le32(sizeof(struct smb311_posix_qinfo));
4719 inc_rfc1001_len(rsp_org, sizeof(struct smb311_posix_qinfo));
4723 static int smb2_get_info_file(struct ksmbd_work *work,
4724 struct smb2_query_info_req *req,
4725 struct smb2_query_info_rsp *rsp)
4727 struct ksmbd_file *fp;
4728 int fileinfoclass = 0;
4730 int file_infoclass_size;
4731 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
4733 if (test_share_config_flag(work->tcon->share_conf,
4734 KSMBD_SHARE_FLAG_PIPE)) {
4735 /* smb2 info file called for pipe */
4736 return smb2_get_info_file_pipe(work->sess, req, rsp,
4737 work->response_buf);
4740 if (work->next_smb2_rcv_hdr_off) {
4741 if (!has_file_id(le64_to_cpu(req->VolatileFileId))) {
4742 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
4743 work->compound_fid);
4744 id = work->compound_fid;
4745 pid = work->compound_pfid;
4749 if (!has_file_id(id)) {
4750 id = le64_to_cpu(req->VolatileFileId);
4751 pid = le64_to_cpu(req->PersistentFileId);
4754 fp = ksmbd_lookup_fd_slow(work, id, pid);
4758 fileinfoclass = req->FileInfoClass;
4760 switch (fileinfoclass) {
4761 case FILE_ACCESS_INFORMATION:
4762 get_file_access_info(rsp, fp, work->response_buf);
4763 file_infoclass_size = FILE_ACCESS_INFORMATION_SIZE;
4766 case FILE_BASIC_INFORMATION:
4767 rc = get_file_basic_info(rsp, fp, work->response_buf);
4768 file_infoclass_size = FILE_BASIC_INFORMATION_SIZE;
4771 case FILE_STANDARD_INFORMATION:
4772 get_file_standard_info(rsp, fp, work->response_buf);
4773 file_infoclass_size = FILE_STANDARD_INFORMATION_SIZE;
4776 case FILE_ALIGNMENT_INFORMATION:
4777 get_file_alignment_info(rsp, work->response_buf);
4778 file_infoclass_size = FILE_ALIGNMENT_INFORMATION_SIZE;
4781 case FILE_ALL_INFORMATION:
4782 rc = get_file_all_info(work, rsp, fp, work->response_buf);
4783 file_infoclass_size = FILE_ALL_INFORMATION_SIZE;
4786 case FILE_ALTERNATE_NAME_INFORMATION:
4787 get_file_alternate_info(work, rsp, fp, work->response_buf);
4788 file_infoclass_size = FILE_ALTERNATE_NAME_INFORMATION_SIZE;
4791 case FILE_STREAM_INFORMATION:
4792 get_file_stream_info(work, rsp, fp, work->response_buf);
4793 file_infoclass_size = FILE_STREAM_INFORMATION_SIZE;
4796 case FILE_INTERNAL_INFORMATION:
4797 get_file_internal_info(rsp, fp, work->response_buf);
4798 file_infoclass_size = FILE_INTERNAL_INFORMATION_SIZE;
4801 case FILE_NETWORK_OPEN_INFORMATION:
4802 rc = get_file_network_open_info(rsp, fp, work->response_buf);
4803 file_infoclass_size = FILE_NETWORK_OPEN_INFORMATION_SIZE;
4806 case FILE_EA_INFORMATION:
4807 get_file_ea_info(rsp, work->response_buf);
4808 file_infoclass_size = FILE_EA_INFORMATION_SIZE;
4811 case FILE_FULL_EA_INFORMATION:
4812 rc = smb2_get_ea(work, fp, req, rsp, work->response_buf);
4813 file_infoclass_size = FILE_FULL_EA_INFORMATION_SIZE;
4816 case FILE_POSITION_INFORMATION:
4817 get_file_position_info(rsp, fp, work->response_buf);
4818 file_infoclass_size = FILE_POSITION_INFORMATION_SIZE;
4821 case FILE_MODE_INFORMATION:
4822 get_file_mode_info(rsp, fp, work->response_buf);
4823 file_infoclass_size = FILE_MODE_INFORMATION_SIZE;
4826 case FILE_COMPRESSION_INFORMATION:
4827 get_file_compression_info(rsp, fp, work->response_buf);
4828 file_infoclass_size = FILE_COMPRESSION_INFORMATION_SIZE;
4831 case FILE_ATTRIBUTE_TAG_INFORMATION:
4832 rc = get_file_attribute_tag_info(rsp, fp, work->response_buf);
4833 file_infoclass_size = FILE_ATTRIBUTE_TAG_INFORMATION_SIZE;
4835 case SMB_FIND_FILE_POSIX_INFO:
4836 if (!work->tcon->posix_extensions) {
4837 pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
4840 rc = find_file_posix_info(rsp, fp, work->response_buf);
4841 file_infoclass_size = sizeof(struct smb311_posix_qinfo);
4845 ksmbd_debug(SMB, "fileinfoclass %d not supported yet\n",
4850 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4851 rsp, work->response_buf,
4852 file_infoclass_size);
4853 ksmbd_fd_put(work, fp);
4857 static int smb2_get_info_filesystem(struct ksmbd_work *work,
4858 struct smb2_query_info_req *req,
4859 struct smb2_query_info_rsp *rsp)
4861 struct ksmbd_session *sess = work->sess;
4862 struct ksmbd_conn *conn = sess->conn;
4863 struct ksmbd_share_config *share = work->tcon->share_conf;
4864 int fsinfoclass = 0;
4865 struct kstatfs stfs;
4868 int fs_infoclass_size = 0;
4870 rc = kern_path(share->path, LOOKUP_NO_SYMLINKS, &path);
4872 pr_err("cannot create vfs path\n");
4876 rc = vfs_statfs(&path, &stfs);
4878 pr_err("cannot do stat of path %s\n", share->path);
4883 fsinfoclass = req->FileInfoClass;
4885 switch (fsinfoclass) {
4886 case FS_DEVICE_INFORMATION:
4888 struct filesystem_device_info *info;
4890 info = (struct filesystem_device_info *)rsp->Buffer;
4892 info->DeviceType = cpu_to_le32(stfs.f_type);
4893 info->DeviceCharacteristics = cpu_to_le32(0x00000020);
4894 rsp->OutputBufferLength = cpu_to_le32(8);
4895 inc_rfc1001_len(work->response_buf, 8);
4896 fs_infoclass_size = FS_DEVICE_INFORMATION_SIZE;
4899 case FS_ATTRIBUTE_INFORMATION:
4901 struct filesystem_attribute_info *info;
4904 info = (struct filesystem_attribute_info *)rsp->Buffer;
4905 info->Attributes = cpu_to_le32(FILE_SUPPORTS_OBJECT_IDS |
4906 FILE_PERSISTENT_ACLS |
4907 FILE_UNICODE_ON_DISK |
4908 FILE_CASE_PRESERVED_NAMES |
4909 FILE_CASE_SENSITIVE_SEARCH |
4910 FILE_SUPPORTS_BLOCK_REFCOUNTING);
4912 info->Attributes |= cpu_to_le32(server_conf.share_fake_fscaps);
4914 info->MaxPathNameComponentLength = cpu_to_le32(stfs.f_namelen);
4915 len = smbConvertToUTF16((__le16 *)info->FileSystemName,
4916 "NTFS", PATH_MAX, conn->local_nls, 0);
4918 info->FileSystemNameLen = cpu_to_le32(len);
4919 sz = sizeof(struct filesystem_attribute_info) - 2 + len;
4920 rsp->OutputBufferLength = cpu_to_le32(sz);
4921 inc_rfc1001_len(work->response_buf, sz);
4922 fs_infoclass_size = FS_ATTRIBUTE_INFORMATION_SIZE;
4925 case FS_VOLUME_INFORMATION:
4927 struct filesystem_vol_info *info;
4929 unsigned int serial_crc = 0;
4931 info = (struct filesystem_vol_info *)(rsp->Buffer);
4932 info->VolumeCreationTime = 0;
4933 serial_crc = crc32_le(serial_crc, share->name,
4934 strlen(share->name));
4935 serial_crc = crc32_le(serial_crc, share->path,
4936 strlen(share->path));
4937 serial_crc = crc32_le(serial_crc, ksmbd_netbios_name(),
4938 strlen(ksmbd_netbios_name()));
4939 /* Taking dummy value of serial number*/
4940 info->SerialNumber = cpu_to_le32(serial_crc);
4941 len = smbConvertToUTF16((__le16 *)info->VolumeLabel,
4942 share->name, PATH_MAX,
4943 conn->local_nls, 0);
4945 info->VolumeLabelSize = cpu_to_le32(len);
4947 sz = sizeof(struct filesystem_vol_info) - 2 + len;
4948 rsp->OutputBufferLength = cpu_to_le32(sz);
4949 inc_rfc1001_len(work->response_buf, sz);
4950 fs_infoclass_size = FS_VOLUME_INFORMATION_SIZE;
4953 case FS_SIZE_INFORMATION:
4955 struct filesystem_info *info;
4957 info = (struct filesystem_info *)(rsp->Buffer);
4958 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
4959 info->FreeAllocationUnits = cpu_to_le64(stfs.f_bfree);
4960 info->SectorsPerAllocationUnit = cpu_to_le32(1);
4961 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
4962 rsp->OutputBufferLength = cpu_to_le32(24);
4963 inc_rfc1001_len(work->response_buf, 24);
4964 fs_infoclass_size = FS_SIZE_INFORMATION_SIZE;
4967 case FS_FULL_SIZE_INFORMATION:
4969 struct smb2_fs_full_size_info *info;
4971 info = (struct smb2_fs_full_size_info *)(rsp->Buffer);
4972 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
4973 info->CallerAvailableAllocationUnits =
4974 cpu_to_le64(stfs.f_bavail);
4975 info->ActualAvailableAllocationUnits =
4976 cpu_to_le64(stfs.f_bfree);
4977 info->SectorsPerAllocationUnit = cpu_to_le32(1);
4978 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
4979 rsp->OutputBufferLength = cpu_to_le32(32);
4980 inc_rfc1001_len(work->response_buf, 32);
4981 fs_infoclass_size = FS_FULL_SIZE_INFORMATION_SIZE;
4984 case FS_OBJECT_ID_INFORMATION:
4986 struct object_id_info *info;
4988 info = (struct object_id_info *)(rsp->Buffer);
4990 if (!user_guest(sess->user))
4991 memcpy(info->objid, user_passkey(sess->user), 16);
4993 memset(info->objid, 0, 16);
4995 info->extended_info.magic = cpu_to_le32(EXTENDED_INFO_MAGIC);
4996 info->extended_info.version = cpu_to_le32(1);
4997 info->extended_info.release = cpu_to_le32(1);
4998 info->extended_info.rel_date = 0;
4999 memcpy(info->extended_info.version_string, "1.1.0", strlen("1.1.0"));
5000 rsp->OutputBufferLength = cpu_to_le32(64);
5001 inc_rfc1001_len(work->response_buf, 64);
5002 fs_infoclass_size = FS_OBJECT_ID_INFORMATION_SIZE;
5005 case FS_SECTOR_SIZE_INFORMATION:
5007 struct smb3_fs_ss_info *info;
5009 info = (struct smb3_fs_ss_info *)(rsp->Buffer);
5011 info->LogicalBytesPerSector = cpu_to_le32(stfs.f_bsize);
5012 info->PhysicalBytesPerSectorForAtomicity =
5013 cpu_to_le32(stfs.f_bsize);
5014 info->PhysicalBytesPerSectorForPerf = cpu_to_le32(stfs.f_bsize);
5015 info->FSEffPhysicalBytesPerSectorForAtomicity =
5016 cpu_to_le32(stfs.f_bsize);
5017 info->Flags = cpu_to_le32(SSINFO_FLAGS_ALIGNED_DEVICE |
5018 SSINFO_FLAGS_PARTITION_ALIGNED_ON_DEVICE);
5019 info->ByteOffsetForSectorAlignment = 0;
5020 info->ByteOffsetForPartitionAlignment = 0;
5021 rsp->OutputBufferLength = cpu_to_le32(28);
5022 inc_rfc1001_len(work->response_buf, 28);
5023 fs_infoclass_size = FS_SECTOR_SIZE_INFORMATION_SIZE;
5026 case FS_CONTROL_INFORMATION:
5029 * TODO : The current implementation is based on
5030 * test result with win7(NTFS) server. It's need to
5031 * modify this to get valid Quota values
5034 struct smb2_fs_control_info *info;
5036 info = (struct smb2_fs_control_info *)(rsp->Buffer);
5037 info->FreeSpaceStartFiltering = 0;
5038 info->FreeSpaceThreshold = 0;
5039 info->FreeSpaceStopFiltering = 0;
5040 info->DefaultQuotaThreshold = cpu_to_le64(SMB2_NO_FID);
5041 info->DefaultQuotaLimit = cpu_to_le64(SMB2_NO_FID);
5043 rsp->OutputBufferLength = cpu_to_le32(48);
5044 inc_rfc1001_len(work->response_buf, 48);
5045 fs_infoclass_size = FS_CONTROL_INFORMATION_SIZE;
5048 case FS_POSIX_INFORMATION:
5050 struct filesystem_posix_info *info;
5052 if (!work->tcon->posix_extensions) {
5053 pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
5056 info = (struct filesystem_posix_info *)(rsp->Buffer);
5057 info->OptimalTransferSize = cpu_to_le32(stfs.f_bsize);
5058 info->BlockSize = cpu_to_le32(stfs.f_bsize);
5059 info->TotalBlocks = cpu_to_le64(stfs.f_blocks);
5060 info->BlocksAvail = cpu_to_le64(stfs.f_bfree);
5061 info->UserBlocksAvail = cpu_to_le64(stfs.f_bavail);
5062 info->TotalFileNodes = cpu_to_le64(stfs.f_files);
5063 info->FreeFileNodes = cpu_to_le64(stfs.f_ffree);
5064 rsp->OutputBufferLength = cpu_to_le32(56);
5065 inc_rfc1001_len(work->response_buf, 56);
5066 fs_infoclass_size = FS_POSIX_INFORMATION_SIZE;
5074 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
5075 rsp, work->response_buf,
5081 static int smb2_get_info_sec(struct ksmbd_work *work,
5082 struct smb2_query_info_req *req,
5083 struct smb2_query_info_rsp *rsp)
5085 struct ksmbd_file *fp;
5086 struct user_namespace *user_ns;
5087 struct smb_ntsd *pntsd = (struct smb_ntsd *)rsp->Buffer, *ppntsd = NULL;
5088 struct smb_fattr fattr = {{0}};
5089 struct inode *inode;
5091 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
5092 int addition_info = le32_to_cpu(req->AdditionalInformation);
5095 if (addition_info & ~(OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO |
5096 PROTECTED_DACL_SECINFO |
5097 UNPROTECTED_DACL_SECINFO)) {
5098 ksmbd_debug(SMB, "Unsupported addition info: 0x%x)\n",
5101 pntsd->revision = cpu_to_le16(1);
5102 pntsd->type = cpu_to_le16(SELF_RELATIVE | DACL_PROTECTED);
5103 pntsd->osidoffset = 0;
5104 pntsd->gsidoffset = 0;
5105 pntsd->sacloffset = 0;
5106 pntsd->dacloffset = 0;
5108 secdesclen = sizeof(struct smb_ntsd);
5109 rsp->OutputBufferLength = cpu_to_le32(secdesclen);
5110 inc_rfc1001_len(work->response_buf, secdesclen);
5115 if (work->next_smb2_rcv_hdr_off) {
5116 if (!has_file_id(le64_to_cpu(req->VolatileFileId))) {
5117 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
5118 work->compound_fid);
5119 id = work->compound_fid;
5120 pid = work->compound_pfid;
5124 if (!has_file_id(id)) {
5125 id = le64_to_cpu(req->VolatileFileId);
5126 pid = le64_to_cpu(req->PersistentFileId);
5129 fp = ksmbd_lookup_fd_slow(work, id, pid);
5133 user_ns = file_mnt_user_ns(fp->filp);
5134 inode = file_inode(fp->filp);
5135 ksmbd_acls_fattr(&fattr, user_ns, inode);
5137 if (test_share_config_flag(work->tcon->share_conf,
5138 KSMBD_SHARE_FLAG_ACL_XATTR))
5139 ksmbd_vfs_get_sd_xattr(work->conn, user_ns,
5140 fp->filp->f_path.dentry, &ppntsd);
5142 rc = build_sec_desc(user_ns, pntsd, ppntsd, addition_info,
5143 &secdesclen, &fattr);
5144 posix_acl_release(fattr.cf_acls);
5145 posix_acl_release(fattr.cf_dacls);
5147 ksmbd_fd_put(work, fp);
5151 rsp->OutputBufferLength = cpu_to_le32(secdesclen);
5152 inc_rfc1001_len(work->response_buf, secdesclen);
5157 * smb2_query_info() - handler for smb2 query info command
5158 * @work: smb work containing query info request buffer
5160 * Return: 0 on success, otherwise error
5162 int smb2_query_info(struct ksmbd_work *work)
5164 struct smb2_query_info_req *req;
5165 struct smb2_query_info_rsp *rsp;
5168 WORK_BUFFERS(work, req, rsp);
5170 ksmbd_debug(SMB, "GOT query info request\n");
5172 switch (req->InfoType) {
5173 case SMB2_O_INFO_FILE:
5174 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
5175 rc = smb2_get_info_file(work, req, rsp);
5177 case SMB2_O_INFO_FILESYSTEM:
5178 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILESYSTEM\n");
5179 rc = smb2_get_info_filesystem(work, req, rsp);
5181 case SMB2_O_INFO_SECURITY:
5182 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
5183 rc = smb2_get_info_sec(work, req, rsp);
5186 ksmbd_debug(SMB, "InfoType %d not supported yet\n",
5193 rsp->hdr.Status = STATUS_ACCESS_DENIED;
5194 else if (rc == -ENOENT)
5195 rsp->hdr.Status = STATUS_FILE_CLOSED;
5196 else if (rc == -EIO)
5197 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
5198 else if (rc == -EOPNOTSUPP || rsp->hdr.Status == 0)
5199 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
5200 smb2_set_err_rsp(work);
5202 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n",
5206 rsp->StructureSize = cpu_to_le16(9);
5207 rsp->OutputBufferOffset = cpu_to_le16(72);
5208 inc_rfc1001_len(work->response_buf, 8);
5213 * smb2_close_pipe() - handler for closing IPC pipe
5214 * @work: smb work containing close request buffer
5218 static noinline int smb2_close_pipe(struct ksmbd_work *work)
5221 struct smb2_close_req *req = smb2_get_msg(work->request_buf);
5222 struct smb2_close_rsp *rsp = smb2_get_msg(work->response_buf);
5224 id = le64_to_cpu(req->VolatileFileId);
5225 ksmbd_session_rpc_close(work->sess, id);
5227 rsp->StructureSize = cpu_to_le16(60);
5230 rsp->CreationTime = 0;
5231 rsp->LastAccessTime = 0;
5232 rsp->LastWriteTime = 0;
5233 rsp->ChangeTime = 0;
5234 rsp->AllocationSize = 0;
5236 rsp->Attributes = 0;
5237 inc_rfc1001_len(work->response_buf, 60);
5242 * smb2_close() - handler for smb2 close file command
5243 * @work: smb work containing close request buffer
5247 int smb2_close(struct ksmbd_work *work)
5249 u64 volatile_id = KSMBD_NO_FID;
5251 struct smb2_close_req *req;
5252 struct smb2_close_rsp *rsp;
5253 struct ksmbd_conn *conn = work->conn;
5254 struct ksmbd_file *fp;
5255 struct inode *inode;
5259 WORK_BUFFERS(work, req, rsp);
5261 if (test_share_config_flag(work->tcon->share_conf,
5262 KSMBD_SHARE_FLAG_PIPE)) {
5263 ksmbd_debug(SMB, "IPC pipe close request\n");
5264 return smb2_close_pipe(work);
5267 sess_id = le64_to_cpu(req->hdr.SessionId);
5268 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5269 sess_id = work->compound_sid;
5271 work->compound_sid = 0;
5272 if (check_session_id(conn, sess_id)) {
5273 work->compound_sid = sess_id;
5275 rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
5276 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5277 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
5282 if (work->next_smb2_rcv_hdr_off &&
5283 !has_file_id(le64_to_cpu(req->VolatileFileId))) {
5284 if (!has_file_id(work->compound_fid)) {
5285 /* file already closed, return FILE_CLOSED */
5286 ksmbd_debug(SMB, "file already closed\n");
5287 rsp->hdr.Status = STATUS_FILE_CLOSED;
5292 "Compound request set FID = %llu:%llu\n",
5294 work->compound_pfid);
5295 volatile_id = work->compound_fid;
5297 /* file closed, stored id is not valid anymore */
5298 work->compound_fid = KSMBD_NO_FID;
5299 work->compound_pfid = KSMBD_NO_FID;
5302 volatile_id = le64_to_cpu(req->VolatileFileId);
5304 ksmbd_debug(SMB, "volatile_id = %llu\n", volatile_id);
5306 rsp->StructureSize = cpu_to_le16(60);
5309 if (req->Flags == SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB) {
5310 fp = ksmbd_lookup_fd_fast(work, volatile_id);
5316 inode = file_inode(fp->filp);
5317 rsp->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB;
5318 rsp->AllocationSize = S_ISDIR(inode->i_mode) ? 0 :
5319 cpu_to_le64(inode->i_blocks << 9);
5320 rsp->EndOfFile = cpu_to_le64(inode->i_size);
5321 rsp->Attributes = fp->f_ci->m_fattr;
5322 rsp->CreationTime = cpu_to_le64(fp->create_time);
5323 time = ksmbd_UnixTimeToNT(inode->i_atime);
5324 rsp->LastAccessTime = cpu_to_le64(time);
5325 time = ksmbd_UnixTimeToNT(inode->i_mtime);
5326 rsp->LastWriteTime = cpu_to_le64(time);
5327 time = ksmbd_UnixTimeToNT(inode->i_ctime);
5328 rsp->ChangeTime = cpu_to_le64(time);
5329 ksmbd_fd_put(work, fp);
5332 rsp->AllocationSize = 0;
5334 rsp->Attributes = 0;
5335 rsp->CreationTime = 0;
5336 rsp->LastAccessTime = 0;
5337 rsp->LastWriteTime = 0;
5338 rsp->ChangeTime = 0;
5341 err = ksmbd_close_fd(work, volatile_id);
5344 if (rsp->hdr.Status == 0)
5345 rsp->hdr.Status = STATUS_FILE_CLOSED;
5346 smb2_set_err_rsp(work);
5348 inc_rfc1001_len(work->response_buf, 60);
5355 * smb2_echo() - handler for smb2 echo(ping) command
5356 * @work: smb work containing echo request buffer
5360 int smb2_echo(struct ksmbd_work *work)
5362 struct smb2_echo_rsp *rsp = smb2_get_msg(work->response_buf);
5364 rsp->StructureSize = cpu_to_le16(4);
5366 inc_rfc1001_len(work->response_buf, 4);
5370 static int smb2_rename(struct ksmbd_work *work,
5371 struct ksmbd_file *fp,
5372 struct user_namespace *user_ns,
5373 struct smb2_file_rename_info *file_info,
5374 struct nls_table *local_nls)
5376 struct ksmbd_share_config *share = fp->tcon->share_conf;
5377 char *new_name = NULL, *abs_oldname = NULL, *old_name = NULL;
5378 char *pathname = NULL;
5380 bool file_present = true;
5383 ksmbd_debug(SMB, "setting FILE_RENAME_INFO\n");
5384 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
5388 abs_oldname = d_path(&fp->filp->f_path, pathname, PATH_MAX);
5389 if (IS_ERR(abs_oldname)) {
5393 old_name = strrchr(abs_oldname, '/');
5394 if (old_name && old_name[1] != '\0') {
5397 ksmbd_debug(SMB, "can't get last component in path %s\n",
5403 new_name = smb2_get_name(file_info->FileName,
5404 le32_to_cpu(file_info->FileNameLength),
5406 if (IS_ERR(new_name)) {
5407 rc = PTR_ERR(new_name);
5411 if (strchr(new_name, ':')) {
5413 char *xattr_stream_name, *stream_name = NULL;
5414 size_t xattr_stream_size;
5417 rc = parse_stream_name(new_name, &stream_name, &s_type);
5421 len = strlen(new_name);
5422 if (len > 0 && new_name[len - 1] != '/') {
5423 pr_err("not allow base filename in rename\n");
5428 rc = ksmbd_vfs_xattr_stream_name(stream_name,
5435 rc = ksmbd_vfs_setxattr(user_ns,
5436 fp->filp->f_path.dentry,
5440 pr_err("failed to store stream name in xattr: %d\n",
5449 ksmbd_debug(SMB, "new name %s\n", new_name);
5450 rc = ksmbd_vfs_kern_path(work, new_name, LOOKUP_NO_SYMLINKS, &path, 1);
5454 file_present = false;
5459 if (ksmbd_share_veto_filename(share, new_name)) {
5461 ksmbd_debug(SMB, "Can't rename vetoed file: %s\n", new_name);
5465 if (file_info->ReplaceIfExists) {
5467 rc = ksmbd_vfs_remove_file(work, new_name);
5469 if (rc != -ENOTEMPTY)
5471 ksmbd_debug(SMB, "cannot delete %s, rc %d\n",
5478 strncmp(old_name, path.dentry->d_name.name, strlen(old_name))) {
5481 "cannot rename already existing file\n");
5486 rc = ksmbd_vfs_fp_rename(work, fp, new_name);
5489 if (!IS_ERR(new_name))
5494 static int smb2_create_link(struct ksmbd_work *work,
5495 struct ksmbd_share_config *share,
5496 struct smb2_file_link_info *file_info,
5497 unsigned int buf_len, struct file *filp,
5498 struct nls_table *local_nls)
5500 char *link_name = NULL, *target_name = NULL, *pathname = NULL;
5502 bool file_present = true;
5505 if (buf_len < (u64)sizeof(struct smb2_file_link_info) +
5506 le32_to_cpu(file_info->FileNameLength))
5509 ksmbd_debug(SMB, "setting FILE_LINK_INFORMATION\n");
5510 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
5514 link_name = smb2_get_name(file_info->FileName,
5515 le32_to_cpu(file_info->FileNameLength),
5517 if (IS_ERR(link_name) || S_ISDIR(file_inode(filp)->i_mode)) {
5522 ksmbd_debug(SMB, "link name is %s\n", link_name);
5523 target_name = d_path(&filp->f_path, pathname, PATH_MAX);
5524 if (IS_ERR(target_name)) {
5529 ksmbd_debug(SMB, "target name is %s\n", target_name);
5530 rc = ksmbd_vfs_kern_path(work, link_name, LOOKUP_NO_SYMLINKS, &path, 0);
5534 file_present = false;
5539 if (file_info->ReplaceIfExists) {
5541 rc = ksmbd_vfs_remove_file(work, link_name);
5544 ksmbd_debug(SMB, "cannot delete %s\n",
5552 ksmbd_debug(SMB, "link already exists\n");
5557 rc = ksmbd_vfs_link(work, target_name, link_name);
5561 if (!IS_ERR(link_name))
5567 static int set_file_basic_info(struct ksmbd_file *fp,
5568 struct smb2_file_basic_info *file_info,
5569 struct ksmbd_share_config *share)
5573 struct inode *inode;
5574 struct user_namespace *user_ns;
5577 if (!(fp->daccess & FILE_WRITE_ATTRIBUTES_LE))
5582 inode = file_inode(filp);
5583 user_ns = file_mnt_user_ns(filp);
5585 if (file_info->CreationTime)
5586 fp->create_time = le64_to_cpu(file_info->CreationTime);
5588 if (file_info->LastAccessTime) {
5589 attrs.ia_atime = ksmbd_NTtimeToUnix(file_info->LastAccessTime);
5590 attrs.ia_valid |= (ATTR_ATIME | ATTR_ATIME_SET);
5593 attrs.ia_valid |= ATTR_CTIME;
5594 if (file_info->ChangeTime)
5595 attrs.ia_ctime = ksmbd_NTtimeToUnix(file_info->ChangeTime);
5597 attrs.ia_ctime = inode->i_ctime;
5599 if (file_info->LastWriteTime) {
5600 attrs.ia_mtime = ksmbd_NTtimeToUnix(file_info->LastWriteTime);
5601 attrs.ia_valid |= (ATTR_MTIME | ATTR_MTIME_SET);
5604 if (file_info->Attributes) {
5605 if (!S_ISDIR(inode->i_mode) &&
5606 file_info->Attributes & FILE_ATTRIBUTE_DIRECTORY_LE) {
5607 pr_err("can't change a file to a directory\n");
5611 if (!(S_ISDIR(inode->i_mode) && file_info->Attributes == FILE_ATTRIBUTE_NORMAL_LE))
5612 fp->f_ci->m_fattr = file_info->Attributes |
5613 (fp->f_ci->m_fattr & FILE_ATTRIBUTE_DIRECTORY_LE);
5616 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_STORE_DOS_ATTRS) &&
5617 (file_info->CreationTime || file_info->Attributes)) {
5618 struct xattr_dos_attrib da = {0};
5621 da.itime = fp->itime;
5622 da.create_time = fp->create_time;
5623 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
5624 da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
5625 XATTR_DOSINFO_ITIME;
5627 rc = ksmbd_vfs_set_dos_attrib_xattr(user_ns,
5628 filp->f_path.dentry, &da);
5631 "failed to restore file attribute in EA\n");
5635 if (attrs.ia_valid) {
5636 struct dentry *dentry = filp->f_path.dentry;
5637 struct inode *inode = d_inode(dentry);
5639 if (IS_IMMUTABLE(inode) || IS_APPEND(inode))
5643 inode->i_ctime = attrs.ia_ctime;
5644 attrs.ia_valid &= ~ATTR_CTIME;
5645 rc = notify_change(user_ns, dentry, &attrs, NULL);
5646 inode_unlock(inode);
5651 static int set_file_allocation_info(struct ksmbd_work *work,
5652 struct ksmbd_file *fp,
5653 struct smb2_file_alloc_info *file_alloc_info)
5656 * TODO : It's working fine only when store dos attributes
5657 * is not yes. need to implement a logic which works
5658 * properly with any smb.conf option
5662 struct inode *inode;
5665 if (!(fp->daccess & FILE_WRITE_DATA_LE))
5668 alloc_blks = (le64_to_cpu(file_alloc_info->AllocationSize) + 511) >> 9;
5669 inode = file_inode(fp->filp);
5671 if (alloc_blks > inode->i_blocks) {
5672 smb_break_all_levII_oplock(work, fp, 1);
5673 rc = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
5675 if (rc && rc != -EOPNOTSUPP) {
5676 pr_err("vfs_fallocate is failed : %d\n", rc);
5679 } else if (alloc_blks < inode->i_blocks) {
5683 * Allocation size could be smaller than original one
5684 * which means allocated blocks in file should be
5685 * deallocated. use truncate to cut out it, but inode
5686 * size is also updated with truncate offset.
5687 * inode size is retained by backup inode size.
5689 size = i_size_read(inode);
5690 rc = ksmbd_vfs_truncate(work, fp, alloc_blks * 512);
5692 pr_err("truncate failed! filename : %s, err %d\n",
5696 if (size < alloc_blks * 512)
5697 i_size_write(inode, size);
5702 static int set_end_of_file_info(struct ksmbd_work *work, struct ksmbd_file *fp,
5703 struct smb2_file_eof_info *file_eof_info)
5706 struct inode *inode;
5709 if (!(fp->daccess & FILE_WRITE_DATA_LE))
5712 newsize = le64_to_cpu(file_eof_info->EndOfFile);
5713 inode = file_inode(fp->filp);
5716 * If FILE_END_OF_FILE_INFORMATION of set_info_file is called
5717 * on FAT32 shared device, truncate execution time is too long
5718 * and network error could cause from windows client. because
5719 * truncate of some filesystem like FAT32 fill zero data in
5722 if (inode->i_sb->s_magic != MSDOS_SUPER_MAGIC) {
5723 ksmbd_debug(SMB, "filename : %s truncated to newsize %lld\n",
5724 fp->filename, newsize);
5725 rc = ksmbd_vfs_truncate(work, fp, newsize);
5727 ksmbd_debug(SMB, "truncate failed! filename : %s err %d\n",
5737 static int set_rename_info(struct ksmbd_work *work, struct ksmbd_file *fp,
5738 struct smb2_file_rename_info *rename_info,
5739 unsigned int buf_len)
5741 struct user_namespace *user_ns;
5742 struct ksmbd_file *parent_fp;
5743 struct dentry *parent;
5744 struct dentry *dentry = fp->filp->f_path.dentry;
5747 if (!(fp->daccess & FILE_DELETE_LE)) {
5748 pr_err("no right to delete : 0x%x\n", fp->daccess);
5752 if (buf_len < (u64)sizeof(struct smb2_file_rename_info) +
5753 le32_to_cpu(rename_info->FileNameLength))
5756 user_ns = file_mnt_user_ns(fp->filp);
5757 if (ksmbd_stream_fd(fp))
5760 parent = dget_parent(dentry);
5761 ret = ksmbd_vfs_lock_parent(user_ns, parent, dentry);
5767 parent_fp = ksmbd_lookup_fd_inode(d_inode(parent));
5768 inode_unlock(d_inode(parent));
5772 if (parent_fp->daccess & FILE_DELETE_LE) {
5773 pr_err("parent dir is opened with delete access\n");
5778 return smb2_rename(work, fp, user_ns, rename_info,
5779 work->sess->conn->local_nls);
5782 static int set_file_disposition_info(struct ksmbd_file *fp,
5783 struct smb2_file_disposition_info *file_info)
5785 struct inode *inode;
5787 if (!(fp->daccess & FILE_DELETE_LE)) {
5788 pr_err("no right to delete : 0x%x\n", fp->daccess);
5792 inode = file_inode(fp->filp);
5793 if (file_info->DeletePending) {
5794 if (S_ISDIR(inode->i_mode) &&
5795 ksmbd_vfs_empty_dir(fp) == -ENOTEMPTY)
5797 ksmbd_set_inode_pending_delete(fp);
5799 ksmbd_clear_inode_pending_delete(fp);
5804 static int set_file_position_info(struct ksmbd_file *fp,
5805 struct smb2_file_pos_info *file_info)
5807 loff_t current_byte_offset;
5808 unsigned long sector_size;
5809 struct inode *inode;
5811 inode = file_inode(fp->filp);
5812 current_byte_offset = le64_to_cpu(file_info->CurrentByteOffset);
5813 sector_size = inode->i_sb->s_blocksize;
5815 if (current_byte_offset < 0 ||
5816 (fp->coption == FILE_NO_INTERMEDIATE_BUFFERING_LE &&
5817 current_byte_offset & (sector_size - 1))) {
5818 pr_err("CurrentByteOffset is not valid : %llu\n",
5819 current_byte_offset);
5823 fp->filp->f_pos = current_byte_offset;
5827 static int set_file_mode_info(struct ksmbd_file *fp,
5828 struct smb2_file_mode_info *file_info)
5832 mode = file_info->Mode;
5834 if ((mode & ~FILE_MODE_INFO_MASK)) {
5835 pr_err("Mode is not valid : 0x%x\n", le32_to_cpu(mode));
5840 * TODO : need to implement consideration for
5841 * FILE_SYNCHRONOUS_IO_ALERT and FILE_SYNCHRONOUS_IO_NONALERT
5843 ksmbd_vfs_set_fadvise(fp->filp, mode);
5849 * smb2_set_info_file() - handler for smb2 set info command
5850 * @work: smb work containing set info command buffer
5851 * @fp: ksmbd_file pointer
5852 * @req: request buffer pointer
5853 * @share: ksmbd_share_config pointer
5855 * Return: 0 on success, otherwise error
5856 * TODO: need to implement an error handling for STATUS_INFO_LENGTH_MISMATCH
5858 static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp,
5859 struct smb2_set_info_req *req,
5860 struct ksmbd_share_config *share)
5862 unsigned int buf_len = le32_to_cpu(req->BufferLength);
5864 switch (req->FileInfoClass) {
5865 case FILE_BASIC_INFORMATION:
5867 if (buf_len < sizeof(struct smb2_file_basic_info))
5870 return set_file_basic_info(fp, (struct smb2_file_basic_info *)req->Buffer, share);
5872 case FILE_ALLOCATION_INFORMATION:
5874 if (buf_len < sizeof(struct smb2_file_alloc_info))
5877 return set_file_allocation_info(work, fp,
5878 (struct smb2_file_alloc_info *)req->Buffer);
5880 case FILE_END_OF_FILE_INFORMATION:
5882 if (buf_len < sizeof(struct smb2_file_eof_info))
5885 return set_end_of_file_info(work, fp,
5886 (struct smb2_file_eof_info *)req->Buffer);
5888 case FILE_RENAME_INFORMATION:
5890 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
5892 "User does not have write permission\n");
5896 if (buf_len < sizeof(struct smb2_file_rename_info))
5899 return set_rename_info(work, fp,
5900 (struct smb2_file_rename_info *)req->Buffer,
5903 case FILE_LINK_INFORMATION:
5905 if (buf_len < sizeof(struct smb2_file_link_info))
5908 return smb2_create_link(work, work->tcon->share_conf,
5909 (struct smb2_file_link_info *)req->Buffer,
5911 work->sess->conn->local_nls);
5913 case FILE_DISPOSITION_INFORMATION:
5915 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
5917 "User does not have write permission\n");
5921 if (buf_len < sizeof(struct smb2_file_disposition_info))
5924 return set_file_disposition_info(fp,
5925 (struct smb2_file_disposition_info *)req->Buffer);
5927 case FILE_FULL_EA_INFORMATION:
5929 if (!(fp->daccess & FILE_WRITE_EA_LE)) {
5930 pr_err("Not permitted to write ext attr: 0x%x\n",
5935 if (buf_len < sizeof(struct smb2_ea_info))
5938 return smb2_set_ea((struct smb2_ea_info *)req->Buffer,
5939 buf_len, &fp->filp->f_path);
5941 case FILE_POSITION_INFORMATION:
5943 if (buf_len < sizeof(struct smb2_file_pos_info))
5946 return set_file_position_info(fp, (struct smb2_file_pos_info *)req->Buffer);
5948 case FILE_MODE_INFORMATION:
5950 if (buf_len < sizeof(struct smb2_file_mode_info))
5953 return set_file_mode_info(fp, (struct smb2_file_mode_info *)req->Buffer);
5957 pr_err("Unimplemented Fileinfoclass :%d\n", req->FileInfoClass);
5961 static int smb2_set_info_sec(struct ksmbd_file *fp, int addition_info,
5962 char *buffer, int buf_len)
5964 struct smb_ntsd *pntsd = (struct smb_ntsd *)buffer;
5966 fp->saccess |= FILE_SHARE_DELETE_LE;
5968 return set_info_sec(fp->conn, fp->tcon, &fp->filp->f_path, pntsd,
5973 * smb2_set_info() - handler for smb2 set info command handler
5974 * @work: smb work containing set info request buffer
5976 * Return: 0 on success, otherwise error
5978 int smb2_set_info(struct ksmbd_work *work)
5980 struct smb2_set_info_req *req;
5981 struct smb2_set_info_rsp *rsp;
5982 struct ksmbd_file *fp;
5984 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
5986 ksmbd_debug(SMB, "Received set info request\n");
5988 if (work->next_smb2_rcv_hdr_off) {
5989 req = ksmbd_req_buf_next(work);
5990 rsp = ksmbd_resp_buf_next(work);
5991 if (!has_file_id(le64_to_cpu(req->VolatileFileId))) {
5992 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
5993 work->compound_fid);
5994 id = work->compound_fid;
5995 pid = work->compound_pfid;
5998 req = smb2_get_msg(work->request_buf);
5999 rsp = smb2_get_msg(work->response_buf);
6002 if (!has_file_id(id)) {
6003 id = le64_to_cpu(req->VolatileFileId);
6004 pid = le64_to_cpu(req->PersistentFileId);
6007 fp = ksmbd_lookup_fd_slow(work, id, pid);
6009 ksmbd_debug(SMB, "Invalid id for close: %u\n", id);
6014 switch (req->InfoType) {
6015 case SMB2_O_INFO_FILE:
6016 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
6017 rc = smb2_set_info_file(work, fp, req, work->tcon->share_conf);
6019 case SMB2_O_INFO_SECURITY:
6020 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
6021 if (ksmbd_override_fsids(work)) {
6025 rc = smb2_set_info_sec(fp,
6026 le32_to_cpu(req->AdditionalInformation),
6028 le32_to_cpu(req->BufferLength));
6029 ksmbd_revert_fsids(work);
6038 rsp->StructureSize = cpu_to_le16(2);
6039 inc_rfc1001_len(work->response_buf, 2);
6040 ksmbd_fd_put(work, fp);
6044 if (rc == -EACCES || rc == -EPERM || rc == -EXDEV)
6045 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6046 else if (rc == -EINVAL)
6047 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6048 else if (rc == -ESHARE)
6049 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6050 else if (rc == -ENOENT)
6051 rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
6052 else if (rc == -EBUSY || rc == -ENOTEMPTY)
6053 rsp->hdr.Status = STATUS_DIRECTORY_NOT_EMPTY;
6054 else if (rc == -EAGAIN)
6055 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6056 else if (rc == -EBADF || rc == -ESTALE)
6057 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6058 else if (rc == -EEXIST)
6059 rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
6060 else if (rsp->hdr.Status == 0 || rc == -EOPNOTSUPP)
6061 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
6062 smb2_set_err_rsp(work);
6063 ksmbd_fd_put(work, fp);
6064 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n", rc);
6069 * smb2_read_pipe() - handler for smb2 read from IPC pipe
6070 * @work: smb work containing read IPC pipe command buffer
6072 * Return: 0 on success, otherwise error
6074 static noinline int smb2_read_pipe(struct ksmbd_work *work)
6076 int nbytes = 0, err;
6078 struct ksmbd_rpc_command *rpc_resp;
6079 struct smb2_read_req *req = smb2_get_msg(work->request_buf);
6080 struct smb2_read_rsp *rsp = smb2_get_msg(work->response_buf);
6082 id = le64_to_cpu(req->VolatileFileId);
6084 inc_rfc1001_len(work->response_buf, 16);
6085 rpc_resp = ksmbd_rpc_read(work->sess, id);
6087 if (rpc_resp->flags != KSMBD_RPC_OK) {
6092 work->aux_payload_buf =
6093 kvmalloc(rpc_resp->payload_sz, GFP_KERNEL | __GFP_ZERO);
6094 if (!work->aux_payload_buf) {
6099 memcpy(work->aux_payload_buf, rpc_resp->payload,
6100 rpc_resp->payload_sz);
6102 nbytes = rpc_resp->payload_sz;
6103 work->resp_hdr_sz = get_rfc1002_len(work->response_buf) + 4;
6104 work->aux_payload_sz = nbytes;
6108 rsp->StructureSize = cpu_to_le16(17);
6109 rsp->DataOffset = 80;
6111 rsp->DataLength = cpu_to_le32(nbytes);
6112 rsp->DataRemaining = 0;
6114 inc_rfc1001_len(work->response_buf, nbytes);
6118 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
6119 smb2_set_err_rsp(work);
6124 static int smb2_set_remote_key_for_rdma(struct ksmbd_work *work,
6125 struct smb2_buffer_desc_v1 *desc,
6127 __le16 ChannelInfoOffset,
6128 __le16 ChannelInfoLength)
6130 unsigned int i, ch_count;
6132 if (work->conn->dialect == SMB30_PROT_ID &&
6133 Channel != SMB2_CHANNEL_RDMA_V1)
6136 ch_count = le16_to_cpu(ChannelInfoLength) / sizeof(*desc);
6137 if (ksmbd_debug_types & KSMBD_DEBUG_RDMA) {
6138 for (i = 0; i < ch_count; i++) {
6139 pr_info("RDMA r/w request %#x: token %#x, length %#x\n",
6141 le32_to_cpu(desc[i].token),
6142 le32_to_cpu(desc[i].length));
6145 if (ch_count != 1) {
6146 ksmbd_debug(RDMA, "RDMA multiple buffer descriptors %d are not supported yet\n",
6151 work->need_invalidate_rkey =
6152 (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE);
6153 work->remote_key = le32_to_cpu(desc->token);
6157 static ssize_t smb2_read_rdma_channel(struct ksmbd_work *work,
6158 struct smb2_read_req *req, void *data_buf,
6161 struct smb2_buffer_desc_v1 *desc =
6162 (struct smb2_buffer_desc_v1 *)&req->Buffer[0];
6165 err = ksmbd_conn_rdma_write(work->conn, data_buf, length,
6166 le32_to_cpu(desc->token),
6167 le64_to_cpu(desc->offset),
6168 le32_to_cpu(desc->length));
6176 * smb2_read() - handler for smb2 read from file
6177 * @work: smb work containing read command buffer
6179 * Return: 0 on success, otherwise error
6181 int smb2_read(struct ksmbd_work *work)
6183 struct ksmbd_conn *conn = work->conn;
6184 struct smb2_read_req *req;
6185 struct smb2_read_rsp *rsp;
6186 struct ksmbd_file *fp = NULL;
6188 size_t length, mincount;
6189 ssize_t nbytes = 0, remain_bytes = 0;
6192 WORK_BUFFERS(work, req, rsp);
6194 if (test_share_config_flag(work->tcon->share_conf,
6195 KSMBD_SHARE_FLAG_PIPE)) {
6196 ksmbd_debug(SMB, "IPC pipe read request\n");
6197 return smb2_read_pipe(work);
6200 if (req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE ||
6201 req->Channel == SMB2_CHANNEL_RDMA_V1) {
6202 unsigned int ch_offset = le16_to_cpu(req->ReadChannelInfoOffset);
6204 if (ch_offset < offsetof(struct smb2_read_req, Buffer)) {
6208 err = smb2_set_remote_key_for_rdma(work,
6209 (struct smb2_buffer_desc_v1 *)
6210 ((char *)req + ch_offset),
6212 req->ReadChannelInfoOffset,
6213 req->ReadChannelInfoLength);
6218 fp = ksmbd_lookup_fd_slow(work, le64_to_cpu(req->VolatileFileId),
6219 le64_to_cpu(req->PersistentFileId));
6225 if (!(fp->daccess & (FILE_READ_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
6226 pr_err("Not permitted to read : 0x%x\n", fp->daccess);
6231 offset = le64_to_cpu(req->Offset);
6232 length = le32_to_cpu(req->Length);
6233 mincount = le32_to_cpu(req->MinimumCount);
6235 if (length > conn->vals->max_read_size) {
6236 ksmbd_debug(SMB, "limiting read size to max size(%u)\n",
6237 conn->vals->max_read_size);
6242 ksmbd_debug(SMB, "filename %pd, offset %lld, len %zu\n",
6243 fp->filp->f_path.dentry, offset, length);
6245 work->aux_payload_buf = kvmalloc(length, GFP_KERNEL | __GFP_ZERO);
6246 if (!work->aux_payload_buf) {
6251 nbytes = ksmbd_vfs_read(work, fp, length, &offset);
6257 if ((nbytes == 0 && length != 0) || nbytes < mincount) {
6258 kvfree(work->aux_payload_buf);
6259 work->aux_payload_buf = NULL;
6260 rsp->hdr.Status = STATUS_END_OF_FILE;
6261 smb2_set_err_rsp(work);
6262 ksmbd_fd_put(work, fp);
6266 ksmbd_debug(SMB, "nbytes %zu, offset %lld mincount %zu\n",
6267 nbytes, offset, mincount);
6269 if (req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE ||
6270 req->Channel == SMB2_CHANNEL_RDMA_V1) {
6271 /* write data to the client using rdma channel */
6272 remain_bytes = smb2_read_rdma_channel(work, req,
6273 work->aux_payload_buf,
6275 kvfree(work->aux_payload_buf);
6276 work->aux_payload_buf = NULL;
6279 if (remain_bytes < 0) {
6280 err = (int)remain_bytes;
6285 rsp->StructureSize = cpu_to_le16(17);
6286 rsp->DataOffset = 80;
6288 rsp->DataLength = cpu_to_le32(nbytes);
6289 rsp->DataRemaining = cpu_to_le32(remain_bytes);
6291 inc_rfc1001_len(work->response_buf, 16);
6292 work->resp_hdr_sz = get_rfc1002_len(work->response_buf) + 4;
6293 work->aux_payload_sz = nbytes;
6294 inc_rfc1001_len(work->response_buf, nbytes);
6295 ksmbd_fd_put(work, fp);
6301 rsp->hdr.Status = STATUS_INVALID_DEVICE_REQUEST;
6302 else if (err == -EAGAIN)
6303 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6304 else if (err == -ENOENT)
6305 rsp->hdr.Status = STATUS_FILE_CLOSED;
6306 else if (err == -EACCES)
6307 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6308 else if (err == -ESHARE)
6309 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6310 else if (err == -EINVAL)
6311 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6313 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6315 smb2_set_err_rsp(work);
6317 ksmbd_fd_put(work, fp);
6322 * smb2_write_pipe() - handler for smb2 write on IPC pipe
6323 * @work: smb work containing write IPC pipe command buffer
6325 * Return: 0 on success, otherwise error
6327 static noinline int smb2_write_pipe(struct ksmbd_work *work)
6329 struct smb2_write_req *req = smb2_get_msg(work->request_buf);
6330 struct smb2_write_rsp *rsp = smb2_get_msg(work->response_buf);
6331 struct ksmbd_rpc_command *rpc_resp;
6333 int err = 0, ret = 0;
6337 length = le32_to_cpu(req->Length);
6338 id = le64_to_cpu(req->VolatileFileId);
6340 if (le16_to_cpu(req->DataOffset) ==
6341 offsetof(struct smb2_write_req, Buffer)) {
6342 data_buf = (char *)&req->Buffer[0];
6344 if ((u64)le16_to_cpu(req->DataOffset) + length >
6345 get_rfc1002_len(work->request_buf)) {
6346 pr_err("invalid write data offset %u, smb_len %u\n",
6347 le16_to_cpu(req->DataOffset),
6348 get_rfc1002_len(work->request_buf));
6353 data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
6354 le16_to_cpu(req->DataOffset));
6357 rpc_resp = ksmbd_rpc_write(work->sess, id, data_buf, length);
6359 if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
6360 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
6362 smb2_set_err_rsp(work);
6365 if (rpc_resp->flags != KSMBD_RPC_OK) {
6366 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6367 smb2_set_err_rsp(work);
6374 rsp->StructureSize = cpu_to_le16(17);
6375 rsp->DataOffset = 0;
6377 rsp->DataLength = cpu_to_le32(length);
6378 rsp->DataRemaining = 0;
6380 inc_rfc1001_len(work->response_buf, 16);
6384 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6385 smb2_set_err_rsp(work);
6391 static ssize_t smb2_write_rdma_channel(struct ksmbd_work *work,
6392 struct smb2_write_req *req,
6393 struct ksmbd_file *fp,
6394 loff_t offset, size_t length, bool sync)
6396 struct smb2_buffer_desc_v1 *desc;
6401 desc = (struct smb2_buffer_desc_v1 *)&req->Buffer[0];
6403 data_buf = kvmalloc(length, GFP_KERNEL | __GFP_ZERO);
6407 ret = ksmbd_conn_rdma_read(work->conn, data_buf, length,
6408 le32_to_cpu(desc->token),
6409 le64_to_cpu(desc->offset),
6410 le32_to_cpu(desc->length));
6416 ret = ksmbd_vfs_write(work, fp, data_buf, length, &offset, sync, &nbytes);
6425 * smb2_write() - handler for smb2 write from file
6426 * @work: smb work containing write command buffer
6428 * Return: 0 on success, otherwise error
6430 int smb2_write(struct ksmbd_work *work)
6432 struct smb2_write_req *req;
6433 struct smb2_write_rsp *rsp;
6434 struct ksmbd_file *fp = NULL;
6439 bool writethrough = false;
6442 WORK_BUFFERS(work, req, rsp);
6444 if (test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_PIPE)) {
6445 ksmbd_debug(SMB, "IPC pipe write request\n");
6446 return smb2_write_pipe(work);
6449 if (req->Channel == SMB2_CHANNEL_RDMA_V1 ||
6450 req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE) {
6451 unsigned int ch_offset = le16_to_cpu(req->WriteChannelInfoOffset);
6453 if (req->Length != 0 || req->DataOffset != 0 ||
6454 ch_offset < offsetof(struct smb2_write_req, Buffer)) {
6458 err = smb2_set_remote_key_for_rdma(work,
6459 (struct smb2_buffer_desc_v1 *)
6460 ((char *)req + ch_offset),
6462 req->WriteChannelInfoOffset,
6463 req->WriteChannelInfoLength);
6468 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
6469 ksmbd_debug(SMB, "User does not have write permission\n");
6474 fp = ksmbd_lookup_fd_slow(work, le64_to_cpu(req->VolatileFileId),
6475 le64_to_cpu(req->PersistentFileId));
6481 if (!(fp->daccess & (FILE_WRITE_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
6482 pr_err("Not permitted to write : 0x%x\n", fp->daccess);
6487 offset = le64_to_cpu(req->Offset);
6488 length = le32_to_cpu(req->Length);
6490 if (length > work->conn->vals->max_write_size) {
6491 ksmbd_debug(SMB, "limiting write size to max size(%u)\n",
6492 work->conn->vals->max_write_size);
6497 if (le32_to_cpu(req->Flags) & SMB2_WRITEFLAG_WRITE_THROUGH)
6498 writethrough = true;
6500 if (req->Channel != SMB2_CHANNEL_RDMA_V1 &&
6501 req->Channel != SMB2_CHANNEL_RDMA_V1_INVALIDATE) {
6502 if (le16_to_cpu(req->DataOffset) ==
6503 offsetof(struct smb2_write_req, Buffer)) {
6504 data_buf = (char *)&req->Buffer[0];
6506 if ((u64)le16_to_cpu(req->DataOffset) + length >
6507 get_rfc1002_len(work->request_buf)) {
6508 pr_err("invalid write data offset %u, smb_len %u\n",
6509 le16_to_cpu(req->DataOffset),
6510 get_rfc1002_len(work->request_buf));
6515 data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
6516 le16_to_cpu(req->DataOffset));
6519 ksmbd_debug(SMB, "flags %u\n", le32_to_cpu(req->Flags));
6520 if (le32_to_cpu(req->Flags) & SMB2_WRITEFLAG_WRITE_THROUGH)
6521 writethrough = true;
6523 ksmbd_debug(SMB, "filename %pd, offset %lld, len %zu\n",
6524 fp->filp->f_path.dentry, offset, length);
6525 err = ksmbd_vfs_write(work, fp, data_buf, length, &offset,
6526 writethrough, &nbytes);
6530 /* read data from the client using rdma channel, and
6533 nbytes = smb2_write_rdma_channel(work, req, fp, offset,
6534 le32_to_cpu(req->RemainingBytes),
6542 rsp->StructureSize = cpu_to_le16(17);
6543 rsp->DataOffset = 0;
6545 rsp->DataLength = cpu_to_le32(nbytes);
6546 rsp->DataRemaining = 0;
6548 inc_rfc1001_len(work->response_buf, 16);
6549 ksmbd_fd_put(work, fp);
6554 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6555 else if (err == -ENOSPC || err == -EFBIG)
6556 rsp->hdr.Status = STATUS_DISK_FULL;
6557 else if (err == -ENOENT)
6558 rsp->hdr.Status = STATUS_FILE_CLOSED;
6559 else if (err == -EACCES)
6560 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6561 else if (err == -ESHARE)
6562 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6563 else if (err == -EINVAL)
6564 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6566 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6568 smb2_set_err_rsp(work);
6569 ksmbd_fd_put(work, fp);
6574 * smb2_flush() - handler for smb2 flush file - fsync
6575 * @work: smb work containing flush command buffer
6577 * Return: 0 on success, otherwise error
6579 int smb2_flush(struct ksmbd_work *work)
6581 struct smb2_flush_req *req;
6582 struct smb2_flush_rsp *rsp;
6585 WORK_BUFFERS(work, req, rsp);
6587 ksmbd_debug(SMB, "SMB2_FLUSH called for fid %llu\n",
6588 le64_to_cpu(req->VolatileFileId));
6590 err = ksmbd_vfs_fsync(work,
6591 le64_to_cpu(req->VolatileFileId),
6592 le64_to_cpu(req->PersistentFileId));
6596 rsp->StructureSize = cpu_to_le16(4);
6598 inc_rfc1001_len(work->response_buf, 4);
6603 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6604 smb2_set_err_rsp(work);
6611 * smb2_cancel() - handler for smb2 cancel command
6612 * @work: smb work containing cancel command buffer
6614 * Return: 0 on success, otherwise error
6616 int smb2_cancel(struct ksmbd_work *work)
6618 struct ksmbd_conn *conn = work->conn;
6619 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
6620 struct smb2_hdr *chdr;
6621 struct ksmbd_work *cancel_work = NULL;
6623 struct list_head *command_list;
6625 ksmbd_debug(SMB, "smb2 cancel called on mid %llu, async flags 0x%x\n",
6626 hdr->MessageId, hdr->Flags);
6628 if (hdr->Flags & SMB2_FLAGS_ASYNC_COMMAND) {
6629 command_list = &conn->async_requests;
6631 spin_lock(&conn->request_lock);
6632 list_for_each_entry(cancel_work, command_list,
6633 async_request_entry) {
6634 chdr = smb2_get_msg(cancel_work->request_buf);
6636 if (cancel_work->async_id !=
6637 le64_to_cpu(hdr->Id.AsyncId))
6641 "smb2 with AsyncId %llu cancelled command = 0x%x\n",
6642 le64_to_cpu(hdr->Id.AsyncId),
6643 le16_to_cpu(chdr->Command));
6647 spin_unlock(&conn->request_lock);
6649 command_list = &conn->requests;
6651 spin_lock(&conn->request_lock);
6652 list_for_each_entry(cancel_work, command_list, request_entry) {
6653 chdr = smb2_get_msg(cancel_work->request_buf);
6655 if (chdr->MessageId != hdr->MessageId ||
6656 cancel_work == work)
6660 "smb2 with mid %llu cancelled command = 0x%x\n",
6661 le64_to_cpu(hdr->MessageId),
6662 le16_to_cpu(chdr->Command));
6666 spin_unlock(&conn->request_lock);
6670 cancel_work->state = KSMBD_WORK_CANCELLED;
6671 if (cancel_work->cancel_fn)
6672 cancel_work->cancel_fn(cancel_work->cancel_argv);
6675 /* For SMB2_CANCEL command itself send no response*/
6676 work->send_no_response = 1;
6680 struct file_lock *smb_flock_init(struct file *f)
6682 struct file_lock *fl;
6684 fl = locks_alloc_lock();
6688 locks_init_lock(fl);
6691 fl->fl_pid = current->tgid;
6693 fl->fl_flags = FL_POSIX;
6695 fl->fl_lmops = NULL;
6701 static int smb2_set_flock_flags(struct file_lock *flock, int flags)
6705 /* Checking for wrong flag combination during lock request*/
6707 case SMB2_LOCKFLAG_SHARED:
6708 ksmbd_debug(SMB, "received shared request\n");
6710 flock->fl_type = F_RDLCK;
6711 flock->fl_flags |= FL_SLEEP;
6713 case SMB2_LOCKFLAG_EXCLUSIVE:
6714 ksmbd_debug(SMB, "received exclusive request\n");
6716 flock->fl_type = F_WRLCK;
6717 flock->fl_flags |= FL_SLEEP;
6719 case SMB2_LOCKFLAG_SHARED | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
6721 "received shared & fail immediately request\n");
6723 flock->fl_type = F_RDLCK;
6725 case SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
6727 "received exclusive & fail immediately request\n");
6729 flock->fl_type = F_WRLCK;
6731 case SMB2_LOCKFLAG_UNLOCK:
6732 ksmbd_debug(SMB, "received unlock request\n");
6733 flock->fl_type = F_UNLCK;
6741 static struct ksmbd_lock *smb2_lock_init(struct file_lock *flock,
6742 unsigned int cmd, int flags,
6743 struct list_head *lock_list)
6745 struct ksmbd_lock *lock;
6747 lock = kzalloc(sizeof(struct ksmbd_lock), GFP_KERNEL);
6753 lock->start = flock->fl_start;
6754 lock->end = flock->fl_end;
6755 lock->flags = flags;
6756 if (lock->start == lock->end)
6758 INIT_LIST_HEAD(&lock->clist);
6759 INIT_LIST_HEAD(&lock->flist);
6760 INIT_LIST_HEAD(&lock->llist);
6761 list_add_tail(&lock->llist, lock_list);
6766 static void smb2_remove_blocked_lock(void **argv)
6768 struct file_lock *flock = (struct file_lock *)argv[0];
6770 ksmbd_vfs_posix_lock_unblock(flock);
6771 wake_up(&flock->fl_wait);
6774 static inline bool lock_defer_pending(struct file_lock *fl)
6776 /* check pending lock waiters */
6777 return waitqueue_active(&fl->fl_wait);
6781 * smb2_lock() - handler for smb2 file lock command
6782 * @work: smb work containing lock command buffer
6784 * Return: 0 on success, otherwise error
6786 int smb2_lock(struct ksmbd_work *work)
6788 struct smb2_lock_req *req = smb2_get_msg(work->request_buf);
6789 struct smb2_lock_rsp *rsp = smb2_get_msg(work->response_buf);
6790 struct smb2_lock_element *lock_ele;
6791 struct ksmbd_file *fp = NULL;
6792 struct file_lock *flock = NULL;
6793 struct file *filp = NULL;
6797 int err = -EIO, i, rc = 0;
6798 u64 lock_start, lock_length;
6799 struct ksmbd_lock *smb_lock = NULL, *cmp_lock, *tmp, *tmp2;
6800 struct ksmbd_conn *conn;
6802 LIST_HEAD(lock_list);
6803 LIST_HEAD(rollback_list);
6806 ksmbd_debug(SMB, "Received lock request\n");
6807 fp = ksmbd_lookup_fd_slow(work,
6808 le64_to_cpu(req->VolatileFileId),
6809 le64_to_cpu(req->PersistentFileId));
6811 ksmbd_debug(SMB, "Invalid file id for lock : %llu\n",
6812 le64_to_cpu(req->VolatileFileId));
6818 lock_count = le16_to_cpu(req->LockCount);
6819 lock_ele = req->locks;
6821 ksmbd_debug(SMB, "lock count is %d\n", lock_count);
6827 for (i = 0; i < lock_count; i++) {
6828 flags = le32_to_cpu(lock_ele[i].Flags);
6830 flock = smb_flock_init(filp);
6834 cmd = smb2_set_flock_flags(flock, flags);
6836 lock_start = le64_to_cpu(lock_ele[i].Offset);
6837 lock_length = le64_to_cpu(lock_ele[i].Length);
6838 if (lock_start > U64_MAX - lock_length) {
6839 pr_err("Invalid lock range requested\n");
6840 rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
6844 if (lock_start > OFFSET_MAX)
6845 flock->fl_start = OFFSET_MAX;
6847 flock->fl_start = lock_start;
6849 lock_length = le64_to_cpu(lock_ele[i].Length);
6850 if (lock_length > OFFSET_MAX - flock->fl_start)
6851 lock_length = OFFSET_MAX - flock->fl_start;
6853 flock->fl_end = flock->fl_start + lock_length;
6855 if (flock->fl_end < flock->fl_start) {
6857 "the end offset(%llx) is smaller than the start offset(%llx)\n",
6858 flock->fl_end, flock->fl_start);
6859 rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
6863 /* Check conflict locks in one request */
6864 list_for_each_entry(cmp_lock, &lock_list, llist) {
6865 if (cmp_lock->fl->fl_start <= flock->fl_start &&
6866 cmp_lock->fl->fl_end >= flock->fl_end) {
6867 if (cmp_lock->fl->fl_type != F_UNLCK &&
6868 flock->fl_type != F_UNLCK) {
6869 pr_err("conflict two locks in one request\n");
6876 smb_lock = smb2_lock_init(flock, cmd, flags, &lock_list);
6883 list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
6884 if (smb_lock->cmd < 0) {
6889 if (!(smb_lock->flags & SMB2_LOCKFLAG_MASK)) {
6894 if ((prior_lock & (SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_SHARED) &&
6895 smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) ||
6896 (prior_lock == SMB2_LOCKFLAG_UNLOCK &&
6897 !(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK))) {
6902 prior_lock = smb_lock->flags;
6904 if (!(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) &&
6905 !(smb_lock->flags & SMB2_LOCKFLAG_FAIL_IMMEDIATELY))
6909 /* check locks in connection list */
6910 read_lock(&conn_list_lock);
6911 list_for_each_entry(conn, &conn_list, conns_list) {
6912 spin_lock(&conn->llist_lock);
6913 list_for_each_entry_safe(cmp_lock, tmp2, &conn->lock_list, clist) {
6914 if (file_inode(cmp_lock->fl->fl_file) !=
6915 file_inode(smb_lock->fl->fl_file))
6918 if (smb_lock->fl->fl_type == F_UNLCK) {
6919 if (cmp_lock->fl->fl_file == smb_lock->fl->fl_file &&
6920 cmp_lock->start == smb_lock->start &&
6921 cmp_lock->end == smb_lock->end &&
6922 !lock_defer_pending(cmp_lock->fl)) {
6924 list_del(&cmp_lock->flist);
6925 list_del(&cmp_lock->clist);
6926 spin_unlock(&conn->llist_lock);
6927 read_unlock(&conn_list_lock);
6929 locks_free_lock(cmp_lock->fl);
6936 if (cmp_lock->fl->fl_file == smb_lock->fl->fl_file) {
6937 if (smb_lock->flags & SMB2_LOCKFLAG_SHARED)
6940 if (cmp_lock->flags & SMB2_LOCKFLAG_SHARED)
6944 /* check zero byte lock range */
6945 if (cmp_lock->zero_len && !smb_lock->zero_len &&
6946 cmp_lock->start > smb_lock->start &&
6947 cmp_lock->start < smb_lock->end) {
6948 spin_unlock(&conn->llist_lock);
6949 read_unlock(&conn_list_lock);
6950 pr_err("previous lock conflict with zero byte lock range\n");
6954 if (smb_lock->zero_len && !cmp_lock->zero_len &&
6955 smb_lock->start > cmp_lock->start &&
6956 smb_lock->start < cmp_lock->end) {
6957 spin_unlock(&conn->llist_lock);
6958 read_unlock(&conn_list_lock);
6959 pr_err("current lock conflict with zero byte lock range\n");
6963 if (((cmp_lock->start <= smb_lock->start &&
6964 cmp_lock->end > smb_lock->start) ||
6965 (cmp_lock->start < smb_lock->end &&
6966 cmp_lock->end >= smb_lock->end)) &&
6967 !cmp_lock->zero_len && !smb_lock->zero_len) {
6968 spin_unlock(&conn->llist_lock);
6969 read_unlock(&conn_list_lock);
6970 pr_err("Not allow lock operation on exclusive lock range\n");
6974 spin_unlock(&conn->llist_lock);
6976 read_unlock(&conn_list_lock);
6978 if (smb_lock->fl->fl_type == F_UNLCK && nolock) {
6979 pr_err("Try to unlock nolocked range\n");
6980 rsp->hdr.Status = STATUS_RANGE_NOT_LOCKED;
6985 if (smb_lock->zero_len) {
6990 flock = smb_lock->fl;
6991 list_del(&smb_lock->llist);
6993 rc = vfs_lock_file(filp, smb_lock->cmd, flock, NULL);
6995 if (flags & SMB2_LOCKFLAG_UNLOCK) {
6997 ksmbd_debug(SMB, "File unlocked\n");
6998 } else if (rc == -ENOENT) {
6999 rsp->hdr.Status = STATUS_NOT_LOCKED;
7002 locks_free_lock(flock);
7005 if (rc == FILE_LOCK_DEFERRED) {
7009 "would have to wait for getting lock\n");
7010 spin_lock(&work->conn->llist_lock);
7011 list_add_tail(&smb_lock->clist,
7012 &work->conn->lock_list);
7013 spin_unlock(&work->conn->llist_lock);
7014 list_add(&smb_lock->llist, &rollback_list);
7016 argv = kmalloc(sizeof(void *), GFP_KERNEL);
7023 rc = setup_async_work(work,
7024 smb2_remove_blocked_lock,
7030 spin_lock(&fp->f_lock);
7031 list_add(&work->fp_entry, &fp->blocked_works);
7032 spin_unlock(&fp->f_lock);
7034 smb2_send_interim_resp(work, STATUS_PENDING);
7036 ksmbd_vfs_posix_lock_wait(flock);
7038 if (work->state != KSMBD_WORK_ACTIVE) {
7039 list_del(&smb_lock->llist);
7040 spin_lock(&work->conn->llist_lock);
7041 list_del(&smb_lock->clist);
7042 spin_unlock(&work->conn->llist_lock);
7043 locks_free_lock(flock);
7045 if (work->state == KSMBD_WORK_CANCELLED) {
7046 spin_lock(&fp->f_lock);
7047 list_del(&work->fp_entry);
7048 spin_unlock(&fp->f_lock);
7052 smb2_send_interim_resp(work,
7054 work->send_no_response = 1;
7057 init_smb2_rsp_hdr(work);
7058 smb2_set_err_rsp(work);
7060 STATUS_RANGE_NOT_LOCKED;
7065 list_del(&smb_lock->llist);
7066 spin_lock(&work->conn->llist_lock);
7067 list_del(&smb_lock->clist);
7068 spin_unlock(&work->conn->llist_lock);
7070 spin_lock(&fp->f_lock);
7071 list_del(&work->fp_entry);
7072 spin_unlock(&fp->f_lock);
7075 spin_lock(&work->conn->llist_lock);
7076 list_add_tail(&smb_lock->clist,
7077 &work->conn->lock_list);
7078 list_add_tail(&smb_lock->flist,
7080 spin_unlock(&work->conn->llist_lock);
7081 list_add(&smb_lock->llist, &rollback_list);
7082 ksmbd_debug(SMB, "successful in taking lock\n");
7089 if (atomic_read(&fp->f_ci->op_count) > 1)
7090 smb_break_all_oplock(work, fp);
7092 rsp->StructureSize = cpu_to_le16(4);
7093 ksmbd_debug(SMB, "successful in taking lock\n");
7094 rsp->hdr.Status = STATUS_SUCCESS;
7096 inc_rfc1001_len(work->response_buf, 4);
7097 ksmbd_fd_put(work, fp);
7101 list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
7102 locks_free_lock(smb_lock->fl);
7103 list_del(&smb_lock->llist);
7107 list_for_each_entry_safe(smb_lock, tmp, &rollback_list, llist) {
7108 struct file_lock *rlock = NULL;
7110 rlock = smb_flock_init(filp);
7111 rlock->fl_type = F_UNLCK;
7112 rlock->fl_start = smb_lock->start;
7113 rlock->fl_end = smb_lock->end;
7115 rc = vfs_lock_file(filp, 0, rlock, NULL);
7117 pr_err("rollback unlock fail : %d\n", rc);
7119 list_del(&smb_lock->llist);
7120 spin_lock(&work->conn->llist_lock);
7121 if (!list_empty(&smb_lock->flist))
7122 list_del(&smb_lock->flist);
7123 list_del(&smb_lock->clist);
7124 spin_unlock(&work->conn->llist_lock);
7126 locks_free_lock(smb_lock->fl);
7127 locks_free_lock(rlock);
7131 ksmbd_debug(SMB, "failed in taking lock(flags : %x), err : %d\n", flags, err);
7133 if (!rsp->hdr.Status) {
7135 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7136 else if (err == -ENOMEM)
7137 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
7138 else if (err == -ENOENT)
7139 rsp->hdr.Status = STATUS_FILE_CLOSED;
7141 rsp->hdr.Status = STATUS_LOCK_NOT_GRANTED;
7144 smb2_set_err_rsp(work);
7145 ksmbd_fd_put(work, fp);
7149 static int fsctl_copychunk(struct ksmbd_work *work,
7150 struct copychunk_ioctl_req *ci_req,
7151 unsigned int cnt_code,
7152 unsigned int input_count,
7153 unsigned long long volatile_id,
7154 unsigned long long persistent_id,
7155 struct smb2_ioctl_rsp *rsp)
7157 struct copychunk_ioctl_rsp *ci_rsp;
7158 struct ksmbd_file *src_fp = NULL, *dst_fp = NULL;
7159 struct srv_copychunk *chunks;
7160 unsigned int i, chunk_count, chunk_count_written = 0;
7161 unsigned int chunk_size_written = 0;
7162 loff_t total_size_written = 0;
7165 ci_rsp = (struct copychunk_ioctl_rsp *)&rsp->Buffer[0];
7167 rsp->VolatileFileId = cpu_to_le64(volatile_id);
7168 rsp->PersistentFileId = cpu_to_le64(persistent_id);
7169 ci_rsp->ChunksWritten =
7170 cpu_to_le32(ksmbd_server_side_copy_max_chunk_count());
7171 ci_rsp->ChunkBytesWritten =
7172 cpu_to_le32(ksmbd_server_side_copy_max_chunk_size());
7173 ci_rsp->TotalBytesWritten =
7174 cpu_to_le32(ksmbd_server_side_copy_max_total_size());
7176 chunks = (struct srv_copychunk *)&ci_req->Chunks[0];
7177 chunk_count = le32_to_cpu(ci_req->ChunkCount);
7178 if (chunk_count == 0)
7180 total_size_written = 0;
7182 /* verify the SRV_COPYCHUNK_COPY packet */
7183 if (chunk_count > ksmbd_server_side_copy_max_chunk_count() ||
7184 input_count < offsetof(struct copychunk_ioctl_req, Chunks) +
7185 chunk_count * sizeof(struct srv_copychunk)) {
7186 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7190 for (i = 0; i < chunk_count; i++) {
7191 if (le32_to_cpu(chunks[i].Length) == 0 ||
7192 le32_to_cpu(chunks[i].Length) > ksmbd_server_side_copy_max_chunk_size())
7194 total_size_written += le32_to_cpu(chunks[i].Length);
7197 if (i < chunk_count ||
7198 total_size_written > ksmbd_server_side_copy_max_total_size()) {
7199 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7203 src_fp = ksmbd_lookup_foreign_fd(work,
7204 le64_to_cpu(ci_req->ResumeKey[0]));
7205 dst_fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
7208 src_fp->persistent_id != le64_to_cpu(ci_req->ResumeKey[1])) {
7209 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
7214 rsp->hdr.Status = STATUS_FILE_CLOSED;
7219 * FILE_READ_DATA should only be included in
7220 * the FSCTL_COPYCHUNK case
7222 if (cnt_code == FSCTL_COPYCHUNK &&
7223 !(dst_fp->daccess & (FILE_READ_DATA_LE | FILE_GENERIC_READ_LE))) {
7224 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7228 ret = ksmbd_vfs_copy_file_ranges(work, src_fp, dst_fp,
7229 chunks, chunk_count,
7230 &chunk_count_written,
7231 &chunk_size_written,
7232 &total_size_written);
7235 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7237 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
7238 else if (ret == -EBADF)
7239 rsp->hdr.Status = STATUS_INVALID_HANDLE;
7240 else if (ret == -EFBIG || ret == -ENOSPC)
7241 rsp->hdr.Status = STATUS_DISK_FULL;
7242 else if (ret == -EINVAL)
7243 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7244 else if (ret == -EISDIR)
7245 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
7246 else if (ret == -E2BIG)
7247 rsp->hdr.Status = STATUS_INVALID_VIEW_SIZE;
7249 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
7252 ci_rsp->ChunksWritten = cpu_to_le32(chunk_count_written);
7253 ci_rsp->ChunkBytesWritten = cpu_to_le32(chunk_size_written);
7254 ci_rsp->TotalBytesWritten = cpu_to_le32(total_size_written);
7256 ksmbd_fd_put(work, src_fp);
7257 ksmbd_fd_put(work, dst_fp);
7261 static __be32 idev_ipv4_address(struct in_device *idev)
7265 struct in_ifaddr *ifa;
7268 in_dev_for_each_ifa_rcu(ifa, idev) {
7269 if (ifa->ifa_flags & IFA_F_SECONDARY)
7272 addr = ifa->ifa_address;
7279 static int fsctl_query_iface_info_ioctl(struct ksmbd_conn *conn,
7280 struct smb2_ioctl_rsp *rsp,
7281 unsigned int out_buf_len)
7283 struct network_interface_info_ioctl_rsp *nii_rsp = NULL;
7285 struct net_device *netdev;
7286 struct sockaddr_storage_rsp *sockaddr_storage;
7288 unsigned long long speed;
7291 for_each_netdev(&init_net, netdev) {
7292 bool ipv4_set = false;
7294 if (netdev->type == ARPHRD_LOOPBACK)
7297 flags = dev_get_flags(netdev);
7298 if (!(flags & IFF_RUNNING))
7302 nbytes + sizeof(struct network_interface_info_ioctl_rsp)) {
7307 nii_rsp = (struct network_interface_info_ioctl_rsp *)
7308 &rsp->Buffer[nbytes];
7309 nii_rsp->IfIndex = cpu_to_le32(netdev->ifindex);
7311 nii_rsp->Capability = 0;
7312 if (netdev->real_num_tx_queues > 1)
7313 nii_rsp->Capability |= cpu_to_le32(RSS_CAPABLE);
7314 if (ksmbd_rdma_capable_netdev(netdev))
7315 nii_rsp->Capability |= cpu_to_le32(RDMA_CAPABLE);
7317 nii_rsp->Next = cpu_to_le32(152);
7318 nii_rsp->Reserved = 0;
7320 if (netdev->ethtool_ops->get_link_ksettings) {
7321 struct ethtool_link_ksettings cmd;
7323 netdev->ethtool_ops->get_link_ksettings(netdev, &cmd);
7324 speed = cmd.base.speed;
7326 ksmbd_debug(SMB, "%s %s\n", netdev->name,
7327 "speed is unknown, defaulting to 1Gb/sec");
7332 nii_rsp->LinkSpeed = cpu_to_le64(speed);
7334 sockaddr_storage = (struct sockaddr_storage_rsp *)
7335 nii_rsp->SockAddr_Storage;
7336 memset(sockaddr_storage, 0, 128);
7339 struct in_device *idev;
7341 sockaddr_storage->Family = cpu_to_le16(INTERNETWORK);
7342 sockaddr_storage->addr4.Port = 0;
7344 idev = __in_dev_get_rtnl(netdev);
7347 sockaddr_storage->addr4.IPv4address =
7348 idev_ipv4_address(idev);
7349 nbytes += sizeof(struct network_interface_info_ioctl_rsp);
7353 struct inet6_dev *idev6;
7354 struct inet6_ifaddr *ifa;
7355 __u8 *ipv6_addr = sockaddr_storage->addr6.IPv6address;
7357 sockaddr_storage->Family = cpu_to_le16(INTERNETWORKV6);
7358 sockaddr_storage->addr6.Port = 0;
7359 sockaddr_storage->addr6.FlowInfo = 0;
7361 idev6 = __in6_dev_get(netdev);
7365 list_for_each_entry(ifa, &idev6->addr_list, if_list) {
7366 if (ifa->flags & (IFA_F_TENTATIVE |
7369 memcpy(ipv6_addr, ifa->addr.s6_addr, 16);
7372 sockaddr_storage->addr6.ScopeId = 0;
7373 nbytes += sizeof(struct network_interface_info_ioctl_rsp);
7378 /* zero if this is last one */
7382 rsp->PersistentFileId = cpu_to_le64(SMB2_NO_FID);
7383 rsp->VolatileFileId = cpu_to_le64(SMB2_NO_FID);
7387 static int fsctl_validate_negotiate_info(struct ksmbd_conn *conn,
7388 struct validate_negotiate_info_req *neg_req,
7389 struct validate_negotiate_info_rsp *neg_rsp,
7390 unsigned int in_buf_len)
7395 if (in_buf_len < offsetof(struct validate_negotiate_info_req, Dialects) +
7396 le16_to_cpu(neg_req->DialectCount) * sizeof(__le16))
7399 dialect = ksmbd_lookup_dialect_by_id(neg_req->Dialects,
7400 neg_req->DialectCount);
7401 if (dialect == BAD_PROT_ID || dialect != conn->dialect) {
7406 if (strncmp(neg_req->Guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE)) {
7411 if (le16_to_cpu(neg_req->SecurityMode) != conn->cli_sec_mode) {
7416 if (le32_to_cpu(neg_req->Capabilities) != conn->cli_cap) {
7421 neg_rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
7422 memset(neg_rsp->Guid, 0, SMB2_CLIENT_GUID_SIZE);
7423 neg_rsp->SecurityMode = cpu_to_le16(conn->srv_sec_mode);
7424 neg_rsp->Dialect = cpu_to_le16(conn->dialect);
7429 static int fsctl_query_allocated_ranges(struct ksmbd_work *work, u64 id,
7430 struct file_allocated_range_buffer *qar_req,
7431 struct file_allocated_range_buffer *qar_rsp,
7432 unsigned int in_count, unsigned int *out_count)
7434 struct ksmbd_file *fp;
7435 loff_t start, length;
7442 fp = ksmbd_lookup_fd_fast(work, id);
7446 start = le64_to_cpu(qar_req->file_offset);
7447 length = le64_to_cpu(qar_req->length);
7449 ret = ksmbd_vfs_fqar_lseek(fp, start, length,
7450 qar_rsp, in_count, out_count);
7451 if (ret && ret != -E2BIG)
7454 ksmbd_fd_put(work, fp);
7458 static int fsctl_pipe_transceive(struct ksmbd_work *work, u64 id,
7459 unsigned int out_buf_len,
7460 struct smb2_ioctl_req *req,
7461 struct smb2_ioctl_rsp *rsp)
7463 struct ksmbd_rpc_command *rpc_resp;
7464 char *data_buf = (char *)&req->Buffer[0];
7467 rpc_resp = ksmbd_rpc_ioctl(work->sess, id, data_buf,
7468 le32_to_cpu(req->InputCount));
7470 if (rpc_resp->flags == KSMBD_RPC_SOME_NOT_MAPPED) {
7472 * set STATUS_SOME_NOT_MAPPED response
7473 * for unknown domain sid.
7475 rsp->hdr.Status = STATUS_SOME_NOT_MAPPED;
7476 } else if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
7477 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7479 } else if (rpc_resp->flags != KSMBD_RPC_OK) {
7480 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7484 nbytes = rpc_resp->payload_sz;
7485 if (rpc_resp->payload_sz > out_buf_len) {
7486 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
7487 nbytes = out_buf_len;
7490 if (!rpc_resp->payload_sz) {
7492 STATUS_UNEXPECTED_IO_ERROR;
7496 memcpy((char *)rsp->Buffer, rpc_resp->payload, nbytes);
7503 static inline int fsctl_set_sparse(struct ksmbd_work *work, u64 id,
7504 struct file_sparse *sparse)
7506 struct ksmbd_file *fp;
7507 struct user_namespace *user_ns;
7511 fp = ksmbd_lookup_fd_fast(work, id);
7514 user_ns = file_mnt_user_ns(fp->filp);
7516 old_fattr = fp->f_ci->m_fattr;
7517 if (sparse->SetSparse)
7518 fp->f_ci->m_fattr |= FILE_ATTRIBUTE_SPARSE_FILE_LE;
7520 fp->f_ci->m_fattr &= ~FILE_ATTRIBUTE_SPARSE_FILE_LE;
7522 if (fp->f_ci->m_fattr != old_fattr &&
7523 test_share_config_flag(work->tcon->share_conf,
7524 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS)) {
7525 struct xattr_dos_attrib da;
7527 ret = ksmbd_vfs_get_dos_attrib_xattr(user_ns,
7528 fp->filp->f_path.dentry, &da);
7532 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
7533 ret = ksmbd_vfs_set_dos_attrib_xattr(user_ns,
7534 fp->filp->f_path.dentry, &da);
7536 fp->f_ci->m_fattr = old_fattr;
7540 ksmbd_fd_put(work, fp);
7544 static int fsctl_request_resume_key(struct ksmbd_work *work,
7545 struct smb2_ioctl_req *req,
7546 struct resume_key_ioctl_rsp *key_rsp)
7548 struct ksmbd_file *fp;
7550 fp = ksmbd_lookup_fd_slow(work,
7551 le64_to_cpu(req->VolatileFileId),
7552 le64_to_cpu(req->PersistentFileId));
7556 memset(key_rsp, 0, sizeof(*key_rsp));
7557 key_rsp->ResumeKey[0] = req->VolatileFileId;
7558 key_rsp->ResumeKey[1] = req->PersistentFileId;
7559 ksmbd_fd_put(work, fp);
7565 * smb2_ioctl() - handler for smb2 ioctl command
7566 * @work: smb work containing ioctl command buffer
7568 * Return: 0 on success, otherwise error
7570 int smb2_ioctl(struct ksmbd_work *work)
7572 struct smb2_ioctl_req *req;
7573 struct smb2_ioctl_rsp *rsp;
7574 unsigned int cnt_code, nbytes = 0, out_buf_len, in_buf_len;
7575 u64 id = KSMBD_NO_FID;
7576 struct ksmbd_conn *conn = work->conn;
7579 if (work->next_smb2_rcv_hdr_off) {
7580 req = ksmbd_req_buf_next(work);
7581 rsp = ksmbd_resp_buf_next(work);
7582 if (!has_file_id(le64_to_cpu(req->VolatileFileId))) {
7583 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
7584 work->compound_fid);
7585 id = work->compound_fid;
7588 req = smb2_get_msg(work->request_buf);
7589 rsp = smb2_get_msg(work->response_buf);
7592 if (!has_file_id(id))
7593 id = le64_to_cpu(req->VolatileFileId);
7595 if (req->Flags != cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL)) {
7596 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7600 cnt_code = le32_to_cpu(req->CntCode);
7601 ret = smb2_calc_max_out_buf_len(work, 48,
7602 le32_to_cpu(req->MaxOutputResponse));
7604 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7607 out_buf_len = (unsigned int)ret;
7608 in_buf_len = le32_to_cpu(req->InputCount);
7611 case FSCTL_DFS_GET_REFERRALS:
7612 case FSCTL_DFS_GET_REFERRALS_EX:
7613 /* Not support DFS yet */
7614 rsp->hdr.Status = STATUS_FS_DRIVER_REQUIRED;
7616 case FSCTL_CREATE_OR_GET_OBJECT_ID:
7618 struct file_object_buf_type1_ioctl_rsp *obj_buf;
7620 nbytes = sizeof(struct file_object_buf_type1_ioctl_rsp);
7621 obj_buf = (struct file_object_buf_type1_ioctl_rsp *)
7625 * TODO: This is dummy implementation to pass smbtorture
7626 * Need to check correct response later
7628 memset(obj_buf->ObjectId, 0x0, 16);
7629 memset(obj_buf->BirthVolumeId, 0x0, 16);
7630 memset(obj_buf->BirthObjectId, 0x0, 16);
7631 memset(obj_buf->DomainId, 0x0, 16);
7635 case FSCTL_PIPE_TRANSCEIVE:
7636 out_buf_len = min_t(u32, KSMBD_IPC_MAX_PAYLOAD, out_buf_len);
7637 nbytes = fsctl_pipe_transceive(work, id, out_buf_len, req, rsp);
7639 case FSCTL_VALIDATE_NEGOTIATE_INFO:
7640 if (conn->dialect < SMB30_PROT_ID) {
7645 if (in_buf_len < sizeof(struct validate_negotiate_info_req))
7648 if (out_buf_len < sizeof(struct validate_negotiate_info_rsp))
7651 ret = fsctl_validate_negotiate_info(conn,
7652 (struct validate_negotiate_info_req *)&req->Buffer[0],
7653 (struct validate_negotiate_info_rsp *)&rsp->Buffer[0],
7658 nbytes = sizeof(struct validate_negotiate_info_rsp);
7659 rsp->PersistentFileId = cpu_to_le64(SMB2_NO_FID);
7660 rsp->VolatileFileId = cpu_to_le64(SMB2_NO_FID);
7662 case FSCTL_QUERY_NETWORK_INTERFACE_INFO:
7663 ret = fsctl_query_iface_info_ioctl(conn, rsp, out_buf_len);
7668 case FSCTL_REQUEST_RESUME_KEY:
7669 if (out_buf_len < sizeof(struct resume_key_ioctl_rsp)) {
7674 ret = fsctl_request_resume_key(work, req,
7675 (struct resume_key_ioctl_rsp *)&rsp->Buffer[0]);
7678 rsp->PersistentFileId = req->PersistentFileId;
7679 rsp->VolatileFileId = req->VolatileFileId;
7680 nbytes = sizeof(struct resume_key_ioctl_rsp);
7682 case FSCTL_COPYCHUNK:
7683 case FSCTL_COPYCHUNK_WRITE:
7684 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7686 "User does not have write permission\n");
7691 if (in_buf_len < sizeof(struct copychunk_ioctl_req)) {
7696 if (out_buf_len < sizeof(struct copychunk_ioctl_rsp)) {
7701 nbytes = sizeof(struct copychunk_ioctl_rsp);
7702 rsp->VolatileFileId = req->VolatileFileId;
7703 rsp->PersistentFileId = req->PersistentFileId;
7704 fsctl_copychunk(work,
7705 (struct copychunk_ioctl_req *)&req->Buffer[0],
7706 le32_to_cpu(req->CntCode),
7707 le32_to_cpu(req->InputCount),
7708 le64_to_cpu(req->VolatileFileId),
7709 le64_to_cpu(req->PersistentFileId),
7712 case FSCTL_SET_SPARSE:
7713 if (in_buf_len < sizeof(struct file_sparse)) {
7718 ret = fsctl_set_sparse(work, id,
7719 (struct file_sparse *)&req->Buffer[0]);
7723 case FSCTL_SET_ZERO_DATA:
7725 struct file_zero_data_information *zero_data;
7726 struct ksmbd_file *fp;
7729 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7731 "User does not have write permission\n");
7736 if (in_buf_len < sizeof(struct file_zero_data_information)) {
7742 (struct file_zero_data_information *)&req->Buffer[0];
7744 fp = ksmbd_lookup_fd_fast(work, id);
7750 off = le64_to_cpu(zero_data->FileOffset);
7751 len = le64_to_cpu(zero_data->BeyondFinalZero) - off;
7753 ret = ksmbd_vfs_zero_data(work, fp, off, len);
7754 ksmbd_fd_put(work, fp);
7759 case FSCTL_QUERY_ALLOCATED_RANGES:
7760 if (in_buf_len < sizeof(struct file_allocated_range_buffer)) {
7765 ret = fsctl_query_allocated_ranges(work, id,
7766 (struct file_allocated_range_buffer *)&req->Buffer[0],
7767 (struct file_allocated_range_buffer *)&rsp->Buffer[0],
7769 sizeof(struct file_allocated_range_buffer), &nbytes);
7770 if (ret == -E2BIG) {
7771 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
7772 } else if (ret < 0) {
7777 nbytes *= sizeof(struct file_allocated_range_buffer);
7779 case FSCTL_GET_REPARSE_POINT:
7781 struct reparse_data_buffer *reparse_ptr;
7782 struct ksmbd_file *fp;
7784 reparse_ptr = (struct reparse_data_buffer *)&rsp->Buffer[0];
7785 fp = ksmbd_lookup_fd_fast(work, id);
7787 pr_err("not found fp!!\n");
7792 reparse_ptr->ReparseTag =
7793 smb2_get_reparse_tag_special_file(file_inode(fp->filp)->i_mode);
7794 reparse_ptr->ReparseDataLength = 0;
7795 ksmbd_fd_put(work, fp);
7796 nbytes = sizeof(struct reparse_data_buffer);
7799 case FSCTL_DUPLICATE_EXTENTS_TO_FILE:
7801 struct ksmbd_file *fp_in, *fp_out = NULL;
7802 struct duplicate_extents_to_file *dup_ext;
7803 loff_t src_off, dst_off, length, cloned;
7805 if (in_buf_len < sizeof(struct duplicate_extents_to_file)) {
7810 dup_ext = (struct duplicate_extents_to_file *)&req->Buffer[0];
7812 fp_in = ksmbd_lookup_fd_slow(work, dup_ext->VolatileFileHandle,
7813 dup_ext->PersistentFileHandle);
7815 pr_err("not found file handle in duplicate extent to file\n");
7820 fp_out = ksmbd_lookup_fd_fast(work, id);
7822 pr_err("not found fp\n");
7827 src_off = le64_to_cpu(dup_ext->SourceFileOffset);
7828 dst_off = le64_to_cpu(dup_ext->TargetFileOffset);
7829 length = le64_to_cpu(dup_ext->ByteCount);
7830 cloned = vfs_clone_file_range(fp_in->filp, src_off, fp_out->filp,
7831 dst_off, length, 0);
7832 if (cloned == -EXDEV || cloned == -EOPNOTSUPP) {
7835 } else if (cloned != length) {
7836 cloned = vfs_copy_file_range(fp_in->filp, src_off,
7837 fp_out->filp, dst_off, length, 0);
7838 if (cloned != length) {
7847 ksmbd_fd_put(work, fp_in);
7848 ksmbd_fd_put(work, fp_out);
7854 ksmbd_debug(SMB, "not implemented yet ioctl command 0x%x\n",
7860 rsp->CntCode = cpu_to_le32(cnt_code);
7861 rsp->InputCount = cpu_to_le32(0);
7862 rsp->InputOffset = cpu_to_le32(112);
7863 rsp->OutputOffset = cpu_to_le32(112);
7864 rsp->OutputCount = cpu_to_le32(nbytes);
7865 rsp->StructureSize = cpu_to_le16(49);
7866 rsp->Reserved = cpu_to_le16(0);
7867 rsp->Flags = cpu_to_le32(0);
7868 rsp->Reserved2 = cpu_to_le32(0);
7869 inc_rfc1001_len(work->response_buf, 48 + nbytes);
7875 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7876 else if (ret == -ENOENT)
7877 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
7878 else if (ret == -EOPNOTSUPP)
7879 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7880 else if (ret == -ENOSPC)
7881 rsp->hdr.Status = STATUS_BUFFER_TOO_SMALL;
7882 else if (ret < 0 || rsp->hdr.Status == 0)
7883 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7884 smb2_set_err_rsp(work);
7889 * smb20_oplock_break_ack() - handler for smb2.0 oplock break command
7890 * @work: smb work containing oplock break command buffer
7894 static void smb20_oplock_break_ack(struct ksmbd_work *work)
7896 struct smb2_oplock_break *req = smb2_get_msg(work->request_buf);
7897 struct smb2_oplock_break *rsp = smb2_get_msg(work->response_buf);
7898 struct ksmbd_file *fp;
7899 struct oplock_info *opinfo = NULL;
7902 u64 volatile_id, persistent_id;
7903 char req_oplevel = 0, rsp_oplevel = 0;
7904 unsigned int oplock_change_type;
7906 volatile_id = le64_to_cpu(req->VolatileFid);
7907 persistent_id = le64_to_cpu(req->PersistentFid);
7908 req_oplevel = req->OplockLevel;
7909 ksmbd_debug(OPLOCK, "v_id %llu, p_id %llu request oplock level %d\n",
7910 volatile_id, persistent_id, req_oplevel);
7912 fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
7914 rsp->hdr.Status = STATUS_FILE_CLOSED;
7915 smb2_set_err_rsp(work);
7919 opinfo = opinfo_get(fp);
7921 pr_err("unexpected null oplock_info\n");
7922 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
7923 smb2_set_err_rsp(work);
7924 ksmbd_fd_put(work, fp);
7928 if (opinfo->level == SMB2_OPLOCK_LEVEL_NONE) {
7929 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
7933 if (opinfo->op_state == OPLOCK_STATE_NONE) {
7934 ksmbd_debug(SMB, "unexpected oplock state 0x%x\n", opinfo->op_state);
7935 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
7939 if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
7940 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
7941 (req_oplevel != SMB2_OPLOCK_LEVEL_II &&
7942 req_oplevel != SMB2_OPLOCK_LEVEL_NONE)) {
7943 err = STATUS_INVALID_OPLOCK_PROTOCOL;
7944 oplock_change_type = OPLOCK_WRITE_TO_NONE;
7945 } else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
7946 req_oplevel != SMB2_OPLOCK_LEVEL_NONE) {
7947 err = STATUS_INVALID_OPLOCK_PROTOCOL;
7948 oplock_change_type = OPLOCK_READ_TO_NONE;
7949 } else if (req_oplevel == SMB2_OPLOCK_LEVEL_II ||
7950 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
7951 err = STATUS_INVALID_DEVICE_STATE;
7952 if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
7953 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
7954 req_oplevel == SMB2_OPLOCK_LEVEL_II) {
7955 oplock_change_type = OPLOCK_WRITE_TO_READ;
7956 } else if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
7957 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
7958 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
7959 oplock_change_type = OPLOCK_WRITE_TO_NONE;
7960 } else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
7961 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
7962 oplock_change_type = OPLOCK_READ_TO_NONE;
7964 oplock_change_type = 0;
7967 oplock_change_type = 0;
7970 switch (oplock_change_type) {
7971 case OPLOCK_WRITE_TO_READ:
7972 ret = opinfo_write_to_read(opinfo);
7973 rsp_oplevel = SMB2_OPLOCK_LEVEL_II;
7975 case OPLOCK_WRITE_TO_NONE:
7976 ret = opinfo_write_to_none(opinfo);
7977 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
7979 case OPLOCK_READ_TO_NONE:
7980 ret = opinfo_read_to_none(opinfo);
7981 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
7984 pr_err("unknown oplock change 0x%x -> 0x%x\n",
7985 opinfo->level, rsp_oplevel);
7989 rsp->hdr.Status = err;
7994 ksmbd_fd_put(work, fp);
7995 opinfo->op_state = OPLOCK_STATE_NONE;
7996 wake_up_interruptible_all(&opinfo->oplock_q);
7998 rsp->StructureSize = cpu_to_le16(24);
7999 rsp->OplockLevel = rsp_oplevel;
8002 rsp->VolatileFid = cpu_to_le64(volatile_id);
8003 rsp->PersistentFid = cpu_to_le64(persistent_id);
8004 inc_rfc1001_len(work->response_buf, 24);
8008 opinfo->op_state = OPLOCK_STATE_NONE;
8009 wake_up_interruptible_all(&opinfo->oplock_q);
8012 ksmbd_fd_put(work, fp);
8013 smb2_set_err_rsp(work);
8016 static int check_lease_state(struct lease *lease, __le32 req_state)
8018 if ((lease->new_state ==
8019 (SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE)) &&
8020 !(req_state & SMB2_LEASE_WRITE_CACHING_LE)) {
8021 lease->new_state = req_state;
8025 if (lease->new_state == req_state)
8032 * smb21_lease_break_ack() - handler for smb2.1 lease break command
8033 * @work: smb work containing lease break command buffer
8037 static void smb21_lease_break_ack(struct ksmbd_work *work)
8039 struct ksmbd_conn *conn = work->conn;
8040 struct smb2_lease_ack *req = smb2_get_msg(work->request_buf);
8041 struct smb2_lease_ack *rsp = smb2_get_msg(work->response_buf);
8042 struct oplock_info *opinfo;
8045 unsigned int lease_change_type;
8047 struct lease *lease;
8049 ksmbd_debug(OPLOCK, "smb21 lease break, lease state(0x%x)\n",
8050 le32_to_cpu(req->LeaseState));
8051 opinfo = lookup_lease_in_table(conn, req->LeaseKey);
8053 ksmbd_debug(OPLOCK, "file not opened\n");
8054 smb2_set_err_rsp(work);
8055 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8058 lease = opinfo->o_lease;
8060 if (opinfo->op_state == OPLOCK_STATE_NONE) {
8061 pr_err("unexpected lease break state 0x%x\n",
8063 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8067 if (check_lease_state(lease, req->LeaseState)) {
8068 rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
8070 "req lease state: 0x%x, expected state: 0x%x\n",
8071 req->LeaseState, lease->new_state);
8075 if (!atomic_read(&opinfo->breaking_cnt)) {
8076 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8080 /* check for bad lease state */
8081 if (req->LeaseState &
8082 (~(SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE))) {
8083 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8084 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8085 lease_change_type = OPLOCK_WRITE_TO_NONE;
8087 lease_change_type = OPLOCK_READ_TO_NONE;
8088 ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8089 le32_to_cpu(lease->state),
8090 le32_to_cpu(req->LeaseState));
8091 } else if (lease->state == SMB2_LEASE_READ_CACHING_LE &&
8092 req->LeaseState != SMB2_LEASE_NONE_LE) {
8093 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8094 lease_change_type = OPLOCK_READ_TO_NONE;
8095 ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8096 le32_to_cpu(lease->state),
8097 le32_to_cpu(req->LeaseState));
8099 /* valid lease state changes */
8100 err = STATUS_INVALID_DEVICE_STATE;
8101 if (req->LeaseState == SMB2_LEASE_NONE_LE) {
8102 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8103 lease_change_type = OPLOCK_WRITE_TO_NONE;
8105 lease_change_type = OPLOCK_READ_TO_NONE;
8106 } else if (req->LeaseState & SMB2_LEASE_READ_CACHING_LE) {
8107 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8108 lease_change_type = OPLOCK_WRITE_TO_READ;
8110 lease_change_type = OPLOCK_READ_HANDLE_TO_READ;
8112 lease_change_type = 0;
8116 switch (lease_change_type) {
8117 case OPLOCK_WRITE_TO_READ:
8118 ret = opinfo_write_to_read(opinfo);
8120 case OPLOCK_READ_HANDLE_TO_READ:
8121 ret = opinfo_read_handle_to_read(opinfo);
8123 case OPLOCK_WRITE_TO_NONE:
8124 ret = opinfo_write_to_none(opinfo);
8126 case OPLOCK_READ_TO_NONE:
8127 ret = opinfo_read_to_none(opinfo);
8130 ksmbd_debug(OPLOCK, "unknown lease change 0x%x -> 0x%x\n",
8131 le32_to_cpu(lease->state),
8132 le32_to_cpu(req->LeaseState));
8135 lease_state = lease->state;
8136 opinfo->op_state = OPLOCK_STATE_NONE;
8137 wake_up_interruptible_all(&opinfo->oplock_q);
8138 atomic_dec(&opinfo->breaking_cnt);
8139 wake_up_interruptible_all(&opinfo->oplock_brk);
8143 rsp->hdr.Status = err;
8147 rsp->StructureSize = cpu_to_le16(36);
8150 memcpy(rsp->LeaseKey, req->LeaseKey, 16);
8151 rsp->LeaseState = lease_state;
8152 rsp->LeaseDuration = 0;
8153 inc_rfc1001_len(work->response_buf, 36);
8157 opinfo->op_state = OPLOCK_STATE_NONE;
8158 wake_up_interruptible_all(&opinfo->oplock_q);
8159 atomic_dec(&opinfo->breaking_cnt);
8160 wake_up_interruptible_all(&opinfo->oplock_brk);
8163 smb2_set_err_rsp(work);
8167 * smb2_oplock_break() - dispatcher for smb2.0 and 2.1 oplock/lease break
8168 * @work: smb work containing oplock/lease break command buffer
8172 int smb2_oplock_break(struct ksmbd_work *work)
8174 struct smb2_oplock_break *req = smb2_get_msg(work->request_buf);
8175 struct smb2_oplock_break *rsp = smb2_get_msg(work->response_buf);
8177 switch (le16_to_cpu(req->StructureSize)) {
8178 case OP_BREAK_STRUCT_SIZE_20:
8179 smb20_oplock_break_ack(work);
8181 case OP_BREAK_STRUCT_SIZE_21:
8182 smb21_lease_break_ack(work);
8185 ksmbd_debug(OPLOCK, "invalid break cmd %d\n",
8186 le16_to_cpu(req->StructureSize));
8187 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8188 smb2_set_err_rsp(work);
8195 * smb2_notify() - handler for smb2 notify request
8196 * @work: smb work containing notify command buffer
8200 int smb2_notify(struct ksmbd_work *work)
8202 struct smb2_change_notify_req *req;
8203 struct smb2_change_notify_rsp *rsp;
8205 WORK_BUFFERS(work, req, rsp);
8207 if (work->next_smb2_rcv_hdr_off && req->hdr.NextCommand) {
8208 rsp->hdr.Status = STATUS_INTERNAL_ERROR;
8209 smb2_set_err_rsp(work);
8213 smb2_set_err_rsp(work);
8214 rsp->hdr.Status = STATUS_NOT_IMPLEMENTED;
8219 * smb2_is_sign_req() - handler for checking packet signing status
8220 * @work: smb work containing notify command buffer
8221 * @command: SMB2 command id
8223 * Return: true if packed is signed, false otherwise
8225 bool smb2_is_sign_req(struct ksmbd_work *work, unsigned int command)
8227 struct smb2_hdr *rcv_hdr2 = smb2_get_msg(work->request_buf);
8229 if ((rcv_hdr2->Flags & SMB2_FLAGS_SIGNED) &&
8230 command != SMB2_NEGOTIATE_HE &&
8231 command != SMB2_SESSION_SETUP_HE &&
8232 command != SMB2_OPLOCK_BREAK_HE)
8239 * smb2_check_sign_req() - handler for req packet sign processing
8240 * @work: smb work containing notify command buffer
8242 * Return: 1 on success, 0 otherwise
8244 int smb2_check_sign_req(struct ksmbd_work *work)
8246 struct smb2_hdr *hdr;
8247 char signature_req[SMB2_SIGNATURE_SIZE];
8248 char signature[SMB2_HMACSHA256_SIZE];
8252 hdr = smb2_get_msg(work->request_buf);
8253 if (work->next_smb2_rcv_hdr_off)
8254 hdr = ksmbd_req_buf_next(work);
8256 if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8257 len = get_rfc1002_len(work->request_buf);
8258 else if (hdr->NextCommand)
8259 len = le32_to_cpu(hdr->NextCommand);
8261 len = get_rfc1002_len(work->request_buf) -
8262 work->next_smb2_rcv_hdr_off;
8264 memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8265 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8267 iov[0].iov_base = (char *)&hdr->ProtocolId;
8268 iov[0].iov_len = len;
8270 if (ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, 1,
8274 if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8275 pr_err("bad smb2 signature\n");
8283 * smb2_set_sign_rsp() - handler for rsp packet sign processing
8284 * @work: smb work containing notify command buffer
8287 void smb2_set_sign_rsp(struct ksmbd_work *work)
8289 struct smb2_hdr *hdr;
8290 struct smb2_hdr *req_hdr;
8291 char signature[SMB2_HMACSHA256_SIZE];
8296 hdr = smb2_get_msg(work->response_buf);
8297 if (work->next_smb2_rsp_hdr_off)
8298 hdr = ksmbd_resp_buf_next(work);
8300 req_hdr = ksmbd_req_buf_next(work);
8302 if (!work->next_smb2_rsp_hdr_off) {
8303 len = get_rfc1002_len(work->response_buf);
8304 if (req_hdr->NextCommand)
8305 len = ALIGN(len, 8);
8307 len = get_rfc1002_len(work->response_buf) -
8308 work->next_smb2_rsp_hdr_off;
8309 len = ALIGN(len, 8);
8312 if (req_hdr->NextCommand)
8313 hdr->NextCommand = cpu_to_le32(len);
8315 hdr->Flags |= SMB2_FLAGS_SIGNED;
8316 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8318 iov[0].iov_base = (char *)&hdr->ProtocolId;
8319 iov[0].iov_len = len;
8321 if (work->aux_payload_sz) {
8322 iov[0].iov_len -= work->aux_payload_sz;
8324 iov[1].iov_base = work->aux_payload_buf;
8325 iov[1].iov_len = work->aux_payload_sz;
8329 if (!ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, n_vec,
8331 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
8335 * smb3_check_sign_req() - handler for req packet sign processing
8336 * @work: smb work containing notify command buffer
8338 * Return: 1 on success, 0 otherwise
8340 int smb3_check_sign_req(struct ksmbd_work *work)
8342 struct ksmbd_conn *conn = work->conn;
8344 struct smb2_hdr *hdr;
8345 struct channel *chann;
8346 char signature_req[SMB2_SIGNATURE_SIZE];
8347 char signature[SMB2_CMACAES_SIZE];
8351 hdr = smb2_get_msg(work->request_buf);
8352 if (work->next_smb2_rcv_hdr_off)
8353 hdr = ksmbd_req_buf_next(work);
8355 if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8356 len = get_rfc1002_len(work->request_buf);
8357 else if (hdr->NextCommand)
8358 len = le32_to_cpu(hdr->NextCommand);
8360 len = get_rfc1002_len(work->request_buf) -
8361 work->next_smb2_rcv_hdr_off;
8363 if (le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8364 signing_key = work->sess->smb3signingkey;
8366 chann = lookup_chann_list(work->sess, conn);
8369 signing_key = chann->smb3signingkey;
8373 pr_err("SMB3 signing key is not generated\n");
8377 memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8378 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8379 iov[0].iov_base = (char *)&hdr->ProtocolId;
8380 iov[0].iov_len = len;
8382 if (ksmbd_sign_smb3_pdu(conn, signing_key, iov, 1, signature))
8385 if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8386 pr_err("bad smb2 signature\n");
8394 * smb3_set_sign_rsp() - handler for rsp packet sign processing
8395 * @work: smb work containing notify command buffer
8398 void smb3_set_sign_rsp(struct ksmbd_work *work)
8400 struct ksmbd_conn *conn = work->conn;
8401 struct smb2_hdr *req_hdr, *hdr;
8402 struct channel *chann;
8403 char signature[SMB2_CMACAES_SIZE];
8409 hdr = smb2_get_msg(work->response_buf);
8410 if (work->next_smb2_rsp_hdr_off)
8411 hdr = ksmbd_resp_buf_next(work);
8413 req_hdr = ksmbd_req_buf_next(work);
8415 if (!work->next_smb2_rsp_hdr_off) {
8416 len = get_rfc1002_len(work->response_buf);
8417 if (req_hdr->NextCommand)
8418 len = ALIGN(len, 8);
8420 len = get_rfc1002_len(work->response_buf) -
8421 work->next_smb2_rsp_hdr_off;
8422 len = ALIGN(len, 8);
8425 if (conn->binding == false &&
8426 le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8427 signing_key = work->sess->smb3signingkey;
8429 chann = lookup_chann_list(work->sess, work->conn);
8432 signing_key = chann->smb3signingkey;
8438 if (req_hdr->NextCommand)
8439 hdr->NextCommand = cpu_to_le32(len);
8441 hdr->Flags |= SMB2_FLAGS_SIGNED;
8442 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8443 iov[0].iov_base = (char *)&hdr->ProtocolId;
8444 iov[0].iov_len = len;
8445 if (work->aux_payload_sz) {
8446 iov[0].iov_len -= work->aux_payload_sz;
8447 iov[1].iov_base = work->aux_payload_buf;
8448 iov[1].iov_len = work->aux_payload_sz;
8452 if (!ksmbd_sign_smb3_pdu(conn, signing_key, iov, n_vec, signature))
8453 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
8457 * smb3_preauth_hash_rsp() - handler for computing preauth hash on response
8458 * @work: smb work containing response buffer
8461 void smb3_preauth_hash_rsp(struct ksmbd_work *work)
8463 struct ksmbd_conn *conn = work->conn;
8464 struct ksmbd_session *sess = work->sess;
8465 struct smb2_hdr *req, *rsp;
8467 if (conn->dialect != SMB311_PROT_ID)
8470 WORK_BUFFERS(work, req, rsp);
8472 if (le16_to_cpu(req->Command) == SMB2_NEGOTIATE_HE &&
8474 ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
8475 conn->preauth_info->Preauth_HashValue);
8477 if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE && sess) {
8480 if (conn->binding) {
8481 struct preauth_session *preauth_sess;
8483 preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
8486 hash_value = preauth_sess->Preauth_HashValue;
8488 hash_value = sess->Preauth_HashValue;
8492 ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
8497 static void fill_transform_hdr(void *tr_buf, char *old_buf, __le16 cipher_type)
8499 struct smb2_transform_hdr *tr_hdr = tr_buf + 4;
8500 struct smb2_hdr *hdr = smb2_get_msg(old_buf);
8501 unsigned int orig_len = get_rfc1002_len(old_buf);
8503 memset(tr_buf, 0, sizeof(struct smb2_transform_hdr) + 4);
8504 tr_hdr->ProtocolId = SMB2_TRANSFORM_PROTO_NUM;
8505 tr_hdr->OriginalMessageSize = cpu_to_le32(orig_len);
8506 tr_hdr->Flags = cpu_to_le16(TRANSFORM_FLAG_ENCRYPTED);
8507 if (cipher_type == SMB2_ENCRYPTION_AES128_GCM ||
8508 cipher_type == SMB2_ENCRYPTION_AES256_GCM)
8509 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_GCM_NONCE);
8511 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_CCM_NONCE);
8512 memcpy(&tr_hdr->SessionId, &hdr->SessionId, 8);
8513 inc_rfc1001_len(tr_buf, sizeof(struct smb2_transform_hdr));
8514 inc_rfc1001_len(tr_buf, orig_len);
8517 int smb3_encrypt_resp(struct ksmbd_work *work)
8519 char *buf = work->response_buf;
8522 int buf_size = 0, rq_nvec = 2 + (work->aux_payload_sz ? 1 : 0);
8524 if (ARRAY_SIZE(iov) < rq_nvec)
8527 work->tr_buf = kzalloc(sizeof(struct smb2_transform_hdr) + 4, GFP_KERNEL);
8531 /* fill transform header */
8532 fill_transform_hdr(work->tr_buf, buf, work->conn->cipher_type);
8534 iov[0].iov_base = work->tr_buf;
8535 iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
8536 buf_size += iov[0].iov_len - 4;
8538 iov[1].iov_base = buf + 4;
8539 iov[1].iov_len = get_rfc1002_len(buf);
8540 if (work->aux_payload_sz) {
8541 iov[1].iov_len = work->resp_hdr_sz - 4;
8543 iov[2].iov_base = work->aux_payload_buf;
8544 iov[2].iov_len = work->aux_payload_sz;
8545 buf_size += iov[2].iov_len;
8547 buf_size += iov[1].iov_len;
8548 work->resp_hdr_sz = iov[1].iov_len;
8550 rc = ksmbd_crypt_message(work->conn, iov, rq_nvec, 1);
8554 memmove(buf, iov[1].iov_base, iov[1].iov_len);
8555 *(__be32 *)work->tr_buf = cpu_to_be32(buf_size);
8560 bool smb3_is_transform_hdr(void *buf)
8562 struct smb2_transform_hdr *trhdr = smb2_get_msg(buf);
8564 return trhdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM;
8567 int smb3_decrypt_req(struct ksmbd_work *work)
8569 struct ksmbd_conn *conn = work->conn;
8570 struct ksmbd_session *sess;
8571 char *buf = work->request_buf;
8572 unsigned int pdu_length = get_rfc1002_len(buf);
8574 int buf_data_size = pdu_length - sizeof(struct smb2_transform_hdr);
8575 struct smb2_transform_hdr *tr_hdr = smb2_get_msg(buf);
8578 if (buf_data_size < sizeof(struct smb2_hdr)) {
8579 pr_err("Transform message is too small (%u)\n",
8581 return -ECONNABORTED;
8584 if (buf_data_size < le32_to_cpu(tr_hdr->OriginalMessageSize)) {
8585 pr_err("Transform message is broken\n");
8586 return -ECONNABORTED;
8589 sess = ksmbd_session_lookup_all(conn, le64_to_cpu(tr_hdr->SessionId));
8591 pr_err("invalid session id(%llx) in transform header\n",
8592 le64_to_cpu(tr_hdr->SessionId));
8593 return -ECONNABORTED;
8596 iov[0].iov_base = buf;
8597 iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
8598 iov[1].iov_base = buf + sizeof(struct smb2_transform_hdr) + 4;
8599 iov[1].iov_len = buf_data_size;
8600 rc = ksmbd_crypt_message(conn, iov, 2, 0);
8604 memmove(buf + 4, iov[1].iov_base, buf_data_size);
8605 *(__be32 *)buf = cpu_to_be32(buf_data_size);
8610 bool smb3_11_final_sess_setup_resp(struct ksmbd_work *work)
8612 struct ksmbd_conn *conn = work->conn;
8613 struct smb2_hdr *rsp = smb2_get_msg(work->response_buf);
8615 if (conn->dialect < SMB30_PROT_ID)
8618 if (work->next_smb2_rcv_hdr_off)
8619 rsp = ksmbd_resp_buf_next(work);
8621 if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE &&
8622 rsp->Status == STATUS_SUCCESS)