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) {
380 work->compound_fid = ((struct smb2_create_rsp *)rsp)->VolatileFileId;
381 work->compound_pfid = ((struct smb2_create_rsp *)rsp)->PersistentFileId;
382 work->compound_sid = le64_to_cpu(rsp->SessionId);
385 len = get_rfc1002_len(work->response_buf) - work->next_smb2_rsp_hdr_off;
386 next_hdr_offset = le32_to_cpu(req->NextCommand);
388 new_len = ALIGN(len, 8);
389 inc_rfc1001_len(work->response_buf,
390 sizeof(struct smb2_hdr) + new_len - len);
391 rsp->NextCommand = cpu_to_le32(new_len);
393 work->next_smb2_rcv_hdr_off += next_hdr_offset;
394 work->next_smb2_rsp_hdr_off += new_len;
396 "Compound req new_len = %d rcv off = %d rsp off = %d\n",
397 new_len, work->next_smb2_rcv_hdr_off,
398 work->next_smb2_rsp_hdr_off);
400 rsp_hdr = ksmbd_resp_buf_next(work);
401 rcv_hdr = ksmbd_req_buf_next(work);
403 if (!(rcv_hdr->Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
404 ksmbd_debug(SMB, "related flag should be set\n");
405 work->compound_fid = KSMBD_NO_FID;
406 work->compound_pfid = KSMBD_NO_FID;
408 memset((char *)rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
409 rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
410 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
411 rsp_hdr->Command = rcv_hdr->Command;
414 * Message is response. We don't grant oplock yet.
416 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR |
417 SMB2_FLAGS_RELATED_OPERATIONS);
418 rsp_hdr->NextCommand = 0;
419 rsp_hdr->MessageId = rcv_hdr->MessageId;
420 rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
421 rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
422 rsp_hdr->SessionId = rcv_hdr->SessionId;
423 memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);
427 * is_chained_smb2_message() - check for chained command
428 * @work: smb work containing smb request buffer
430 * Return: true if chained request, otherwise false
432 bool is_chained_smb2_message(struct ksmbd_work *work)
434 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
435 unsigned int len, next_cmd;
437 if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
440 hdr = ksmbd_req_buf_next(work);
441 next_cmd = le32_to_cpu(hdr->NextCommand);
443 if ((u64)work->next_smb2_rcv_hdr_off + next_cmd +
444 __SMB2_HEADER_STRUCTURE_SIZE >
445 get_rfc1002_len(work->request_buf)) {
446 pr_err("next command(%u) offset exceeds smb msg size\n",
451 if ((u64)get_rfc1002_len(work->response_buf) + MAX_CIFS_SMALL_BUFFER_SIZE >
453 pr_err("next response offset exceeds response buffer size\n");
457 ksmbd_debug(SMB, "got SMB2 chained command\n");
458 init_chained_smb2_rsp(work);
460 } else if (work->next_smb2_rcv_hdr_off) {
462 * This is last request in chained command,
463 * align response to 8 byte
465 len = ALIGN(get_rfc1002_len(work->response_buf), 8);
466 len = len - get_rfc1002_len(work->response_buf);
468 ksmbd_debug(SMB, "padding len %u\n", len);
469 inc_rfc1001_len(work->response_buf, len);
470 if (work->aux_payload_sz)
471 work->aux_payload_sz += len;
478 * init_smb2_rsp_hdr() - initialize smb2 response
479 * @work: smb work containing smb request buffer
483 int init_smb2_rsp_hdr(struct ksmbd_work *work)
485 struct smb2_hdr *rsp_hdr = smb2_get_msg(work->response_buf);
486 struct smb2_hdr *rcv_hdr = smb2_get_msg(work->request_buf);
487 struct ksmbd_conn *conn = work->conn;
489 memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
490 *(__be32 *)work->response_buf =
491 cpu_to_be32(conn->vals->header_size);
492 rsp_hdr->ProtocolId = rcv_hdr->ProtocolId;
493 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
494 rsp_hdr->Command = rcv_hdr->Command;
497 * Message is response. We don't grant oplock yet.
499 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
500 rsp_hdr->NextCommand = 0;
501 rsp_hdr->MessageId = rcv_hdr->MessageId;
502 rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
503 rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
504 rsp_hdr->SessionId = rcv_hdr->SessionId;
505 memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);
507 work->syncronous = true;
508 if (work->async_id) {
509 ksmbd_release_id(&conn->async_ida, work->async_id);
517 * smb2_allocate_rsp_buf() - allocate smb2 response buffer
518 * @work: smb work containing smb request buffer
520 * Return: 0 on success, otherwise -ENOMEM
522 int smb2_allocate_rsp_buf(struct ksmbd_work *work)
524 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
525 size_t small_sz = MAX_CIFS_SMALL_BUFFER_SIZE;
526 size_t large_sz = small_sz + work->conn->vals->max_trans_size;
527 size_t sz = small_sz;
528 int cmd = le16_to_cpu(hdr->Command);
530 if (cmd == SMB2_IOCTL_HE || cmd == SMB2_QUERY_DIRECTORY_HE)
533 if (cmd == SMB2_QUERY_INFO_HE) {
534 struct smb2_query_info_req *req;
536 req = smb2_get_msg(work->request_buf);
537 if (req->InfoType == SMB2_O_INFO_FILE &&
538 (req->FileInfoClass == FILE_FULL_EA_INFORMATION ||
539 req->FileInfoClass == FILE_ALL_INFORMATION))
543 /* allocate large response buf for chained commands */
544 if (le32_to_cpu(hdr->NextCommand) > 0)
547 work->response_buf = kvmalloc(sz, GFP_KERNEL | __GFP_ZERO);
548 if (!work->response_buf)
551 work->response_sz = sz;
556 * smb2_check_user_session() - check for valid session for a user
557 * @work: smb work containing smb request buffer
559 * Return: 0 on success, otherwise error
561 int smb2_check_user_session(struct ksmbd_work *work)
563 struct smb2_hdr *req_hdr = smb2_get_msg(work->request_buf);
564 struct ksmbd_conn *conn = work->conn;
565 unsigned int cmd = conn->ops->get_cmd_val(work);
566 unsigned long long sess_id;
570 * SMB2_ECHO, SMB2_NEGOTIATE, SMB2_SESSION_SETUP command do not
571 * require a session id, so no need to validate user session's for
574 if (cmd == SMB2_ECHO_HE || cmd == SMB2_NEGOTIATE_HE ||
575 cmd == SMB2_SESSION_SETUP_HE)
578 if (!ksmbd_conn_good(work))
581 sess_id = le64_to_cpu(req_hdr->SessionId);
582 /* Check for validity of user session */
583 work->sess = ksmbd_session_lookup_all(conn, sess_id);
586 ksmbd_debug(SMB, "Invalid user session, Uid %llu\n", sess_id);
590 static void destroy_previous_session(struct ksmbd_user *user, u64 id)
592 struct ksmbd_session *prev_sess = ksmbd_session_lookup_slowpath(id);
593 struct ksmbd_user *prev_user;
598 prev_user = prev_sess->user;
601 strcmp(user->name, prev_user->name) ||
602 user->passkey_sz != prev_user->passkey_sz ||
603 memcmp(user->passkey, prev_user->passkey, user->passkey_sz)) {
604 put_session(prev_sess);
608 put_session(prev_sess);
609 ksmbd_session_destroy(prev_sess);
613 * smb2_get_name() - get filename string from on the wire smb format
614 * @src: source buffer
615 * @maxlen: maxlen of source string
616 * @local_nls: nls_table pointer
618 * Return: matching converted filename on success, otherwise error ptr
621 smb2_get_name(const char *src, const int maxlen, struct nls_table *local_nls)
625 name = smb_strndup_from_utf16(src, maxlen, 1, local_nls);
627 pr_err("failed to get name %ld\n", PTR_ERR(name));
631 ksmbd_conv_path_to_unix(name);
632 ksmbd_strip_last_slash(name);
636 int setup_async_work(struct ksmbd_work *work, void (*fn)(void **), void **arg)
638 struct smb2_hdr *rsp_hdr;
639 struct ksmbd_conn *conn = work->conn;
642 rsp_hdr = smb2_get_msg(work->response_buf);
643 rsp_hdr->Flags |= SMB2_FLAGS_ASYNC_COMMAND;
645 id = ksmbd_acquire_async_msg_id(&conn->async_ida);
647 pr_err("Failed to alloc async message id\n");
650 work->syncronous = false;
652 rsp_hdr->Id.AsyncId = cpu_to_le64(id);
655 "Send interim Response to inform async request id : %d\n",
658 work->cancel_fn = fn;
659 work->cancel_argv = arg;
661 if (list_empty(&work->async_request_entry)) {
662 spin_lock(&conn->request_lock);
663 list_add_tail(&work->async_request_entry, &conn->async_requests);
664 spin_unlock(&conn->request_lock);
670 void smb2_send_interim_resp(struct ksmbd_work *work, __le32 status)
672 struct smb2_hdr *rsp_hdr;
674 rsp_hdr = smb2_get_msg(work->response_buf);
675 smb2_set_err_rsp(work);
676 rsp_hdr->Status = status;
679 ksmbd_conn_write(work);
684 static __le32 smb2_get_reparse_tag_special_file(umode_t mode)
686 if (S_ISDIR(mode) || S_ISREG(mode))
690 return IO_REPARSE_TAG_LX_SYMLINK_LE;
691 else if (S_ISFIFO(mode))
692 return IO_REPARSE_TAG_LX_FIFO_LE;
693 else if (S_ISSOCK(mode))
694 return IO_REPARSE_TAG_AF_UNIX_LE;
695 else if (S_ISCHR(mode))
696 return IO_REPARSE_TAG_LX_CHR_LE;
697 else if (S_ISBLK(mode))
698 return IO_REPARSE_TAG_LX_BLK_LE;
704 * smb2_get_dos_mode() - get file mode in dos format from unix mode
705 * @stat: kstat containing file mode
706 * @attribute: attribute flags
708 * Return: converted dos mode
710 static int smb2_get_dos_mode(struct kstat *stat, int attribute)
714 if (S_ISDIR(stat->mode)) {
715 attr = FILE_ATTRIBUTE_DIRECTORY |
716 (attribute & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM));
718 attr = (attribute & 0x00005137) | FILE_ATTRIBUTE_ARCHIVE;
719 attr &= ~(FILE_ATTRIBUTE_DIRECTORY);
720 if (S_ISREG(stat->mode) && (server_conf.share_fake_fscaps &
721 FILE_SUPPORTS_SPARSE_FILES))
722 attr |= FILE_ATTRIBUTE_SPARSE_FILE;
724 if (smb2_get_reparse_tag_special_file(stat->mode))
725 attr |= FILE_ATTRIBUTE_REPARSE_POINT;
731 static void build_preauth_ctxt(struct smb2_preauth_neg_context *pneg_ctxt,
734 pneg_ctxt->ContextType = SMB2_PREAUTH_INTEGRITY_CAPABILITIES;
735 pneg_ctxt->DataLength = cpu_to_le16(38);
736 pneg_ctxt->HashAlgorithmCount = cpu_to_le16(1);
737 pneg_ctxt->Reserved = cpu_to_le32(0);
738 pneg_ctxt->SaltLength = cpu_to_le16(SMB311_SALT_SIZE);
739 get_random_bytes(pneg_ctxt->Salt, SMB311_SALT_SIZE);
740 pneg_ctxt->HashAlgorithms = hash_id;
743 static void build_encrypt_ctxt(struct smb2_encryption_neg_context *pneg_ctxt,
746 pneg_ctxt->ContextType = SMB2_ENCRYPTION_CAPABILITIES;
747 pneg_ctxt->DataLength = cpu_to_le16(4);
748 pneg_ctxt->Reserved = cpu_to_le32(0);
749 pneg_ctxt->CipherCount = cpu_to_le16(1);
750 pneg_ctxt->Ciphers[0] = cipher_type;
753 static void build_compression_ctxt(struct smb2_compression_capabilities_context *pneg_ctxt,
756 pneg_ctxt->ContextType = SMB2_COMPRESSION_CAPABILITIES;
757 pneg_ctxt->DataLength =
758 cpu_to_le16(sizeof(struct smb2_compression_capabilities_context)
759 - sizeof(struct smb2_neg_context));
760 pneg_ctxt->Reserved = cpu_to_le32(0);
761 pneg_ctxt->CompressionAlgorithmCount = cpu_to_le16(1);
762 pneg_ctxt->Flags = cpu_to_le32(0);
763 pneg_ctxt->CompressionAlgorithms[0] = comp_algo;
766 static void build_sign_cap_ctxt(struct smb2_signing_capabilities *pneg_ctxt,
769 pneg_ctxt->ContextType = SMB2_SIGNING_CAPABILITIES;
770 pneg_ctxt->DataLength =
771 cpu_to_le16((sizeof(struct smb2_signing_capabilities) + 2)
772 - sizeof(struct smb2_neg_context));
773 pneg_ctxt->Reserved = cpu_to_le32(0);
774 pneg_ctxt->SigningAlgorithmCount = cpu_to_le16(1);
775 pneg_ctxt->SigningAlgorithms[0] = sign_algo;
778 static void build_posix_ctxt(struct smb2_posix_neg_context *pneg_ctxt)
780 pneg_ctxt->ContextType = SMB2_POSIX_EXTENSIONS_AVAILABLE;
781 pneg_ctxt->DataLength = cpu_to_le16(POSIX_CTXT_DATA_LEN);
782 /* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */
783 pneg_ctxt->Name[0] = 0x93;
784 pneg_ctxt->Name[1] = 0xAD;
785 pneg_ctxt->Name[2] = 0x25;
786 pneg_ctxt->Name[3] = 0x50;
787 pneg_ctxt->Name[4] = 0x9C;
788 pneg_ctxt->Name[5] = 0xB4;
789 pneg_ctxt->Name[6] = 0x11;
790 pneg_ctxt->Name[7] = 0xE7;
791 pneg_ctxt->Name[8] = 0xB4;
792 pneg_ctxt->Name[9] = 0x23;
793 pneg_ctxt->Name[10] = 0x83;
794 pneg_ctxt->Name[11] = 0xDE;
795 pneg_ctxt->Name[12] = 0x96;
796 pneg_ctxt->Name[13] = 0x8B;
797 pneg_ctxt->Name[14] = 0xCD;
798 pneg_ctxt->Name[15] = 0x7C;
801 static void assemble_neg_contexts(struct ksmbd_conn *conn,
802 struct smb2_negotiate_rsp *rsp,
805 char *pneg_ctxt = (char *)rsp +
806 le32_to_cpu(rsp->NegotiateContextOffset);
807 int neg_ctxt_cnt = 1;
811 "assemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
812 build_preauth_ctxt((struct smb2_preauth_neg_context *)pneg_ctxt,
813 conn->preauth_info->Preauth_HashId);
814 rsp->NegotiateContextCount = cpu_to_le16(neg_ctxt_cnt);
815 inc_rfc1001_len(smb2_buf_len, AUTH_GSS_PADDING);
816 ctxt_size = sizeof(struct smb2_preauth_neg_context);
817 /* Round to 8 byte boundary */
818 pneg_ctxt += round_up(sizeof(struct smb2_preauth_neg_context), 8);
820 if (conn->cipher_type) {
821 ctxt_size = round_up(ctxt_size, 8);
823 "assemble SMB2_ENCRYPTION_CAPABILITIES context\n");
824 build_encrypt_ctxt((struct smb2_encryption_neg_context *)pneg_ctxt,
826 rsp->NegotiateContextCount = cpu_to_le16(++neg_ctxt_cnt);
827 ctxt_size += sizeof(struct smb2_encryption_neg_context) + 2;
828 /* Round to 8 byte boundary */
830 round_up(sizeof(struct smb2_encryption_neg_context) + 2,
834 if (conn->compress_algorithm) {
835 ctxt_size = round_up(ctxt_size, 8);
837 "assemble SMB2_COMPRESSION_CAPABILITIES context\n");
838 /* Temporarily set to SMB3_COMPRESS_NONE */
839 build_compression_ctxt((struct smb2_compression_capabilities_context *)pneg_ctxt,
840 conn->compress_algorithm);
841 rsp->NegotiateContextCount = cpu_to_le16(++neg_ctxt_cnt);
842 ctxt_size += sizeof(struct smb2_compression_capabilities_context) + 2;
843 /* Round to 8 byte boundary */
844 pneg_ctxt += round_up(sizeof(struct smb2_compression_capabilities_context) + 2,
848 if (conn->posix_ext_supported) {
849 ctxt_size = round_up(ctxt_size, 8);
851 "assemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
852 build_posix_ctxt((struct smb2_posix_neg_context *)pneg_ctxt);
853 rsp->NegotiateContextCount = cpu_to_le16(++neg_ctxt_cnt);
854 ctxt_size += sizeof(struct smb2_posix_neg_context);
855 /* Round to 8 byte boundary */
856 pneg_ctxt += round_up(sizeof(struct smb2_posix_neg_context), 8);
859 if (conn->signing_negotiated) {
860 ctxt_size = round_up(ctxt_size, 8);
862 "assemble SMB2_SIGNING_CAPABILITIES context\n");
863 build_sign_cap_ctxt((struct smb2_signing_capabilities *)pneg_ctxt,
864 conn->signing_algorithm);
865 rsp->NegotiateContextCount = cpu_to_le16(++neg_ctxt_cnt);
866 ctxt_size += sizeof(struct smb2_signing_capabilities) + 2;
869 inc_rfc1001_len(smb2_buf_len, ctxt_size);
872 static __le32 decode_preauth_ctxt(struct ksmbd_conn *conn,
873 struct smb2_preauth_neg_context *pneg_ctxt)
875 __le32 err = STATUS_NO_PREAUTH_INTEGRITY_HASH_OVERLAP;
877 if (pneg_ctxt->HashAlgorithms == SMB2_PREAUTH_INTEGRITY_SHA512) {
878 conn->preauth_info->Preauth_HashId =
879 SMB2_PREAUTH_INTEGRITY_SHA512;
880 err = STATUS_SUCCESS;
886 static void decode_encrypt_ctxt(struct ksmbd_conn *conn,
887 struct smb2_encryption_neg_context *pneg_ctxt,
890 int cph_cnt = le16_to_cpu(pneg_ctxt->CipherCount);
891 int i, cphs_size = cph_cnt * sizeof(__le16);
893 conn->cipher_type = 0;
895 if (sizeof(struct smb2_encryption_neg_context) + cphs_size >
897 pr_err("Invalid cipher count(%d)\n", cph_cnt);
901 if (!(server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION))
904 for (i = 0; i < cph_cnt; i++) {
905 if (pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_GCM ||
906 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_CCM ||
907 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_CCM ||
908 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_GCM) {
909 ksmbd_debug(SMB, "Cipher ID = 0x%x\n",
910 pneg_ctxt->Ciphers[i]);
911 conn->cipher_type = pneg_ctxt->Ciphers[i];
918 * smb3_encryption_negotiated() - checks if server and client agreed on enabling encryption
919 * @conn: smb connection
921 * Return: true if connection should be encrypted, else false
923 static bool smb3_encryption_negotiated(struct ksmbd_conn *conn)
925 if (!conn->ops->generate_encryptionkey)
929 * SMB 3.0 and 3.0.2 dialects use the SMB2_GLOBAL_CAP_ENCRYPTION flag.
930 * SMB 3.1.1 uses the cipher_type field.
932 return (conn->vals->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION) ||
936 static void decode_compress_ctxt(struct ksmbd_conn *conn,
937 struct smb2_compression_capabilities_context *pneg_ctxt)
939 conn->compress_algorithm = SMB3_COMPRESS_NONE;
942 static void decode_sign_cap_ctxt(struct ksmbd_conn *conn,
943 struct smb2_signing_capabilities *pneg_ctxt,
946 int sign_algo_cnt = le16_to_cpu(pneg_ctxt->SigningAlgorithmCount);
947 int i, sign_alos_size = sign_algo_cnt * sizeof(__le16);
949 conn->signing_negotiated = false;
951 if (sizeof(struct smb2_signing_capabilities) + sign_alos_size >
953 pr_err("Invalid signing algorithm count(%d)\n", sign_algo_cnt);
957 for (i = 0; i < sign_algo_cnt; i++) {
958 if (pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_HMAC_SHA256_LE ||
959 pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_AES_CMAC_LE) {
960 ksmbd_debug(SMB, "Signing Algorithm ID = 0x%x\n",
961 pneg_ctxt->SigningAlgorithms[i]);
962 conn->signing_negotiated = true;
963 conn->signing_algorithm =
964 pneg_ctxt->SigningAlgorithms[i];
970 static __le32 deassemble_neg_contexts(struct ksmbd_conn *conn,
971 struct smb2_negotiate_req *req,
974 /* +4 is to account for the RFC1001 len field */
975 struct smb2_neg_context *pctx = (struct smb2_neg_context *)req;
976 int i = 0, len_of_ctxts;
977 int offset = le32_to_cpu(req->NegotiateContextOffset);
978 int neg_ctxt_cnt = le16_to_cpu(req->NegotiateContextCount);
979 __le32 status = STATUS_INVALID_PARAMETER;
981 ksmbd_debug(SMB, "decoding %d negotiate contexts\n", neg_ctxt_cnt);
982 if (len_of_smb <= offset) {
983 ksmbd_debug(SMB, "Invalid response: negotiate context offset\n");
987 len_of_ctxts = len_of_smb - offset;
989 while (i++ < neg_ctxt_cnt) {
992 /* check that offset is not beyond end of SMB */
993 if (len_of_ctxts == 0)
996 if (len_of_ctxts < sizeof(struct smb2_neg_context))
999 pctx = (struct smb2_neg_context *)((char *)pctx + offset);
1000 clen = le16_to_cpu(pctx->DataLength);
1001 if (clen + sizeof(struct smb2_neg_context) > len_of_ctxts)
1004 if (pctx->ContextType == SMB2_PREAUTH_INTEGRITY_CAPABILITIES) {
1006 "deassemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
1007 if (conn->preauth_info->Preauth_HashId)
1010 status = decode_preauth_ctxt(conn,
1011 (struct smb2_preauth_neg_context *)pctx);
1012 if (status != STATUS_SUCCESS)
1014 } else if (pctx->ContextType == SMB2_ENCRYPTION_CAPABILITIES) {
1016 "deassemble SMB2_ENCRYPTION_CAPABILITIES context\n");
1017 if (conn->cipher_type)
1020 decode_encrypt_ctxt(conn,
1021 (struct smb2_encryption_neg_context *)pctx,
1023 } else if (pctx->ContextType == SMB2_COMPRESSION_CAPABILITIES) {
1025 "deassemble SMB2_COMPRESSION_CAPABILITIES context\n");
1026 if (conn->compress_algorithm)
1029 decode_compress_ctxt(conn,
1030 (struct smb2_compression_capabilities_context *)pctx);
1031 } else if (pctx->ContextType == SMB2_NETNAME_NEGOTIATE_CONTEXT_ID) {
1033 "deassemble SMB2_NETNAME_NEGOTIATE_CONTEXT_ID context\n");
1034 } else if (pctx->ContextType == SMB2_POSIX_EXTENSIONS_AVAILABLE) {
1036 "deassemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
1037 conn->posix_ext_supported = true;
1038 } else if (pctx->ContextType == SMB2_SIGNING_CAPABILITIES) {
1040 "deassemble SMB2_SIGNING_CAPABILITIES context\n");
1041 decode_sign_cap_ctxt(conn,
1042 (struct smb2_signing_capabilities *)pctx,
1046 /* offsets must be 8 byte aligned */
1047 clen = (clen + 7) & ~0x7;
1048 offset = clen + sizeof(struct smb2_neg_context);
1049 len_of_ctxts -= clen + sizeof(struct smb2_neg_context);
1055 * smb2_handle_negotiate() - handler for smb2 negotiate command
1056 * @work: smb work containing smb request buffer
1060 int smb2_handle_negotiate(struct ksmbd_work *work)
1062 struct ksmbd_conn *conn = work->conn;
1063 struct smb2_negotiate_req *req = smb2_get_msg(work->request_buf);
1064 struct smb2_negotiate_rsp *rsp = smb2_get_msg(work->response_buf);
1066 unsigned int smb2_buf_len, smb2_neg_size;
1069 ksmbd_debug(SMB, "Received negotiate request\n");
1070 conn->need_neg = false;
1071 if (ksmbd_conn_good(work)) {
1072 pr_err("conn->tcp_status is already in CifsGood State\n");
1073 work->send_no_response = 1;
1077 if (req->DialectCount == 0) {
1078 pr_err("malformed packet\n");
1079 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1084 smb2_buf_len = get_rfc1002_len(work->request_buf);
1085 smb2_neg_size = offsetof(struct smb2_negotiate_req, Dialects);
1086 if (smb2_neg_size > smb2_buf_len) {
1087 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1092 if (conn->dialect == SMB311_PROT_ID) {
1093 unsigned int nego_ctxt_off = le32_to_cpu(req->NegotiateContextOffset);
1095 if (smb2_buf_len < nego_ctxt_off) {
1096 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1101 if (smb2_neg_size > nego_ctxt_off) {
1102 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1107 if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
1109 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1114 if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
1116 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1122 conn->cli_cap = le32_to_cpu(req->Capabilities);
1123 switch (conn->dialect) {
1124 case SMB311_PROT_ID:
1125 conn->preauth_info =
1126 kzalloc(sizeof(struct preauth_integrity_info),
1128 if (!conn->preauth_info) {
1130 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1134 status = deassemble_neg_contexts(conn, req,
1135 get_rfc1002_len(work->request_buf));
1136 if (status != STATUS_SUCCESS) {
1137 pr_err("deassemble_neg_contexts error(0x%x)\n",
1139 rsp->hdr.Status = status;
1144 rc = init_smb3_11_server(conn);
1146 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1150 ksmbd_gen_preauth_integrity_hash(conn,
1152 conn->preauth_info->Preauth_HashValue);
1153 rsp->NegotiateContextOffset =
1154 cpu_to_le32(OFFSET_OF_NEG_CONTEXT);
1155 assemble_neg_contexts(conn, rsp, work->response_buf);
1157 case SMB302_PROT_ID:
1158 init_smb3_02_server(conn);
1161 init_smb3_0_server(conn);
1164 init_smb2_1_server(conn);
1169 ksmbd_debug(SMB, "Server dialect :0x%x not supported\n",
1171 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
1175 rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
1178 conn->connection_type = conn->dialect;
1180 rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
1181 rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
1182 rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);
1184 memcpy(conn->ClientGUID, req->ClientGUID,
1185 SMB2_CLIENT_GUID_SIZE);
1186 conn->cli_sec_mode = le16_to_cpu(req->SecurityMode);
1188 rsp->StructureSize = cpu_to_le16(65);
1189 rsp->DialectRevision = cpu_to_le16(conn->dialect);
1190 /* Not setting conn guid rsp->ServerGUID, as it
1191 * not used by client for identifying server
1193 memset(rsp->ServerGUID, 0, SMB2_CLIENT_GUID_SIZE);
1195 rsp->SystemTime = cpu_to_le64(ksmbd_systime());
1196 rsp->ServerStartTime = 0;
1197 ksmbd_debug(SMB, "negotiate context offset %d, count %d\n",
1198 le32_to_cpu(rsp->NegotiateContextOffset),
1199 le16_to_cpu(rsp->NegotiateContextCount));
1201 rsp->SecurityBufferOffset = cpu_to_le16(128);
1202 rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
1203 ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) +
1204 le16_to_cpu(rsp->SecurityBufferOffset));
1205 inc_rfc1001_len(work->response_buf, sizeof(struct smb2_negotiate_rsp) -
1206 sizeof(struct smb2_hdr) - sizeof(rsp->Buffer) +
1208 rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
1209 conn->use_spnego = true;
1211 if ((server_conf.signing == KSMBD_CONFIG_OPT_AUTO ||
1212 server_conf.signing == KSMBD_CONFIG_OPT_DISABLED) &&
1213 req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED_LE)
1215 else if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY) {
1216 server_conf.enforced_signing = true;
1217 rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
1221 conn->srv_sec_mode = le16_to_cpu(rsp->SecurityMode);
1222 ksmbd_conn_set_need_negotiate(work);
1226 smb2_set_err_rsp(work);
1231 static int alloc_preauth_hash(struct ksmbd_session *sess,
1232 struct ksmbd_conn *conn)
1234 if (sess->Preauth_HashValue)
1237 sess->Preauth_HashValue = kmemdup(conn->preauth_info->Preauth_HashValue,
1238 PREAUTH_HASHVALUE_SIZE, GFP_KERNEL);
1239 if (!sess->Preauth_HashValue)
1245 static int generate_preauth_hash(struct ksmbd_work *work)
1247 struct ksmbd_conn *conn = work->conn;
1248 struct ksmbd_session *sess = work->sess;
1251 if (conn->dialect != SMB311_PROT_ID)
1254 if (conn->binding) {
1255 struct preauth_session *preauth_sess;
1257 preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
1258 if (!preauth_sess) {
1259 preauth_sess = ksmbd_preauth_session_alloc(conn, sess->id);
1264 preauth_hash = preauth_sess->Preauth_HashValue;
1266 if (!sess->Preauth_HashValue)
1267 if (alloc_preauth_hash(sess, conn))
1269 preauth_hash = sess->Preauth_HashValue;
1272 ksmbd_gen_preauth_integrity_hash(conn, work->request_buf, preauth_hash);
1276 static int decode_negotiation_token(struct ksmbd_conn *conn,
1277 struct negotiate_message *negblob,
1280 if (!conn->use_spnego)
1283 if (ksmbd_decode_negTokenInit((char *)negblob, sz, conn)) {
1284 if (ksmbd_decode_negTokenTarg((char *)negblob, sz, conn)) {
1285 conn->auth_mechs |= KSMBD_AUTH_NTLMSSP;
1286 conn->preferred_auth_mech = KSMBD_AUTH_NTLMSSP;
1287 conn->use_spnego = false;
1293 static int ntlm_negotiate(struct ksmbd_work *work,
1294 struct negotiate_message *negblob,
1297 struct smb2_sess_setup_rsp *rsp = smb2_get_msg(work->response_buf);
1298 struct challenge_message *chgblob;
1299 unsigned char *spnego_blob = NULL;
1300 u16 spnego_blob_len;
1304 ksmbd_debug(SMB, "negotiate phase\n");
1305 rc = ksmbd_decode_ntlmssp_neg_blob(negblob, negblob_len, work->conn);
1309 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1311 (struct challenge_message *)((char *)&rsp->hdr.ProtocolId + sz);
1312 memset(chgblob, 0, sizeof(struct challenge_message));
1314 if (!work->conn->use_spnego) {
1315 sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
1319 rsp->SecurityBufferLength = cpu_to_le16(sz);
1323 sz = sizeof(struct challenge_message);
1324 sz += (strlen(ksmbd_netbios_name()) * 2 + 1 + 4) * 6;
1326 neg_blob = kzalloc(sz, GFP_KERNEL);
1330 chgblob = (struct challenge_message *)neg_blob;
1331 sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
1337 rc = build_spnego_ntlmssp_neg_blob(&spnego_blob, &spnego_blob_len,
1344 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1345 memcpy((char *)&rsp->hdr.ProtocolId + sz, spnego_blob, spnego_blob_len);
1346 rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
1354 static struct authenticate_message *user_authblob(struct ksmbd_conn *conn,
1355 struct smb2_sess_setup_req *req)
1359 if (conn->use_spnego && conn->mechToken)
1360 return (struct authenticate_message *)conn->mechToken;
1362 sz = le16_to_cpu(req->SecurityBufferOffset);
1363 return (struct authenticate_message *)((char *)&req->hdr.ProtocolId
1367 static struct ksmbd_user *session_user(struct ksmbd_conn *conn,
1368 struct smb2_sess_setup_req *req)
1370 struct authenticate_message *authblob;
1371 struct ksmbd_user *user;
1373 unsigned int auth_msg_len, name_off, name_len, secbuf_len;
1375 secbuf_len = le16_to_cpu(req->SecurityBufferLength);
1376 if (secbuf_len < sizeof(struct authenticate_message)) {
1377 ksmbd_debug(SMB, "blob len %d too small\n", secbuf_len);
1380 authblob = user_authblob(conn, req);
1381 name_off = le32_to_cpu(authblob->UserName.BufferOffset);
1382 name_len = le16_to_cpu(authblob->UserName.Length);
1383 auth_msg_len = le16_to_cpu(req->SecurityBufferOffset) + secbuf_len;
1385 if (auth_msg_len < (u64)name_off + name_len)
1388 name = smb_strndup_from_utf16((const char *)authblob + name_off,
1393 pr_err("cannot allocate memory\n");
1397 ksmbd_debug(SMB, "session setup request for user %s\n", name);
1398 user = ksmbd_login_user(name);
1403 static int ntlm_authenticate(struct ksmbd_work *work)
1405 struct smb2_sess_setup_req *req = smb2_get_msg(work->request_buf);
1406 struct smb2_sess_setup_rsp *rsp = smb2_get_msg(work->response_buf);
1407 struct ksmbd_conn *conn = work->conn;
1408 struct ksmbd_session *sess = work->sess;
1409 struct channel *chann = NULL;
1410 struct ksmbd_user *user;
1414 ksmbd_debug(SMB, "authenticate phase\n");
1415 if (conn->use_spnego) {
1416 unsigned char *spnego_blob;
1417 u16 spnego_blob_len;
1419 rc = build_spnego_ntlmssp_auth_blob(&spnego_blob,
1425 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1426 memcpy((char *)&rsp->hdr.ProtocolId + sz, spnego_blob, spnego_blob_len);
1427 rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
1429 inc_rfc1001_len(work->response_buf, spnego_blob_len - 1);
1432 user = session_user(conn, req);
1434 ksmbd_debug(SMB, "Unknown user name or an error\n");
1438 /* Check for previous session */
1439 prev_id = le64_to_cpu(req->PreviousSessionId);
1440 if (prev_id && prev_id != sess->id)
1441 destroy_previous_session(user, prev_id);
1443 if (sess->state == SMB2_SESSION_VALID) {
1445 * Reuse session if anonymous try to connect
1446 * on reauthetication.
1448 if (ksmbd_anonymous_user(user)) {
1449 ksmbd_free_user(user);
1453 if (!ksmbd_compare_user(sess->user, user)) {
1454 ksmbd_free_user(user);
1457 ksmbd_free_user(user);
1462 if (user_guest(sess->user)) {
1463 rsp->SessionFlags = SMB2_SESSION_FLAG_IS_GUEST_LE;
1465 struct authenticate_message *authblob;
1467 authblob = user_authblob(conn, req);
1468 sz = le16_to_cpu(req->SecurityBufferLength);
1469 rc = ksmbd_decode_ntlmssp_auth_blob(authblob, sz, conn, sess);
1471 set_user_flag(sess->user, KSMBD_USER_FLAG_BAD_PASSWORD);
1472 ksmbd_debug(SMB, "authentication failed\n");
1478 * If session state is SMB2_SESSION_VALID, We can assume
1479 * that it is reauthentication. And the user/password
1480 * has been verified, so return it here.
1482 if (sess->state == SMB2_SESSION_VALID) {
1484 goto binding_session;
1488 if ((rsp->SessionFlags != SMB2_SESSION_FLAG_IS_GUEST_LE &&
1489 (conn->sign || server_conf.enforced_signing)) ||
1490 (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
1493 if (smb3_encryption_negotiated(conn) &&
1494 !(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1495 rc = conn->ops->generate_encryptionkey(sess);
1498 "SMB3 encryption key generation failed\n");
1502 rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
1504 * signing is disable if encryption is enable
1511 if (conn->dialect >= SMB30_PROT_ID) {
1512 chann = lookup_chann_list(sess, conn);
1514 chann = kmalloc(sizeof(struct channel), GFP_KERNEL);
1519 INIT_LIST_HEAD(&chann->chann_list);
1520 list_add(&chann->chann_list, &sess->ksmbd_chann_list);
1524 if (conn->ops->generate_signingkey) {
1525 rc = conn->ops->generate_signingkey(sess, conn);
1527 ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
1532 if (!ksmbd_conn_lookup_dialect(conn)) {
1533 pr_err("fail to verify the dialect\n");
1539 #ifdef CONFIG_SMB_SERVER_KERBEROS5
1540 static int krb5_authenticate(struct ksmbd_work *work)
1542 struct smb2_sess_setup_req *req = smb2_get_msg(work->request_buf);
1543 struct smb2_sess_setup_rsp *rsp = smb2_get_msg(work->response_buf);
1544 struct ksmbd_conn *conn = work->conn;
1545 struct ksmbd_session *sess = work->sess;
1546 char *in_blob, *out_blob;
1547 struct channel *chann = NULL;
1549 int in_len, out_len;
1552 in_blob = (char *)&req->hdr.ProtocolId +
1553 le16_to_cpu(req->SecurityBufferOffset);
1554 in_len = le16_to_cpu(req->SecurityBufferLength);
1555 out_blob = (char *)&rsp->hdr.ProtocolId +
1556 le16_to_cpu(rsp->SecurityBufferOffset);
1557 out_len = work->response_sz -
1558 (le16_to_cpu(rsp->SecurityBufferOffset) + 4);
1560 /* Check previous session */
1561 prev_sess_id = le64_to_cpu(req->PreviousSessionId);
1562 if (prev_sess_id && prev_sess_id != sess->id)
1563 destroy_previous_session(sess->user, prev_sess_id);
1565 if (sess->state == SMB2_SESSION_VALID)
1566 ksmbd_free_user(sess->user);
1568 retval = ksmbd_krb5_authenticate(sess, in_blob, in_len,
1569 out_blob, &out_len);
1571 ksmbd_debug(SMB, "krb5 authentication failed\n");
1574 rsp->SecurityBufferLength = cpu_to_le16(out_len);
1575 inc_rfc1001_len(work->response_buf, out_len - 1);
1577 if ((conn->sign || server_conf.enforced_signing) ||
1578 (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
1581 if (smb3_encryption_negotiated(conn)) {
1582 retval = conn->ops->generate_encryptionkey(sess);
1585 "SMB3 encryption key generation failed\n");
1589 rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
1593 if (conn->dialect >= SMB30_PROT_ID) {
1594 chann = lookup_chann_list(sess, conn);
1596 chann = kmalloc(sizeof(struct channel), GFP_KERNEL);
1601 INIT_LIST_HEAD(&chann->chann_list);
1602 list_add(&chann->chann_list, &sess->ksmbd_chann_list);
1606 if (conn->ops->generate_signingkey) {
1607 retval = conn->ops->generate_signingkey(sess, conn);
1609 ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
1614 if (!ksmbd_conn_lookup_dialect(conn)) {
1615 pr_err("fail to verify the dialect\n");
1621 static int krb5_authenticate(struct ksmbd_work *work)
1627 int smb2_sess_setup(struct ksmbd_work *work)
1629 struct ksmbd_conn *conn = work->conn;
1630 struct smb2_sess_setup_req *req = smb2_get_msg(work->request_buf);
1631 struct smb2_sess_setup_rsp *rsp = smb2_get_msg(work->response_buf);
1632 struct ksmbd_session *sess;
1633 struct negotiate_message *negblob;
1634 unsigned int negblob_len, negblob_off;
1637 ksmbd_debug(SMB, "Received request for session setup\n");
1639 rsp->StructureSize = cpu_to_le16(9);
1640 rsp->SessionFlags = 0;
1641 rsp->SecurityBufferOffset = cpu_to_le16(72);
1642 rsp->SecurityBufferLength = 0;
1643 inc_rfc1001_len(work->response_buf, 9);
1645 if (!req->hdr.SessionId) {
1646 sess = ksmbd_smb2_session_create();
1651 rsp->hdr.SessionId = cpu_to_le64(sess->id);
1652 ksmbd_session_register(conn, sess);
1653 } else if (conn->dialect >= SMB30_PROT_ID &&
1654 (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
1655 req->Flags & SMB2_SESSION_REQ_FLAG_BINDING) {
1656 u64 sess_id = le64_to_cpu(req->hdr.SessionId);
1658 sess = ksmbd_session_lookup_slowpath(sess_id);
1664 if (conn->dialect != sess->conn->dialect) {
1669 if (!(req->hdr.Flags & SMB2_FLAGS_SIGNED)) {
1674 if (strncmp(conn->ClientGUID, sess->conn->ClientGUID,
1675 SMB2_CLIENT_GUID_SIZE)) {
1680 if (sess->state == SMB2_SESSION_IN_PROGRESS) {
1685 if (sess->state == SMB2_SESSION_EXPIRED) {
1690 if (ksmbd_session_lookup(conn, sess_id)) {
1695 conn->binding = true;
1696 } else if ((conn->dialect < SMB30_PROT_ID ||
1697 server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
1698 (req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1703 sess = ksmbd_session_lookup(conn,
1704 le64_to_cpu(req->hdr.SessionId));
1712 if (sess->state == SMB2_SESSION_EXPIRED)
1713 sess->state = SMB2_SESSION_IN_PROGRESS;
1715 negblob_off = le16_to_cpu(req->SecurityBufferOffset);
1716 negblob_len = le16_to_cpu(req->SecurityBufferLength);
1717 if (negblob_off < offsetof(struct smb2_sess_setup_req, Buffer) ||
1718 negblob_len < offsetof(struct negotiate_message, NegotiateFlags)) {
1723 negblob = (struct negotiate_message *)((char *)&req->hdr.ProtocolId +
1726 if (decode_negotiation_token(conn, negblob, negblob_len) == 0) {
1727 if (conn->mechToken)
1728 negblob = (struct negotiate_message *)conn->mechToken;
1731 if (server_conf.auth_mechs & conn->auth_mechs) {
1732 rc = generate_preauth_hash(work);
1736 if (conn->preferred_auth_mech &
1737 (KSMBD_AUTH_KRB5 | KSMBD_AUTH_MSKRB5)) {
1738 rc = krb5_authenticate(work);
1744 ksmbd_conn_set_good(work);
1745 sess->state = SMB2_SESSION_VALID;
1746 kfree(sess->Preauth_HashValue);
1747 sess->Preauth_HashValue = NULL;
1748 } else if (conn->preferred_auth_mech == KSMBD_AUTH_NTLMSSP) {
1749 if (negblob->MessageType == NtLmNegotiate) {
1750 rc = ntlm_negotiate(work, negblob, negblob_len);
1754 STATUS_MORE_PROCESSING_REQUIRED;
1756 * Note: here total size -1 is done as an
1757 * adjustment for 0 size blob
1759 inc_rfc1001_len(work->response_buf,
1760 le16_to_cpu(rsp->SecurityBufferLength) - 1);
1762 } else if (negblob->MessageType == NtLmAuthenticate) {
1763 rc = ntlm_authenticate(work);
1767 ksmbd_conn_set_good(work);
1768 sess->state = SMB2_SESSION_VALID;
1769 if (conn->binding) {
1770 struct preauth_session *preauth_sess;
1773 ksmbd_preauth_session_lookup(conn, sess->id);
1775 list_del(&preauth_sess->preauth_entry);
1776 kfree(preauth_sess);
1779 kfree(sess->Preauth_HashValue);
1780 sess->Preauth_HashValue = NULL;
1783 /* TODO: need one more negotiation */
1784 pr_err("Not support the preferred authentication\n");
1788 pr_err("Not support authentication\n");
1794 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1795 else if (rc == -ENOENT)
1796 rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
1797 else if (rc == -EACCES)
1798 rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
1799 else if (rc == -EFAULT)
1800 rsp->hdr.Status = STATUS_NETWORK_SESSION_EXPIRED;
1801 else if (rc == -ENOMEM)
1802 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
1804 rsp->hdr.Status = STATUS_LOGON_FAILURE;
1806 if (conn->use_spnego && conn->mechToken) {
1807 kfree(conn->mechToken);
1808 conn->mechToken = NULL;
1813 * SecurityBufferOffset should be set to zero
1814 * in session setup error response.
1816 rsp->SecurityBufferOffset = 0;
1819 bool try_delay = false;
1822 * To avoid dictionary attacks (repeated session setups rapidly sent) to
1823 * connect to server, ksmbd make a delay of a 5 seconds on session setup
1824 * failure to make it harder to send enough random connection requests
1825 * to break into a server.
1827 if (sess->user && sess->user->flags & KSMBD_USER_FLAG_DELAY_SESSION)
1830 ksmbd_session_destroy(sess);
1841 * smb2_tree_connect() - handler for smb2 tree connect command
1842 * @work: smb work containing smb request buffer
1844 * Return: 0 on success, otherwise error
1846 int smb2_tree_connect(struct ksmbd_work *work)
1848 struct ksmbd_conn *conn = work->conn;
1849 struct smb2_tree_connect_req *req = smb2_get_msg(work->request_buf);
1850 struct smb2_tree_connect_rsp *rsp = smb2_get_msg(work->response_buf);
1851 struct ksmbd_session *sess = work->sess;
1852 char *treename = NULL, *name = NULL;
1853 struct ksmbd_tree_conn_status status;
1854 struct ksmbd_share_config *share;
1857 treename = smb_strndup_from_utf16(req->Buffer,
1858 le16_to_cpu(req->PathLength), true,
1860 if (IS_ERR(treename)) {
1861 pr_err("treename is NULL\n");
1862 status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
1866 name = ksmbd_extract_sharename(treename);
1868 status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
1872 ksmbd_debug(SMB, "tree connect request for tree %s treename %s\n",
1875 status = ksmbd_tree_conn_connect(sess, name);
1876 if (status.ret == KSMBD_TREE_CONN_STATUS_OK)
1877 rsp->hdr.Id.SyncId.TreeId = cpu_to_le32(status.tree_conn->id);
1881 share = status.tree_conn->share_conf;
1882 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
1883 ksmbd_debug(SMB, "IPC share path request\n");
1884 rsp->ShareType = SMB2_SHARE_TYPE_PIPE;
1885 rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
1886 FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE |
1887 FILE_DELETE_LE | FILE_READ_CONTROL_LE |
1888 FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
1889 FILE_SYNCHRONIZE_LE;
1891 rsp->ShareType = SMB2_SHARE_TYPE_DISK;
1892 rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
1893 FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE;
1894 if (test_tree_conn_flag(status.tree_conn,
1895 KSMBD_TREE_CONN_FLAG_WRITABLE)) {
1896 rsp->MaximalAccess |= FILE_WRITE_DATA_LE |
1897 FILE_APPEND_DATA_LE | FILE_WRITE_EA_LE |
1898 FILE_DELETE_LE | FILE_WRITE_ATTRIBUTES_LE |
1899 FILE_DELETE_CHILD_LE | FILE_READ_CONTROL_LE |
1900 FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
1901 FILE_SYNCHRONIZE_LE;
1905 status.tree_conn->maximal_access = le32_to_cpu(rsp->MaximalAccess);
1906 if (conn->posix_ext_supported)
1907 status.tree_conn->posix_extensions = true;
1910 rsp->StructureSize = cpu_to_le16(16);
1911 rsp->Capabilities = 0;
1913 /* default manual caching */
1914 rsp->ShareFlags = SMB2_SHAREFLAG_MANUAL_CACHING;
1915 inc_rfc1001_len(work->response_buf, 16);
1917 if (!IS_ERR(treename))
1922 switch (status.ret) {
1923 case KSMBD_TREE_CONN_STATUS_OK:
1924 rsp->hdr.Status = STATUS_SUCCESS;
1927 case KSMBD_TREE_CONN_STATUS_NO_SHARE:
1928 rsp->hdr.Status = STATUS_BAD_NETWORK_PATH;
1931 case KSMBD_TREE_CONN_STATUS_NOMEM:
1932 rsp->hdr.Status = STATUS_NO_MEMORY;
1934 case KSMBD_TREE_CONN_STATUS_ERROR:
1935 case KSMBD_TREE_CONN_STATUS_TOO_MANY_CONNS:
1936 case KSMBD_TREE_CONN_STATUS_TOO_MANY_SESSIONS:
1937 rsp->hdr.Status = STATUS_ACCESS_DENIED;
1940 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1943 rsp->hdr.Status = STATUS_ACCESS_DENIED;
1950 * smb2_create_open_flags() - convert smb open flags to unix open flags
1951 * @file_present: is file already present
1952 * @access: file access flags
1953 * @disposition: file disposition flags
1954 * @may_flags: set with MAY_ flags
1956 * Return: file open flags
1958 static int smb2_create_open_flags(bool file_present, __le32 access,
1962 int oflags = O_NONBLOCK | O_LARGEFILE;
1964 if (access & FILE_READ_DESIRED_ACCESS_LE &&
1965 access & FILE_WRITE_DESIRE_ACCESS_LE) {
1967 *may_flags = MAY_OPEN | MAY_READ | MAY_WRITE;
1968 } else if (access & FILE_WRITE_DESIRE_ACCESS_LE) {
1970 *may_flags = MAY_OPEN | MAY_WRITE;
1973 *may_flags = MAY_OPEN | MAY_READ;
1976 if (access == FILE_READ_ATTRIBUTES_LE)
1980 switch (disposition & FILE_CREATE_MASK_LE) {
1982 case FILE_CREATE_LE:
1984 case FILE_SUPERSEDE_LE:
1985 case FILE_OVERWRITE_LE:
1986 case FILE_OVERWRITE_IF_LE:
1993 switch (disposition & FILE_CREATE_MASK_LE) {
1994 case FILE_SUPERSEDE_LE:
1995 case FILE_CREATE_LE:
1996 case FILE_OPEN_IF_LE:
1997 case FILE_OVERWRITE_IF_LE:
2001 case FILE_OVERWRITE_LE:
2013 * smb2_tree_disconnect() - handler for smb tree connect request
2014 * @work: smb work containing request buffer
2018 int smb2_tree_disconnect(struct ksmbd_work *work)
2020 struct smb2_tree_disconnect_rsp *rsp = smb2_get_msg(work->response_buf);
2021 struct ksmbd_session *sess = work->sess;
2022 struct ksmbd_tree_connect *tcon = work->tcon;
2024 rsp->StructureSize = cpu_to_le16(4);
2025 inc_rfc1001_len(work->response_buf, 4);
2027 ksmbd_debug(SMB, "request\n");
2030 struct smb2_tree_disconnect_req *req =
2031 smb2_get_msg(work->request_buf);
2033 ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
2034 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2035 smb2_set_err_rsp(work);
2039 ksmbd_close_tree_conn_fds(work);
2040 ksmbd_tree_conn_disconnect(sess, tcon);
2045 * smb2_session_logoff() - handler for session log off request
2046 * @work: smb work containing request buffer
2050 int smb2_session_logoff(struct ksmbd_work *work)
2052 struct ksmbd_conn *conn = work->conn;
2053 struct smb2_logoff_rsp *rsp = smb2_get_msg(work->response_buf);
2054 struct ksmbd_session *sess = work->sess;
2056 rsp->StructureSize = cpu_to_le16(4);
2057 inc_rfc1001_len(work->response_buf, 4);
2059 ksmbd_debug(SMB, "request\n");
2061 /* setting CifsExiting here may race with start_tcp_sess */
2062 ksmbd_conn_set_need_reconnect(work);
2063 ksmbd_close_session_fds(work);
2064 ksmbd_conn_wait_idle(conn);
2066 if (ksmbd_tree_conn_session_logoff(sess)) {
2067 struct smb2_logoff_req *req = smb2_get_msg(work->request_buf);
2069 ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
2070 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2071 smb2_set_err_rsp(work);
2075 ksmbd_destroy_file_table(&sess->file_table);
2076 sess->state = SMB2_SESSION_EXPIRED;
2078 ksmbd_free_user(sess->user);
2081 /* let start_tcp_sess free connection info now */
2082 ksmbd_conn_set_need_negotiate(work);
2087 * create_smb2_pipe() - create IPC pipe
2088 * @work: smb work containing request buffer
2090 * Return: 0 on success, otherwise error
2092 static noinline int create_smb2_pipe(struct ksmbd_work *work)
2094 struct smb2_create_rsp *rsp = smb2_get_msg(work->response_buf);
2095 struct smb2_create_req *req = smb2_get_msg(work->request_buf);
2100 name = smb_strndup_from_utf16(req->Buffer, le16_to_cpu(req->NameLength),
2101 1, work->conn->local_nls);
2103 rsp->hdr.Status = STATUS_NO_MEMORY;
2104 err = PTR_ERR(name);
2108 id = ksmbd_session_rpc_open(work->sess, name);
2110 pr_err("Unable to open RPC pipe: %d\n", id);
2115 rsp->hdr.Status = STATUS_SUCCESS;
2116 rsp->StructureSize = cpu_to_le16(89);
2117 rsp->OplockLevel = SMB2_OPLOCK_LEVEL_NONE;
2119 rsp->CreateAction = cpu_to_le32(FILE_OPENED);
2121 rsp->CreationTime = cpu_to_le64(0);
2122 rsp->LastAccessTime = cpu_to_le64(0);
2123 rsp->ChangeTime = cpu_to_le64(0);
2124 rsp->AllocationSize = cpu_to_le64(0);
2125 rsp->EndofFile = cpu_to_le64(0);
2126 rsp->FileAttributes = FILE_ATTRIBUTE_NORMAL_LE;
2128 rsp->VolatileFileId = id;
2129 rsp->PersistentFileId = 0;
2130 rsp->CreateContextsOffset = 0;
2131 rsp->CreateContextsLength = 0;
2133 inc_rfc1001_len(work->response_buf, 88); /* StructureSize - 1*/
2140 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2144 rsp->hdr.Status = STATUS_NO_MEMORY;
2151 smb2_set_err_rsp(work);
2156 * smb2_set_ea() - handler for setting extended attributes using set
2158 * @eabuf: set info command buffer
2159 * @buf_len: set info command buffer length
2160 * @path: dentry path for get ea
2162 * Return: 0 on success, otherwise error
2164 static int smb2_set_ea(struct smb2_ea_info *eabuf, unsigned int buf_len,
2167 struct user_namespace *user_ns = mnt_user_ns(path->mnt);
2168 char *attr_name = NULL, *value;
2170 unsigned int next = 0;
2172 if (buf_len < sizeof(struct smb2_ea_info) + eabuf->EaNameLength +
2173 le16_to_cpu(eabuf->EaValueLength))
2176 attr_name = kmalloc(XATTR_NAME_MAX + 1, GFP_KERNEL);
2181 if (!eabuf->EaNameLength)
2185 "name : <%s>, name_len : %u, value_len : %u, next : %u\n",
2186 eabuf->name, eabuf->EaNameLength,
2187 le16_to_cpu(eabuf->EaValueLength),
2188 le32_to_cpu(eabuf->NextEntryOffset));
2190 if (eabuf->EaNameLength >
2191 (XATTR_NAME_MAX - XATTR_USER_PREFIX_LEN)) {
2196 memcpy(attr_name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN);
2197 memcpy(&attr_name[XATTR_USER_PREFIX_LEN], eabuf->name,
2198 eabuf->EaNameLength);
2199 attr_name[XATTR_USER_PREFIX_LEN + eabuf->EaNameLength] = '\0';
2200 value = (char *)&eabuf->name + eabuf->EaNameLength + 1;
2202 if (!eabuf->EaValueLength) {
2203 rc = ksmbd_vfs_casexattr_len(user_ns,
2206 XATTR_USER_PREFIX_LEN +
2207 eabuf->EaNameLength);
2209 /* delete the EA only when it exits */
2211 rc = ksmbd_vfs_remove_xattr(user_ns,
2217 "remove xattr failed(%d)\n",
2223 /* if the EA doesn't exist, just do nothing. */
2226 rc = ksmbd_vfs_setxattr(user_ns,
2227 path->dentry, attr_name, value,
2228 le16_to_cpu(eabuf->EaValueLength), 0);
2231 "ksmbd_vfs_setxattr is failed(%d)\n",
2238 next = le32_to_cpu(eabuf->NextEntryOffset);
2239 if (next == 0 || buf_len < next)
2242 eabuf = (struct smb2_ea_info *)((char *)eabuf + next);
2243 if (next < (u32)eabuf->EaNameLength + le16_to_cpu(eabuf->EaValueLength))
2246 } while (next != 0);
2252 static noinline int smb2_set_stream_name_xattr(struct path *path,
2253 struct ksmbd_file *fp,
2254 char *stream_name, int s_type)
2256 struct user_namespace *user_ns = mnt_user_ns(path->mnt);
2257 size_t xattr_stream_size;
2258 char *xattr_stream_name;
2261 rc = ksmbd_vfs_xattr_stream_name(stream_name,
2268 fp->stream.name = xattr_stream_name;
2269 fp->stream.size = xattr_stream_size;
2271 /* Check if there is stream prefix in xattr space */
2272 rc = ksmbd_vfs_casexattr_len(user_ns,
2279 if (fp->cdoption == FILE_OPEN_LE) {
2280 ksmbd_debug(SMB, "XATTR stream name lookup failed: %d\n", rc);
2284 rc = ksmbd_vfs_setxattr(user_ns, path->dentry,
2285 xattr_stream_name, NULL, 0, 0);
2287 pr_err("Failed to store XATTR stream name :%d\n", rc);
2291 static int smb2_remove_smb_xattrs(struct path *path)
2293 struct user_namespace *user_ns = mnt_user_ns(path->mnt);
2294 char *name, *xattr_list = NULL;
2295 ssize_t xattr_list_len;
2298 xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
2299 if (xattr_list_len < 0) {
2301 } else if (!xattr_list_len) {
2302 ksmbd_debug(SMB, "empty xattr in the file\n");
2306 for (name = xattr_list; name - xattr_list < xattr_list_len;
2307 name += strlen(name) + 1) {
2308 ksmbd_debug(SMB, "%s, len %zd\n", name, strlen(name));
2310 if (strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN) &&
2311 strncmp(&name[XATTR_USER_PREFIX_LEN], DOS_ATTRIBUTE_PREFIX,
2312 DOS_ATTRIBUTE_PREFIX_LEN) &&
2313 strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX, STREAM_PREFIX_LEN))
2316 err = ksmbd_vfs_remove_xattr(user_ns, path->dentry, name);
2318 ksmbd_debug(SMB, "remove xattr failed : %s\n", name);
2325 static int smb2_create_truncate(struct path *path)
2327 int rc = vfs_truncate(path, 0);
2330 pr_err("vfs_truncate failed, rc %d\n", rc);
2334 rc = smb2_remove_smb_xattrs(path);
2335 if (rc == -EOPNOTSUPP)
2339 "ksmbd_truncate_stream_name_xattr failed, rc %d\n",
2344 static void smb2_new_xattrs(struct ksmbd_tree_connect *tcon, struct path *path,
2345 struct ksmbd_file *fp)
2347 struct xattr_dos_attrib da = {0};
2350 if (!test_share_config_flag(tcon->share_conf,
2351 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2355 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
2356 da.itime = da.create_time = fp->create_time;
2357 da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
2358 XATTR_DOSINFO_ITIME;
2360 rc = ksmbd_vfs_set_dos_attrib_xattr(mnt_user_ns(path->mnt),
2363 ksmbd_debug(SMB, "failed to store file attribute into xattr\n");
2366 static void smb2_update_xattrs(struct ksmbd_tree_connect *tcon,
2367 struct path *path, struct ksmbd_file *fp)
2369 struct xattr_dos_attrib da;
2372 fp->f_ci->m_fattr &= ~(FILE_ATTRIBUTE_HIDDEN_LE | FILE_ATTRIBUTE_SYSTEM_LE);
2374 /* get FileAttributes from XATTR_NAME_DOS_ATTRIBUTE */
2375 if (!test_share_config_flag(tcon->share_conf,
2376 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2379 rc = ksmbd_vfs_get_dos_attrib_xattr(mnt_user_ns(path->mnt),
2382 fp->f_ci->m_fattr = cpu_to_le32(da.attr);
2383 fp->create_time = da.create_time;
2384 fp->itime = da.itime;
2388 static int smb2_creat(struct ksmbd_work *work, struct path *path, char *name,
2389 int open_flags, umode_t posix_mode, bool is_dir)
2391 struct ksmbd_tree_connect *tcon = work->tcon;
2392 struct ksmbd_share_config *share = tcon->share_conf;
2396 if (!(open_flags & O_CREAT))
2399 ksmbd_debug(SMB, "file does not exist, so creating\n");
2400 if (is_dir == true) {
2401 ksmbd_debug(SMB, "creating directory\n");
2403 mode = share_config_directory_mode(share, posix_mode);
2404 rc = ksmbd_vfs_mkdir(work, name, mode);
2408 ksmbd_debug(SMB, "creating regular file\n");
2410 mode = share_config_create_mode(share, posix_mode);
2411 rc = ksmbd_vfs_create(work, name, mode);
2416 rc = ksmbd_vfs_kern_path(work, name, 0, path, 0);
2418 pr_err("cannot get linux path (%s), err = %d\n",
2425 static int smb2_create_sd_buffer(struct ksmbd_work *work,
2426 struct smb2_create_req *req,
2429 struct create_context *context;
2430 struct create_sd_buf_req *sd_buf;
2432 if (!req->CreateContextsOffset)
2435 /* Parse SD BUFFER create contexts */
2436 context = smb2_find_context_vals(req, SMB2_CREATE_SD_BUFFER);
2439 else if (IS_ERR(context))
2440 return PTR_ERR(context);
2443 "Set ACLs using SMB2_CREATE_SD_BUFFER context\n");
2444 sd_buf = (struct create_sd_buf_req *)context;
2445 if (le16_to_cpu(context->DataOffset) +
2446 le32_to_cpu(context->DataLength) <
2447 sizeof(struct create_sd_buf_req))
2449 return set_info_sec(work->conn, work->tcon, path, &sd_buf->ntsd,
2450 le32_to_cpu(sd_buf->ccontext.DataLength), true);
2453 static void ksmbd_acls_fattr(struct smb_fattr *fattr,
2454 struct user_namespace *mnt_userns,
2455 struct inode *inode)
2457 fattr->cf_uid = i_uid_into_mnt(mnt_userns, inode);
2458 fattr->cf_gid = i_gid_into_mnt(mnt_userns, inode);
2459 fattr->cf_mode = inode->i_mode;
2460 fattr->cf_acls = NULL;
2461 fattr->cf_dacls = NULL;
2463 if (IS_ENABLED(CONFIG_FS_POSIX_ACL)) {
2464 fattr->cf_acls = get_acl(inode, ACL_TYPE_ACCESS);
2465 if (S_ISDIR(inode->i_mode))
2466 fattr->cf_dacls = get_acl(inode, ACL_TYPE_DEFAULT);
2471 * smb2_open() - handler for smb file open request
2472 * @work: smb work containing request buffer
2474 * Return: 0 on success, otherwise error
2476 int smb2_open(struct ksmbd_work *work)
2478 struct ksmbd_conn *conn = work->conn;
2479 struct ksmbd_session *sess = work->sess;
2480 struct ksmbd_tree_connect *tcon = work->tcon;
2481 struct smb2_create_req *req;
2482 struct smb2_create_rsp *rsp;
2484 struct ksmbd_share_config *share = tcon->share_conf;
2485 struct ksmbd_file *fp = NULL;
2486 struct file *filp = NULL;
2487 struct user_namespace *user_ns = NULL;
2489 struct create_context *context;
2490 struct lease_ctx_info *lc = NULL;
2491 struct create_ea_buf_req *ea_buf = NULL;
2492 struct oplock_info *opinfo;
2493 __le32 *next_ptr = NULL;
2494 int req_op_level = 0, open_flags = 0, may_flags = 0, file_info = 0;
2496 int contxt_cnt = 0, query_disk_id = 0;
2497 int maximal_access_ctxt = 0, posix_ctxt = 0;
2501 char *stream_name = NULL;
2502 bool file_present = false, created = false, already_permitted = false;
2503 int share_ret, need_truncate = 0;
2505 umode_t posix_mode = 0;
2506 __le32 daccess, maximal_access = 0;
2508 WORK_BUFFERS(work, req, rsp);
2510 if (req->hdr.NextCommand && !work->next_smb2_rcv_hdr_off &&
2511 (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
2512 ksmbd_debug(SMB, "invalid flag in chained command\n");
2513 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2514 smb2_set_err_rsp(work);
2518 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
2519 ksmbd_debug(SMB, "IPC pipe create request\n");
2520 return create_smb2_pipe(work);
2523 if (req->NameLength) {
2524 if ((req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
2525 *(char *)req->Buffer == '\\') {
2526 pr_err("not allow directory name included leading slash\n");
2531 name = smb2_get_name(req->Buffer,
2532 le16_to_cpu(req->NameLength),
2533 work->conn->local_nls);
2542 ksmbd_debug(SMB, "converted name = %s\n", name);
2543 if (strchr(name, ':')) {
2544 if (!test_share_config_flag(work->tcon->share_conf,
2545 KSMBD_SHARE_FLAG_STREAMS)) {
2549 rc = parse_stream_name(name, &stream_name, &s_type);
2554 rc = ksmbd_validate_filename(name);
2558 if (ksmbd_share_veto_filename(share, name)) {
2560 ksmbd_debug(SMB, "Reject open(), vetoed file: %s\n",
2565 name = kstrdup("", GFP_KERNEL);
2572 req_op_level = req->RequestedOplockLevel;
2573 if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE)
2574 lc = parse_lease_state(req);
2576 if (le32_to_cpu(req->ImpersonationLevel) > le32_to_cpu(IL_DELEGATE)) {
2577 pr_err("Invalid impersonationlevel : 0x%x\n",
2578 le32_to_cpu(req->ImpersonationLevel));
2580 rsp->hdr.Status = STATUS_BAD_IMPERSONATION_LEVEL;
2584 if (req->CreateOptions && !(req->CreateOptions & CREATE_OPTIONS_MASK_LE)) {
2585 pr_err("Invalid create options : 0x%x\n",
2586 le32_to_cpu(req->CreateOptions));
2590 if (req->CreateOptions & FILE_SEQUENTIAL_ONLY_LE &&
2591 req->CreateOptions & FILE_RANDOM_ACCESS_LE)
2592 req->CreateOptions = ~(FILE_SEQUENTIAL_ONLY_LE);
2594 if (req->CreateOptions &
2595 (FILE_OPEN_BY_FILE_ID_LE | CREATE_TREE_CONNECTION |
2596 FILE_RESERVE_OPFILTER_LE)) {
2601 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
2602 if (req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE) {
2605 } else if (req->CreateOptions & FILE_NO_COMPRESSION_LE) {
2606 req->CreateOptions = ~(FILE_NO_COMPRESSION_LE);
2611 if (le32_to_cpu(req->CreateDisposition) >
2612 le32_to_cpu(FILE_OVERWRITE_IF_LE)) {
2613 pr_err("Invalid create disposition : 0x%x\n",
2614 le32_to_cpu(req->CreateDisposition));
2619 if (!(req->DesiredAccess & DESIRED_ACCESS_MASK)) {
2620 pr_err("Invalid desired access : 0x%x\n",
2621 le32_to_cpu(req->DesiredAccess));
2626 if (req->FileAttributes && !(req->FileAttributes & FILE_ATTRIBUTE_MASK_LE)) {
2627 pr_err("Invalid file attribute : 0x%x\n",
2628 le32_to_cpu(req->FileAttributes));
2633 if (req->CreateContextsOffset) {
2634 /* Parse non-durable handle create contexts */
2635 context = smb2_find_context_vals(req, SMB2_CREATE_EA_BUFFER);
2636 if (IS_ERR(context)) {
2637 rc = PTR_ERR(context);
2639 } else if (context) {
2640 ea_buf = (struct create_ea_buf_req *)context;
2641 if (le16_to_cpu(context->DataOffset) +
2642 le32_to_cpu(context->DataLength) <
2643 sizeof(struct create_ea_buf_req)) {
2647 if (req->CreateOptions & FILE_NO_EA_KNOWLEDGE_LE) {
2648 rsp->hdr.Status = STATUS_ACCESS_DENIED;
2654 context = smb2_find_context_vals(req,
2655 SMB2_CREATE_QUERY_MAXIMAL_ACCESS_REQUEST);
2656 if (IS_ERR(context)) {
2657 rc = PTR_ERR(context);
2659 } else if (context) {
2661 "get query maximal access context\n");
2662 maximal_access_ctxt = 1;
2665 context = smb2_find_context_vals(req,
2666 SMB2_CREATE_TIMEWARP_REQUEST);
2667 if (IS_ERR(context)) {
2668 rc = PTR_ERR(context);
2670 } else if (context) {
2671 ksmbd_debug(SMB, "get timewarp context\n");
2676 if (tcon->posix_extensions) {
2677 context = smb2_find_context_vals(req,
2678 SMB2_CREATE_TAG_POSIX);
2679 if (IS_ERR(context)) {
2680 rc = PTR_ERR(context);
2682 } else if (context) {
2683 struct create_posix *posix =
2684 (struct create_posix *)context;
2685 if (le16_to_cpu(context->DataOffset) +
2686 le32_to_cpu(context->DataLength) <
2687 sizeof(struct create_posix) - 4) {
2691 ksmbd_debug(SMB, "get posix context\n");
2693 posix_mode = le32_to_cpu(posix->Mode);
2699 if (ksmbd_override_fsids(work)) {
2704 rc = ksmbd_vfs_kern_path(work, name, LOOKUP_NO_SYMLINKS, &path, 1);
2706 if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE) {
2708 * If file exists with under flags, return access
2711 if (req->CreateDisposition == FILE_OVERWRITE_IF_LE ||
2712 req->CreateDisposition == FILE_OPEN_IF_LE) {
2718 if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
2720 "User does not have write permission\n");
2725 } else if (d_is_symlink(path.dentry)) {
2735 ksmbd_debug(SMB, "can not get linux path for %s, rc = %d\n",
2739 file_present = true;
2740 user_ns = mnt_user_ns(path.mnt);
2741 generic_fillattr(user_ns, d_inode(path.dentry), &stat);
2744 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
2745 if (s_type == DATA_STREAM) {
2747 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2750 if (S_ISDIR(stat.mode) && s_type == DATA_STREAM) {
2752 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
2756 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE &&
2757 req->FileAttributes & FILE_ATTRIBUTE_NORMAL_LE) {
2758 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2766 if (file_present && req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE &&
2767 S_ISDIR(stat.mode) && !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2768 ksmbd_debug(SMB, "open() argument is a directory: %s, %x\n",
2769 name, req->CreateOptions);
2770 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
2775 if (file_present && (req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
2776 !(req->CreateDisposition == FILE_CREATE_LE) &&
2777 !S_ISDIR(stat.mode)) {
2778 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2783 if (!stream_name && file_present &&
2784 req->CreateDisposition == FILE_CREATE_LE) {
2789 daccess = smb_map_generic_desired_access(req->DesiredAccess);
2791 if (file_present && !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2792 rc = smb_check_perm_dacl(conn, &path, &daccess,
2798 if (daccess & FILE_MAXIMAL_ACCESS_LE) {
2799 if (!file_present) {
2800 daccess = cpu_to_le32(GENERIC_ALL_FLAGS);
2802 rc = ksmbd_vfs_query_maximal_access(user_ns,
2807 already_permitted = true;
2809 maximal_access = daccess;
2812 open_flags = smb2_create_open_flags(file_present, daccess,
2813 req->CreateDisposition,
2816 if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
2817 if (open_flags & O_CREAT) {
2819 "User does not have write permission\n");
2825 /*create file if not present */
2826 if (!file_present) {
2827 rc = smb2_creat(work, &path, name, open_flags, posix_mode,
2828 req->CreateOptions & FILE_DIRECTORY_FILE_LE);
2830 if (rc == -ENOENT) {
2832 rsp->hdr.Status = STATUS_OBJECT_PATH_NOT_FOUND;
2838 user_ns = mnt_user_ns(path.mnt);
2840 if (le32_to_cpu(ea_buf->ccontext.DataLength) <
2841 sizeof(struct smb2_ea_info)) {
2846 rc = smb2_set_ea(&ea_buf->ea,
2847 le32_to_cpu(ea_buf->ccontext.DataLength),
2849 if (rc == -EOPNOTSUPP)
2854 } else if (!already_permitted) {
2855 /* FILE_READ_ATTRIBUTE is allowed without inode_permission,
2856 * because execute(search) permission on a parent directory,
2857 * is already granted.
2859 if (daccess & ~(FILE_READ_ATTRIBUTES_LE | FILE_READ_CONTROL_LE)) {
2860 rc = inode_permission(user_ns,
2861 d_inode(path.dentry),
2866 if ((daccess & FILE_DELETE_LE) ||
2867 (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2868 rc = ksmbd_vfs_may_delete(user_ns,
2876 rc = ksmbd_query_inode_status(d_inode(path.dentry->d_parent));
2877 if (rc == KSMBD_INODE_STATUS_PENDING_DELETE) {
2883 filp = dentry_open(&path, open_flags, current_cred());
2886 pr_err("dentry open for dir failed, rc %d\n", rc);
2891 if (!(open_flags & O_TRUNC))
2892 file_info = FILE_OPENED;
2894 file_info = FILE_OVERWRITTEN;
2896 if ((req->CreateDisposition & FILE_CREATE_MASK_LE) ==
2898 file_info = FILE_SUPERSEDED;
2899 } else if (open_flags & O_CREAT) {
2900 file_info = FILE_CREATED;
2903 ksmbd_vfs_set_fadvise(filp, req->CreateOptions);
2905 /* Obtain Volatile-ID */
2906 fp = ksmbd_open_fd(work, filp);
2914 /* Get Persistent-ID */
2915 ksmbd_open_durable_fd(fp);
2916 if (!has_file_id(fp->persistent_id)) {
2921 fp->filename = name;
2922 fp->cdoption = req->CreateDisposition;
2923 fp->daccess = daccess;
2924 fp->saccess = req->ShareAccess;
2925 fp->coption = req->CreateOptions;
2927 /* Set default windows and posix acls if creating new file */
2930 struct inode *inode = d_inode(path.dentry);
2932 posix_acl_rc = ksmbd_vfs_inherit_posix_acl(user_ns,
2934 d_inode(path.dentry->d_parent));
2936 ksmbd_debug(SMB, "inherit posix acl failed : %d\n", posix_acl_rc);
2938 if (test_share_config_flag(work->tcon->share_conf,
2939 KSMBD_SHARE_FLAG_ACL_XATTR)) {
2940 rc = smb_inherit_dacl(conn, &path, sess->user->uid,
2945 rc = smb2_create_sd_buffer(work, req, &path);
2948 ksmbd_vfs_set_init_posix_acl(user_ns,
2951 if (test_share_config_flag(work->tcon->share_conf,
2952 KSMBD_SHARE_FLAG_ACL_XATTR)) {
2953 struct smb_fattr fattr;
2954 struct smb_ntsd *pntsd;
2955 int pntsd_size, ace_num = 0;
2957 ksmbd_acls_fattr(&fattr, user_ns, inode);
2959 ace_num = fattr.cf_acls->a_count;
2961 ace_num += fattr.cf_dacls->a_count;
2963 pntsd = kmalloc(sizeof(struct smb_ntsd) +
2964 sizeof(struct smb_sid) * 3 +
2965 sizeof(struct smb_acl) +
2966 sizeof(struct smb_ace) * ace_num * 2,
2971 rc = build_sec_desc(user_ns,
2976 &pntsd_size, &fattr);
2977 posix_acl_release(fattr.cf_acls);
2978 posix_acl_release(fattr.cf_dacls);
2984 rc = ksmbd_vfs_set_sd_xattr(conn,
2991 pr_err("failed to store ntacl in xattr : %d\n",
3000 rc = smb2_set_stream_name_xattr(&path,
3006 file_info = FILE_CREATED;
3009 fp->attrib_only = !(req->DesiredAccess & ~(FILE_READ_ATTRIBUTES_LE |
3010 FILE_WRITE_ATTRIBUTES_LE | FILE_SYNCHRONIZE_LE));
3011 if (!S_ISDIR(file_inode(filp)->i_mode) && open_flags & O_TRUNC &&
3012 !fp->attrib_only && !stream_name) {
3013 smb_break_all_oplock(work, fp);
3017 /* fp should be searchable through ksmbd_inode.m_fp_list
3018 * after daccess, saccess, attrib_only, and stream are
3021 write_lock(&fp->f_ci->m_lock);
3022 list_add(&fp->node, &fp->f_ci->m_fp_list);
3023 write_unlock(&fp->f_ci->m_lock);
3025 rc = ksmbd_vfs_getattr(&path, &stat);
3027 generic_fillattr(user_ns, d_inode(path.dentry), &stat);
3031 /* Check delete pending among previous fp before oplock break */
3032 if (ksmbd_inode_pending_delete(fp)) {
3037 share_ret = ksmbd_smb_check_shared_mode(fp->filp, fp);
3038 if (!test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_OPLOCKS) ||
3039 (req_op_level == SMB2_OPLOCK_LEVEL_LEASE &&
3040 !(conn->vals->capabilities & SMB2_GLOBAL_CAP_LEASING))) {
3041 if (share_ret < 0 && !S_ISDIR(file_inode(fp->filp)->i_mode)) {
3046 if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE) {
3047 req_op_level = smb2_map_lease_to_oplock(lc->req_state);
3049 "lease req for(%s) req oplock state 0x%x, lease state 0x%x\n",
3050 name, req_op_level, lc->req_state);
3051 rc = find_same_lease_key(sess, fp->f_ci, lc);
3054 } else if (open_flags == O_RDONLY &&
3055 (req_op_level == SMB2_OPLOCK_LEVEL_BATCH ||
3056 req_op_level == SMB2_OPLOCK_LEVEL_EXCLUSIVE))
3057 req_op_level = SMB2_OPLOCK_LEVEL_II;
3059 rc = smb_grant_oplock(work, req_op_level,
3060 fp->persistent_id, fp,
3061 le32_to_cpu(req->hdr.Id.SyncId.TreeId),
3067 if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)
3068 ksmbd_fd_set_delete_on_close(fp, file_info);
3070 if (need_truncate) {
3071 rc = smb2_create_truncate(&path);
3076 if (req->CreateContextsOffset) {
3077 struct create_alloc_size_req *az_req;
3079 az_req = (struct create_alloc_size_req *)smb2_find_context_vals(req,
3080 SMB2_CREATE_ALLOCATION_SIZE);
3081 if (IS_ERR(az_req)) {
3082 rc = PTR_ERR(az_req);
3084 } else if (az_req) {
3088 if (le16_to_cpu(az_req->ccontext.DataOffset) +
3089 le32_to_cpu(az_req->ccontext.DataLength) <
3090 sizeof(struct create_alloc_size_req)) {
3094 alloc_size = le64_to_cpu(az_req->AllocationSize);
3096 "request smb2 create allocate size : %llu\n",
3098 smb_break_all_levII_oplock(work, fp, 1);
3099 err = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
3103 "vfs_fallocate is failed : %d\n",
3107 context = smb2_find_context_vals(req, SMB2_CREATE_QUERY_ON_DISK_ID);
3108 if (IS_ERR(context)) {
3109 rc = PTR_ERR(context);
3111 } else if (context) {
3112 ksmbd_debug(SMB, "get query on disk id context\n");
3117 if (stat.result_mask & STATX_BTIME)
3118 fp->create_time = ksmbd_UnixTimeToNT(stat.btime);
3120 fp->create_time = ksmbd_UnixTimeToNT(stat.ctime);
3121 if (req->FileAttributes || fp->f_ci->m_fattr == 0)
3123 cpu_to_le32(smb2_get_dos_mode(&stat, le32_to_cpu(req->FileAttributes)));
3126 smb2_update_xattrs(tcon, &path, fp);
3128 smb2_new_xattrs(tcon, &path, fp);
3130 memcpy(fp->client_guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE);
3132 generic_fillattr(user_ns, file_inode(fp->filp),
3135 rsp->StructureSize = cpu_to_le16(89);
3137 opinfo = rcu_dereference(fp->f_opinfo);
3138 rsp->OplockLevel = opinfo != NULL ? opinfo->level : 0;
3141 rsp->CreateAction = cpu_to_le32(file_info);
3142 rsp->CreationTime = cpu_to_le64(fp->create_time);
3143 time = ksmbd_UnixTimeToNT(stat.atime);
3144 rsp->LastAccessTime = cpu_to_le64(time);
3145 time = ksmbd_UnixTimeToNT(stat.mtime);
3146 rsp->LastWriteTime = cpu_to_le64(time);
3147 time = ksmbd_UnixTimeToNT(stat.ctime);
3148 rsp->ChangeTime = cpu_to_le64(time);
3149 rsp->AllocationSize = S_ISDIR(stat.mode) ? 0 :
3150 cpu_to_le64(stat.blocks << 9);
3151 rsp->EndofFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
3152 rsp->FileAttributes = fp->f_ci->m_fattr;
3156 rsp->PersistentFileId = fp->persistent_id;
3157 rsp->VolatileFileId = fp->volatile_id;
3159 rsp->CreateContextsOffset = 0;
3160 rsp->CreateContextsLength = 0;
3161 inc_rfc1001_len(work->response_buf, 88); /* StructureSize - 1*/
3163 /* If lease is request send lease context response */
3164 if (opinfo && opinfo->is_lease) {
3165 struct create_context *lease_ccontext;
3167 ksmbd_debug(SMB, "lease granted on(%s) lease state 0x%x\n",
3168 name, opinfo->o_lease->state);
3169 rsp->OplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
3171 lease_ccontext = (struct create_context *)rsp->Buffer;
3173 create_lease_buf(rsp->Buffer, opinfo->o_lease);
3174 le32_add_cpu(&rsp->CreateContextsLength,
3175 conn->vals->create_lease_size);
3176 inc_rfc1001_len(work->response_buf,
3177 conn->vals->create_lease_size);
3178 next_ptr = &lease_ccontext->Next;
3179 next_off = conn->vals->create_lease_size;
3182 if (maximal_access_ctxt) {
3183 struct create_context *mxac_ccontext;
3185 if (maximal_access == 0)
3186 ksmbd_vfs_query_maximal_access(user_ns,
3189 mxac_ccontext = (struct create_context *)(rsp->Buffer +
3190 le32_to_cpu(rsp->CreateContextsLength));
3192 create_mxac_rsp_buf(rsp->Buffer +
3193 le32_to_cpu(rsp->CreateContextsLength),
3194 le32_to_cpu(maximal_access));
3195 le32_add_cpu(&rsp->CreateContextsLength,
3196 conn->vals->create_mxac_size);
3197 inc_rfc1001_len(work->response_buf,
3198 conn->vals->create_mxac_size);
3200 *next_ptr = cpu_to_le32(next_off);
3201 next_ptr = &mxac_ccontext->Next;
3202 next_off = conn->vals->create_mxac_size;
3205 if (query_disk_id) {
3206 struct create_context *disk_id_ccontext;
3208 disk_id_ccontext = (struct create_context *)(rsp->Buffer +
3209 le32_to_cpu(rsp->CreateContextsLength));
3211 create_disk_id_rsp_buf(rsp->Buffer +
3212 le32_to_cpu(rsp->CreateContextsLength),
3213 stat.ino, tcon->id);
3214 le32_add_cpu(&rsp->CreateContextsLength,
3215 conn->vals->create_disk_id_size);
3216 inc_rfc1001_len(work->response_buf,
3217 conn->vals->create_disk_id_size);
3219 *next_ptr = cpu_to_le32(next_off);
3220 next_ptr = &disk_id_ccontext->Next;
3221 next_off = conn->vals->create_disk_id_size;
3226 create_posix_rsp_buf(rsp->Buffer +
3227 le32_to_cpu(rsp->CreateContextsLength),
3229 le32_add_cpu(&rsp->CreateContextsLength,
3230 conn->vals->create_posix_size);
3231 inc_rfc1001_len(work->response_buf,
3232 conn->vals->create_posix_size);
3234 *next_ptr = cpu_to_le32(next_off);
3237 if (contxt_cnt > 0) {
3238 rsp->CreateContextsOffset =
3239 cpu_to_le32(offsetof(struct smb2_create_rsp, Buffer));
3243 if (file_present || created)
3245 ksmbd_revert_fsids(work);
3249 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
3250 else if (rc == -EOPNOTSUPP)
3251 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
3252 else if (rc == -EACCES || rc == -ESTALE || rc == -EXDEV)
3253 rsp->hdr.Status = STATUS_ACCESS_DENIED;
3254 else if (rc == -ENOENT)
3255 rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
3256 else if (rc == -EPERM)
3257 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
3258 else if (rc == -EBUSY)
3259 rsp->hdr.Status = STATUS_DELETE_PENDING;
3260 else if (rc == -EBADF)
3261 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
3262 else if (rc == -ENOEXEC)
3263 rsp->hdr.Status = STATUS_DUPLICATE_OBJECTID;
3264 else if (rc == -ENXIO)
3265 rsp->hdr.Status = STATUS_NO_SUCH_DEVICE;
3266 else if (rc == -EEXIST)
3267 rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
3268 else if (rc == -EMFILE)
3269 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
3270 if (!rsp->hdr.Status)
3271 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
3273 if (!fp || !fp->filename)
3276 ksmbd_fd_put(work, fp);
3277 smb2_set_err_rsp(work);
3278 ksmbd_debug(SMB, "Error response: %x\n", rsp->hdr.Status);
3286 static int readdir_info_level_struct_sz(int info_level)
3288 switch (info_level) {
3289 case FILE_FULL_DIRECTORY_INFORMATION:
3290 return sizeof(struct file_full_directory_info);
3291 case FILE_BOTH_DIRECTORY_INFORMATION:
3292 return sizeof(struct file_both_directory_info);
3293 case FILE_DIRECTORY_INFORMATION:
3294 return sizeof(struct file_directory_info);
3295 case FILE_NAMES_INFORMATION:
3296 return sizeof(struct file_names_info);
3297 case FILEID_FULL_DIRECTORY_INFORMATION:
3298 return sizeof(struct file_id_full_dir_info);
3299 case FILEID_BOTH_DIRECTORY_INFORMATION:
3300 return sizeof(struct file_id_both_directory_info);
3301 case SMB_FIND_FILE_POSIX_INFO:
3302 return sizeof(struct smb2_posix_info);
3308 static int dentry_name(struct ksmbd_dir_info *d_info, int info_level)
3310 switch (info_level) {
3311 case FILE_FULL_DIRECTORY_INFORMATION:
3313 struct file_full_directory_info *ffdinfo;
3315 ffdinfo = (struct file_full_directory_info *)d_info->rptr;
3316 d_info->rptr += le32_to_cpu(ffdinfo->NextEntryOffset);
3317 d_info->name = ffdinfo->FileName;
3318 d_info->name_len = le32_to_cpu(ffdinfo->FileNameLength);
3321 case FILE_BOTH_DIRECTORY_INFORMATION:
3323 struct file_both_directory_info *fbdinfo;
3325 fbdinfo = (struct file_both_directory_info *)d_info->rptr;
3326 d_info->rptr += le32_to_cpu(fbdinfo->NextEntryOffset);
3327 d_info->name = fbdinfo->FileName;
3328 d_info->name_len = le32_to_cpu(fbdinfo->FileNameLength);
3331 case FILE_DIRECTORY_INFORMATION:
3333 struct file_directory_info *fdinfo;
3335 fdinfo = (struct file_directory_info *)d_info->rptr;
3336 d_info->rptr += le32_to_cpu(fdinfo->NextEntryOffset);
3337 d_info->name = fdinfo->FileName;
3338 d_info->name_len = le32_to_cpu(fdinfo->FileNameLength);
3341 case FILE_NAMES_INFORMATION:
3343 struct file_names_info *fninfo;
3345 fninfo = (struct file_names_info *)d_info->rptr;
3346 d_info->rptr += le32_to_cpu(fninfo->NextEntryOffset);
3347 d_info->name = fninfo->FileName;
3348 d_info->name_len = le32_to_cpu(fninfo->FileNameLength);
3351 case FILEID_FULL_DIRECTORY_INFORMATION:
3353 struct file_id_full_dir_info *dinfo;
3355 dinfo = (struct file_id_full_dir_info *)d_info->rptr;
3356 d_info->rptr += le32_to_cpu(dinfo->NextEntryOffset);
3357 d_info->name = dinfo->FileName;
3358 d_info->name_len = le32_to_cpu(dinfo->FileNameLength);
3361 case FILEID_BOTH_DIRECTORY_INFORMATION:
3363 struct file_id_both_directory_info *fibdinfo;
3365 fibdinfo = (struct file_id_both_directory_info *)d_info->rptr;
3366 d_info->rptr += le32_to_cpu(fibdinfo->NextEntryOffset);
3367 d_info->name = fibdinfo->FileName;
3368 d_info->name_len = le32_to_cpu(fibdinfo->FileNameLength);
3371 case SMB_FIND_FILE_POSIX_INFO:
3373 struct smb2_posix_info *posix_info;
3375 posix_info = (struct smb2_posix_info *)d_info->rptr;
3376 d_info->rptr += le32_to_cpu(posix_info->NextEntryOffset);
3377 d_info->name = posix_info->name;
3378 d_info->name_len = le32_to_cpu(posix_info->name_len);
3387 * smb2_populate_readdir_entry() - encode directory entry in smb2 response
3389 * @conn: connection instance
3390 * @info_level: smb information level
3391 * @d_info: structure included variables for query dir
3392 * @ksmbd_kstat: ksmbd wrapper of dirent stat information
3394 * if directory has many entries, find first can't read it fully.
3395 * find next might be called multiple times to read remaining dir entries
3397 * Return: 0 on success, otherwise error
3399 static int smb2_populate_readdir_entry(struct ksmbd_conn *conn, int info_level,
3400 struct ksmbd_dir_info *d_info,
3401 struct ksmbd_kstat *ksmbd_kstat)
3403 int next_entry_offset = 0;
3407 int struct_sz, rc = 0;
3409 conv_name = ksmbd_convert_dir_info_name(d_info,
3415 /* Somehow the name has only terminating NULL bytes */
3418 goto free_conv_name;
3421 struct_sz = readdir_info_level_struct_sz(info_level) - 1 + conv_len;
3422 next_entry_offset = ALIGN(struct_sz, KSMBD_DIR_INFO_ALIGNMENT);
3423 d_info->last_entry_off_align = next_entry_offset - struct_sz;
3425 if (next_entry_offset > d_info->out_buf_len) {
3426 d_info->out_buf_len = 0;
3428 goto free_conv_name;
3431 kstat = d_info->wptr;
3432 if (info_level != FILE_NAMES_INFORMATION)
3433 kstat = ksmbd_vfs_init_kstat(&d_info->wptr, ksmbd_kstat);
3435 switch (info_level) {
3436 case FILE_FULL_DIRECTORY_INFORMATION:
3438 struct file_full_directory_info *ffdinfo;
3440 ffdinfo = (struct file_full_directory_info *)kstat;
3441 ffdinfo->FileNameLength = cpu_to_le32(conv_len);
3443 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3444 if (ffdinfo->EaSize)
3445 ffdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3446 if (d_info->hide_dot_file && d_info->name[0] == '.')
3447 ffdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3448 memcpy(ffdinfo->FileName, conv_name, conv_len);
3449 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3452 case FILE_BOTH_DIRECTORY_INFORMATION:
3454 struct file_both_directory_info *fbdinfo;
3456 fbdinfo = (struct file_both_directory_info *)kstat;
3457 fbdinfo->FileNameLength = cpu_to_le32(conv_len);
3459 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3460 if (fbdinfo->EaSize)
3461 fbdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3462 fbdinfo->ShortNameLength = 0;
3463 fbdinfo->Reserved = 0;
3464 if (d_info->hide_dot_file && d_info->name[0] == '.')
3465 fbdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3466 memcpy(fbdinfo->FileName, conv_name, conv_len);
3467 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3470 case FILE_DIRECTORY_INFORMATION:
3472 struct file_directory_info *fdinfo;
3474 fdinfo = (struct file_directory_info *)kstat;
3475 fdinfo->FileNameLength = cpu_to_le32(conv_len);
3476 if (d_info->hide_dot_file && d_info->name[0] == '.')
3477 fdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3478 memcpy(fdinfo->FileName, conv_name, conv_len);
3479 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3482 case FILE_NAMES_INFORMATION:
3484 struct file_names_info *fninfo;
3486 fninfo = (struct file_names_info *)kstat;
3487 fninfo->FileNameLength = cpu_to_le32(conv_len);
3488 memcpy(fninfo->FileName, conv_name, conv_len);
3489 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3492 case FILEID_FULL_DIRECTORY_INFORMATION:
3494 struct file_id_full_dir_info *dinfo;
3496 dinfo = (struct file_id_full_dir_info *)kstat;
3497 dinfo->FileNameLength = cpu_to_le32(conv_len);
3499 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3501 dinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3502 dinfo->Reserved = 0;
3503 dinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
3504 if (d_info->hide_dot_file && d_info->name[0] == '.')
3505 dinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3506 memcpy(dinfo->FileName, conv_name, conv_len);
3507 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3510 case FILEID_BOTH_DIRECTORY_INFORMATION:
3512 struct file_id_both_directory_info *fibdinfo;
3514 fibdinfo = (struct file_id_both_directory_info *)kstat;
3515 fibdinfo->FileNameLength = cpu_to_le32(conv_len);
3517 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3518 if (fibdinfo->EaSize)
3519 fibdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3520 fibdinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
3521 fibdinfo->ShortNameLength = 0;
3522 fibdinfo->Reserved = 0;
3523 fibdinfo->Reserved2 = cpu_to_le16(0);
3524 if (d_info->hide_dot_file && d_info->name[0] == '.')
3525 fibdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3526 memcpy(fibdinfo->FileName, conv_name, conv_len);
3527 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3530 case SMB_FIND_FILE_POSIX_INFO:
3532 struct smb2_posix_info *posix_info;
3535 posix_info = (struct smb2_posix_info *)kstat;
3536 posix_info->Ignored = 0;
3537 posix_info->CreationTime = cpu_to_le64(ksmbd_kstat->create_time);
3538 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->ctime);
3539 posix_info->ChangeTime = cpu_to_le64(time);
3540 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->atime);
3541 posix_info->LastAccessTime = cpu_to_le64(time);
3542 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->mtime);
3543 posix_info->LastWriteTime = cpu_to_le64(time);
3544 posix_info->EndOfFile = cpu_to_le64(ksmbd_kstat->kstat->size);
3545 posix_info->AllocationSize = cpu_to_le64(ksmbd_kstat->kstat->blocks << 9);
3546 posix_info->DeviceId = cpu_to_le32(ksmbd_kstat->kstat->rdev);
3547 posix_info->HardLinks = cpu_to_le32(ksmbd_kstat->kstat->nlink);
3548 posix_info->Mode = cpu_to_le32(ksmbd_kstat->kstat->mode);
3549 posix_info->Inode = cpu_to_le64(ksmbd_kstat->kstat->ino);
3550 posix_info->DosAttributes =
3551 S_ISDIR(ksmbd_kstat->kstat->mode) ?
3552 FILE_ATTRIBUTE_DIRECTORY_LE : FILE_ATTRIBUTE_ARCHIVE_LE;
3553 if (d_info->hide_dot_file && d_info->name[0] == '.')
3554 posix_info->DosAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3555 id_to_sid(from_kuid_munged(&init_user_ns, ksmbd_kstat->kstat->uid),
3556 SIDNFS_USER, (struct smb_sid *)&posix_info->SidBuffer[0]);
3557 id_to_sid(from_kgid_munged(&init_user_ns, ksmbd_kstat->kstat->gid),
3558 SIDNFS_GROUP, (struct smb_sid *)&posix_info->SidBuffer[20]);
3559 memcpy(posix_info->name, conv_name, conv_len);
3560 posix_info->name_len = cpu_to_le32(conv_len);
3561 posix_info->NextEntryOffset = cpu_to_le32(next_entry_offset);
3565 } /* switch (info_level) */
3567 d_info->last_entry_offset = d_info->data_count;
3568 d_info->data_count += next_entry_offset;
3569 d_info->out_buf_len -= next_entry_offset;
3570 d_info->wptr += next_entry_offset;
3573 "info_level : %d, buf_len :%d, next_offset : %d, data_count : %d\n",
3574 info_level, d_info->out_buf_len,
3575 next_entry_offset, d_info->data_count);
3582 struct smb2_query_dir_private {
3583 struct ksmbd_work *work;
3584 char *search_pattern;
3585 struct ksmbd_file *dir_fp;
3587 struct ksmbd_dir_info *d_info;
3591 static void lock_dir(struct ksmbd_file *dir_fp)
3593 struct dentry *dir = dir_fp->filp->f_path.dentry;
3595 inode_lock_nested(d_inode(dir), I_MUTEX_PARENT);
3598 static void unlock_dir(struct ksmbd_file *dir_fp)
3600 struct dentry *dir = dir_fp->filp->f_path.dentry;
3602 inode_unlock(d_inode(dir));
3605 static int process_query_dir_entries(struct smb2_query_dir_private *priv)
3607 struct user_namespace *user_ns = file_mnt_user_ns(priv->dir_fp->filp);
3609 struct ksmbd_kstat ksmbd_kstat;
3613 for (i = 0; i < priv->d_info->num_entry; i++) {
3614 struct dentry *dent;
3616 if (dentry_name(priv->d_info, priv->info_level))
3619 lock_dir(priv->dir_fp);
3620 dent = lookup_one(user_ns, priv->d_info->name,
3621 priv->dir_fp->filp->f_path.dentry,
3622 priv->d_info->name_len);
3623 unlock_dir(priv->dir_fp);
3626 ksmbd_debug(SMB, "Cannot lookup `%s' [%ld]\n",
3631 if (unlikely(d_is_negative(dent))) {
3633 ksmbd_debug(SMB, "Negative dentry `%s'\n",
3634 priv->d_info->name);
3638 ksmbd_kstat.kstat = &kstat;
3639 if (priv->info_level != FILE_NAMES_INFORMATION)
3640 ksmbd_vfs_fill_dentry_attrs(priv->work,
3645 rc = smb2_populate_readdir_entry(priv->work->conn,
3656 static int reserve_populate_dentry(struct ksmbd_dir_info *d_info,
3661 int next_entry_offset;
3663 struct_sz = readdir_info_level_struct_sz(info_level);
3664 if (struct_sz == -EOPNOTSUPP)
3667 conv_len = (d_info->name_len + 1) * 2;
3668 next_entry_offset = ALIGN(struct_sz - 1 + conv_len,
3669 KSMBD_DIR_INFO_ALIGNMENT);
3671 if (next_entry_offset > d_info->out_buf_len) {
3672 d_info->out_buf_len = 0;
3676 switch (info_level) {
3677 case FILE_FULL_DIRECTORY_INFORMATION:
3679 struct file_full_directory_info *ffdinfo;
3681 ffdinfo = (struct file_full_directory_info *)d_info->wptr;
3682 memcpy(ffdinfo->FileName, d_info->name, d_info->name_len);
3683 ffdinfo->FileName[d_info->name_len] = 0x00;
3684 ffdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3685 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3688 case FILE_BOTH_DIRECTORY_INFORMATION:
3690 struct file_both_directory_info *fbdinfo;
3692 fbdinfo = (struct file_both_directory_info *)d_info->wptr;
3693 memcpy(fbdinfo->FileName, d_info->name, d_info->name_len);
3694 fbdinfo->FileName[d_info->name_len] = 0x00;
3695 fbdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3696 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3699 case FILE_DIRECTORY_INFORMATION:
3701 struct file_directory_info *fdinfo;
3703 fdinfo = (struct file_directory_info *)d_info->wptr;
3704 memcpy(fdinfo->FileName, d_info->name, d_info->name_len);
3705 fdinfo->FileName[d_info->name_len] = 0x00;
3706 fdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3707 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3710 case FILE_NAMES_INFORMATION:
3712 struct file_names_info *fninfo;
3714 fninfo = (struct file_names_info *)d_info->wptr;
3715 memcpy(fninfo->FileName, d_info->name, d_info->name_len);
3716 fninfo->FileName[d_info->name_len] = 0x00;
3717 fninfo->FileNameLength = cpu_to_le32(d_info->name_len);
3718 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3721 case FILEID_FULL_DIRECTORY_INFORMATION:
3723 struct file_id_full_dir_info *dinfo;
3725 dinfo = (struct file_id_full_dir_info *)d_info->wptr;
3726 memcpy(dinfo->FileName, d_info->name, d_info->name_len);
3727 dinfo->FileName[d_info->name_len] = 0x00;
3728 dinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3729 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3732 case FILEID_BOTH_DIRECTORY_INFORMATION:
3734 struct file_id_both_directory_info *fibdinfo;
3736 fibdinfo = (struct file_id_both_directory_info *)d_info->wptr;
3737 memcpy(fibdinfo->FileName, d_info->name, d_info->name_len);
3738 fibdinfo->FileName[d_info->name_len] = 0x00;
3739 fibdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3740 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3743 case SMB_FIND_FILE_POSIX_INFO:
3745 struct smb2_posix_info *posix_info;
3747 posix_info = (struct smb2_posix_info *)d_info->wptr;
3748 memcpy(posix_info->name, d_info->name, d_info->name_len);
3749 posix_info->name[d_info->name_len] = 0x00;
3750 posix_info->name_len = cpu_to_le32(d_info->name_len);
3751 posix_info->NextEntryOffset =
3752 cpu_to_le32(next_entry_offset);
3755 } /* switch (info_level) */
3757 d_info->num_entry++;
3758 d_info->out_buf_len -= next_entry_offset;
3759 d_info->wptr += next_entry_offset;
3763 static int __query_dir(struct dir_context *ctx, const char *name, int namlen,
3764 loff_t offset, u64 ino, unsigned int d_type)
3766 struct ksmbd_readdir_data *buf;
3767 struct smb2_query_dir_private *priv;
3768 struct ksmbd_dir_info *d_info;
3771 buf = container_of(ctx, struct ksmbd_readdir_data, ctx);
3772 priv = buf->private;
3773 d_info = priv->d_info;
3775 /* dot and dotdot entries are already reserved */
3776 if (!strcmp(".", name) || !strcmp("..", name))
3778 if (ksmbd_share_veto_filename(priv->work->tcon->share_conf, name))
3780 if (!match_pattern(name, namlen, priv->search_pattern))
3783 d_info->name = name;
3784 d_info->name_len = namlen;
3785 rc = reserve_populate_dentry(d_info, priv->info_level);
3788 if (d_info->flags & SMB2_RETURN_SINGLE_ENTRY) {
3789 d_info->out_buf_len = 0;
3795 static void restart_ctx(struct dir_context *ctx)
3800 static int verify_info_level(int info_level)
3802 switch (info_level) {
3803 case FILE_FULL_DIRECTORY_INFORMATION:
3804 case FILE_BOTH_DIRECTORY_INFORMATION:
3805 case FILE_DIRECTORY_INFORMATION:
3806 case FILE_NAMES_INFORMATION:
3807 case FILEID_FULL_DIRECTORY_INFORMATION:
3808 case FILEID_BOTH_DIRECTORY_INFORMATION:
3809 case SMB_FIND_FILE_POSIX_INFO:
3818 static int smb2_calc_max_out_buf_len(struct ksmbd_work *work,
3819 unsigned short hdr2_len,
3820 unsigned int out_buf_len)
3824 if (out_buf_len > work->conn->vals->max_trans_size)
3827 free_len = (int)(work->response_sz -
3828 (get_rfc1002_len(work->response_buf) + 4)) -
3833 return min_t(int, out_buf_len, free_len);
3836 int smb2_query_dir(struct ksmbd_work *work)
3838 struct ksmbd_conn *conn = work->conn;
3839 struct smb2_query_directory_req *req;
3840 struct smb2_query_directory_rsp *rsp;
3841 struct ksmbd_share_config *share = work->tcon->share_conf;
3842 struct ksmbd_file *dir_fp = NULL;
3843 struct ksmbd_dir_info d_info;
3845 char *srch_ptr = NULL;
3846 unsigned char srch_flag;
3848 struct smb2_query_dir_private query_dir_private = {NULL, };
3850 WORK_BUFFERS(work, req, rsp);
3852 if (ksmbd_override_fsids(work)) {
3853 rsp->hdr.Status = STATUS_NO_MEMORY;
3854 smb2_set_err_rsp(work);
3858 rc = verify_info_level(req->FileInformationClass);
3864 dir_fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
3870 if (!(dir_fp->daccess & FILE_LIST_DIRECTORY_LE) ||
3871 inode_permission(file_mnt_user_ns(dir_fp->filp),
3872 file_inode(dir_fp->filp),
3873 MAY_READ | MAY_EXEC)) {
3874 pr_err("no right to enumerate directory (%pd)\n",
3875 dir_fp->filp->f_path.dentry);
3880 if (!S_ISDIR(file_inode(dir_fp->filp)->i_mode)) {
3881 pr_err("can't do query dir for a file\n");
3886 srch_flag = req->Flags;
3887 srch_ptr = smb_strndup_from_utf16(req->Buffer,
3888 le16_to_cpu(req->FileNameLength), 1,
3890 if (IS_ERR(srch_ptr)) {
3891 ksmbd_debug(SMB, "Search Pattern not found\n");
3895 ksmbd_debug(SMB, "Search pattern is %s\n", srch_ptr);
3898 ksmbd_debug(SMB, "Directory name is %s\n", dir_fp->filename);
3900 if (srch_flag & SMB2_REOPEN || srch_flag & SMB2_RESTART_SCANS) {
3901 ksmbd_debug(SMB, "Restart directory scan\n");
3902 generic_file_llseek(dir_fp->filp, 0, SEEK_SET);
3903 restart_ctx(&dir_fp->readdir_data.ctx);
3906 memset(&d_info, 0, sizeof(struct ksmbd_dir_info));
3907 d_info.wptr = (char *)rsp->Buffer;
3908 d_info.rptr = (char *)rsp->Buffer;
3909 d_info.out_buf_len =
3910 smb2_calc_max_out_buf_len(work, 8,
3911 le32_to_cpu(req->OutputBufferLength));
3912 if (d_info.out_buf_len < 0) {
3916 d_info.flags = srch_flag;
3919 * reserve dot and dotdot entries in head of buffer
3922 rc = ksmbd_populate_dot_dotdot_entries(work, req->FileInformationClass,
3923 dir_fp, &d_info, srch_ptr,
3924 smb2_populate_readdir_entry);
3930 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_HIDE_DOT_FILES))
3931 d_info.hide_dot_file = true;
3933 buffer_sz = d_info.out_buf_len;
3934 d_info.rptr = d_info.wptr;
3935 query_dir_private.work = work;
3936 query_dir_private.search_pattern = srch_ptr;
3937 query_dir_private.dir_fp = dir_fp;
3938 query_dir_private.d_info = &d_info;
3939 query_dir_private.info_level = req->FileInformationClass;
3940 dir_fp->readdir_data.private = &query_dir_private;
3941 set_ctx_actor(&dir_fp->readdir_data.ctx, __query_dir);
3943 rc = iterate_dir(dir_fp->filp, &dir_fp->readdir_data.ctx);
3945 restart_ctx(&dir_fp->readdir_data.ctx);
3951 d_info.wptr = d_info.rptr;
3952 d_info.out_buf_len = buffer_sz;
3953 rc = process_query_dir_entries(&query_dir_private);
3957 if (!d_info.data_count && d_info.out_buf_len >= 0) {
3958 if (srch_flag & SMB2_RETURN_SINGLE_ENTRY && !is_asterisk(srch_ptr)) {
3959 rsp->hdr.Status = STATUS_NO_SUCH_FILE;
3961 dir_fp->dot_dotdot[0] = dir_fp->dot_dotdot[1] = 0;
3962 rsp->hdr.Status = STATUS_NO_MORE_FILES;
3964 rsp->StructureSize = cpu_to_le16(9);
3965 rsp->OutputBufferOffset = cpu_to_le16(0);
3966 rsp->OutputBufferLength = cpu_to_le32(0);
3968 inc_rfc1001_len(work->response_buf, 9);
3970 ((struct file_directory_info *)
3971 ((char *)rsp->Buffer + d_info.last_entry_offset))
3972 ->NextEntryOffset = 0;
3973 d_info.data_count -= d_info.last_entry_off_align;
3975 rsp->StructureSize = cpu_to_le16(9);
3976 rsp->OutputBufferOffset = cpu_to_le16(72);
3977 rsp->OutputBufferLength = cpu_to_le32(d_info.data_count);
3978 inc_rfc1001_len(work->response_buf, 8 + d_info.data_count);
3982 ksmbd_fd_put(work, dir_fp);
3983 ksmbd_revert_fsids(work);
3987 pr_err("error while processing smb2 query dir rc = %d\n", rc);
3992 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
3993 else if (rc == -EACCES)
3994 rsp->hdr.Status = STATUS_ACCESS_DENIED;
3995 else if (rc == -ENOENT)
3996 rsp->hdr.Status = STATUS_NO_SUCH_FILE;
3997 else if (rc == -EBADF)
3998 rsp->hdr.Status = STATUS_FILE_CLOSED;
3999 else if (rc == -ENOMEM)
4000 rsp->hdr.Status = STATUS_NO_MEMORY;
4001 else if (rc == -EFAULT)
4002 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
4003 if (!rsp->hdr.Status)
4004 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
4006 smb2_set_err_rsp(work);
4007 ksmbd_fd_put(work, dir_fp);
4008 ksmbd_revert_fsids(work);
4013 * buffer_check_err() - helper function to check buffer errors
4014 * @reqOutputBufferLength: max buffer length expected in command response
4015 * @rsp: query info response buffer contains output buffer length
4016 * @rsp_org: base response buffer pointer in case of chained response
4017 * @infoclass_size: query info class response buffer size
4019 * Return: 0 on success, otherwise error
4021 static int buffer_check_err(int reqOutputBufferLength,
4022 struct smb2_query_info_rsp *rsp,
4023 void *rsp_org, int infoclass_size)
4025 if (reqOutputBufferLength < le32_to_cpu(rsp->OutputBufferLength)) {
4026 if (reqOutputBufferLength < infoclass_size) {
4027 pr_err("Invalid Buffer Size Requested\n");
4028 rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
4029 *(__be32 *)rsp_org = cpu_to_be32(sizeof(struct smb2_hdr));
4033 ksmbd_debug(SMB, "Buffer Overflow\n");
4034 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
4035 *(__be32 *)rsp_org = cpu_to_be32(sizeof(struct smb2_hdr) +
4036 reqOutputBufferLength);
4037 rsp->OutputBufferLength = cpu_to_le32(reqOutputBufferLength);
4042 static void get_standard_info_pipe(struct smb2_query_info_rsp *rsp,
4045 struct smb2_file_standard_info *sinfo;
4047 sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
4049 sinfo->AllocationSize = cpu_to_le64(4096);
4050 sinfo->EndOfFile = cpu_to_le64(0);
4051 sinfo->NumberOfLinks = cpu_to_le32(1);
4052 sinfo->DeletePending = 1;
4053 sinfo->Directory = 0;
4054 rsp->OutputBufferLength =
4055 cpu_to_le32(sizeof(struct smb2_file_standard_info));
4056 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_standard_info));
4059 static void get_internal_info_pipe(struct smb2_query_info_rsp *rsp, u64 num,
4062 struct smb2_file_internal_info *file_info;
4064 file_info = (struct smb2_file_internal_info *)rsp->Buffer;
4066 /* any unique number */
4067 file_info->IndexNumber = cpu_to_le64(num | (1ULL << 63));
4068 rsp->OutputBufferLength =
4069 cpu_to_le32(sizeof(struct smb2_file_internal_info));
4070 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_internal_info));
4073 static int smb2_get_info_file_pipe(struct ksmbd_session *sess,
4074 struct smb2_query_info_req *req,
4075 struct smb2_query_info_rsp *rsp,
4082 * Windows can sometime send query file info request on
4083 * pipe without opening it, checking error condition here
4085 id = req->VolatileFileId;
4086 if (!ksmbd_session_rpc_method(sess, id))
4089 ksmbd_debug(SMB, "FileInfoClass %u, FileId 0x%llx\n",
4090 req->FileInfoClass, req->VolatileFileId);
4092 switch (req->FileInfoClass) {
4093 case FILE_STANDARD_INFORMATION:
4094 get_standard_info_pipe(rsp, rsp_org);
4095 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4097 FILE_STANDARD_INFORMATION_SIZE);
4099 case FILE_INTERNAL_INFORMATION:
4100 get_internal_info_pipe(rsp, id, rsp_org);
4101 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4103 FILE_INTERNAL_INFORMATION_SIZE);
4106 ksmbd_debug(SMB, "smb2_info_file_pipe for %u not supported\n",
4107 req->FileInfoClass);
4114 * smb2_get_ea() - handler for smb2 get extended attribute command
4115 * @work: smb work containing query info command buffer
4116 * @fp: ksmbd_file pointer
4117 * @req: get extended attribute request
4118 * @rsp: response buffer pointer
4119 * @rsp_org: base response buffer pointer in case of chained response
4121 * Return: 0 on success, otherwise error
4123 static int smb2_get_ea(struct ksmbd_work *work, struct ksmbd_file *fp,
4124 struct smb2_query_info_req *req,
4125 struct smb2_query_info_rsp *rsp, void *rsp_org)
4127 struct smb2_ea_info *eainfo, *prev_eainfo;
4128 char *name, *ptr, *xattr_list = NULL, *buf;
4129 int rc, name_len, value_len, xattr_list_len, idx;
4130 ssize_t buf_free_len, alignment_bytes, next_offset, rsp_data_cnt = 0;
4131 struct smb2_ea_info_req *ea_req = NULL;
4133 struct user_namespace *user_ns = file_mnt_user_ns(fp->filp);
4135 if (!(fp->daccess & FILE_READ_EA_LE)) {
4136 pr_err("Not permitted to read ext attr : 0x%x\n",
4141 path = &fp->filp->f_path;
4142 /* single EA entry is requested with given user.* name */
4143 if (req->InputBufferLength) {
4144 if (le32_to_cpu(req->InputBufferLength) <
4145 sizeof(struct smb2_ea_info_req))
4148 ea_req = (struct smb2_ea_info_req *)req->Buffer;
4150 /* need to send all EAs, if no specific EA is requested*/
4151 if (le32_to_cpu(req->Flags) & SL_RETURN_SINGLE_ENTRY)
4153 "All EAs are requested but need to send single EA entry in rsp flags 0x%x\n",
4154 le32_to_cpu(req->Flags));
4158 smb2_calc_max_out_buf_len(work, 8,
4159 le32_to_cpu(req->OutputBufferLength));
4160 if (buf_free_len < 0)
4163 rc = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
4165 rsp->hdr.Status = STATUS_INVALID_HANDLE;
4167 } else if (!rc) { /* there is no EA in the file */
4168 ksmbd_debug(SMB, "no ea data in the file\n");
4171 xattr_list_len = rc;
4173 ptr = (char *)rsp->Buffer;
4174 eainfo = (struct smb2_ea_info *)ptr;
4175 prev_eainfo = eainfo;
4178 while (idx < xattr_list_len) {
4179 name = xattr_list + idx;
4180 name_len = strlen(name);
4182 ksmbd_debug(SMB, "%s, len %d\n", name, name_len);
4183 idx += name_len + 1;
4186 * CIFS does not support EA other than user.* namespace,
4187 * still keep the framework generic, to list other attrs
4190 if (strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4193 if (!strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
4197 if (req->InputBufferLength &&
4198 strncmp(&name[XATTR_USER_PREFIX_LEN], ea_req->name,
4199 ea_req->EaNameLength))
4202 if (!strncmp(&name[XATTR_USER_PREFIX_LEN],
4203 DOS_ATTRIBUTE_PREFIX, DOS_ATTRIBUTE_PREFIX_LEN))
4206 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4207 name_len -= XATTR_USER_PREFIX_LEN;
4209 ptr = (char *)(&eainfo->name + name_len + 1);
4210 buf_free_len -= (offsetof(struct smb2_ea_info, name) +
4212 /* bailout if xattr can't fit in buf_free_len */
4213 value_len = ksmbd_vfs_getxattr(user_ns, path->dentry,
4215 if (value_len <= 0) {
4217 rsp->hdr.Status = STATUS_INVALID_HANDLE;
4221 buf_free_len -= value_len;
4222 if (buf_free_len < 0) {
4227 memcpy(ptr, buf, value_len);
4232 eainfo->EaNameLength = name_len;
4234 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4235 memcpy(eainfo->name, &name[XATTR_USER_PREFIX_LEN],
4238 memcpy(eainfo->name, name, name_len);
4240 eainfo->name[name_len] = '\0';
4241 eainfo->EaValueLength = cpu_to_le16(value_len);
4242 next_offset = offsetof(struct smb2_ea_info, name) +
4243 name_len + 1 + value_len;
4245 /* align next xattr entry at 4 byte bundary */
4246 alignment_bytes = ((next_offset + 3) & ~3) - next_offset;
4247 if (alignment_bytes) {
4248 memset(ptr, '\0', alignment_bytes);
4249 ptr += alignment_bytes;
4250 next_offset += alignment_bytes;
4251 buf_free_len -= alignment_bytes;
4253 eainfo->NextEntryOffset = cpu_to_le32(next_offset);
4254 prev_eainfo = eainfo;
4255 eainfo = (struct smb2_ea_info *)ptr;
4256 rsp_data_cnt += next_offset;
4258 if (req->InputBufferLength) {
4259 ksmbd_debug(SMB, "single entry requested\n");
4264 /* no more ea entries */
4265 prev_eainfo->NextEntryOffset = 0;
4268 if (rsp_data_cnt == 0)
4269 rsp->hdr.Status = STATUS_NO_EAS_ON_FILE;
4270 rsp->OutputBufferLength = cpu_to_le32(rsp_data_cnt);
4271 inc_rfc1001_len(rsp_org, rsp_data_cnt);
4277 static void get_file_access_info(struct smb2_query_info_rsp *rsp,
4278 struct ksmbd_file *fp, void *rsp_org)
4280 struct smb2_file_access_info *file_info;
4282 file_info = (struct smb2_file_access_info *)rsp->Buffer;
4283 file_info->AccessFlags = fp->daccess;
4284 rsp->OutputBufferLength =
4285 cpu_to_le32(sizeof(struct smb2_file_access_info));
4286 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_access_info));
4289 static int get_file_basic_info(struct smb2_query_info_rsp *rsp,
4290 struct ksmbd_file *fp, void *rsp_org)
4292 struct smb2_file_basic_info *basic_info;
4296 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4297 pr_err("no right to read the attributes : 0x%x\n",
4302 basic_info = (struct smb2_file_basic_info *)rsp->Buffer;
4303 generic_fillattr(file_mnt_user_ns(fp->filp), file_inode(fp->filp),
4305 basic_info->CreationTime = cpu_to_le64(fp->create_time);
4306 time = ksmbd_UnixTimeToNT(stat.atime);
4307 basic_info->LastAccessTime = cpu_to_le64(time);
4308 time = ksmbd_UnixTimeToNT(stat.mtime);
4309 basic_info->LastWriteTime = cpu_to_le64(time);
4310 time = ksmbd_UnixTimeToNT(stat.ctime);
4311 basic_info->ChangeTime = cpu_to_le64(time);
4312 basic_info->Attributes = fp->f_ci->m_fattr;
4313 basic_info->Pad1 = 0;
4314 rsp->OutputBufferLength =
4315 cpu_to_le32(sizeof(struct smb2_file_basic_info));
4316 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_basic_info));
4320 static unsigned long long get_allocation_size(struct inode *inode,
4323 unsigned long long alloc_size = 0;
4325 if (!S_ISDIR(stat->mode)) {
4326 if ((inode->i_blocks << 9) <= stat->size)
4327 alloc_size = stat->size;
4329 alloc_size = inode->i_blocks << 9;
4335 static void get_file_standard_info(struct smb2_query_info_rsp *rsp,
4336 struct ksmbd_file *fp, void *rsp_org)
4338 struct smb2_file_standard_info *sinfo;
4339 unsigned int delete_pending;
4340 struct inode *inode;
4343 inode = file_inode(fp->filp);
4344 generic_fillattr(file_mnt_user_ns(fp->filp), inode, &stat);
4346 sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
4347 delete_pending = ksmbd_inode_pending_delete(fp);
4349 sinfo->AllocationSize = cpu_to_le64(get_allocation_size(inode, &stat));
4350 sinfo->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4351 sinfo->NumberOfLinks = cpu_to_le32(get_nlink(&stat) - delete_pending);
4352 sinfo->DeletePending = delete_pending;
4353 sinfo->Directory = S_ISDIR(stat.mode) ? 1 : 0;
4354 rsp->OutputBufferLength =
4355 cpu_to_le32(sizeof(struct smb2_file_standard_info));
4356 inc_rfc1001_len(rsp_org,
4357 sizeof(struct smb2_file_standard_info));
4360 static void get_file_alignment_info(struct smb2_query_info_rsp *rsp,
4363 struct smb2_file_alignment_info *file_info;
4365 file_info = (struct smb2_file_alignment_info *)rsp->Buffer;
4366 file_info->AlignmentRequirement = 0;
4367 rsp->OutputBufferLength =
4368 cpu_to_le32(sizeof(struct smb2_file_alignment_info));
4369 inc_rfc1001_len(rsp_org,
4370 sizeof(struct smb2_file_alignment_info));
4373 static int get_file_all_info(struct ksmbd_work *work,
4374 struct smb2_query_info_rsp *rsp,
4375 struct ksmbd_file *fp,
4378 struct ksmbd_conn *conn = work->conn;
4379 struct smb2_file_all_info *file_info;
4380 unsigned int delete_pending;
4381 struct inode *inode;
4387 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4388 ksmbd_debug(SMB, "no right to read the attributes : 0x%x\n",
4393 filename = convert_to_nt_pathname(fp->filename);
4397 inode = file_inode(fp->filp);
4398 generic_fillattr(file_mnt_user_ns(fp->filp), inode, &stat);
4400 ksmbd_debug(SMB, "filename = %s\n", filename);
4401 delete_pending = ksmbd_inode_pending_delete(fp);
4402 file_info = (struct smb2_file_all_info *)rsp->Buffer;
4404 file_info->CreationTime = cpu_to_le64(fp->create_time);
4405 time = ksmbd_UnixTimeToNT(stat.atime);
4406 file_info->LastAccessTime = cpu_to_le64(time);
4407 time = ksmbd_UnixTimeToNT(stat.mtime);
4408 file_info->LastWriteTime = cpu_to_le64(time);
4409 time = ksmbd_UnixTimeToNT(stat.ctime);
4410 file_info->ChangeTime = cpu_to_le64(time);
4411 file_info->Attributes = fp->f_ci->m_fattr;
4412 file_info->Pad1 = 0;
4413 file_info->AllocationSize =
4414 cpu_to_le64(get_allocation_size(inode, &stat));
4415 file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4416 file_info->NumberOfLinks =
4417 cpu_to_le32(get_nlink(&stat) - delete_pending);
4418 file_info->DeletePending = delete_pending;
4419 file_info->Directory = S_ISDIR(stat.mode) ? 1 : 0;
4420 file_info->Pad2 = 0;
4421 file_info->IndexNumber = cpu_to_le64(stat.ino);
4422 file_info->EASize = 0;
4423 file_info->AccessFlags = fp->daccess;
4424 file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
4425 file_info->Mode = fp->coption;
4426 file_info->AlignmentRequirement = 0;
4427 conv_len = smbConvertToUTF16((__le16 *)file_info->FileName, filename,
4428 PATH_MAX, conn->local_nls, 0);
4430 file_info->FileNameLength = cpu_to_le32(conv_len);
4431 rsp->OutputBufferLength =
4432 cpu_to_le32(sizeof(struct smb2_file_all_info) + conv_len - 1);
4434 inc_rfc1001_len(rsp_org, le32_to_cpu(rsp->OutputBufferLength));
4438 static void get_file_alternate_info(struct ksmbd_work *work,
4439 struct smb2_query_info_rsp *rsp,
4440 struct ksmbd_file *fp,
4443 struct ksmbd_conn *conn = work->conn;
4444 struct smb2_file_alt_name_info *file_info;
4445 struct dentry *dentry = fp->filp->f_path.dentry;
4448 spin_lock(&dentry->d_lock);
4449 file_info = (struct smb2_file_alt_name_info *)rsp->Buffer;
4450 conv_len = ksmbd_extract_shortname(conn,
4451 dentry->d_name.name,
4452 file_info->FileName);
4453 spin_unlock(&dentry->d_lock);
4454 file_info->FileNameLength = cpu_to_le32(conv_len);
4455 rsp->OutputBufferLength =
4456 cpu_to_le32(sizeof(struct smb2_file_alt_name_info) + conv_len);
4457 inc_rfc1001_len(rsp_org, le32_to_cpu(rsp->OutputBufferLength));
4460 static void get_file_stream_info(struct ksmbd_work *work,
4461 struct smb2_query_info_rsp *rsp,
4462 struct ksmbd_file *fp,
4465 struct ksmbd_conn *conn = work->conn;
4466 struct smb2_file_stream_info *file_info;
4467 char *stream_name, *xattr_list = NULL, *stream_buf;
4469 struct path *path = &fp->filp->f_path;
4470 ssize_t xattr_list_len;
4471 int nbytes = 0, streamlen, stream_name_len, next, idx = 0;
4473 struct smb2_query_info_req *req = ksmbd_req_buf_next(work);
4475 generic_fillattr(file_mnt_user_ns(fp->filp), file_inode(fp->filp),
4477 file_info = (struct smb2_file_stream_info *)rsp->Buffer;
4480 smb2_calc_max_out_buf_len(work, 8,
4481 le32_to_cpu(req->OutputBufferLength));
4482 if (buf_free_len < 0)
4485 xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
4486 if (xattr_list_len < 0) {
4488 } else if (!xattr_list_len) {
4489 ksmbd_debug(SMB, "empty xattr in the file\n");
4493 while (idx < xattr_list_len) {
4494 stream_name = xattr_list + idx;
4495 streamlen = strlen(stream_name);
4496 idx += streamlen + 1;
4498 ksmbd_debug(SMB, "%s, len %d\n", stream_name, streamlen);
4500 if (strncmp(&stream_name[XATTR_USER_PREFIX_LEN],
4501 STREAM_PREFIX, STREAM_PREFIX_LEN))
4504 stream_name_len = streamlen - (XATTR_USER_PREFIX_LEN +
4506 streamlen = stream_name_len;
4510 stream_buf = kmalloc(streamlen + 1, GFP_KERNEL);
4514 streamlen = snprintf(stream_buf, streamlen + 1,
4515 ":%s", &stream_name[XATTR_NAME_STREAM_LEN]);
4517 next = sizeof(struct smb2_file_stream_info) + streamlen * 2;
4518 if (next > buf_free_len) {
4523 file_info = (struct smb2_file_stream_info *)&rsp->Buffer[nbytes];
4524 streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
4525 stream_buf, streamlen,
4526 conn->local_nls, 0);
4529 file_info->StreamNameLength = cpu_to_le32(streamlen);
4530 file_info->StreamSize = cpu_to_le64(stream_name_len);
4531 file_info->StreamAllocationSize = cpu_to_le64(stream_name_len);
4534 buf_free_len -= next;
4535 file_info->NextEntryOffset = cpu_to_le32(next);
4539 if (!S_ISDIR(stat.mode) &&
4540 buf_free_len >= sizeof(struct smb2_file_stream_info) + 7 * 2) {
4541 file_info = (struct smb2_file_stream_info *)
4542 &rsp->Buffer[nbytes];
4543 streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
4544 "::$DATA", 7, conn->local_nls, 0);
4546 file_info->StreamNameLength = cpu_to_le32(streamlen);
4547 file_info->StreamSize = cpu_to_le64(stat.size);
4548 file_info->StreamAllocationSize = cpu_to_le64(stat.blocks << 9);
4549 nbytes += sizeof(struct smb2_file_stream_info) + streamlen;
4552 /* last entry offset should be 0 */
4553 file_info->NextEntryOffset = 0;
4556 rsp->OutputBufferLength = cpu_to_le32(nbytes);
4557 inc_rfc1001_len(rsp_org, nbytes);
4560 static void get_file_internal_info(struct smb2_query_info_rsp *rsp,
4561 struct ksmbd_file *fp, void *rsp_org)
4563 struct smb2_file_internal_info *file_info;
4566 generic_fillattr(file_mnt_user_ns(fp->filp), file_inode(fp->filp),
4568 file_info = (struct smb2_file_internal_info *)rsp->Buffer;
4569 file_info->IndexNumber = cpu_to_le64(stat.ino);
4570 rsp->OutputBufferLength =
4571 cpu_to_le32(sizeof(struct smb2_file_internal_info));
4572 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_internal_info));
4575 static int get_file_network_open_info(struct smb2_query_info_rsp *rsp,
4576 struct ksmbd_file *fp, void *rsp_org)
4578 struct smb2_file_ntwrk_info *file_info;
4579 struct inode *inode;
4583 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4584 pr_err("no right to read the attributes : 0x%x\n",
4589 file_info = (struct smb2_file_ntwrk_info *)rsp->Buffer;
4591 inode = file_inode(fp->filp);
4592 generic_fillattr(file_mnt_user_ns(fp->filp), inode, &stat);
4594 file_info->CreationTime = cpu_to_le64(fp->create_time);
4595 time = ksmbd_UnixTimeToNT(stat.atime);
4596 file_info->LastAccessTime = cpu_to_le64(time);
4597 time = ksmbd_UnixTimeToNT(stat.mtime);
4598 file_info->LastWriteTime = cpu_to_le64(time);
4599 time = ksmbd_UnixTimeToNT(stat.ctime);
4600 file_info->ChangeTime = cpu_to_le64(time);
4601 file_info->Attributes = fp->f_ci->m_fattr;
4602 file_info->AllocationSize =
4603 cpu_to_le64(get_allocation_size(inode, &stat));
4604 file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4605 file_info->Reserved = cpu_to_le32(0);
4606 rsp->OutputBufferLength =
4607 cpu_to_le32(sizeof(struct smb2_file_ntwrk_info));
4608 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_ntwrk_info));
4612 static void get_file_ea_info(struct smb2_query_info_rsp *rsp, void *rsp_org)
4614 struct smb2_file_ea_info *file_info;
4616 file_info = (struct smb2_file_ea_info *)rsp->Buffer;
4617 file_info->EASize = 0;
4618 rsp->OutputBufferLength =
4619 cpu_to_le32(sizeof(struct smb2_file_ea_info));
4620 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_ea_info));
4623 static void get_file_position_info(struct smb2_query_info_rsp *rsp,
4624 struct ksmbd_file *fp, void *rsp_org)
4626 struct smb2_file_pos_info *file_info;
4628 file_info = (struct smb2_file_pos_info *)rsp->Buffer;
4629 file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
4630 rsp->OutputBufferLength =
4631 cpu_to_le32(sizeof(struct smb2_file_pos_info));
4632 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_pos_info));
4635 static void get_file_mode_info(struct smb2_query_info_rsp *rsp,
4636 struct ksmbd_file *fp, void *rsp_org)
4638 struct smb2_file_mode_info *file_info;
4640 file_info = (struct smb2_file_mode_info *)rsp->Buffer;
4641 file_info->Mode = fp->coption & FILE_MODE_INFO_MASK;
4642 rsp->OutputBufferLength =
4643 cpu_to_le32(sizeof(struct smb2_file_mode_info));
4644 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_mode_info));
4647 static void get_file_compression_info(struct smb2_query_info_rsp *rsp,
4648 struct ksmbd_file *fp, void *rsp_org)
4650 struct smb2_file_comp_info *file_info;
4653 generic_fillattr(file_mnt_user_ns(fp->filp), file_inode(fp->filp),
4656 file_info = (struct smb2_file_comp_info *)rsp->Buffer;
4657 file_info->CompressedFileSize = cpu_to_le64(stat.blocks << 9);
4658 file_info->CompressionFormat = COMPRESSION_FORMAT_NONE;
4659 file_info->CompressionUnitShift = 0;
4660 file_info->ChunkShift = 0;
4661 file_info->ClusterShift = 0;
4662 memset(&file_info->Reserved[0], 0, 3);
4664 rsp->OutputBufferLength =
4665 cpu_to_le32(sizeof(struct smb2_file_comp_info));
4666 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_comp_info));
4669 static int get_file_attribute_tag_info(struct smb2_query_info_rsp *rsp,
4670 struct ksmbd_file *fp, void *rsp_org)
4672 struct smb2_file_attr_tag_info *file_info;
4674 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4675 pr_err("no right to read the attributes : 0x%x\n",
4680 file_info = (struct smb2_file_attr_tag_info *)rsp->Buffer;
4681 file_info->FileAttributes = fp->f_ci->m_fattr;
4682 file_info->ReparseTag = 0;
4683 rsp->OutputBufferLength =
4684 cpu_to_le32(sizeof(struct smb2_file_attr_tag_info));
4685 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_attr_tag_info));
4689 static int find_file_posix_info(struct smb2_query_info_rsp *rsp,
4690 struct ksmbd_file *fp, void *rsp_org)
4692 struct smb311_posix_qinfo *file_info;
4693 struct inode *inode = file_inode(fp->filp);
4696 file_info = (struct smb311_posix_qinfo *)rsp->Buffer;
4697 file_info->CreationTime = cpu_to_le64(fp->create_time);
4698 time = ksmbd_UnixTimeToNT(inode->i_atime);
4699 file_info->LastAccessTime = cpu_to_le64(time);
4700 time = ksmbd_UnixTimeToNT(inode->i_mtime);
4701 file_info->LastWriteTime = cpu_to_le64(time);
4702 time = ksmbd_UnixTimeToNT(inode->i_ctime);
4703 file_info->ChangeTime = cpu_to_le64(time);
4704 file_info->DosAttributes = fp->f_ci->m_fattr;
4705 file_info->Inode = cpu_to_le64(inode->i_ino);
4706 file_info->EndOfFile = cpu_to_le64(inode->i_size);
4707 file_info->AllocationSize = cpu_to_le64(inode->i_blocks << 9);
4708 file_info->HardLinks = cpu_to_le32(inode->i_nlink);
4709 file_info->Mode = cpu_to_le32(inode->i_mode);
4710 file_info->DeviceId = cpu_to_le32(inode->i_rdev);
4711 rsp->OutputBufferLength =
4712 cpu_to_le32(sizeof(struct smb311_posix_qinfo));
4713 inc_rfc1001_len(rsp_org, sizeof(struct smb311_posix_qinfo));
4717 static int smb2_get_info_file(struct ksmbd_work *work,
4718 struct smb2_query_info_req *req,
4719 struct smb2_query_info_rsp *rsp)
4721 struct ksmbd_file *fp;
4722 int fileinfoclass = 0;
4724 int file_infoclass_size;
4725 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
4727 if (test_share_config_flag(work->tcon->share_conf,
4728 KSMBD_SHARE_FLAG_PIPE)) {
4729 /* smb2 info file called for pipe */
4730 return smb2_get_info_file_pipe(work->sess, req, rsp,
4731 work->response_buf);
4734 if (work->next_smb2_rcv_hdr_off) {
4735 if (!has_file_id(req->VolatileFileId)) {
4736 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
4737 work->compound_fid);
4738 id = work->compound_fid;
4739 pid = work->compound_pfid;
4743 if (!has_file_id(id)) {
4744 id = req->VolatileFileId;
4745 pid = req->PersistentFileId;
4748 fp = ksmbd_lookup_fd_slow(work, id, pid);
4752 fileinfoclass = req->FileInfoClass;
4754 switch (fileinfoclass) {
4755 case FILE_ACCESS_INFORMATION:
4756 get_file_access_info(rsp, fp, work->response_buf);
4757 file_infoclass_size = FILE_ACCESS_INFORMATION_SIZE;
4760 case FILE_BASIC_INFORMATION:
4761 rc = get_file_basic_info(rsp, fp, work->response_buf);
4762 file_infoclass_size = FILE_BASIC_INFORMATION_SIZE;
4765 case FILE_STANDARD_INFORMATION:
4766 get_file_standard_info(rsp, fp, work->response_buf);
4767 file_infoclass_size = FILE_STANDARD_INFORMATION_SIZE;
4770 case FILE_ALIGNMENT_INFORMATION:
4771 get_file_alignment_info(rsp, work->response_buf);
4772 file_infoclass_size = FILE_ALIGNMENT_INFORMATION_SIZE;
4775 case FILE_ALL_INFORMATION:
4776 rc = get_file_all_info(work, rsp, fp, work->response_buf);
4777 file_infoclass_size = FILE_ALL_INFORMATION_SIZE;
4780 case FILE_ALTERNATE_NAME_INFORMATION:
4781 get_file_alternate_info(work, rsp, fp, work->response_buf);
4782 file_infoclass_size = FILE_ALTERNATE_NAME_INFORMATION_SIZE;
4785 case FILE_STREAM_INFORMATION:
4786 get_file_stream_info(work, rsp, fp, work->response_buf);
4787 file_infoclass_size = FILE_STREAM_INFORMATION_SIZE;
4790 case FILE_INTERNAL_INFORMATION:
4791 get_file_internal_info(rsp, fp, work->response_buf);
4792 file_infoclass_size = FILE_INTERNAL_INFORMATION_SIZE;
4795 case FILE_NETWORK_OPEN_INFORMATION:
4796 rc = get_file_network_open_info(rsp, fp, work->response_buf);
4797 file_infoclass_size = FILE_NETWORK_OPEN_INFORMATION_SIZE;
4800 case FILE_EA_INFORMATION:
4801 get_file_ea_info(rsp, work->response_buf);
4802 file_infoclass_size = FILE_EA_INFORMATION_SIZE;
4805 case FILE_FULL_EA_INFORMATION:
4806 rc = smb2_get_ea(work, fp, req, rsp, work->response_buf);
4807 file_infoclass_size = FILE_FULL_EA_INFORMATION_SIZE;
4810 case FILE_POSITION_INFORMATION:
4811 get_file_position_info(rsp, fp, work->response_buf);
4812 file_infoclass_size = FILE_POSITION_INFORMATION_SIZE;
4815 case FILE_MODE_INFORMATION:
4816 get_file_mode_info(rsp, fp, work->response_buf);
4817 file_infoclass_size = FILE_MODE_INFORMATION_SIZE;
4820 case FILE_COMPRESSION_INFORMATION:
4821 get_file_compression_info(rsp, fp, work->response_buf);
4822 file_infoclass_size = FILE_COMPRESSION_INFORMATION_SIZE;
4825 case FILE_ATTRIBUTE_TAG_INFORMATION:
4826 rc = get_file_attribute_tag_info(rsp, fp, work->response_buf);
4827 file_infoclass_size = FILE_ATTRIBUTE_TAG_INFORMATION_SIZE;
4829 case SMB_FIND_FILE_POSIX_INFO:
4830 if (!work->tcon->posix_extensions) {
4831 pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
4834 rc = find_file_posix_info(rsp, fp, work->response_buf);
4835 file_infoclass_size = sizeof(struct smb311_posix_qinfo);
4839 ksmbd_debug(SMB, "fileinfoclass %d not supported yet\n",
4844 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4845 rsp, work->response_buf,
4846 file_infoclass_size);
4847 ksmbd_fd_put(work, fp);
4851 static int smb2_get_info_filesystem(struct ksmbd_work *work,
4852 struct smb2_query_info_req *req,
4853 struct smb2_query_info_rsp *rsp)
4855 struct ksmbd_session *sess = work->sess;
4856 struct ksmbd_conn *conn = sess->conn;
4857 struct ksmbd_share_config *share = work->tcon->share_conf;
4858 int fsinfoclass = 0;
4859 struct kstatfs stfs;
4862 int fs_infoclass_size = 0;
4864 rc = kern_path(share->path, LOOKUP_NO_SYMLINKS, &path);
4866 pr_err("cannot create vfs path\n");
4870 rc = vfs_statfs(&path, &stfs);
4872 pr_err("cannot do stat of path %s\n", share->path);
4877 fsinfoclass = req->FileInfoClass;
4879 switch (fsinfoclass) {
4880 case FS_DEVICE_INFORMATION:
4882 struct filesystem_device_info *info;
4884 info = (struct filesystem_device_info *)rsp->Buffer;
4886 info->DeviceType = cpu_to_le32(stfs.f_type);
4887 info->DeviceCharacteristics = cpu_to_le32(0x00000020);
4888 rsp->OutputBufferLength = cpu_to_le32(8);
4889 inc_rfc1001_len(work->response_buf, 8);
4890 fs_infoclass_size = FS_DEVICE_INFORMATION_SIZE;
4893 case FS_ATTRIBUTE_INFORMATION:
4895 struct filesystem_attribute_info *info;
4898 info = (struct filesystem_attribute_info *)rsp->Buffer;
4899 info->Attributes = cpu_to_le32(FILE_SUPPORTS_OBJECT_IDS |
4900 FILE_PERSISTENT_ACLS |
4901 FILE_UNICODE_ON_DISK |
4902 FILE_CASE_PRESERVED_NAMES |
4903 FILE_CASE_SENSITIVE_SEARCH |
4904 FILE_SUPPORTS_BLOCK_REFCOUNTING);
4906 info->Attributes |= cpu_to_le32(server_conf.share_fake_fscaps);
4908 info->MaxPathNameComponentLength = cpu_to_le32(stfs.f_namelen);
4909 len = smbConvertToUTF16((__le16 *)info->FileSystemName,
4910 "NTFS", PATH_MAX, conn->local_nls, 0);
4912 info->FileSystemNameLen = cpu_to_le32(len);
4913 sz = sizeof(struct filesystem_attribute_info) - 2 + len;
4914 rsp->OutputBufferLength = cpu_to_le32(sz);
4915 inc_rfc1001_len(work->response_buf, sz);
4916 fs_infoclass_size = FS_ATTRIBUTE_INFORMATION_SIZE;
4919 case FS_VOLUME_INFORMATION:
4921 struct filesystem_vol_info *info;
4923 unsigned int serial_crc = 0;
4925 info = (struct filesystem_vol_info *)(rsp->Buffer);
4926 info->VolumeCreationTime = 0;
4927 serial_crc = crc32_le(serial_crc, share->name,
4928 strlen(share->name));
4929 serial_crc = crc32_le(serial_crc, share->path,
4930 strlen(share->path));
4931 serial_crc = crc32_le(serial_crc, ksmbd_netbios_name(),
4932 strlen(ksmbd_netbios_name()));
4933 /* Taking dummy value of serial number*/
4934 info->SerialNumber = cpu_to_le32(serial_crc);
4935 len = smbConvertToUTF16((__le16 *)info->VolumeLabel,
4936 share->name, PATH_MAX,
4937 conn->local_nls, 0);
4939 info->VolumeLabelSize = cpu_to_le32(len);
4941 sz = sizeof(struct filesystem_vol_info) - 2 + len;
4942 rsp->OutputBufferLength = cpu_to_le32(sz);
4943 inc_rfc1001_len(work->response_buf, sz);
4944 fs_infoclass_size = FS_VOLUME_INFORMATION_SIZE;
4947 case FS_SIZE_INFORMATION:
4949 struct filesystem_info *info;
4951 info = (struct filesystem_info *)(rsp->Buffer);
4952 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
4953 info->FreeAllocationUnits = cpu_to_le64(stfs.f_bfree);
4954 info->SectorsPerAllocationUnit = cpu_to_le32(1);
4955 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
4956 rsp->OutputBufferLength = cpu_to_le32(24);
4957 inc_rfc1001_len(work->response_buf, 24);
4958 fs_infoclass_size = FS_SIZE_INFORMATION_SIZE;
4961 case FS_FULL_SIZE_INFORMATION:
4963 struct smb2_fs_full_size_info *info;
4965 info = (struct smb2_fs_full_size_info *)(rsp->Buffer);
4966 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
4967 info->CallerAvailableAllocationUnits =
4968 cpu_to_le64(stfs.f_bavail);
4969 info->ActualAvailableAllocationUnits =
4970 cpu_to_le64(stfs.f_bfree);
4971 info->SectorsPerAllocationUnit = cpu_to_le32(1);
4972 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
4973 rsp->OutputBufferLength = cpu_to_le32(32);
4974 inc_rfc1001_len(work->response_buf, 32);
4975 fs_infoclass_size = FS_FULL_SIZE_INFORMATION_SIZE;
4978 case FS_OBJECT_ID_INFORMATION:
4980 struct object_id_info *info;
4982 info = (struct object_id_info *)(rsp->Buffer);
4984 if (!user_guest(sess->user))
4985 memcpy(info->objid, user_passkey(sess->user), 16);
4987 memset(info->objid, 0, 16);
4989 info->extended_info.magic = cpu_to_le32(EXTENDED_INFO_MAGIC);
4990 info->extended_info.version = cpu_to_le32(1);
4991 info->extended_info.release = cpu_to_le32(1);
4992 info->extended_info.rel_date = 0;
4993 memcpy(info->extended_info.version_string, "1.1.0", strlen("1.1.0"));
4994 rsp->OutputBufferLength = cpu_to_le32(64);
4995 inc_rfc1001_len(work->response_buf, 64);
4996 fs_infoclass_size = FS_OBJECT_ID_INFORMATION_SIZE;
4999 case FS_SECTOR_SIZE_INFORMATION:
5001 struct smb3_fs_ss_info *info;
5003 info = (struct smb3_fs_ss_info *)(rsp->Buffer);
5005 info->LogicalBytesPerSector = cpu_to_le32(stfs.f_bsize);
5006 info->PhysicalBytesPerSectorForAtomicity =
5007 cpu_to_le32(stfs.f_bsize);
5008 info->PhysicalBytesPerSectorForPerf = cpu_to_le32(stfs.f_bsize);
5009 info->FSEffPhysicalBytesPerSectorForAtomicity =
5010 cpu_to_le32(stfs.f_bsize);
5011 info->Flags = cpu_to_le32(SSINFO_FLAGS_ALIGNED_DEVICE |
5012 SSINFO_FLAGS_PARTITION_ALIGNED_ON_DEVICE);
5013 info->ByteOffsetForSectorAlignment = 0;
5014 info->ByteOffsetForPartitionAlignment = 0;
5015 rsp->OutputBufferLength = cpu_to_le32(28);
5016 inc_rfc1001_len(work->response_buf, 28);
5017 fs_infoclass_size = FS_SECTOR_SIZE_INFORMATION_SIZE;
5020 case FS_CONTROL_INFORMATION:
5023 * TODO : The current implementation is based on
5024 * test result with win7(NTFS) server. It's need to
5025 * modify this to get valid Quota values
5028 struct smb2_fs_control_info *info;
5030 info = (struct smb2_fs_control_info *)(rsp->Buffer);
5031 info->FreeSpaceStartFiltering = 0;
5032 info->FreeSpaceThreshold = 0;
5033 info->FreeSpaceStopFiltering = 0;
5034 info->DefaultQuotaThreshold = cpu_to_le64(SMB2_NO_FID);
5035 info->DefaultQuotaLimit = cpu_to_le64(SMB2_NO_FID);
5037 rsp->OutputBufferLength = cpu_to_le32(48);
5038 inc_rfc1001_len(work->response_buf, 48);
5039 fs_infoclass_size = FS_CONTROL_INFORMATION_SIZE;
5042 case FS_POSIX_INFORMATION:
5044 struct filesystem_posix_info *info;
5046 if (!work->tcon->posix_extensions) {
5047 pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
5050 info = (struct filesystem_posix_info *)(rsp->Buffer);
5051 info->OptimalTransferSize = cpu_to_le32(stfs.f_bsize);
5052 info->BlockSize = cpu_to_le32(stfs.f_bsize);
5053 info->TotalBlocks = cpu_to_le64(stfs.f_blocks);
5054 info->BlocksAvail = cpu_to_le64(stfs.f_bfree);
5055 info->UserBlocksAvail = cpu_to_le64(stfs.f_bavail);
5056 info->TotalFileNodes = cpu_to_le64(stfs.f_files);
5057 info->FreeFileNodes = cpu_to_le64(stfs.f_ffree);
5058 rsp->OutputBufferLength = cpu_to_le32(56);
5059 inc_rfc1001_len(work->response_buf, 56);
5060 fs_infoclass_size = FS_POSIX_INFORMATION_SIZE;
5068 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
5069 rsp, work->response_buf,
5075 static int smb2_get_info_sec(struct ksmbd_work *work,
5076 struct smb2_query_info_req *req,
5077 struct smb2_query_info_rsp *rsp)
5079 struct ksmbd_file *fp;
5080 struct user_namespace *user_ns;
5081 struct smb_ntsd *pntsd = (struct smb_ntsd *)rsp->Buffer, *ppntsd = NULL;
5082 struct smb_fattr fattr = {{0}};
5083 struct inode *inode;
5085 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
5086 int addition_info = le32_to_cpu(req->AdditionalInformation);
5089 if (addition_info & ~(OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO |
5090 PROTECTED_DACL_SECINFO |
5091 UNPROTECTED_DACL_SECINFO)) {
5092 ksmbd_debug(SMB, "Unsupported addition info: 0x%x)\n",
5095 pntsd->revision = cpu_to_le16(1);
5096 pntsd->type = cpu_to_le16(SELF_RELATIVE | DACL_PROTECTED);
5097 pntsd->osidoffset = 0;
5098 pntsd->gsidoffset = 0;
5099 pntsd->sacloffset = 0;
5100 pntsd->dacloffset = 0;
5102 secdesclen = sizeof(struct smb_ntsd);
5103 rsp->OutputBufferLength = cpu_to_le32(secdesclen);
5104 inc_rfc1001_len(work->response_buf, secdesclen);
5109 if (work->next_smb2_rcv_hdr_off) {
5110 if (!has_file_id(req->VolatileFileId)) {
5111 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
5112 work->compound_fid);
5113 id = work->compound_fid;
5114 pid = work->compound_pfid;
5118 if (!has_file_id(id)) {
5119 id = req->VolatileFileId;
5120 pid = req->PersistentFileId;
5123 fp = ksmbd_lookup_fd_slow(work, id, pid);
5127 user_ns = file_mnt_user_ns(fp->filp);
5128 inode = file_inode(fp->filp);
5129 ksmbd_acls_fattr(&fattr, user_ns, inode);
5131 if (test_share_config_flag(work->tcon->share_conf,
5132 KSMBD_SHARE_FLAG_ACL_XATTR))
5133 ksmbd_vfs_get_sd_xattr(work->conn, user_ns,
5134 fp->filp->f_path.dentry, &ppntsd);
5136 rc = build_sec_desc(user_ns, pntsd, ppntsd, addition_info,
5137 &secdesclen, &fattr);
5138 posix_acl_release(fattr.cf_acls);
5139 posix_acl_release(fattr.cf_dacls);
5141 ksmbd_fd_put(work, fp);
5145 rsp->OutputBufferLength = cpu_to_le32(secdesclen);
5146 inc_rfc1001_len(work->response_buf, secdesclen);
5151 * smb2_query_info() - handler for smb2 query info command
5152 * @work: smb work containing query info request buffer
5154 * Return: 0 on success, otherwise error
5156 int smb2_query_info(struct ksmbd_work *work)
5158 struct smb2_query_info_req *req;
5159 struct smb2_query_info_rsp *rsp;
5162 WORK_BUFFERS(work, req, rsp);
5164 ksmbd_debug(SMB, "GOT query info request\n");
5166 switch (req->InfoType) {
5167 case SMB2_O_INFO_FILE:
5168 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
5169 rc = smb2_get_info_file(work, req, rsp);
5171 case SMB2_O_INFO_FILESYSTEM:
5172 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILESYSTEM\n");
5173 rc = smb2_get_info_filesystem(work, req, rsp);
5175 case SMB2_O_INFO_SECURITY:
5176 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
5177 rc = smb2_get_info_sec(work, req, rsp);
5180 ksmbd_debug(SMB, "InfoType %d not supported yet\n",
5187 rsp->hdr.Status = STATUS_ACCESS_DENIED;
5188 else if (rc == -ENOENT)
5189 rsp->hdr.Status = STATUS_FILE_CLOSED;
5190 else if (rc == -EIO)
5191 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
5192 else if (rc == -EOPNOTSUPP || rsp->hdr.Status == 0)
5193 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
5194 smb2_set_err_rsp(work);
5196 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n",
5200 rsp->StructureSize = cpu_to_le16(9);
5201 rsp->OutputBufferOffset = cpu_to_le16(72);
5202 inc_rfc1001_len(work->response_buf, 8);
5207 * smb2_close_pipe() - handler for closing IPC pipe
5208 * @work: smb work containing close request buffer
5212 static noinline int smb2_close_pipe(struct ksmbd_work *work)
5215 struct smb2_close_req *req = smb2_get_msg(work->request_buf);
5216 struct smb2_close_rsp *rsp = smb2_get_msg(work->response_buf);
5218 id = req->VolatileFileId;
5219 ksmbd_session_rpc_close(work->sess, id);
5221 rsp->StructureSize = cpu_to_le16(60);
5224 rsp->CreationTime = 0;
5225 rsp->LastAccessTime = 0;
5226 rsp->LastWriteTime = 0;
5227 rsp->ChangeTime = 0;
5228 rsp->AllocationSize = 0;
5230 rsp->Attributes = 0;
5231 inc_rfc1001_len(work->response_buf, 60);
5236 * smb2_close() - handler for smb2 close file command
5237 * @work: smb work containing close request buffer
5241 int smb2_close(struct ksmbd_work *work)
5243 u64 volatile_id = KSMBD_NO_FID;
5245 struct smb2_close_req *req;
5246 struct smb2_close_rsp *rsp;
5247 struct ksmbd_conn *conn = work->conn;
5248 struct ksmbd_file *fp;
5249 struct inode *inode;
5253 WORK_BUFFERS(work, req, rsp);
5255 if (test_share_config_flag(work->tcon->share_conf,
5256 KSMBD_SHARE_FLAG_PIPE)) {
5257 ksmbd_debug(SMB, "IPC pipe close request\n");
5258 return smb2_close_pipe(work);
5261 sess_id = le64_to_cpu(req->hdr.SessionId);
5262 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5263 sess_id = work->compound_sid;
5265 work->compound_sid = 0;
5266 if (check_session_id(conn, sess_id)) {
5267 work->compound_sid = sess_id;
5269 rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
5270 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5271 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
5276 if (work->next_smb2_rcv_hdr_off &&
5277 !has_file_id(req->VolatileFileId)) {
5278 if (!has_file_id(work->compound_fid)) {
5279 /* file already closed, return FILE_CLOSED */
5280 ksmbd_debug(SMB, "file already closed\n");
5281 rsp->hdr.Status = STATUS_FILE_CLOSED;
5286 "Compound request set FID = %llu:%llu\n",
5288 work->compound_pfid);
5289 volatile_id = work->compound_fid;
5291 /* file closed, stored id is not valid anymore */
5292 work->compound_fid = KSMBD_NO_FID;
5293 work->compound_pfid = KSMBD_NO_FID;
5296 volatile_id = req->VolatileFileId;
5298 ksmbd_debug(SMB, "volatile_id = %llu\n", volatile_id);
5300 rsp->StructureSize = cpu_to_le16(60);
5303 if (req->Flags == SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB) {
5304 fp = ksmbd_lookup_fd_fast(work, volatile_id);
5310 inode = file_inode(fp->filp);
5311 rsp->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB;
5312 rsp->AllocationSize = S_ISDIR(inode->i_mode) ? 0 :
5313 cpu_to_le64(inode->i_blocks << 9);
5314 rsp->EndOfFile = cpu_to_le64(inode->i_size);
5315 rsp->Attributes = fp->f_ci->m_fattr;
5316 rsp->CreationTime = cpu_to_le64(fp->create_time);
5317 time = ksmbd_UnixTimeToNT(inode->i_atime);
5318 rsp->LastAccessTime = cpu_to_le64(time);
5319 time = ksmbd_UnixTimeToNT(inode->i_mtime);
5320 rsp->LastWriteTime = cpu_to_le64(time);
5321 time = ksmbd_UnixTimeToNT(inode->i_ctime);
5322 rsp->ChangeTime = cpu_to_le64(time);
5323 ksmbd_fd_put(work, fp);
5326 rsp->AllocationSize = 0;
5328 rsp->Attributes = 0;
5329 rsp->CreationTime = 0;
5330 rsp->LastAccessTime = 0;
5331 rsp->LastWriteTime = 0;
5332 rsp->ChangeTime = 0;
5335 err = ksmbd_close_fd(work, volatile_id);
5338 if (rsp->hdr.Status == 0)
5339 rsp->hdr.Status = STATUS_FILE_CLOSED;
5340 smb2_set_err_rsp(work);
5342 inc_rfc1001_len(work->response_buf, 60);
5349 * smb2_echo() - handler for smb2 echo(ping) command
5350 * @work: smb work containing echo request buffer
5354 int smb2_echo(struct ksmbd_work *work)
5356 struct smb2_echo_rsp *rsp = smb2_get_msg(work->response_buf);
5358 rsp->StructureSize = cpu_to_le16(4);
5360 inc_rfc1001_len(work->response_buf, 4);
5364 static int smb2_rename(struct ksmbd_work *work,
5365 struct ksmbd_file *fp,
5366 struct user_namespace *user_ns,
5367 struct smb2_file_rename_info *file_info,
5368 struct nls_table *local_nls)
5370 struct ksmbd_share_config *share = fp->tcon->share_conf;
5371 char *new_name = NULL, *abs_oldname = NULL, *old_name = NULL;
5372 char *pathname = NULL;
5374 bool file_present = true;
5377 ksmbd_debug(SMB, "setting FILE_RENAME_INFO\n");
5378 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
5382 abs_oldname = d_path(&fp->filp->f_path, pathname, PATH_MAX);
5383 if (IS_ERR(abs_oldname)) {
5387 old_name = strrchr(abs_oldname, '/');
5388 if (old_name && old_name[1] != '\0') {
5391 ksmbd_debug(SMB, "can't get last component in path %s\n",
5397 new_name = smb2_get_name(file_info->FileName,
5398 le32_to_cpu(file_info->FileNameLength),
5400 if (IS_ERR(new_name)) {
5401 rc = PTR_ERR(new_name);
5405 if (strchr(new_name, ':')) {
5407 char *xattr_stream_name, *stream_name = NULL;
5408 size_t xattr_stream_size;
5411 rc = parse_stream_name(new_name, &stream_name, &s_type);
5415 len = strlen(new_name);
5416 if (len > 0 && new_name[len - 1] != '/') {
5417 pr_err("not allow base filename in rename\n");
5422 rc = ksmbd_vfs_xattr_stream_name(stream_name,
5429 rc = ksmbd_vfs_setxattr(user_ns,
5430 fp->filp->f_path.dentry,
5434 pr_err("failed to store stream name in xattr: %d\n",
5443 ksmbd_debug(SMB, "new name %s\n", new_name);
5444 rc = ksmbd_vfs_kern_path(work, new_name, LOOKUP_NO_SYMLINKS, &path, 1);
5448 file_present = false;
5453 if (ksmbd_share_veto_filename(share, new_name)) {
5455 ksmbd_debug(SMB, "Can't rename vetoed file: %s\n", new_name);
5459 if (file_info->ReplaceIfExists) {
5461 rc = ksmbd_vfs_remove_file(work, new_name);
5463 if (rc != -ENOTEMPTY)
5465 ksmbd_debug(SMB, "cannot delete %s, rc %d\n",
5472 strncmp(old_name, path.dentry->d_name.name, strlen(old_name))) {
5475 "cannot rename already existing file\n");
5480 rc = ksmbd_vfs_fp_rename(work, fp, new_name);
5483 if (!IS_ERR(new_name))
5488 static int smb2_create_link(struct ksmbd_work *work,
5489 struct ksmbd_share_config *share,
5490 struct smb2_file_link_info *file_info,
5491 unsigned int buf_len, struct file *filp,
5492 struct nls_table *local_nls)
5494 char *link_name = NULL, *target_name = NULL, *pathname = NULL;
5496 bool file_present = true;
5499 if (buf_len < (u64)sizeof(struct smb2_file_link_info) +
5500 le32_to_cpu(file_info->FileNameLength))
5503 ksmbd_debug(SMB, "setting FILE_LINK_INFORMATION\n");
5504 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
5508 link_name = smb2_get_name(file_info->FileName,
5509 le32_to_cpu(file_info->FileNameLength),
5511 if (IS_ERR(link_name) || S_ISDIR(file_inode(filp)->i_mode)) {
5516 ksmbd_debug(SMB, "link name is %s\n", link_name);
5517 target_name = d_path(&filp->f_path, pathname, PATH_MAX);
5518 if (IS_ERR(target_name)) {
5523 ksmbd_debug(SMB, "target name is %s\n", target_name);
5524 rc = ksmbd_vfs_kern_path(work, link_name, LOOKUP_NO_SYMLINKS, &path, 0);
5528 file_present = false;
5533 if (file_info->ReplaceIfExists) {
5535 rc = ksmbd_vfs_remove_file(work, link_name);
5538 ksmbd_debug(SMB, "cannot delete %s\n",
5546 ksmbd_debug(SMB, "link already exists\n");
5551 rc = ksmbd_vfs_link(work, target_name, link_name);
5555 if (!IS_ERR(link_name))
5561 static int set_file_basic_info(struct ksmbd_file *fp,
5562 struct smb2_file_basic_info *file_info,
5563 struct ksmbd_share_config *share)
5567 struct inode *inode;
5568 struct user_namespace *user_ns;
5571 if (!(fp->daccess & FILE_WRITE_ATTRIBUTES_LE))
5576 inode = file_inode(filp);
5577 user_ns = file_mnt_user_ns(filp);
5579 if (file_info->CreationTime)
5580 fp->create_time = le64_to_cpu(file_info->CreationTime);
5582 if (file_info->LastAccessTime) {
5583 attrs.ia_atime = ksmbd_NTtimeToUnix(file_info->LastAccessTime);
5584 attrs.ia_valid |= (ATTR_ATIME | ATTR_ATIME_SET);
5587 attrs.ia_valid |= ATTR_CTIME;
5588 if (file_info->ChangeTime)
5589 attrs.ia_ctime = ksmbd_NTtimeToUnix(file_info->ChangeTime);
5591 attrs.ia_ctime = inode->i_ctime;
5593 if (file_info->LastWriteTime) {
5594 attrs.ia_mtime = ksmbd_NTtimeToUnix(file_info->LastWriteTime);
5595 attrs.ia_valid |= (ATTR_MTIME | ATTR_MTIME_SET);
5598 if (file_info->Attributes) {
5599 if (!S_ISDIR(inode->i_mode) &&
5600 file_info->Attributes & FILE_ATTRIBUTE_DIRECTORY_LE) {
5601 pr_err("can't change a file to a directory\n");
5605 if (!(S_ISDIR(inode->i_mode) && file_info->Attributes == FILE_ATTRIBUTE_NORMAL_LE))
5606 fp->f_ci->m_fattr = file_info->Attributes |
5607 (fp->f_ci->m_fattr & FILE_ATTRIBUTE_DIRECTORY_LE);
5610 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_STORE_DOS_ATTRS) &&
5611 (file_info->CreationTime || file_info->Attributes)) {
5612 struct xattr_dos_attrib da = {0};
5615 da.itime = fp->itime;
5616 da.create_time = fp->create_time;
5617 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
5618 da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
5619 XATTR_DOSINFO_ITIME;
5621 rc = ksmbd_vfs_set_dos_attrib_xattr(user_ns,
5622 filp->f_path.dentry, &da);
5625 "failed to restore file attribute in EA\n");
5629 if (attrs.ia_valid) {
5630 struct dentry *dentry = filp->f_path.dentry;
5631 struct inode *inode = d_inode(dentry);
5633 if (IS_IMMUTABLE(inode) || IS_APPEND(inode))
5637 inode->i_ctime = attrs.ia_ctime;
5638 attrs.ia_valid &= ~ATTR_CTIME;
5639 rc = notify_change(user_ns, dentry, &attrs, NULL);
5640 inode_unlock(inode);
5645 static int set_file_allocation_info(struct ksmbd_work *work,
5646 struct ksmbd_file *fp,
5647 struct smb2_file_alloc_info *file_alloc_info)
5650 * TODO : It's working fine only when store dos attributes
5651 * is not yes. need to implement a logic which works
5652 * properly with any smb.conf option
5656 struct inode *inode;
5659 if (!(fp->daccess & FILE_WRITE_DATA_LE))
5662 alloc_blks = (le64_to_cpu(file_alloc_info->AllocationSize) + 511) >> 9;
5663 inode = file_inode(fp->filp);
5665 if (alloc_blks > inode->i_blocks) {
5666 smb_break_all_levII_oplock(work, fp, 1);
5667 rc = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
5669 if (rc && rc != -EOPNOTSUPP) {
5670 pr_err("vfs_fallocate is failed : %d\n", rc);
5673 } else if (alloc_blks < inode->i_blocks) {
5677 * Allocation size could be smaller than original one
5678 * which means allocated blocks in file should be
5679 * deallocated. use truncate to cut out it, but inode
5680 * size is also updated with truncate offset.
5681 * inode size is retained by backup inode size.
5683 size = i_size_read(inode);
5684 rc = ksmbd_vfs_truncate(work, fp, alloc_blks * 512);
5686 pr_err("truncate failed! filename : %s, err %d\n",
5690 if (size < alloc_blks * 512)
5691 i_size_write(inode, size);
5696 static int set_end_of_file_info(struct ksmbd_work *work, struct ksmbd_file *fp,
5697 struct smb2_file_eof_info *file_eof_info)
5700 struct inode *inode;
5703 if (!(fp->daccess & FILE_WRITE_DATA_LE))
5706 newsize = le64_to_cpu(file_eof_info->EndOfFile);
5707 inode = file_inode(fp->filp);
5710 * If FILE_END_OF_FILE_INFORMATION of set_info_file is called
5711 * on FAT32 shared device, truncate execution time is too long
5712 * and network error could cause from windows client. because
5713 * truncate of some filesystem like FAT32 fill zero data in
5716 if (inode->i_sb->s_magic != MSDOS_SUPER_MAGIC) {
5717 ksmbd_debug(SMB, "filename : %s truncated to newsize %lld\n",
5718 fp->filename, newsize);
5719 rc = ksmbd_vfs_truncate(work, fp, newsize);
5721 ksmbd_debug(SMB, "truncate failed! filename : %s err %d\n",
5731 static int set_rename_info(struct ksmbd_work *work, struct ksmbd_file *fp,
5732 struct smb2_file_rename_info *rename_info,
5733 unsigned int buf_len)
5735 struct user_namespace *user_ns;
5736 struct ksmbd_file *parent_fp;
5737 struct dentry *parent;
5738 struct dentry *dentry = fp->filp->f_path.dentry;
5741 if (!(fp->daccess & FILE_DELETE_LE)) {
5742 pr_err("no right to delete : 0x%x\n", fp->daccess);
5746 if (buf_len < (u64)sizeof(struct smb2_file_rename_info) +
5747 le32_to_cpu(rename_info->FileNameLength))
5750 user_ns = file_mnt_user_ns(fp->filp);
5751 if (ksmbd_stream_fd(fp))
5754 parent = dget_parent(dentry);
5755 ret = ksmbd_vfs_lock_parent(user_ns, parent, dentry);
5761 parent_fp = ksmbd_lookup_fd_inode(d_inode(parent));
5762 inode_unlock(d_inode(parent));
5766 if (parent_fp->daccess & FILE_DELETE_LE) {
5767 pr_err("parent dir is opened with delete access\n");
5772 return smb2_rename(work, fp, user_ns, rename_info,
5773 work->sess->conn->local_nls);
5776 static int set_file_disposition_info(struct ksmbd_file *fp,
5777 struct smb2_file_disposition_info *file_info)
5779 struct inode *inode;
5781 if (!(fp->daccess & FILE_DELETE_LE)) {
5782 pr_err("no right to delete : 0x%x\n", fp->daccess);
5786 inode = file_inode(fp->filp);
5787 if (file_info->DeletePending) {
5788 if (S_ISDIR(inode->i_mode) &&
5789 ksmbd_vfs_empty_dir(fp) == -ENOTEMPTY)
5791 ksmbd_set_inode_pending_delete(fp);
5793 ksmbd_clear_inode_pending_delete(fp);
5798 static int set_file_position_info(struct ksmbd_file *fp,
5799 struct smb2_file_pos_info *file_info)
5801 loff_t current_byte_offset;
5802 unsigned long sector_size;
5803 struct inode *inode;
5805 inode = file_inode(fp->filp);
5806 current_byte_offset = le64_to_cpu(file_info->CurrentByteOffset);
5807 sector_size = inode->i_sb->s_blocksize;
5809 if (current_byte_offset < 0 ||
5810 (fp->coption == FILE_NO_INTERMEDIATE_BUFFERING_LE &&
5811 current_byte_offset & (sector_size - 1))) {
5812 pr_err("CurrentByteOffset is not valid : %llu\n",
5813 current_byte_offset);
5817 fp->filp->f_pos = current_byte_offset;
5821 static int set_file_mode_info(struct ksmbd_file *fp,
5822 struct smb2_file_mode_info *file_info)
5826 mode = file_info->Mode;
5828 if ((mode & ~FILE_MODE_INFO_MASK)) {
5829 pr_err("Mode is not valid : 0x%x\n", le32_to_cpu(mode));
5834 * TODO : need to implement consideration for
5835 * FILE_SYNCHRONOUS_IO_ALERT and FILE_SYNCHRONOUS_IO_NONALERT
5837 ksmbd_vfs_set_fadvise(fp->filp, mode);
5843 * smb2_set_info_file() - handler for smb2 set info command
5844 * @work: smb work containing set info command buffer
5845 * @fp: ksmbd_file pointer
5846 * @req: request buffer pointer
5847 * @share: ksmbd_share_config pointer
5849 * Return: 0 on success, otherwise error
5850 * TODO: need to implement an error handling for STATUS_INFO_LENGTH_MISMATCH
5852 static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp,
5853 struct smb2_set_info_req *req,
5854 struct ksmbd_share_config *share)
5856 unsigned int buf_len = le32_to_cpu(req->BufferLength);
5858 switch (req->FileInfoClass) {
5859 case FILE_BASIC_INFORMATION:
5861 if (buf_len < sizeof(struct smb2_file_basic_info))
5864 return set_file_basic_info(fp, (struct smb2_file_basic_info *)req->Buffer, share);
5866 case FILE_ALLOCATION_INFORMATION:
5868 if (buf_len < sizeof(struct smb2_file_alloc_info))
5871 return set_file_allocation_info(work, fp,
5872 (struct smb2_file_alloc_info *)req->Buffer);
5874 case FILE_END_OF_FILE_INFORMATION:
5876 if (buf_len < sizeof(struct smb2_file_eof_info))
5879 return set_end_of_file_info(work, fp,
5880 (struct smb2_file_eof_info *)req->Buffer);
5882 case FILE_RENAME_INFORMATION:
5884 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
5886 "User does not have write permission\n");
5890 if (buf_len < sizeof(struct smb2_file_rename_info))
5893 return set_rename_info(work, fp,
5894 (struct smb2_file_rename_info *)req->Buffer,
5897 case FILE_LINK_INFORMATION:
5899 if (buf_len < sizeof(struct smb2_file_link_info))
5902 return smb2_create_link(work, work->tcon->share_conf,
5903 (struct smb2_file_link_info *)req->Buffer,
5905 work->sess->conn->local_nls);
5907 case FILE_DISPOSITION_INFORMATION:
5909 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
5911 "User does not have write permission\n");
5915 if (buf_len < sizeof(struct smb2_file_disposition_info))
5918 return set_file_disposition_info(fp,
5919 (struct smb2_file_disposition_info *)req->Buffer);
5921 case FILE_FULL_EA_INFORMATION:
5923 if (!(fp->daccess & FILE_WRITE_EA_LE)) {
5924 pr_err("Not permitted to write ext attr: 0x%x\n",
5929 if (buf_len < sizeof(struct smb2_ea_info))
5932 return smb2_set_ea((struct smb2_ea_info *)req->Buffer,
5933 buf_len, &fp->filp->f_path);
5935 case FILE_POSITION_INFORMATION:
5937 if (buf_len < sizeof(struct smb2_file_pos_info))
5940 return set_file_position_info(fp, (struct smb2_file_pos_info *)req->Buffer);
5942 case FILE_MODE_INFORMATION:
5944 if (buf_len < sizeof(struct smb2_file_mode_info))
5947 return set_file_mode_info(fp, (struct smb2_file_mode_info *)req->Buffer);
5951 pr_err("Unimplemented Fileinfoclass :%d\n", req->FileInfoClass);
5955 static int smb2_set_info_sec(struct ksmbd_file *fp, int addition_info,
5956 char *buffer, int buf_len)
5958 struct smb_ntsd *pntsd = (struct smb_ntsd *)buffer;
5960 fp->saccess |= FILE_SHARE_DELETE_LE;
5962 return set_info_sec(fp->conn, fp->tcon, &fp->filp->f_path, pntsd,
5967 * smb2_set_info() - handler for smb2 set info command handler
5968 * @work: smb work containing set info request buffer
5970 * Return: 0 on success, otherwise error
5972 int smb2_set_info(struct ksmbd_work *work)
5974 struct smb2_set_info_req *req;
5975 struct smb2_set_info_rsp *rsp;
5976 struct ksmbd_file *fp;
5978 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
5980 ksmbd_debug(SMB, "Received set info request\n");
5982 if (work->next_smb2_rcv_hdr_off) {
5983 req = ksmbd_req_buf_next(work);
5984 rsp = ksmbd_resp_buf_next(work);
5985 if (!has_file_id(req->VolatileFileId)) {
5986 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
5987 work->compound_fid);
5988 id = work->compound_fid;
5989 pid = work->compound_pfid;
5992 req = smb2_get_msg(work->request_buf);
5993 rsp = smb2_get_msg(work->response_buf);
5996 if (!has_file_id(id)) {
5997 id = req->VolatileFileId;
5998 pid = req->PersistentFileId;
6001 fp = ksmbd_lookup_fd_slow(work, id, pid);
6003 ksmbd_debug(SMB, "Invalid id for close: %u\n", id);
6008 switch (req->InfoType) {
6009 case SMB2_O_INFO_FILE:
6010 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
6011 rc = smb2_set_info_file(work, fp, req, work->tcon->share_conf);
6013 case SMB2_O_INFO_SECURITY:
6014 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
6015 if (ksmbd_override_fsids(work)) {
6019 rc = smb2_set_info_sec(fp,
6020 le32_to_cpu(req->AdditionalInformation),
6022 le32_to_cpu(req->BufferLength));
6023 ksmbd_revert_fsids(work);
6032 rsp->StructureSize = cpu_to_le16(2);
6033 inc_rfc1001_len(work->response_buf, 2);
6034 ksmbd_fd_put(work, fp);
6038 if (rc == -EACCES || rc == -EPERM || rc == -EXDEV)
6039 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6040 else if (rc == -EINVAL)
6041 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6042 else if (rc == -ESHARE)
6043 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6044 else if (rc == -ENOENT)
6045 rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
6046 else if (rc == -EBUSY || rc == -ENOTEMPTY)
6047 rsp->hdr.Status = STATUS_DIRECTORY_NOT_EMPTY;
6048 else if (rc == -EAGAIN)
6049 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6050 else if (rc == -EBADF || rc == -ESTALE)
6051 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6052 else if (rc == -EEXIST)
6053 rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
6054 else if (rsp->hdr.Status == 0 || rc == -EOPNOTSUPP)
6055 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
6056 smb2_set_err_rsp(work);
6057 ksmbd_fd_put(work, fp);
6058 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n", rc);
6063 * smb2_read_pipe() - handler for smb2 read from IPC pipe
6064 * @work: smb work containing read IPC pipe command buffer
6066 * Return: 0 on success, otherwise error
6068 static noinline int smb2_read_pipe(struct ksmbd_work *work)
6070 int nbytes = 0, err;
6072 struct ksmbd_rpc_command *rpc_resp;
6073 struct smb2_read_req *req = smb2_get_msg(work->request_buf);
6074 struct smb2_read_rsp *rsp = smb2_get_msg(work->response_buf);
6076 id = req->VolatileFileId;
6078 inc_rfc1001_len(work->response_buf, 16);
6079 rpc_resp = ksmbd_rpc_read(work->sess, id);
6081 if (rpc_resp->flags != KSMBD_RPC_OK) {
6086 work->aux_payload_buf =
6087 kvmalloc(rpc_resp->payload_sz, GFP_KERNEL | __GFP_ZERO);
6088 if (!work->aux_payload_buf) {
6093 memcpy(work->aux_payload_buf, rpc_resp->payload,
6094 rpc_resp->payload_sz);
6096 nbytes = rpc_resp->payload_sz;
6097 work->resp_hdr_sz = get_rfc1002_len(work->response_buf) + 4;
6098 work->aux_payload_sz = nbytes;
6102 rsp->StructureSize = cpu_to_le16(17);
6103 rsp->DataOffset = 80;
6105 rsp->DataLength = cpu_to_le32(nbytes);
6106 rsp->DataRemaining = 0;
6108 inc_rfc1001_len(work->response_buf, nbytes);
6112 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
6113 smb2_set_err_rsp(work);
6118 static int smb2_set_remote_key_for_rdma(struct ksmbd_work *work,
6119 struct smb2_buffer_desc_v1 *desc,
6121 __le16 ChannelInfoOffset,
6122 __le16 ChannelInfoLength)
6124 unsigned int i, ch_count;
6126 if (work->conn->dialect == SMB30_PROT_ID &&
6127 Channel != SMB2_CHANNEL_RDMA_V1)
6130 ch_count = le16_to_cpu(ChannelInfoLength) / sizeof(*desc);
6131 if (ksmbd_debug_types & KSMBD_DEBUG_RDMA) {
6132 for (i = 0; i < ch_count; i++) {
6133 pr_info("RDMA r/w request %#x: token %#x, length %#x\n",
6135 le32_to_cpu(desc[i].token),
6136 le32_to_cpu(desc[i].length));
6139 if (ch_count != 1) {
6140 ksmbd_debug(RDMA, "RDMA multiple buffer descriptors %d are not supported yet\n",
6145 work->need_invalidate_rkey =
6146 (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE);
6147 work->remote_key = le32_to_cpu(desc->token);
6151 static ssize_t smb2_read_rdma_channel(struct ksmbd_work *work,
6152 struct smb2_read_req *req, void *data_buf,
6155 struct smb2_buffer_desc_v1 *desc =
6156 (struct smb2_buffer_desc_v1 *)&req->Buffer[0];
6159 err = ksmbd_conn_rdma_write(work->conn, data_buf, length,
6160 le32_to_cpu(desc->token),
6161 le64_to_cpu(desc->offset),
6162 le32_to_cpu(desc->length));
6170 * smb2_read() - handler for smb2 read from file
6171 * @work: smb work containing read command buffer
6173 * Return: 0 on success, otherwise error
6175 int smb2_read(struct ksmbd_work *work)
6177 struct ksmbd_conn *conn = work->conn;
6178 struct smb2_read_req *req;
6179 struct smb2_read_rsp *rsp;
6180 struct ksmbd_file *fp = NULL;
6182 size_t length, mincount;
6183 ssize_t nbytes = 0, remain_bytes = 0;
6186 WORK_BUFFERS(work, req, rsp);
6188 if (test_share_config_flag(work->tcon->share_conf,
6189 KSMBD_SHARE_FLAG_PIPE)) {
6190 ksmbd_debug(SMB, "IPC pipe read request\n");
6191 return smb2_read_pipe(work);
6194 if (req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE ||
6195 req->Channel == SMB2_CHANNEL_RDMA_V1) {
6196 unsigned int ch_offset = le16_to_cpu(req->ReadChannelInfoOffset);
6198 if (ch_offset < offsetof(struct smb2_read_req, Buffer)) {
6202 err = smb2_set_remote_key_for_rdma(work,
6203 (struct smb2_buffer_desc_v1 *)
6204 ((char *)req + ch_offset),
6206 req->ReadChannelInfoOffset,
6207 req->ReadChannelInfoLength);
6212 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
6218 if (!(fp->daccess & (FILE_READ_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
6219 pr_err("Not permitted to read : 0x%x\n", fp->daccess);
6224 offset = le64_to_cpu(req->Offset);
6225 length = le32_to_cpu(req->Length);
6226 mincount = le32_to_cpu(req->MinimumCount);
6228 if (length > conn->vals->max_read_size) {
6229 ksmbd_debug(SMB, "limiting read size to max size(%u)\n",
6230 conn->vals->max_read_size);
6235 ksmbd_debug(SMB, "filename %pd, offset %lld, len %zu\n",
6236 fp->filp->f_path.dentry, offset, length);
6238 work->aux_payload_buf = kvmalloc(length, GFP_KERNEL | __GFP_ZERO);
6239 if (!work->aux_payload_buf) {
6244 nbytes = ksmbd_vfs_read(work, fp, length, &offset);
6250 if ((nbytes == 0 && length != 0) || nbytes < mincount) {
6251 kvfree(work->aux_payload_buf);
6252 work->aux_payload_buf = NULL;
6253 rsp->hdr.Status = STATUS_END_OF_FILE;
6254 smb2_set_err_rsp(work);
6255 ksmbd_fd_put(work, fp);
6259 ksmbd_debug(SMB, "nbytes %zu, offset %lld mincount %zu\n",
6260 nbytes, offset, mincount);
6262 if (req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE ||
6263 req->Channel == SMB2_CHANNEL_RDMA_V1) {
6264 /* write data to the client using rdma channel */
6265 remain_bytes = smb2_read_rdma_channel(work, req,
6266 work->aux_payload_buf,
6268 kvfree(work->aux_payload_buf);
6269 work->aux_payload_buf = NULL;
6272 if (remain_bytes < 0) {
6273 err = (int)remain_bytes;
6278 rsp->StructureSize = cpu_to_le16(17);
6279 rsp->DataOffset = 80;
6281 rsp->DataLength = cpu_to_le32(nbytes);
6282 rsp->DataRemaining = cpu_to_le32(remain_bytes);
6284 inc_rfc1001_len(work->response_buf, 16);
6285 work->resp_hdr_sz = get_rfc1002_len(work->response_buf) + 4;
6286 work->aux_payload_sz = nbytes;
6287 inc_rfc1001_len(work->response_buf, nbytes);
6288 ksmbd_fd_put(work, fp);
6294 rsp->hdr.Status = STATUS_INVALID_DEVICE_REQUEST;
6295 else if (err == -EAGAIN)
6296 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6297 else if (err == -ENOENT)
6298 rsp->hdr.Status = STATUS_FILE_CLOSED;
6299 else if (err == -EACCES)
6300 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6301 else if (err == -ESHARE)
6302 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6303 else if (err == -EINVAL)
6304 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6306 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6308 smb2_set_err_rsp(work);
6310 ksmbd_fd_put(work, fp);
6315 * smb2_write_pipe() - handler for smb2 write on IPC pipe
6316 * @work: smb work containing write IPC pipe command buffer
6318 * Return: 0 on success, otherwise error
6320 static noinline int smb2_write_pipe(struct ksmbd_work *work)
6322 struct smb2_write_req *req = smb2_get_msg(work->request_buf);
6323 struct smb2_write_rsp *rsp = smb2_get_msg(work->response_buf);
6324 struct ksmbd_rpc_command *rpc_resp;
6326 int err = 0, ret = 0;
6330 length = le32_to_cpu(req->Length);
6331 id = req->VolatileFileId;
6333 if (le16_to_cpu(req->DataOffset) ==
6334 offsetof(struct smb2_write_req, Buffer)) {
6335 data_buf = (char *)&req->Buffer[0];
6337 if ((u64)le16_to_cpu(req->DataOffset) + length >
6338 get_rfc1002_len(work->request_buf)) {
6339 pr_err("invalid write data offset %u, smb_len %u\n",
6340 le16_to_cpu(req->DataOffset),
6341 get_rfc1002_len(work->request_buf));
6346 data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
6347 le16_to_cpu(req->DataOffset));
6350 rpc_resp = ksmbd_rpc_write(work->sess, id, data_buf, length);
6352 if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
6353 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
6355 smb2_set_err_rsp(work);
6358 if (rpc_resp->flags != KSMBD_RPC_OK) {
6359 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6360 smb2_set_err_rsp(work);
6367 rsp->StructureSize = cpu_to_le16(17);
6368 rsp->DataOffset = 0;
6370 rsp->DataLength = cpu_to_le32(length);
6371 rsp->DataRemaining = 0;
6373 inc_rfc1001_len(work->response_buf, 16);
6377 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6378 smb2_set_err_rsp(work);
6384 static ssize_t smb2_write_rdma_channel(struct ksmbd_work *work,
6385 struct smb2_write_req *req,
6386 struct ksmbd_file *fp,
6387 loff_t offset, size_t length, bool sync)
6389 struct smb2_buffer_desc_v1 *desc;
6394 desc = (struct smb2_buffer_desc_v1 *)&req->Buffer[0];
6396 data_buf = kvmalloc(length, GFP_KERNEL | __GFP_ZERO);
6400 ret = ksmbd_conn_rdma_read(work->conn, data_buf, length,
6401 le32_to_cpu(desc->token),
6402 le64_to_cpu(desc->offset),
6403 le32_to_cpu(desc->length));
6409 ret = ksmbd_vfs_write(work, fp, data_buf, length, &offset, sync, &nbytes);
6418 * smb2_write() - handler for smb2 write from file
6419 * @work: smb work containing write command buffer
6421 * Return: 0 on success, otherwise error
6423 int smb2_write(struct ksmbd_work *work)
6425 struct smb2_write_req *req;
6426 struct smb2_write_rsp *rsp;
6427 struct ksmbd_file *fp = NULL;
6432 bool writethrough = false;
6435 WORK_BUFFERS(work, req, rsp);
6437 if (test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_PIPE)) {
6438 ksmbd_debug(SMB, "IPC pipe write request\n");
6439 return smb2_write_pipe(work);
6442 if (req->Channel == SMB2_CHANNEL_RDMA_V1 ||
6443 req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE) {
6444 unsigned int ch_offset = le16_to_cpu(req->WriteChannelInfoOffset);
6446 if (req->Length != 0 || req->DataOffset != 0 ||
6447 ch_offset < offsetof(struct smb2_write_req, Buffer)) {
6451 err = smb2_set_remote_key_for_rdma(work,
6452 (struct smb2_buffer_desc_v1 *)
6453 ((char *)req + ch_offset),
6455 req->WriteChannelInfoOffset,
6456 req->WriteChannelInfoLength);
6461 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
6462 ksmbd_debug(SMB, "User does not have write permission\n");
6467 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
6473 if (!(fp->daccess & (FILE_WRITE_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
6474 pr_err("Not permitted to write : 0x%x\n", fp->daccess);
6479 offset = le64_to_cpu(req->Offset);
6480 length = le32_to_cpu(req->Length);
6482 if (length > work->conn->vals->max_write_size) {
6483 ksmbd_debug(SMB, "limiting write size to max size(%u)\n",
6484 work->conn->vals->max_write_size);
6489 if (le32_to_cpu(req->Flags) & SMB2_WRITEFLAG_WRITE_THROUGH)
6490 writethrough = true;
6492 if (req->Channel != SMB2_CHANNEL_RDMA_V1 &&
6493 req->Channel != SMB2_CHANNEL_RDMA_V1_INVALIDATE) {
6494 if (le16_to_cpu(req->DataOffset) ==
6495 offsetof(struct smb2_write_req, Buffer)) {
6496 data_buf = (char *)&req->Buffer[0];
6498 if ((u64)le16_to_cpu(req->DataOffset) + length >
6499 get_rfc1002_len(work->request_buf)) {
6500 pr_err("invalid write data offset %u, smb_len %u\n",
6501 le16_to_cpu(req->DataOffset),
6502 get_rfc1002_len(work->request_buf));
6507 data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
6508 le16_to_cpu(req->DataOffset));
6511 ksmbd_debug(SMB, "flags %u\n", le32_to_cpu(req->Flags));
6512 if (le32_to_cpu(req->Flags) & SMB2_WRITEFLAG_WRITE_THROUGH)
6513 writethrough = true;
6515 ksmbd_debug(SMB, "filename %pd, offset %lld, len %zu\n",
6516 fp->filp->f_path.dentry, offset, length);
6517 err = ksmbd_vfs_write(work, fp, data_buf, length, &offset,
6518 writethrough, &nbytes);
6522 /* read data from the client using rdma channel, and
6525 nbytes = smb2_write_rdma_channel(work, req, fp, offset,
6526 le32_to_cpu(req->RemainingBytes),
6534 rsp->StructureSize = cpu_to_le16(17);
6535 rsp->DataOffset = 0;
6537 rsp->DataLength = cpu_to_le32(nbytes);
6538 rsp->DataRemaining = 0;
6540 inc_rfc1001_len(work->response_buf, 16);
6541 ksmbd_fd_put(work, fp);
6546 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6547 else if (err == -ENOSPC || err == -EFBIG)
6548 rsp->hdr.Status = STATUS_DISK_FULL;
6549 else if (err == -ENOENT)
6550 rsp->hdr.Status = STATUS_FILE_CLOSED;
6551 else if (err == -EACCES)
6552 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6553 else if (err == -ESHARE)
6554 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6555 else if (err == -EINVAL)
6556 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6558 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6560 smb2_set_err_rsp(work);
6561 ksmbd_fd_put(work, fp);
6566 * smb2_flush() - handler for smb2 flush file - fsync
6567 * @work: smb work containing flush command buffer
6569 * Return: 0 on success, otherwise error
6571 int smb2_flush(struct ksmbd_work *work)
6573 struct smb2_flush_req *req;
6574 struct smb2_flush_rsp *rsp;
6577 WORK_BUFFERS(work, req, rsp);
6579 ksmbd_debug(SMB, "SMB2_FLUSH called for fid %llu\n", req->VolatileFileId);
6581 err = ksmbd_vfs_fsync(work, req->VolatileFileId, req->PersistentFileId);
6585 rsp->StructureSize = cpu_to_le16(4);
6587 inc_rfc1001_len(work->response_buf, 4);
6592 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6593 smb2_set_err_rsp(work);
6600 * smb2_cancel() - handler for smb2 cancel command
6601 * @work: smb work containing cancel command buffer
6603 * Return: 0 on success, otherwise error
6605 int smb2_cancel(struct ksmbd_work *work)
6607 struct ksmbd_conn *conn = work->conn;
6608 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
6609 struct smb2_hdr *chdr;
6610 struct ksmbd_work *cancel_work = NULL, *iter;
6611 struct list_head *command_list;
6613 ksmbd_debug(SMB, "smb2 cancel called on mid %llu, async flags 0x%x\n",
6614 hdr->MessageId, hdr->Flags);
6616 if (hdr->Flags & SMB2_FLAGS_ASYNC_COMMAND) {
6617 command_list = &conn->async_requests;
6619 spin_lock(&conn->request_lock);
6620 list_for_each_entry(iter, command_list,
6621 async_request_entry) {
6622 chdr = smb2_get_msg(iter->request_buf);
6624 if (iter->async_id !=
6625 le64_to_cpu(hdr->Id.AsyncId))
6629 "smb2 with AsyncId %llu cancelled command = 0x%x\n",
6630 le64_to_cpu(hdr->Id.AsyncId),
6631 le16_to_cpu(chdr->Command));
6635 spin_unlock(&conn->request_lock);
6637 command_list = &conn->requests;
6639 spin_lock(&conn->request_lock);
6640 list_for_each_entry(iter, command_list, request_entry) {
6641 chdr = smb2_get_msg(iter->request_buf);
6643 if (chdr->MessageId != hdr->MessageId ||
6648 "smb2 with mid %llu cancelled command = 0x%x\n",
6649 le64_to_cpu(hdr->MessageId),
6650 le16_to_cpu(chdr->Command));
6654 spin_unlock(&conn->request_lock);
6658 cancel_work->state = KSMBD_WORK_CANCELLED;
6659 if (cancel_work->cancel_fn)
6660 cancel_work->cancel_fn(cancel_work->cancel_argv);
6663 /* For SMB2_CANCEL command itself send no response*/
6664 work->send_no_response = 1;
6668 struct file_lock *smb_flock_init(struct file *f)
6670 struct file_lock *fl;
6672 fl = locks_alloc_lock();
6676 locks_init_lock(fl);
6679 fl->fl_pid = current->tgid;
6681 fl->fl_flags = FL_POSIX;
6683 fl->fl_lmops = NULL;
6689 static int smb2_set_flock_flags(struct file_lock *flock, int flags)
6693 /* Checking for wrong flag combination during lock request*/
6695 case SMB2_LOCKFLAG_SHARED:
6696 ksmbd_debug(SMB, "received shared request\n");
6698 flock->fl_type = F_RDLCK;
6699 flock->fl_flags |= FL_SLEEP;
6701 case SMB2_LOCKFLAG_EXCLUSIVE:
6702 ksmbd_debug(SMB, "received exclusive request\n");
6704 flock->fl_type = F_WRLCK;
6705 flock->fl_flags |= FL_SLEEP;
6707 case SMB2_LOCKFLAG_SHARED | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
6709 "received shared & fail immediately request\n");
6711 flock->fl_type = F_RDLCK;
6713 case SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
6715 "received exclusive & fail immediately request\n");
6717 flock->fl_type = F_WRLCK;
6719 case SMB2_LOCKFLAG_UNLOCK:
6720 ksmbd_debug(SMB, "received unlock request\n");
6721 flock->fl_type = F_UNLCK;
6729 static struct ksmbd_lock *smb2_lock_init(struct file_lock *flock,
6730 unsigned int cmd, int flags,
6731 struct list_head *lock_list)
6733 struct ksmbd_lock *lock;
6735 lock = kzalloc(sizeof(struct ksmbd_lock), GFP_KERNEL);
6741 lock->start = flock->fl_start;
6742 lock->end = flock->fl_end;
6743 lock->flags = flags;
6744 if (lock->start == lock->end)
6746 INIT_LIST_HEAD(&lock->clist);
6747 INIT_LIST_HEAD(&lock->flist);
6748 INIT_LIST_HEAD(&lock->llist);
6749 list_add_tail(&lock->llist, lock_list);
6754 static void smb2_remove_blocked_lock(void **argv)
6756 struct file_lock *flock = (struct file_lock *)argv[0];
6758 ksmbd_vfs_posix_lock_unblock(flock);
6759 wake_up(&flock->fl_wait);
6762 static inline bool lock_defer_pending(struct file_lock *fl)
6764 /* check pending lock waiters */
6765 return waitqueue_active(&fl->fl_wait);
6769 * smb2_lock() - handler for smb2 file lock command
6770 * @work: smb work containing lock command buffer
6772 * Return: 0 on success, otherwise error
6774 int smb2_lock(struct ksmbd_work *work)
6776 struct smb2_lock_req *req = smb2_get_msg(work->request_buf);
6777 struct smb2_lock_rsp *rsp = smb2_get_msg(work->response_buf);
6778 struct smb2_lock_element *lock_ele;
6779 struct ksmbd_file *fp = NULL;
6780 struct file_lock *flock = NULL;
6781 struct file *filp = NULL;
6785 int err = -EIO, i, rc = 0;
6786 u64 lock_start, lock_length;
6787 struct ksmbd_lock *smb_lock = NULL, *cmp_lock, *tmp, *tmp2;
6788 struct ksmbd_conn *conn;
6790 LIST_HEAD(lock_list);
6791 LIST_HEAD(rollback_list);
6794 ksmbd_debug(SMB, "Received lock request\n");
6795 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
6797 ksmbd_debug(SMB, "Invalid file id for lock : %llu\n", req->VolatileFileId);
6803 lock_count = le16_to_cpu(req->LockCount);
6804 lock_ele = req->locks;
6806 ksmbd_debug(SMB, "lock count is %d\n", lock_count);
6812 for (i = 0; i < lock_count; i++) {
6813 flags = le32_to_cpu(lock_ele[i].Flags);
6815 flock = smb_flock_init(filp);
6819 cmd = smb2_set_flock_flags(flock, flags);
6821 lock_start = le64_to_cpu(lock_ele[i].Offset);
6822 lock_length = le64_to_cpu(lock_ele[i].Length);
6823 if (lock_start > U64_MAX - lock_length) {
6824 pr_err("Invalid lock range requested\n");
6825 rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
6829 if (lock_start > OFFSET_MAX)
6830 flock->fl_start = OFFSET_MAX;
6832 flock->fl_start = lock_start;
6834 lock_length = le64_to_cpu(lock_ele[i].Length);
6835 if (lock_length > OFFSET_MAX - flock->fl_start)
6836 lock_length = OFFSET_MAX - flock->fl_start;
6838 flock->fl_end = flock->fl_start + lock_length;
6840 if (flock->fl_end < flock->fl_start) {
6842 "the end offset(%llx) is smaller than the start offset(%llx)\n",
6843 flock->fl_end, flock->fl_start);
6844 rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
6848 /* Check conflict locks in one request */
6849 list_for_each_entry(cmp_lock, &lock_list, llist) {
6850 if (cmp_lock->fl->fl_start <= flock->fl_start &&
6851 cmp_lock->fl->fl_end >= flock->fl_end) {
6852 if (cmp_lock->fl->fl_type != F_UNLCK &&
6853 flock->fl_type != F_UNLCK) {
6854 pr_err("conflict two locks in one request\n");
6861 smb_lock = smb2_lock_init(flock, cmd, flags, &lock_list);
6868 list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
6869 if (smb_lock->cmd < 0) {
6874 if (!(smb_lock->flags & SMB2_LOCKFLAG_MASK)) {
6879 if ((prior_lock & (SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_SHARED) &&
6880 smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) ||
6881 (prior_lock == SMB2_LOCKFLAG_UNLOCK &&
6882 !(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK))) {
6887 prior_lock = smb_lock->flags;
6889 if (!(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) &&
6890 !(smb_lock->flags & SMB2_LOCKFLAG_FAIL_IMMEDIATELY))
6894 /* check locks in connection list */
6895 read_lock(&conn_list_lock);
6896 list_for_each_entry(conn, &conn_list, conns_list) {
6897 spin_lock(&conn->llist_lock);
6898 list_for_each_entry_safe(cmp_lock, tmp2, &conn->lock_list, clist) {
6899 if (file_inode(cmp_lock->fl->fl_file) !=
6900 file_inode(smb_lock->fl->fl_file))
6903 if (smb_lock->fl->fl_type == F_UNLCK) {
6904 if (cmp_lock->fl->fl_file == smb_lock->fl->fl_file &&
6905 cmp_lock->start == smb_lock->start &&
6906 cmp_lock->end == smb_lock->end &&
6907 !lock_defer_pending(cmp_lock->fl)) {
6909 list_del(&cmp_lock->flist);
6910 list_del(&cmp_lock->clist);
6911 spin_unlock(&conn->llist_lock);
6912 read_unlock(&conn_list_lock);
6914 locks_free_lock(cmp_lock->fl);
6921 if (cmp_lock->fl->fl_file == smb_lock->fl->fl_file) {
6922 if (smb_lock->flags & SMB2_LOCKFLAG_SHARED)
6925 if (cmp_lock->flags & SMB2_LOCKFLAG_SHARED)
6929 /* check zero byte lock range */
6930 if (cmp_lock->zero_len && !smb_lock->zero_len &&
6931 cmp_lock->start > smb_lock->start &&
6932 cmp_lock->start < smb_lock->end) {
6933 spin_unlock(&conn->llist_lock);
6934 read_unlock(&conn_list_lock);
6935 pr_err("previous lock conflict with zero byte lock range\n");
6939 if (smb_lock->zero_len && !cmp_lock->zero_len &&
6940 smb_lock->start > cmp_lock->start &&
6941 smb_lock->start < cmp_lock->end) {
6942 spin_unlock(&conn->llist_lock);
6943 read_unlock(&conn_list_lock);
6944 pr_err("current lock conflict with zero byte lock range\n");
6948 if (((cmp_lock->start <= smb_lock->start &&
6949 cmp_lock->end > smb_lock->start) ||
6950 (cmp_lock->start < smb_lock->end &&
6951 cmp_lock->end >= smb_lock->end)) &&
6952 !cmp_lock->zero_len && !smb_lock->zero_len) {
6953 spin_unlock(&conn->llist_lock);
6954 read_unlock(&conn_list_lock);
6955 pr_err("Not allow lock operation on exclusive lock range\n");
6959 spin_unlock(&conn->llist_lock);
6961 read_unlock(&conn_list_lock);
6963 if (smb_lock->fl->fl_type == F_UNLCK && nolock) {
6964 pr_err("Try to unlock nolocked range\n");
6965 rsp->hdr.Status = STATUS_RANGE_NOT_LOCKED;
6970 if (smb_lock->zero_len) {
6975 flock = smb_lock->fl;
6976 list_del(&smb_lock->llist);
6978 rc = vfs_lock_file(filp, smb_lock->cmd, flock, NULL);
6980 if (flags & SMB2_LOCKFLAG_UNLOCK) {
6982 ksmbd_debug(SMB, "File unlocked\n");
6983 } else if (rc == -ENOENT) {
6984 rsp->hdr.Status = STATUS_NOT_LOCKED;
6987 locks_free_lock(flock);
6990 if (rc == FILE_LOCK_DEFERRED) {
6994 "would have to wait for getting lock\n");
6995 spin_lock(&work->conn->llist_lock);
6996 list_add_tail(&smb_lock->clist,
6997 &work->conn->lock_list);
6998 spin_unlock(&work->conn->llist_lock);
6999 list_add(&smb_lock->llist, &rollback_list);
7001 argv = kmalloc(sizeof(void *), GFP_KERNEL);
7008 rc = setup_async_work(work,
7009 smb2_remove_blocked_lock,
7015 spin_lock(&fp->f_lock);
7016 list_add(&work->fp_entry, &fp->blocked_works);
7017 spin_unlock(&fp->f_lock);
7019 smb2_send_interim_resp(work, STATUS_PENDING);
7021 ksmbd_vfs_posix_lock_wait(flock);
7023 if (work->state != KSMBD_WORK_ACTIVE) {
7024 list_del(&smb_lock->llist);
7025 spin_lock(&work->conn->llist_lock);
7026 list_del(&smb_lock->clist);
7027 spin_unlock(&work->conn->llist_lock);
7028 locks_free_lock(flock);
7030 if (work->state == KSMBD_WORK_CANCELLED) {
7031 spin_lock(&fp->f_lock);
7032 list_del(&work->fp_entry);
7033 spin_unlock(&fp->f_lock);
7037 smb2_send_interim_resp(work,
7039 work->send_no_response = 1;
7042 init_smb2_rsp_hdr(work);
7043 smb2_set_err_rsp(work);
7045 STATUS_RANGE_NOT_LOCKED;
7050 list_del(&smb_lock->llist);
7051 spin_lock(&work->conn->llist_lock);
7052 list_del(&smb_lock->clist);
7053 spin_unlock(&work->conn->llist_lock);
7055 spin_lock(&fp->f_lock);
7056 list_del(&work->fp_entry);
7057 spin_unlock(&fp->f_lock);
7060 spin_lock(&work->conn->llist_lock);
7061 list_add_tail(&smb_lock->clist,
7062 &work->conn->lock_list);
7063 list_add_tail(&smb_lock->flist,
7065 spin_unlock(&work->conn->llist_lock);
7066 list_add(&smb_lock->llist, &rollback_list);
7067 ksmbd_debug(SMB, "successful in taking lock\n");
7074 if (atomic_read(&fp->f_ci->op_count) > 1)
7075 smb_break_all_oplock(work, fp);
7077 rsp->StructureSize = cpu_to_le16(4);
7078 ksmbd_debug(SMB, "successful in taking lock\n");
7079 rsp->hdr.Status = STATUS_SUCCESS;
7081 inc_rfc1001_len(work->response_buf, 4);
7082 ksmbd_fd_put(work, fp);
7086 list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
7087 locks_free_lock(smb_lock->fl);
7088 list_del(&smb_lock->llist);
7092 list_for_each_entry_safe(smb_lock, tmp, &rollback_list, llist) {
7093 struct file_lock *rlock = NULL;
7095 rlock = smb_flock_init(filp);
7096 rlock->fl_type = F_UNLCK;
7097 rlock->fl_start = smb_lock->start;
7098 rlock->fl_end = smb_lock->end;
7100 rc = vfs_lock_file(filp, 0, rlock, NULL);
7102 pr_err("rollback unlock fail : %d\n", rc);
7104 list_del(&smb_lock->llist);
7105 spin_lock(&work->conn->llist_lock);
7106 if (!list_empty(&smb_lock->flist))
7107 list_del(&smb_lock->flist);
7108 list_del(&smb_lock->clist);
7109 spin_unlock(&work->conn->llist_lock);
7111 locks_free_lock(smb_lock->fl);
7112 locks_free_lock(rlock);
7116 ksmbd_debug(SMB, "failed in taking lock(flags : %x), err : %d\n", flags, err);
7118 if (!rsp->hdr.Status) {
7120 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7121 else if (err == -ENOMEM)
7122 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
7123 else if (err == -ENOENT)
7124 rsp->hdr.Status = STATUS_FILE_CLOSED;
7126 rsp->hdr.Status = STATUS_LOCK_NOT_GRANTED;
7129 smb2_set_err_rsp(work);
7130 ksmbd_fd_put(work, fp);
7134 static int fsctl_copychunk(struct ksmbd_work *work,
7135 struct copychunk_ioctl_req *ci_req,
7136 unsigned int cnt_code,
7137 unsigned int input_count,
7138 unsigned long long volatile_id,
7139 unsigned long long persistent_id,
7140 struct smb2_ioctl_rsp *rsp)
7142 struct copychunk_ioctl_rsp *ci_rsp;
7143 struct ksmbd_file *src_fp = NULL, *dst_fp = NULL;
7144 struct srv_copychunk *chunks;
7145 unsigned int i, chunk_count, chunk_count_written = 0;
7146 unsigned int chunk_size_written = 0;
7147 loff_t total_size_written = 0;
7150 ci_rsp = (struct copychunk_ioctl_rsp *)&rsp->Buffer[0];
7152 rsp->VolatileFileId = volatile_id;
7153 rsp->PersistentFileId = persistent_id;
7154 ci_rsp->ChunksWritten =
7155 cpu_to_le32(ksmbd_server_side_copy_max_chunk_count());
7156 ci_rsp->ChunkBytesWritten =
7157 cpu_to_le32(ksmbd_server_side_copy_max_chunk_size());
7158 ci_rsp->TotalBytesWritten =
7159 cpu_to_le32(ksmbd_server_side_copy_max_total_size());
7161 chunks = (struct srv_copychunk *)&ci_req->Chunks[0];
7162 chunk_count = le32_to_cpu(ci_req->ChunkCount);
7163 if (chunk_count == 0)
7165 total_size_written = 0;
7167 /* verify the SRV_COPYCHUNK_COPY packet */
7168 if (chunk_count > ksmbd_server_side_copy_max_chunk_count() ||
7169 input_count < offsetof(struct copychunk_ioctl_req, Chunks) +
7170 chunk_count * sizeof(struct srv_copychunk)) {
7171 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7175 for (i = 0; i < chunk_count; i++) {
7176 if (le32_to_cpu(chunks[i].Length) == 0 ||
7177 le32_to_cpu(chunks[i].Length) > ksmbd_server_side_copy_max_chunk_size())
7179 total_size_written += le32_to_cpu(chunks[i].Length);
7182 if (i < chunk_count ||
7183 total_size_written > ksmbd_server_side_copy_max_total_size()) {
7184 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7188 src_fp = ksmbd_lookup_foreign_fd(work,
7189 le64_to_cpu(ci_req->ResumeKey[0]));
7190 dst_fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
7193 src_fp->persistent_id != le64_to_cpu(ci_req->ResumeKey[1])) {
7194 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
7199 rsp->hdr.Status = STATUS_FILE_CLOSED;
7204 * FILE_READ_DATA should only be included in
7205 * the FSCTL_COPYCHUNK case
7207 if (cnt_code == FSCTL_COPYCHUNK &&
7208 !(dst_fp->daccess & (FILE_READ_DATA_LE | FILE_GENERIC_READ_LE))) {
7209 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7213 ret = ksmbd_vfs_copy_file_ranges(work, src_fp, dst_fp,
7214 chunks, chunk_count,
7215 &chunk_count_written,
7216 &chunk_size_written,
7217 &total_size_written);
7220 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7222 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
7223 else if (ret == -EBADF)
7224 rsp->hdr.Status = STATUS_INVALID_HANDLE;
7225 else if (ret == -EFBIG || ret == -ENOSPC)
7226 rsp->hdr.Status = STATUS_DISK_FULL;
7227 else if (ret == -EINVAL)
7228 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7229 else if (ret == -EISDIR)
7230 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
7231 else if (ret == -E2BIG)
7232 rsp->hdr.Status = STATUS_INVALID_VIEW_SIZE;
7234 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
7237 ci_rsp->ChunksWritten = cpu_to_le32(chunk_count_written);
7238 ci_rsp->ChunkBytesWritten = cpu_to_le32(chunk_size_written);
7239 ci_rsp->TotalBytesWritten = cpu_to_le32(total_size_written);
7241 ksmbd_fd_put(work, src_fp);
7242 ksmbd_fd_put(work, dst_fp);
7246 static __be32 idev_ipv4_address(struct in_device *idev)
7250 struct in_ifaddr *ifa;
7253 in_dev_for_each_ifa_rcu(ifa, idev) {
7254 if (ifa->ifa_flags & IFA_F_SECONDARY)
7257 addr = ifa->ifa_address;
7264 static int fsctl_query_iface_info_ioctl(struct ksmbd_conn *conn,
7265 struct smb2_ioctl_rsp *rsp,
7266 unsigned int out_buf_len)
7268 struct network_interface_info_ioctl_rsp *nii_rsp = NULL;
7270 struct net_device *netdev;
7271 struct sockaddr_storage_rsp *sockaddr_storage;
7273 unsigned long long speed;
7276 for_each_netdev(&init_net, netdev) {
7277 bool ipv4_set = false;
7279 if (netdev->type == ARPHRD_LOOPBACK)
7282 flags = dev_get_flags(netdev);
7283 if (!(flags & IFF_RUNNING))
7287 nbytes + sizeof(struct network_interface_info_ioctl_rsp)) {
7292 nii_rsp = (struct network_interface_info_ioctl_rsp *)
7293 &rsp->Buffer[nbytes];
7294 nii_rsp->IfIndex = cpu_to_le32(netdev->ifindex);
7296 nii_rsp->Capability = 0;
7297 if (netdev->real_num_tx_queues > 1)
7298 nii_rsp->Capability |= cpu_to_le32(RSS_CAPABLE);
7299 if (ksmbd_rdma_capable_netdev(netdev))
7300 nii_rsp->Capability |= cpu_to_le32(RDMA_CAPABLE);
7302 nii_rsp->Next = cpu_to_le32(152);
7303 nii_rsp->Reserved = 0;
7305 if (netdev->ethtool_ops->get_link_ksettings) {
7306 struct ethtool_link_ksettings cmd;
7308 netdev->ethtool_ops->get_link_ksettings(netdev, &cmd);
7309 speed = cmd.base.speed;
7311 ksmbd_debug(SMB, "%s %s\n", netdev->name,
7312 "speed is unknown, defaulting to 1Gb/sec");
7317 nii_rsp->LinkSpeed = cpu_to_le64(speed);
7319 sockaddr_storage = (struct sockaddr_storage_rsp *)
7320 nii_rsp->SockAddr_Storage;
7321 memset(sockaddr_storage, 0, 128);
7324 struct in_device *idev;
7326 sockaddr_storage->Family = cpu_to_le16(INTERNETWORK);
7327 sockaddr_storage->addr4.Port = 0;
7329 idev = __in_dev_get_rtnl(netdev);
7332 sockaddr_storage->addr4.IPv4address =
7333 idev_ipv4_address(idev);
7334 nbytes += sizeof(struct network_interface_info_ioctl_rsp);
7338 struct inet6_dev *idev6;
7339 struct inet6_ifaddr *ifa;
7340 __u8 *ipv6_addr = sockaddr_storage->addr6.IPv6address;
7342 sockaddr_storage->Family = cpu_to_le16(INTERNETWORKV6);
7343 sockaddr_storage->addr6.Port = 0;
7344 sockaddr_storage->addr6.FlowInfo = 0;
7346 idev6 = __in6_dev_get(netdev);
7350 list_for_each_entry(ifa, &idev6->addr_list, if_list) {
7351 if (ifa->flags & (IFA_F_TENTATIVE |
7354 memcpy(ipv6_addr, ifa->addr.s6_addr, 16);
7357 sockaddr_storage->addr6.ScopeId = 0;
7358 nbytes += sizeof(struct network_interface_info_ioctl_rsp);
7363 /* zero if this is last one */
7367 rsp->PersistentFileId = SMB2_NO_FID;
7368 rsp->VolatileFileId = SMB2_NO_FID;
7372 static int fsctl_validate_negotiate_info(struct ksmbd_conn *conn,
7373 struct validate_negotiate_info_req *neg_req,
7374 struct validate_negotiate_info_rsp *neg_rsp,
7375 unsigned int in_buf_len)
7380 if (in_buf_len < offsetof(struct validate_negotiate_info_req, Dialects) +
7381 le16_to_cpu(neg_req->DialectCount) * sizeof(__le16))
7384 dialect = ksmbd_lookup_dialect_by_id(neg_req->Dialects,
7385 neg_req->DialectCount);
7386 if (dialect == BAD_PROT_ID || dialect != conn->dialect) {
7391 if (strncmp(neg_req->Guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE)) {
7396 if (le16_to_cpu(neg_req->SecurityMode) != conn->cli_sec_mode) {
7401 if (le32_to_cpu(neg_req->Capabilities) != conn->cli_cap) {
7406 neg_rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
7407 memset(neg_rsp->Guid, 0, SMB2_CLIENT_GUID_SIZE);
7408 neg_rsp->SecurityMode = cpu_to_le16(conn->srv_sec_mode);
7409 neg_rsp->Dialect = cpu_to_le16(conn->dialect);
7414 static int fsctl_query_allocated_ranges(struct ksmbd_work *work, u64 id,
7415 struct file_allocated_range_buffer *qar_req,
7416 struct file_allocated_range_buffer *qar_rsp,
7417 unsigned int in_count, unsigned int *out_count)
7419 struct ksmbd_file *fp;
7420 loff_t start, length;
7427 fp = ksmbd_lookup_fd_fast(work, id);
7431 start = le64_to_cpu(qar_req->file_offset);
7432 length = le64_to_cpu(qar_req->length);
7434 ret = ksmbd_vfs_fqar_lseek(fp, start, length,
7435 qar_rsp, in_count, out_count);
7436 if (ret && ret != -E2BIG)
7439 ksmbd_fd_put(work, fp);
7443 static int fsctl_pipe_transceive(struct ksmbd_work *work, u64 id,
7444 unsigned int out_buf_len,
7445 struct smb2_ioctl_req *req,
7446 struct smb2_ioctl_rsp *rsp)
7448 struct ksmbd_rpc_command *rpc_resp;
7449 char *data_buf = (char *)&req->Buffer[0];
7452 rpc_resp = ksmbd_rpc_ioctl(work->sess, id, data_buf,
7453 le32_to_cpu(req->InputCount));
7455 if (rpc_resp->flags == KSMBD_RPC_SOME_NOT_MAPPED) {
7457 * set STATUS_SOME_NOT_MAPPED response
7458 * for unknown domain sid.
7460 rsp->hdr.Status = STATUS_SOME_NOT_MAPPED;
7461 } else if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
7462 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7464 } else if (rpc_resp->flags != KSMBD_RPC_OK) {
7465 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7469 nbytes = rpc_resp->payload_sz;
7470 if (rpc_resp->payload_sz > out_buf_len) {
7471 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
7472 nbytes = out_buf_len;
7475 if (!rpc_resp->payload_sz) {
7477 STATUS_UNEXPECTED_IO_ERROR;
7481 memcpy((char *)rsp->Buffer, rpc_resp->payload, nbytes);
7488 static inline int fsctl_set_sparse(struct ksmbd_work *work, u64 id,
7489 struct file_sparse *sparse)
7491 struct ksmbd_file *fp;
7492 struct user_namespace *user_ns;
7496 fp = ksmbd_lookup_fd_fast(work, id);
7499 user_ns = file_mnt_user_ns(fp->filp);
7501 old_fattr = fp->f_ci->m_fattr;
7502 if (sparse->SetSparse)
7503 fp->f_ci->m_fattr |= FILE_ATTRIBUTE_SPARSE_FILE_LE;
7505 fp->f_ci->m_fattr &= ~FILE_ATTRIBUTE_SPARSE_FILE_LE;
7507 if (fp->f_ci->m_fattr != old_fattr &&
7508 test_share_config_flag(work->tcon->share_conf,
7509 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS)) {
7510 struct xattr_dos_attrib da;
7512 ret = ksmbd_vfs_get_dos_attrib_xattr(user_ns,
7513 fp->filp->f_path.dentry, &da);
7517 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
7518 ret = ksmbd_vfs_set_dos_attrib_xattr(user_ns,
7519 fp->filp->f_path.dentry, &da);
7521 fp->f_ci->m_fattr = old_fattr;
7525 ksmbd_fd_put(work, fp);
7529 static int fsctl_request_resume_key(struct ksmbd_work *work,
7530 struct smb2_ioctl_req *req,
7531 struct resume_key_ioctl_rsp *key_rsp)
7533 struct ksmbd_file *fp;
7535 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
7539 memset(key_rsp, 0, sizeof(*key_rsp));
7540 key_rsp->ResumeKey[0] = req->VolatileFileId;
7541 key_rsp->ResumeKey[1] = req->PersistentFileId;
7542 ksmbd_fd_put(work, fp);
7548 * smb2_ioctl() - handler for smb2 ioctl command
7549 * @work: smb work containing ioctl command buffer
7551 * Return: 0 on success, otherwise error
7553 int smb2_ioctl(struct ksmbd_work *work)
7555 struct smb2_ioctl_req *req;
7556 struct smb2_ioctl_rsp *rsp;
7557 unsigned int cnt_code, nbytes = 0, out_buf_len, in_buf_len;
7558 u64 id = KSMBD_NO_FID;
7559 struct ksmbd_conn *conn = work->conn;
7562 if (work->next_smb2_rcv_hdr_off) {
7563 req = ksmbd_req_buf_next(work);
7564 rsp = ksmbd_resp_buf_next(work);
7565 if (!has_file_id(req->VolatileFileId)) {
7566 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
7567 work->compound_fid);
7568 id = work->compound_fid;
7571 req = smb2_get_msg(work->request_buf);
7572 rsp = smb2_get_msg(work->response_buf);
7575 if (!has_file_id(id))
7576 id = req->VolatileFileId;
7578 if (req->Flags != cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL)) {
7579 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7583 cnt_code = le32_to_cpu(req->CtlCode);
7584 ret = smb2_calc_max_out_buf_len(work, 48,
7585 le32_to_cpu(req->MaxOutputResponse));
7587 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7590 out_buf_len = (unsigned int)ret;
7591 in_buf_len = le32_to_cpu(req->InputCount);
7594 case FSCTL_DFS_GET_REFERRALS:
7595 case FSCTL_DFS_GET_REFERRALS_EX:
7596 /* Not support DFS yet */
7597 rsp->hdr.Status = STATUS_FS_DRIVER_REQUIRED;
7599 case FSCTL_CREATE_OR_GET_OBJECT_ID:
7601 struct file_object_buf_type1_ioctl_rsp *obj_buf;
7603 nbytes = sizeof(struct file_object_buf_type1_ioctl_rsp);
7604 obj_buf = (struct file_object_buf_type1_ioctl_rsp *)
7608 * TODO: This is dummy implementation to pass smbtorture
7609 * Need to check correct response later
7611 memset(obj_buf->ObjectId, 0x0, 16);
7612 memset(obj_buf->BirthVolumeId, 0x0, 16);
7613 memset(obj_buf->BirthObjectId, 0x0, 16);
7614 memset(obj_buf->DomainId, 0x0, 16);
7618 case FSCTL_PIPE_TRANSCEIVE:
7619 out_buf_len = min_t(u32, KSMBD_IPC_MAX_PAYLOAD, out_buf_len);
7620 nbytes = fsctl_pipe_transceive(work, id, out_buf_len, req, rsp);
7622 case FSCTL_VALIDATE_NEGOTIATE_INFO:
7623 if (conn->dialect < SMB30_PROT_ID) {
7628 if (in_buf_len < sizeof(struct validate_negotiate_info_req))
7631 if (out_buf_len < sizeof(struct validate_negotiate_info_rsp))
7634 ret = fsctl_validate_negotiate_info(conn,
7635 (struct validate_negotiate_info_req *)&req->Buffer[0],
7636 (struct validate_negotiate_info_rsp *)&rsp->Buffer[0],
7641 nbytes = sizeof(struct validate_negotiate_info_rsp);
7642 rsp->PersistentFileId = SMB2_NO_FID;
7643 rsp->VolatileFileId = SMB2_NO_FID;
7645 case FSCTL_QUERY_NETWORK_INTERFACE_INFO:
7646 ret = fsctl_query_iface_info_ioctl(conn, rsp, out_buf_len);
7651 case FSCTL_REQUEST_RESUME_KEY:
7652 if (out_buf_len < sizeof(struct resume_key_ioctl_rsp)) {
7657 ret = fsctl_request_resume_key(work, req,
7658 (struct resume_key_ioctl_rsp *)&rsp->Buffer[0]);
7661 rsp->PersistentFileId = req->PersistentFileId;
7662 rsp->VolatileFileId = req->VolatileFileId;
7663 nbytes = sizeof(struct resume_key_ioctl_rsp);
7665 case FSCTL_COPYCHUNK:
7666 case FSCTL_COPYCHUNK_WRITE:
7667 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7669 "User does not have write permission\n");
7674 if (in_buf_len < sizeof(struct copychunk_ioctl_req)) {
7679 if (out_buf_len < sizeof(struct copychunk_ioctl_rsp)) {
7684 nbytes = sizeof(struct copychunk_ioctl_rsp);
7685 rsp->VolatileFileId = req->VolatileFileId;
7686 rsp->PersistentFileId = req->PersistentFileId;
7687 fsctl_copychunk(work,
7688 (struct copychunk_ioctl_req *)&req->Buffer[0],
7689 le32_to_cpu(req->CtlCode),
7690 le32_to_cpu(req->InputCount),
7691 req->VolatileFileId,
7692 req->PersistentFileId,
7695 case FSCTL_SET_SPARSE:
7696 if (in_buf_len < sizeof(struct file_sparse)) {
7701 ret = fsctl_set_sparse(work, id,
7702 (struct file_sparse *)&req->Buffer[0]);
7706 case FSCTL_SET_ZERO_DATA:
7708 struct file_zero_data_information *zero_data;
7709 struct ksmbd_file *fp;
7712 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7714 "User does not have write permission\n");
7719 if (in_buf_len < sizeof(struct file_zero_data_information)) {
7725 (struct file_zero_data_information *)&req->Buffer[0];
7727 fp = ksmbd_lookup_fd_fast(work, id);
7733 off = le64_to_cpu(zero_data->FileOffset);
7734 len = le64_to_cpu(zero_data->BeyondFinalZero) - off;
7736 ret = ksmbd_vfs_zero_data(work, fp, off, len);
7737 ksmbd_fd_put(work, fp);
7742 case FSCTL_QUERY_ALLOCATED_RANGES:
7743 if (in_buf_len < sizeof(struct file_allocated_range_buffer)) {
7748 ret = fsctl_query_allocated_ranges(work, id,
7749 (struct file_allocated_range_buffer *)&req->Buffer[0],
7750 (struct file_allocated_range_buffer *)&rsp->Buffer[0],
7752 sizeof(struct file_allocated_range_buffer), &nbytes);
7753 if (ret == -E2BIG) {
7754 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
7755 } else if (ret < 0) {
7760 nbytes *= sizeof(struct file_allocated_range_buffer);
7762 case FSCTL_GET_REPARSE_POINT:
7764 struct reparse_data_buffer *reparse_ptr;
7765 struct ksmbd_file *fp;
7767 reparse_ptr = (struct reparse_data_buffer *)&rsp->Buffer[0];
7768 fp = ksmbd_lookup_fd_fast(work, id);
7770 pr_err("not found fp!!\n");
7775 reparse_ptr->ReparseTag =
7776 smb2_get_reparse_tag_special_file(file_inode(fp->filp)->i_mode);
7777 reparse_ptr->ReparseDataLength = 0;
7778 ksmbd_fd_put(work, fp);
7779 nbytes = sizeof(struct reparse_data_buffer);
7782 case FSCTL_DUPLICATE_EXTENTS_TO_FILE:
7784 struct ksmbd_file *fp_in, *fp_out = NULL;
7785 struct duplicate_extents_to_file *dup_ext;
7786 loff_t src_off, dst_off, length, cloned;
7788 if (in_buf_len < sizeof(struct duplicate_extents_to_file)) {
7793 dup_ext = (struct duplicate_extents_to_file *)&req->Buffer[0];
7795 fp_in = ksmbd_lookup_fd_slow(work, dup_ext->VolatileFileHandle,
7796 dup_ext->PersistentFileHandle);
7798 pr_err("not found file handle in duplicate extent to file\n");
7803 fp_out = ksmbd_lookup_fd_fast(work, id);
7805 pr_err("not found fp\n");
7810 src_off = le64_to_cpu(dup_ext->SourceFileOffset);
7811 dst_off = le64_to_cpu(dup_ext->TargetFileOffset);
7812 length = le64_to_cpu(dup_ext->ByteCount);
7813 cloned = vfs_clone_file_range(fp_in->filp, src_off, fp_out->filp,
7814 dst_off, length, 0);
7815 if (cloned == -EXDEV || cloned == -EOPNOTSUPP) {
7818 } else if (cloned != length) {
7819 cloned = vfs_copy_file_range(fp_in->filp, src_off,
7820 fp_out->filp, dst_off, length, 0);
7821 if (cloned != length) {
7830 ksmbd_fd_put(work, fp_in);
7831 ksmbd_fd_put(work, fp_out);
7837 ksmbd_debug(SMB, "not implemented yet ioctl command 0x%x\n",
7843 rsp->CtlCode = cpu_to_le32(cnt_code);
7844 rsp->InputCount = cpu_to_le32(0);
7845 rsp->InputOffset = cpu_to_le32(112);
7846 rsp->OutputOffset = cpu_to_le32(112);
7847 rsp->OutputCount = cpu_to_le32(nbytes);
7848 rsp->StructureSize = cpu_to_le16(49);
7849 rsp->Reserved = cpu_to_le16(0);
7850 rsp->Flags = cpu_to_le32(0);
7851 rsp->Reserved2 = cpu_to_le32(0);
7852 inc_rfc1001_len(work->response_buf, 48 + nbytes);
7858 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7859 else if (ret == -ENOENT)
7860 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
7861 else if (ret == -EOPNOTSUPP)
7862 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7863 else if (ret == -ENOSPC)
7864 rsp->hdr.Status = STATUS_BUFFER_TOO_SMALL;
7865 else if (ret < 0 || rsp->hdr.Status == 0)
7866 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7867 smb2_set_err_rsp(work);
7872 * smb20_oplock_break_ack() - handler for smb2.0 oplock break command
7873 * @work: smb work containing oplock break command buffer
7877 static void smb20_oplock_break_ack(struct ksmbd_work *work)
7879 struct smb2_oplock_break *req = smb2_get_msg(work->request_buf);
7880 struct smb2_oplock_break *rsp = smb2_get_msg(work->response_buf);
7881 struct ksmbd_file *fp;
7882 struct oplock_info *opinfo = NULL;
7885 u64 volatile_id, persistent_id;
7886 char req_oplevel = 0, rsp_oplevel = 0;
7887 unsigned int oplock_change_type;
7889 volatile_id = req->VolatileFid;
7890 persistent_id = req->PersistentFid;
7891 req_oplevel = req->OplockLevel;
7892 ksmbd_debug(OPLOCK, "v_id %llu, p_id %llu request oplock level %d\n",
7893 volatile_id, persistent_id, req_oplevel);
7895 fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
7897 rsp->hdr.Status = STATUS_FILE_CLOSED;
7898 smb2_set_err_rsp(work);
7902 opinfo = opinfo_get(fp);
7904 pr_err("unexpected null oplock_info\n");
7905 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
7906 smb2_set_err_rsp(work);
7907 ksmbd_fd_put(work, fp);
7911 if (opinfo->level == SMB2_OPLOCK_LEVEL_NONE) {
7912 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
7916 if (opinfo->op_state == OPLOCK_STATE_NONE) {
7917 ksmbd_debug(SMB, "unexpected oplock state 0x%x\n", opinfo->op_state);
7918 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
7922 if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
7923 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
7924 (req_oplevel != SMB2_OPLOCK_LEVEL_II &&
7925 req_oplevel != SMB2_OPLOCK_LEVEL_NONE)) {
7926 err = STATUS_INVALID_OPLOCK_PROTOCOL;
7927 oplock_change_type = OPLOCK_WRITE_TO_NONE;
7928 } else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
7929 req_oplevel != SMB2_OPLOCK_LEVEL_NONE) {
7930 err = STATUS_INVALID_OPLOCK_PROTOCOL;
7931 oplock_change_type = OPLOCK_READ_TO_NONE;
7932 } else if (req_oplevel == SMB2_OPLOCK_LEVEL_II ||
7933 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
7934 err = STATUS_INVALID_DEVICE_STATE;
7935 if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
7936 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
7937 req_oplevel == SMB2_OPLOCK_LEVEL_II) {
7938 oplock_change_type = OPLOCK_WRITE_TO_READ;
7939 } else if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
7940 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
7941 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
7942 oplock_change_type = OPLOCK_WRITE_TO_NONE;
7943 } else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
7944 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
7945 oplock_change_type = OPLOCK_READ_TO_NONE;
7947 oplock_change_type = 0;
7950 oplock_change_type = 0;
7953 switch (oplock_change_type) {
7954 case OPLOCK_WRITE_TO_READ:
7955 ret = opinfo_write_to_read(opinfo);
7956 rsp_oplevel = SMB2_OPLOCK_LEVEL_II;
7958 case OPLOCK_WRITE_TO_NONE:
7959 ret = opinfo_write_to_none(opinfo);
7960 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
7962 case OPLOCK_READ_TO_NONE:
7963 ret = opinfo_read_to_none(opinfo);
7964 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
7967 pr_err("unknown oplock change 0x%x -> 0x%x\n",
7968 opinfo->level, rsp_oplevel);
7972 rsp->hdr.Status = err;
7977 ksmbd_fd_put(work, fp);
7978 opinfo->op_state = OPLOCK_STATE_NONE;
7979 wake_up_interruptible_all(&opinfo->oplock_q);
7981 rsp->StructureSize = cpu_to_le16(24);
7982 rsp->OplockLevel = rsp_oplevel;
7985 rsp->VolatileFid = volatile_id;
7986 rsp->PersistentFid = persistent_id;
7987 inc_rfc1001_len(work->response_buf, 24);
7991 opinfo->op_state = OPLOCK_STATE_NONE;
7992 wake_up_interruptible_all(&opinfo->oplock_q);
7995 ksmbd_fd_put(work, fp);
7996 smb2_set_err_rsp(work);
7999 static int check_lease_state(struct lease *lease, __le32 req_state)
8001 if ((lease->new_state ==
8002 (SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE)) &&
8003 !(req_state & SMB2_LEASE_WRITE_CACHING_LE)) {
8004 lease->new_state = req_state;
8008 if (lease->new_state == req_state)
8015 * smb21_lease_break_ack() - handler for smb2.1 lease break command
8016 * @work: smb work containing lease break command buffer
8020 static void smb21_lease_break_ack(struct ksmbd_work *work)
8022 struct ksmbd_conn *conn = work->conn;
8023 struct smb2_lease_ack *req = smb2_get_msg(work->request_buf);
8024 struct smb2_lease_ack *rsp = smb2_get_msg(work->response_buf);
8025 struct oplock_info *opinfo;
8028 unsigned int lease_change_type;
8030 struct lease *lease;
8032 ksmbd_debug(OPLOCK, "smb21 lease break, lease state(0x%x)\n",
8033 le32_to_cpu(req->LeaseState));
8034 opinfo = lookup_lease_in_table(conn, req->LeaseKey);
8036 ksmbd_debug(OPLOCK, "file not opened\n");
8037 smb2_set_err_rsp(work);
8038 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8041 lease = opinfo->o_lease;
8043 if (opinfo->op_state == OPLOCK_STATE_NONE) {
8044 pr_err("unexpected lease break state 0x%x\n",
8046 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8050 if (check_lease_state(lease, req->LeaseState)) {
8051 rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
8053 "req lease state: 0x%x, expected state: 0x%x\n",
8054 req->LeaseState, lease->new_state);
8058 if (!atomic_read(&opinfo->breaking_cnt)) {
8059 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8063 /* check for bad lease state */
8064 if (req->LeaseState &
8065 (~(SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE))) {
8066 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8067 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8068 lease_change_type = OPLOCK_WRITE_TO_NONE;
8070 lease_change_type = OPLOCK_READ_TO_NONE;
8071 ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8072 le32_to_cpu(lease->state),
8073 le32_to_cpu(req->LeaseState));
8074 } else if (lease->state == SMB2_LEASE_READ_CACHING_LE &&
8075 req->LeaseState != SMB2_LEASE_NONE_LE) {
8076 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8077 lease_change_type = OPLOCK_READ_TO_NONE;
8078 ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8079 le32_to_cpu(lease->state),
8080 le32_to_cpu(req->LeaseState));
8082 /* valid lease state changes */
8083 err = STATUS_INVALID_DEVICE_STATE;
8084 if (req->LeaseState == SMB2_LEASE_NONE_LE) {
8085 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8086 lease_change_type = OPLOCK_WRITE_TO_NONE;
8088 lease_change_type = OPLOCK_READ_TO_NONE;
8089 } else if (req->LeaseState & SMB2_LEASE_READ_CACHING_LE) {
8090 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8091 lease_change_type = OPLOCK_WRITE_TO_READ;
8093 lease_change_type = OPLOCK_READ_HANDLE_TO_READ;
8095 lease_change_type = 0;
8099 switch (lease_change_type) {
8100 case OPLOCK_WRITE_TO_READ:
8101 ret = opinfo_write_to_read(opinfo);
8103 case OPLOCK_READ_HANDLE_TO_READ:
8104 ret = opinfo_read_handle_to_read(opinfo);
8106 case OPLOCK_WRITE_TO_NONE:
8107 ret = opinfo_write_to_none(opinfo);
8109 case OPLOCK_READ_TO_NONE:
8110 ret = opinfo_read_to_none(opinfo);
8113 ksmbd_debug(OPLOCK, "unknown lease change 0x%x -> 0x%x\n",
8114 le32_to_cpu(lease->state),
8115 le32_to_cpu(req->LeaseState));
8118 lease_state = lease->state;
8119 opinfo->op_state = OPLOCK_STATE_NONE;
8120 wake_up_interruptible_all(&opinfo->oplock_q);
8121 atomic_dec(&opinfo->breaking_cnt);
8122 wake_up_interruptible_all(&opinfo->oplock_brk);
8126 rsp->hdr.Status = err;
8130 rsp->StructureSize = cpu_to_le16(36);
8133 memcpy(rsp->LeaseKey, req->LeaseKey, 16);
8134 rsp->LeaseState = lease_state;
8135 rsp->LeaseDuration = 0;
8136 inc_rfc1001_len(work->response_buf, 36);
8140 opinfo->op_state = OPLOCK_STATE_NONE;
8141 wake_up_interruptible_all(&opinfo->oplock_q);
8142 atomic_dec(&opinfo->breaking_cnt);
8143 wake_up_interruptible_all(&opinfo->oplock_brk);
8146 smb2_set_err_rsp(work);
8150 * smb2_oplock_break() - dispatcher for smb2.0 and 2.1 oplock/lease break
8151 * @work: smb work containing oplock/lease break command buffer
8155 int smb2_oplock_break(struct ksmbd_work *work)
8157 struct smb2_oplock_break *req = smb2_get_msg(work->request_buf);
8158 struct smb2_oplock_break *rsp = smb2_get_msg(work->response_buf);
8160 switch (le16_to_cpu(req->StructureSize)) {
8161 case OP_BREAK_STRUCT_SIZE_20:
8162 smb20_oplock_break_ack(work);
8164 case OP_BREAK_STRUCT_SIZE_21:
8165 smb21_lease_break_ack(work);
8168 ksmbd_debug(OPLOCK, "invalid break cmd %d\n",
8169 le16_to_cpu(req->StructureSize));
8170 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8171 smb2_set_err_rsp(work);
8178 * smb2_notify() - handler for smb2 notify request
8179 * @work: smb work containing notify command buffer
8183 int smb2_notify(struct ksmbd_work *work)
8185 struct smb2_change_notify_req *req;
8186 struct smb2_change_notify_rsp *rsp;
8188 WORK_BUFFERS(work, req, rsp);
8190 if (work->next_smb2_rcv_hdr_off && req->hdr.NextCommand) {
8191 rsp->hdr.Status = STATUS_INTERNAL_ERROR;
8192 smb2_set_err_rsp(work);
8196 smb2_set_err_rsp(work);
8197 rsp->hdr.Status = STATUS_NOT_IMPLEMENTED;
8202 * smb2_is_sign_req() - handler for checking packet signing status
8203 * @work: smb work containing notify command buffer
8204 * @command: SMB2 command id
8206 * Return: true if packed is signed, false otherwise
8208 bool smb2_is_sign_req(struct ksmbd_work *work, unsigned int command)
8210 struct smb2_hdr *rcv_hdr2 = smb2_get_msg(work->request_buf);
8212 if ((rcv_hdr2->Flags & SMB2_FLAGS_SIGNED) &&
8213 command != SMB2_NEGOTIATE_HE &&
8214 command != SMB2_SESSION_SETUP_HE &&
8215 command != SMB2_OPLOCK_BREAK_HE)
8222 * smb2_check_sign_req() - handler for req packet sign processing
8223 * @work: smb work containing notify command buffer
8225 * Return: 1 on success, 0 otherwise
8227 int smb2_check_sign_req(struct ksmbd_work *work)
8229 struct smb2_hdr *hdr;
8230 char signature_req[SMB2_SIGNATURE_SIZE];
8231 char signature[SMB2_HMACSHA256_SIZE];
8235 hdr = smb2_get_msg(work->request_buf);
8236 if (work->next_smb2_rcv_hdr_off)
8237 hdr = ksmbd_req_buf_next(work);
8239 if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8240 len = get_rfc1002_len(work->request_buf);
8241 else if (hdr->NextCommand)
8242 len = le32_to_cpu(hdr->NextCommand);
8244 len = get_rfc1002_len(work->request_buf) -
8245 work->next_smb2_rcv_hdr_off;
8247 memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8248 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8250 iov[0].iov_base = (char *)&hdr->ProtocolId;
8251 iov[0].iov_len = len;
8253 if (ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, 1,
8257 if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8258 pr_err("bad smb2 signature\n");
8266 * smb2_set_sign_rsp() - handler for rsp packet sign processing
8267 * @work: smb work containing notify command buffer
8270 void smb2_set_sign_rsp(struct ksmbd_work *work)
8272 struct smb2_hdr *hdr;
8273 struct smb2_hdr *req_hdr;
8274 char signature[SMB2_HMACSHA256_SIZE];
8279 hdr = smb2_get_msg(work->response_buf);
8280 if (work->next_smb2_rsp_hdr_off)
8281 hdr = ksmbd_resp_buf_next(work);
8283 req_hdr = ksmbd_req_buf_next(work);
8285 if (!work->next_smb2_rsp_hdr_off) {
8286 len = get_rfc1002_len(work->response_buf);
8287 if (req_hdr->NextCommand)
8288 len = ALIGN(len, 8);
8290 len = get_rfc1002_len(work->response_buf) -
8291 work->next_smb2_rsp_hdr_off;
8292 len = ALIGN(len, 8);
8295 if (req_hdr->NextCommand)
8296 hdr->NextCommand = cpu_to_le32(len);
8298 hdr->Flags |= SMB2_FLAGS_SIGNED;
8299 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8301 iov[0].iov_base = (char *)&hdr->ProtocolId;
8302 iov[0].iov_len = len;
8304 if (work->aux_payload_sz) {
8305 iov[0].iov_len -= work->aux_payload_sz;
8307 iov[1].iov_base = work->aux_payload_buf;
8308 iov[1].iov_len = work->aux_payload_sz;
8312 if (!ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, n_vec,
8314 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
8318 * smb3_check_sign_req() - handler for req packet sign processing
8319 * @work: smb work containing notify command buffer
8321 * Return: 1 on success, 0 otherwise
8323 int smb3_check_sign_req(struct ksmbd_work *work)
8325 struct ksmbd_conn *conn = work->conn;
8327 struct smb2_hdr *hdr;
8328 struct channel *chann;
8329 char signature_req[SMB2_SIGNATURE_SIZE];
8330 char signature[SMB2_CMACAES_SIZE];
8334 hdr = smb2_get_msg(work->request_buf);
8335 if (work->next_smb2_rcv_hdr_off)
8336 hdr = ksmbd_req_buf_next(work);
8338 if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8339 len = get_rfc1002_len(work->request_buf);
8340 else if (hdr->NextCommand)
8341 len = le32_to_cpu(hdr->NextCommand);
8343 len = get_rfc1002_len(work->request_buf) -
8344 work->next_smb2_rcv_hdr_off;
8346 if (le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8347 signing_key = work->sess->smb3signingkey;
8349 chann = lookup_chann_list(work->sess, conn);
8352 signing_key = chann->smb3signingkey;
8356 pr_err("SMB3 signing key is not generated\n");
8360 memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8361 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8362 iov[0].iov_base = (char *)&hdr->ProtocolId;
8363 iov[0].iov_len = len;
8365 if (ksmbd_sign_smb3_pdu(conn, signing_key, iov, 1, signature))
8368 if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8369 pr_err("bad smb2 signature\n");
8377 * smb3_set_sign_rsp() - handler for rsp packet sign processing
8378 * @work: smb work containing notify command buffer
8381 void smb3_set_sign_rsp(struct ksmbd_work *work)
8383 struct ksmbd_conn *conn = work->conn;
8384 struct smb2_hdr *req_hdr, *hdr;
8385 struct channel *chann;
8386 char signature[SMB2_CMACAES_SIZE];
8392 hdr = smb2_get_msg(work->response_buf);
8393 if (work->next_smb2_rsp_hdr_off)
8394 hdr = ksmbd_resp_buf_next(work);
8396 req_hdr = ksmbd_req_buf_next(work);
8398 if (!work->next_smb2_rsp_hdr_off) {
8399 len = get_rfc1002_len(work->response_buf);
8400 if (req_hdr->NextCommand)
8401 len = ALIGN(len, 8);
8403 len = get_rfc1002_len(work->response_buf) -
8404 work->next_smb2_rsp_hdr_off;
8405 len = ALIGN(len, 8);
8408 if (conn->binding == false &&
8409 le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8410 signing_key = work->sess->smb3signingkey;
8412 chann = lookup_chann_list(work->sess, work->conn);
8415 signing_key = chann->smb3signingkey;
8421 if (req_hdr->NextCommand)
8422 hdr->NextCommand = cpu_to_le32(len);
8424 hdr->Flags |= SMB2_FLAGS_SIGNED;
8425 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8426 iov[0].iov_base = (char *)&hdr->ProtocolId;
8427 iov[0].iov_len = len;
8428 if (work->aux_payload_sz) {
8429 iov[0].iov_len -= work->aux_payload_sz;
8430 iov[1].iov_base = work->aux_payload_buf;
8431 iov[1].iov_len = work->aux_payload_sz;
8435 if (!ksmbd_sign_smb3_pdu(conn, signing_key, iov, n_vec, signature))
8436 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
8440 * smb3_preauth_hash_rsp() - handler for computing preauth hash on response
8441 * @work: smb work containing response buffer
8444 void smb3_preauth_hash_rsp(struct ksmbd_work *work)
8446 struct ksmbd_conn *conn = work->conn;
8447 struct ksmbd_session *sess = work->sess;
8448 struct smb2_hdr *req, *rsp;
8450 if (conn->dialect != SMB311_PROT_ID)
8453 WORK_BUFFERS(work, req, rsp);
8455 if (le16_to_cpu(req->Command) == SMB2_NEGOTIATE_HE &&
8457 ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
8458 conn->preauth_info->Preauth_HashValue);
8460 if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE && sess) {
8463 if (conn->binding) {
8464 struct preauth_session *preauth_sess;
8466 preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
8469 hash_value = preauth_sess->Preauth_HashValue;
8471 hash_value = sess->Preauth_HashValue;
8475 ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
8480 static void fill_transform_hdr(void *tr_buf, char *old_buf, __le16 cipher_type)
8482 struct smb2_transform_hdr *tr_hdr = tr_buf + 4;
8483 struct smb2_hdr *hdr = smb2_get_msg(old_buf);
8484 unsigned int orig_len = get_rfc1002_len(old_buf);
8486 /* tr_buf must be cleared by the caller */
8487 tr_hdr->ProtocolId = SMB2_TRANSFORM_PROTO_NUM;
8488 tr_hdr->OriginalMessageSize = cpu_to_le32(orig_len);
8489 tr_hdr->Flags = cpu_to_le16(TRANSFORM_FLAG_ENCRYPTED);
8490 if (cipher_type == SMB2_ENCRYPTION_AES128_GCM ||
8491 cipher_type == SMB2_ENCRYPTION_AES256_GCM)
8492 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_GCM_NONCE);
8494 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_CCM_NONCE);
8495 memcpy(&tr_hdr->SessionId, &hdr->SessionId, 8);
8496 inc_rfc1001_len(tr_buf, sizeof(struct smb2_transform_hdr));
8497 inc_rfc1001_len(tr_buf, orig_len);
8500 int smb3_encrypt_resp(struct ksmbd_work *work)
8502 char *buf = work->response_buf;
8505 int buf_size = 0, rq_nvec = 2 + (work->aux_payload_sz ? 1 : 0);
8507 if (ARRAY_SIZE(iov) < rq_nvec)
8510 work->tr_buf = kzalloc(sizeof(struct smb2_transform_hdr) + 4, GFP_KERNEL);
8514 /* fill transform header */
8515 fill_transform_hdr(work->tr_buf, buf, work->conn->cipher_type);
8517 iov[0].iov_base = work->tr_buf;
8518 iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
8519 buf_size += iov[0].iov_len - 4;
8521 iov[1].iov_base = buf + 4;
8522 iov[1].iov_len = get_rfc1002_len(buf);
8523 if (work->aux_payload_sz) {
8524 iov[1].iov_len = work->resp_hdr_sz - 4;
8526 iov[2].iov_base = work->aux_payload_buf;
8527 iov[2].iov_len = work->aux_payload_sz;
8528 buf_size += iov[2].iov_len;
8530 buf_size += iov[1].iov_len;
8531 work->resp_hdr_sz = iov[1].iov_len;
8533 rc = ksmbd_crypt_message(work->conn, iov, rq_nvec, 1);
8537 memmove(buf, iov[1].iov_base, iov[1].iov_len);
8538 *(__be32 *)work->tr_buf = cpu_to_be32(buf_size);
8543 bool smb3_is_transform_hdr(void *buf)
8545 struct smb2_transform_hdr *trhdr = smb2_get_msg(buf);
8547 return trhdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM;
8550 int smb3_decrypt_req(struct ksmbd_work *work)
8552 struct ksmbd_conn *conn = work->conn;
8553 struct ksmbd_session *sess;
8554 char *buf = work->request_buf;
8555 unsigned int pdu_length = get_rfc1002_len(buf);
8557 int buf_data_size = pdu_length - sizeof(struct smb2_transform_hdr);
8558 struct smb2_transform_hdr *tr_hdr = smb2_get_msg(buf);
8561 if (buf_data_size < sizeof(struct smb2_hdr)) {
8562 pr_err("Transform message is too small (%u)\n",
8564 return -ECONNABORTED;
8567 if (buf_data_size < le32_to_cpu(tr_hdr->OriginalMessageSize)) {
8568 pr_err("Transform message is broken\n");
8569 return -ECONNABORTED;
8572 sess = ksmbd_session_lookup_all(conn, le64_to_cpu(tr_hdr->SessionId));
8574 pr_err("invalid session id(%llx) in transform header\n",
8575 le64_to_cpu(tr_hdr->SessionId));
8576 return -ECONNABORTED;
8579 iov[0].iov_base = buf;
8580 iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
8581 iov[1].iov_base = buf + sizeof(struct smb2_transform_hdr) + 4;
8582 iov[1].iov_len = buf_data_size;
8583 rc = ksmbd_crypt_message(conn, iov, 2, 0);
8587 memmove(buf + 4, iov[1].iov_base, buf_data_size);
8588 *(__be32 *)buf = cpu_to_be32(buf_data_size);
8593 bool smb3_11_final_sess_setup_resp(struct ksmbd_work *work)
8595 struct ksmbd_conn *conn = work->conn;
8596 struct smb2_hdr *rsp = smb2_get_msg(work->response_buf);
8598 if (conn->dialect < SMB30_PROT_ID)
8601 if (work->next_smb2_rcv_hdr_off)
8602 rsp = ksmbd_resp_buf_next(work);
8604 if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE &&
8605 rsp->Status == STATUS_SUCCESS)