1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * Copyright (C) 2016 Namjae Jeon <linkinjeon@kernel.org>
4 * Copyright (C) 2018 Samsung Electronics Co., Ltd.
7 #include <linux/inetdevice.h>
8 #include <net/addrconf.h>
9 #include <linux/syscalls.h>
10 #include <linux/namei.h>
11 #include <linux/statfs.h>
12 #include <linux/ethtool.h>
13 #include <linux/falloc.h>
14 #include <linux/mount.h>
23 #include "connection.h"
24 #include "transport_ipc.h"
25 #include "transport_rdma.h"
27 #include "vfs_cache.h"
31 #include "smb_common.h"
32 #include "smbstatus.h"
33 #include "ksmbd_work.h"
34 #include "mgmt/user_config.h"
35 #include "mgmt/share_config.h"
36 #include "mgmt/tree_connect.h"
37 #include "mgmt/user_session.h"
38 #include "mgmt/ksmbd_ida.h"
41 static void __wbuf(struct ksmbd_work *work, void **req, void **rsp)
43 if (work->next_smb2_rcv_hdr_off) {
44 *req = ksmbd_req_buf_next(work);
45 *rsp = ksmbd_resp_buf_next(work);
47 *req = smb2_get_msg(work->request_buf);
48 *rsp = smb2_get_msg(work->response_buf);
52 #define WORK_BUFFERS(w, rq, rs) __wbuf((w), (void **)&(rq), (void **)&(rs))
55 * check_session_id() - check for valid session id in smb header
56 * @conn: connection instance
57 * @id: session id from smb header
59 * Return: 1 if valid session id, otherwise 0
61 static inline bool check_session_id(struct ksmbd_conn *conn, u64 id)
63 struct ksmbd_session *sess;
65 if (id == 0 || id == -1)
68 sess = ksmbd_session_lookup_all(conn, id);
71 pr_err("Invalid user session id: %llu\n", id);
75 struct channel *lookup_chann_list(struct ksmbd_session *sess, struct ksmbd_conn *conn)
77 struct channel *chann;
79 list_for_each_entry(chann, &sess->ksmbd_chann_list, chann_list) {
80 if (chann->conn == conn)
88 * smb2_get_ksmbd_tcon() - get tree connection information using a tree id.
91 * Return: 0 if there is a tree connection matched or these are
92 * skipable commands, otherwise error
94 int smb2_get_ksmbd_tcon(struct ksmbd_work *work)
96 struct smb2_hdr *req_hdr = smb2_get_msg(work->request_buf);
97 unsigned int cmd = le16_to_cpu(req_hdr->Command);
101 if (cmd == SMB2_TREE_CONNECT_HE ||
102 cmd == SMB2_CANCEL_HE ||
103 cmd == SMB2_LOGOFF_HE) {
104 ksmbd_debug(SMB, "skip to check tree connect request\n");
108 if (xa_empty(&work->sess->tree_conns)) {
109 ksmbd_debug(SMB, "NO tree connected\n");
113 tree_id = le32_to_cpu(req_hdr->Id.SyncId.TreeId);
114 work->tcon = ksmbd_tree_conn_lookup(work->sess, tree_id);
116 pr_err("Invalid tid %d\n", tree_id);
124 * smb2_set_err_rsp() - set error response code on smb response
125 * @work: smb work containing response buffer
127 void smb2_set_err_rsp(struct ksmbd_work *work)
129 struct smb2_err_rsp *err_rsp;
131 if (work->next_smb2_rcv_hdr_off)
132 err_rsp = ksmbd_resp_buf_next(work);
134 err_rsp = smb2_get_msg(work->response_buf);
136 if (err_rsp->hdr.Status != STATUS_STOPPED_ON_SYMLINK) {
137 err_rsp->StructureSize = SMB2_ERROR_STRUCTURE_SIZE2_LE;
138 err_rsp->ErrorContextCount = 0;
139 err_rsp->Reserved = 0;
140 err_rsp->ByteCount = 0;
141 err_rsp->ErrorData[0] = 0;
142 inc_rfc1001_len(work->response_buf, SMB2_ERROR_STRUCTURE_SIZE2);
147 * is_smb2_neg_cmd() - is it smb2 negotiation command
148 * @work: smb work containing smb header
150 * Return: true if smb2 negotiation command, otherwise false
152 bool is_smb2_neg_cmd(struct ksmbd_work *work)
154 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
156 /* is it SMB2 header ? */
157 if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
160 /* make sure it is request not response message */
161 if (hdr->Flags & SMB2_FLAGS_SERVER_TO_REDIR)
164 if (hdr->Command != SMB2_NEGOTIATE)
171 * is_smb2_rsp() - is it smb2 response
172 * @work: smb work containing smb response buffer
174 * Return: true if smb2 response, otherwise false
176 bool is_smb2_rsp(struct ksmbd_work *work)
178 struct smb2_hdr *hdr = smb2_get_msg(work->response_buf);
180 /* is it SMB2 header ? */
181 if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
184 /* make sure it is response not request message */
185 if (!(hdr->Flags & SMB2_FLAGS_SERVER_TO_REDIR))
192 * get_smb2_cmd_val() - get smb command code from smb header
193 * @work: smb work containing smb request buffer
195 * Return: smb2 request command value
197 u16 get_smb2_cmd_val(struct ksmbd_work *work)
199 struct smb2_hdr *rcv_hdr;
201 if (work->next_smb2_rcv_hdr_off)
202 rcv_hdr = ksmbd_req_buf_next(work);
204 rcv_hdr = smb2_get_msg(work->request_buf);
205 return le16_to_cpu(rcv_hdr->Command);
209 * set_smb2_rsp_status() - set error response code on smb2 header
210 * @work: smb work containing response buffer
211 * @err: error response code
213 void set_smb2_rsp_status(struct ksmbd_work *work, __le32 err)
215 struct smb2_hdr *rsp_hdr;
217 if (work->next_smb2_rcv_hdr_off)
218 rsp_hdr = ksmbd_resp_buf_next(work);
220 rsp_hdr = smb2_get_msg(work->response_buf);
221 rsp_hdr->Status = err;
222 smb2_set_err_rsp(work);
226 * init_smb2_neg_rsp() - initialize smb2 response for negotiate command
227 * @work: smb work containing smb request buffer
229 * smb2 negotiate response is sent in reply of smb1 negotiate command for
230 * dialect auto-negotiation.
232 int init_smb2_neg_rsp(struct ksmbd_work *work)
234 struct smb2_hdr *rsp_hdr;
235 struct smb2_negotiate_rsp *rsp;
236 struct ksmbd_conn *conn = work->conn;
238 if (conn->need_neg == false)
241 *(__be32 *)work->response_buf =
242 cpu_to_be32(conn->vals->header_size);
244 rsp_hdr = smb2_get_msg(work->response_buf);
245 memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
246 rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
247 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
248 rsp_hdr->CreditRequest = cpu_to_le16(2);
249 rsp_hdr->Command = SMB2_NEGOTIATE;
250 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
251 rsp_hdr->NextCommand = 0;
252 rsp_hdr->MessageId = 0;
253 rsp_hdr->Id.SyncId.ProcessId = 0;
254 rsp_hdr->Id.SyncId.TreeId = 0;
255 rsp_hdr->SessionId = 0;
256 memset(rsp_hdr->Signature, 0, 16);
258 rsp = smb2_get_msg(work->response_buf);
260 WARN_ON(ksmbd_conn_good(work));
262 rsp->StructureSize = cpu_to_le16(65);
263 ksmbd_debug(SMB, "conn->dialect 0x%x\n", conn->dialect);
264 rsp->DialectRevision = cpu_to_le16(conn->dialect);
265 /* Not setting conn guid rsp->ServerGUID, as it
266 * not used by client for identifying connection
268 rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
269 /* Default Max Message Size till SMB2.0, 64K*/
270 rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
271 rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
272 rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);
274 rsp->SystemTime = cpu_to_le64(ksmbd_systime());
275 rsp->ServerStartTime = 0;
277 rsp->SecurityBufferOffset = cpu_to_le16(128);
278 rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
279 ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) +
280 le16_to_cpu(rsp->SecurityBufferOffset));
281 inc_rfc1001_len(work->response_buf,
282 sizeof(struct smb2_negotiate_rsp) -
283 sizeof(struct smb2_hdr) - sizeof(rsp->Buffer) +
285 rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
286 if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY)
287 rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
288 conn->use_spnego = true;
290 ksmbd_conn_set_need_negotiate(work);
295 * smb2_set_rsp_credits() - set number of credits in response buffer
296 * @work: smb work containing smb response buffer
298 int smb2_set_rsp_credits(struct ksmbd_work *work)
300 struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
301 struct smb2_hdr *hdr = ksmbd_resp_buf_next(work);
302 struct ksmbd_conn *conn = work->conn;
303 unsigned short credits_requested, aux_max;
304 unsigned short credit_charge, credits_granted = 0;
306 if (work->send_no_response)
309 hdr->CreditCharge = req_hdr->CreditCharge;
311 if (conn->total_credits > conn->vals->max_credits) {
312 hdr->CreditRequest = 0;
313 pr_err("Total credits overflow: %d\n", conn->total_credits);
317 credit_charge = max_t(unsigned short,
318 le16_to_cpu(req_hdr->CreditCharge), 1);
319 if (credit_charge > conn->total_credits) {
320 ksmbd_debug(SMB, "Insufficient credits granted, given: %u, granted: %u\n",
321 credit_charge, conn->total_credits);
325 conn->total_credits -= credit_charge;
326 conn->outstanding_credits -= credit_charge;
327 credits_requested = max_t(unsigned short,
328 le16_to_cpu(req_hdr->CreditRequest), 1);
330 /* according to smb2.credits smbtorture, Windows server
331 * 2016 or later grant up to 8192 credits at once.
333 * TODO: Need to adjuct CreditRequest value according to
336 if (hdr->Command == SMB2_NEGOTIATE)
339 aux_max = conn->vals->max_credits - credit_charge;
340 credits_granted = min_t(unsigned short, credits_requested, aux_max);
342 if (conn->vals->max_credits - conn->total_credits < credits_granted)
343 credits_granted = conn->vals->max_credits -
346 conn->total_credits += credits_granted;
347 work->credits_granted += credits_granted;
349 if (!req_hdr->NextCommand) {
350 /* Update CreditRequest in last request */
351 hdr->CreditRequest = cpu_to_le16(work->credits_granted);
354 "credits: requested[%d] granted[%d] total_granted[%d]\n",
355 credits_requested, credits_granted,
356 conn->total_credits);
361 * init_chained_smb2_rsp() - initialize smb2 chained response
362 * @work: smb work containing smb response buffer
364 static void init_chained_smb2_rsp(struct ksmbd_work *work)
366 struct smb2_hdr *req = ksmbd_req_buf_next(work);
367 struct smb2_hdr *rsp = ksmbd_resp_buf_next(work);
368 struct smb2_hdr *rsp_hdr;
369 struct smb2_hdr *rcv_hdr;
370 int next_hdr_offset = 0;
373 /* Len of this response = updated RFC len - offset of previous cmd
374 * in the compound rsp
377 /* Storing the current local FID which may be needed by subsequent
378 * command in the compound request
380 if (req->Command == SMB2_CREATE && rsp->Status == STATUS_SUCCESS) {
381 work->compound_fid = ((struct smb2_create_rsp *)rsp)->VolatileFileId;
382 work->compound_pfid = ((struct smb2_create_rsp *)rsp)->PersistentFileId;
383 work->compound_sid = le64_to_cpu(rsp->SessionId);
386 len = get_rfc1002_len(work->response_buf) - work->next_smb2_rsp_hdr_off;
387 next_hdr_offset = le32_to_cpu(req->NextCommand);
389 new_len = ALIGN(len, 8);
390 inc_rfc1001_len(work->response_buf,
391 sizeof(struct smb2_hdr) + new_len - len);
392 rsp->NextCommand = cpu_to_le32(new_len);
394 work->next_smb2_rcv_hdr_off += next_hdr_offset;
395 work->next_smb2_rsp_hdr_off += new_len;
397 "Compound req new_len = %d rcv off = %d rsp off = %d\n",
398 new_len, work->next_smb2_rcv_hdr_off,
399 work->next_smb2_rsp_hdr_off);
401 rsp_hdr = ksmbd_resp_buf_next(work);
402 rcv_hdr = ksmbd_req_buf_next(work);
404 if (!(rcv_hdr->Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
405 ksmbd_debug(SMB, "related flag should be set\n");
406 work->compound_fid = KSMBD_NO_FID;
407 work->compound_pfid = KSMBD_NO_FID;
409 memset((char *)rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
410 rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
411 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
412 rsp_hdr->Command = rcv_hdr->Command;
415 * Message is response. We don't grant oplock yet.
417 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR |
418 SMB2_FLAGS_RELATED_OPERATIONS);
419 rsp_hdr->NextCommand = 0;
420 rsp_hdr->MessageId = rcv_hdr->MessageId;
421 rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
422 rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
423 rsp_hdr->SessionId = rcv_hdr->SessionId;
424 memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);
428 * is_chained_smb2_message() - check for chained command
429 * @work: smb work containing smb request buffer
431 * Return: true if chained request, otherwise false
433 bool is_chained_smb2_message(struct ksmbd_work *work)
435 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
436 unsigned int len, next_cmd;
438 if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
441 hdr = ksmbd_req_buf_next(work);
442 next_cmd = le32_to_cpu(hdr->NextCommand);
444 if ((u64)work->next_smb2_rcv_hdr_off + next_cmd +
445 __SMB2_HEADER_STRUCTURE_SIZE >
446 get_rfc1002_len(work->request_buf)) {
447 pr_err("next command(%u) offset exceeds smb msg size\n",
452 if ((u64)get_rfc1002_len(work->response_buf) + MAX_CIFS_SMALL_BUFFER_SIZE >
454 pr_err("next response offset exceeds response buffer size\n");
458 ksmbd_debug(SMB, "got SMB2 chained command\n");
459 init_chained_smb2_rsp(work);
461 } else if (work->next_smb2_rcv_hdr_off) {
463 * This is last request in chained command,
464 * align response to 8 byte
466 len = ALIGN(get_rfc1002_len(work->response_buf), 8);
467 len = len - get_rfc1002_len(work->response_buf);
469 ksmbd_debug(SMB, "padding len %u\n", len);
470 inc_rfc1001_len(work->response_buf, len);
471 if (work->aux_payload_sz)
472 work->aux_payload_sz += len;
479 * init_smb2_rsp_hdr() - initialize smb2 response
480 * @work: smb work containing smb request buffer
484 int init_smb2_rsp_hdr(struct ksmbd_work *work)
486 struct smb2_hdr *rsp_hdr = smb2_get_msg(work->response_buf);
487 struct smb2_hdr *rcv_hdr = smb2_get_msg(work->request_buf);
488 struct ksmbd_conn *conn = work->conn;
490 memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
491 *(__be32 *)work->response_buf =
492 cpu_to_be32(conn->vals->header_size);
493 rsp_hdr->ProtocolId = rcv_hdr->ProtocolId;
494 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
495 rsp_hdr->Command = rcv_hdr->Command;
498 * Message is response. We don't grant oplock yet.
500 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
501 rsp_hdr->NextCommand = 0;
502 rsp_hdr->MessageId = rcv_hdr->MessageId;
503 rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
504 rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
505 rsp_hdr->SessionId = rcv_hdr->SessionId;
506 memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);
508 work->syncronous = true;
509 if (work->async_id) {
510 ksmbd_release_id(&conn->async_ida, work->async_id);
518 * smb2_allocate_rsp_buf() - allocate smb2 response buffer
519 * @work: smb work containing smb request buffer
521 * Return: 0 on success, otherwise -ENOMEM
523 int smb2_allocate_rsp_buf(struct ksmbd_work *work)
525 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
526 size_t small_sz = MAX_CIFS_SMALL_BUFFER_SIZE;
527 size_t large_sz = small_sz + work->conn->vals->max_trans_size;
528 size_t sz = small_sz;
529 int cmd = le16_to_cpu(hdr->Command);
531 if (cmd == SMB2_IOCTL_HE || cmd == SMB2_QUERY_DIRECTORY_HE)
534 if (cmd == SMB2_QUERY_INFO_HE) {
535 struct smb2_query_info_req *req;
537 req = smb2_get_msg(work->request_buf);
538 if (req->InfoType == SMB2_O_INFO_FILE &&
539 (req->FileInfoClass == FILE_FULL_EA_INFORMATION ||
540 req->FileInfoClass == FILE_ALL_INFORMATION))
544 /* allocate large response buf for chained commands */
545 if (le32_to_cpu(hdr->NextCommand) > 0)
548 work->response_buf = kvmalloc(sz, GFP_KERNEL | __GFP_ZERO);
549 if (!work->response_buf)
552 work->response_sz = sz;
557 * smb2_check_user_session() - check for valid session for a user
558 * @work: smb work containing smb request buffer
560 * Return: 0 on success, otherwise error
562 int smb2_check_user_session(struct ksmbd_work *work)
564 struct smb2_hdr *req_hdr = smb2_get_msg(work->request_buf);
565 struct ksmbd_conn *conn = work->conn;
566 unsigned int cmd = conn->ops->get_cmd_val(work);
567 unsigned long long sess_id;
571 * SMB2_ECHO, SMB2_NEGOTIATE, SMB2_SESSION_SETUP command do not
572 * require a session id, so no need to validate user session's for
575 if (cmd == SMB2_ECHO_HE || cmd == SMB2_NEGOTIATE_HE ||
576 cmd == SMB2_SESSION_SETUP_HE)
579 if (!ksmbd_conn_good(work))
582 sess_id = le64_to_cpu(req_hdr->SessionId);
583 /* Check for validity of user session */
584 work->sess = ksmbd_session_lookup_all(conn, sess_id);
587 ksmbd_debug(SMB, "Invalid user session, Uid %llu\n", sess_id);
591 static void destroy_previous_session(struct ksmbd_conn *conn,
592 struct ksmbd_user *user, u64 id)
594 struct ksmbd_session *prev_sess = ksmbd_session_lookup_slowpath(id);
595 struct ksmbd_user *prev_user;
596 struct channel *chann;
601 prev_user = prev_sess->user;
604 strcmp(user->name, prev_user->name) ||
605 user->passkey_sz != prev_user->passkey_sz ||
606 memcmp(user->passkey, prev_user->passkey, user->passkey_sz))
609 prev_sess->state = SMB2_SESSION_EXPIRED;
610 write_lock(&prev_sess->chann_lock);
611 list_for_each_entry(chann, &prev_sess->ksmbd_chann_list, chann_list)
612 chann->conn->status = KSMBD_SESS_EXITING;
613 write_unlock(&prev_sess->chann_lock);
617 * smb2_get_name() - get filename string from on the wire smb format
618 * @src: source buffer
619 * @maxlen: maxlen of source string
620 * @local_nls: nls_table pointer
622 * Return: matching converted filename on success, otherwise error ptr
625 smb2_get_name(const char *src, const int maxlen, struct nls_table *local_nls)
629 name = smb_strndup_from_utf16(src, maxlen, 1, local_nls);
631 pr_err("failed to get name %ld\n", PTR_ERR(name));
635 ksmbd_conv_path_to_unix(name);
636 ksmbd_strip_last_slash(name);
640 int setup_async_work(struct ksmbd_work *work, void (*fn)(void **), void **arg)
642 struct smb2_hdr *rsp_hdr;
643 struct ksmbd_conn *conn = work->conn;
646 rsp_hdr = smb2_get_msg(work->response_buf);
647 rsp_hdr->Flags |= SMB2_FLAGS_ASYNC_COMMAND;
649 id = ksmbd_acquire_async_msg_id(&conn->async_ida);
651 pr_err("Failed to alloc async message id\n");
654 work->syncronous = false;
656 rsp_hdr->Id.AsyncId = cpu_to_le64(id);
659 "Send interim Response to inform async request id : %d\n",
662 work->cancel_fn = fn;
663 work->cancel_argv = arg;
665 if (list_empty(&work->async_request_entry)) {
666 spin_lock(&conn->request_lock);
667 list_add_tail(&work->async_request_entry, &conn->async_requests);
668 spin_unlock(&conn->request_lock);
674 void smb2_send_interim_resp(struct ksmbd_work *work, __le32 status)
676 struct smb2_hdr *rsp_hdr;
678 rsp_hdr = smb2_get_msg(work->response_buf);
679 smb2_set_err_rsp(work);
680 rsp_hdr->Status = status;
683 ksmbd_conn_write(work);
688 static __le32 smb2_get_reparse_tag_special_file(umode_t mode)
690 if (S_ISDIR(mode) || S_ISREG(mode))
694 return IO_REPARSE_TAG_LX_SYMLINK_LE;
695 else if (S_ISFIFO(mode))
696 return IO_REPARSE_TAG_LX_FIFO_LE;
697 else if (S_ISSOCK(mode))
698 return IO_REPARSE_TAG_AF_UNIX_LE;
699 else if (S_ISCHR(mode))
700 return IO_REPARSE_TAG_LX_CHR_LE;
701 else if (S_ISBLK(mode))
702 return IO_REPARSE_TAG_LX_BLK_LE;
708 * smb2_get_dos_mode() - get file mode in dos format from unix mode
709 * @stat: kstat containing file mode
710 * @attribute: attribute flags
712 * Return: converted dos mode
714 static int smb2_get_dos_mode(struct kstat *stat, int attribute)
718 if (S_ISDIR(stat->mode)) {
719 attr = FILE_ATTRIBUTE_DIRECTORY |
720 (attribute & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM));
722 attr = (attribute & 0x00005137) | FILE_ATTRIBUTE_ARCHIVE;
723 attr &= ~(FILE_ATTRIBUTE_DIRECTORY);
724 if (S_ISREG(stat->mode) && (server_conf.share_fake_fscaps &
725 FILE_SUPPORTS_SPARSE_FILES))
726 attr |= FILE_ATTRIBUTE_SPARSE_FILE;
728 if (smb2_get_reparse_tag_special_file(stat->mode))
729 attr |= FILE_ATTRIBUTE_REPARSE_POINT;
735 static void build_preauth_ctxt(struct smb2_preauth_neg_context *pneg_ctxt,
738 pneg_ctxt->ContextType = SMB2_PREAUTH_INTEGRITY_CAPABILITIES;
739 pneg_ctxt->DataLength = cpu_to_le16(38);
740 pneg_ctxt->HashAlgorithmCount = cpu_to_le16(1);
741 pneg_ctxt->Reserved = cpu_to_le32(0);
742 pneg_ctxt->SaltLength = cpu_to_le16(SMB311_SALT_SIZE);
743 get_random_bytes(pneg_ctxt->Salt, SMB311_SALT_SIZE);
744 pneg_ctxt->HashAlgorithms = hash_id;
747 static void build_encrypt_ctxt(struct smb2_encryption_neg_context *pneg_ctxt,
750 pneg_ctxt->ContextType = SMB2_ENCRYPTION_CAPABILITIES;
751 pneg_ctxt->DataLength = cpu_to_le16(4);
752 pneg_ctxt->Reserved = cpu_to_le32(0);
753 pneg_ctxt->CipherCount = cpu_to_le16(1);
754 pneg_ctxt->Ciphers[0] = cipher_type;
757 static void build_compression_ctxt(struct smb2_compression_capabilities_context *pneg_ctxt,
760 pneg_ctxt->ContextType = SMB2_COMPRESSION_CAPABILITIES;
761 pneg_ctxt->DataLength =
762 cpu_to_le16(sizeof(struct smb2_compression_capabilities_context)
763 - sizeof(struct smb2_neg_context));
764 pneg_ctxt->Reserved = cpu_to_le32(0);
765 pneg_ctxt->CompressionAlgorithmCount = cpu_to_le16(1);
766 pneg_ctxt->Flags = cpu_to_le32(0);
767 pneg_ctxt->CompressionAlgorithms[0] = comp_algo;
770 static void build_sign_cap_ctxt(struct smb2_signing_capabilities *pneg_ctxt,
773 pneg_ctxt->ContextType = SMB2_SIGNING_CAPABILITIES;
774 pneg_ctxt->DataLength =
775 cpu_to_le16((sizeof(struct smb2_signing_capabilities) + 2)
776 - sizeof(struct smb2_neg_context));
777 pneg_ctxt->Reserved = cpu_to_le32(0);
778 pneg_ctxt->SigningAlgorithmCount = cpu_to_le16(1);
779 pneg_ctxt->SigningAlgorithms[0] = sign_algo;
782 static void build_posix_ctxt(struct smb2_posix_neg_context *pneg_ctxt)
784 pneg_ctxt->ContextType = SMB2_POSIX_EXTENSIONS_AVAILABLE;
785 pneg_ctxt->DataLength = cpu_to_le16(POSIX_CTXT_DATA_LEN);
786 /* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */
787 pneg_ctxt->Name[0] = 0x93;
788 pneg_ctxt->Name[1] = 0xAD;
789 pneg_ctxt->Name[2] = 0x25;
790 pneg_ctxt->Name[3] = 0x50;
791 pneg_ctxt->Name[4] = 0x9C;
792 pneg_ctxt->Name[5] = 0xB4;
793 pneg_ctxt->Name[6] = 0x11;
794 pneg_ctxt->Name[7] = 0xE7;
795 pneg_ctxt->Name[8] = 0xB4;
796 pneg_ctxt->Name[9] = 0x23;
797 pneg_ctxt->Name[10] = 0x83;
798 pneg_ctxt->Name[11] = 0xDE;
799 pneg_ctxt->Name[12] = 0x96;
800 pneg_ctxt->Name[13] = 0x8B;
801 pneg_ctxt->Name[14] = 0xCD;
802 pneg_ctxt->Name[15] = 0x7C;
805 static void assemble_neg_contexts(struct ksmbd_conn *conn,
806 struct smb2_negotiate_rsp *rsp,
809 char *pneg_ctxt = (char *)rsp +
810 le32_to_cpu(rsp->NegotiateContextOffset);
811 int neg_ctxt_cnt = 1;
815 "assemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
816 build_preauth_ctxt((struct smb2_preauth_neg_context *)pneg_ctxt,
817 conn->preauth_info->Preauth_HashId);
818 rsp->NegotiateContextCount = cpu_to_le16(neg_ctxt_cnt);
819 inc_rfc1001_len(smb2_buf_len, AUTH_GSS_PADDING);
820 ctxt_size = sizeof(struct smb2_preauth_neg_context);
821 /* Round to 8 byte boundary */
822 pneg_ctxt += round_up(sizeof(struct smb2_preauth_neg_context), 8);
824 if (conn->cipher_type) {
825 ctxt_size = round_up(ctxt_size, 8);
827 "assemble SMB2_ENCRYPTION_CAPABILITIES context\n");
828 build_encrypt_ctxt((struct smb2_encryption_neg_context *)pneg_ctxt,
830 rsp->NegotiateContextCount = cpu_to_le16(++neg_ctxt_cnt);
831 ctxt_size += sizeof(struct smb2_encryption_neg_context) + 2;
832 /* Round to 8 byte boundary */
834 round_up(sizeof(struct smb2_encryption_neg_context) + 2,
838 if (conn->compress_algorithm) {
839 ctxt_size = round_up(ctxt_size, 8);
841 "assemble SMB2_COMPRESSION_CAPABILITIES context\n");
842 /* Temporarily set to SMB3_COMPRESS_NONE */
843 build_compression_ctxt((struct smb2_compression_capabilities_context *)pneg_ctxt,
844 conn->compress_algorithm);
845 rsp->NegotiateContextCount = cpu_to_le16(++neg_ctxt_cnt);
846 ctxt_size += sizeof(struct smb2_compression_capabilities_context) + 2;
847 /* Round to 8 byte boundary */
848 pneg_ctxt += round_up(sizeof(struct smb2_compression_capabilities_context) + 2,
852 if (conn->posix_ext_supported) {
853 ctxt_size = round_up(ctxt_size, 8);
855 "assemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
856 build_posix_ctxt((struct smb2_posix_neg_context *)pneg_ctxt);
857 rsp->NegotiateContextCount = cpu_to_le16(++neg_ctxt_cnt);
858 ctxt_size += sizeof(struct smb2_posix_neg_context);
859 /* Round to 8 byte boundary */
860 pneg_ctxt += round_up(sizeof(struct smb2_posix_neg_context), 8);
863 if (conn->signing_negotiated) {
864 ctxt_size = round_up(ctxt_size, 8);
866 "assemble SMB2_SIGNING_CAPABILITIES context\n");
867 build_sign_cap_ctxt((struct smb2_signing_capabilities *)pneg_ctxt,
868 conn->signing_algorithm);
869 rsp->NegotiateContextCount = cpu_to_le16(++neg_ctxt_cnt);
870 ctxt_size += sizeof(struct smb2_signing_capabilities) + 2;
873 inc_rfc1001_len(smb2_buf_len, ctxt_size);
876 static __le32 decode_preauth_ctxt(struct ksmbd_conn *conn,
877 struct smb2_preauth_neg_context *pneg_ctxt)
879 __le32 err = STATUS_NO_PREAUTH_INTEGRITY_HASH_OVERLAP;
881 if (pneg_ctxt->HashAlgorithms == SMB2_PREAUTH_INTEGRITY_SHA512) {
882 conn->preauth_info->Preauth_HashId =
883 SMB2_PREAUTH_INTEGRITY_SHA512;
884 err = STATUS_SUCCESS;
890 static void decode_encrypt_ctxt(struct ksmbd_conn *conn,
891 struct smb2_encryption_neg_context *pneg_ctxt,
894 int cph_cnt = le16_to_cpu(pneg_ctxt->CipherCount);
895 int i, cphs_size = cph_cnt * sizeof(__le16);
897 conn->cipher_type = 0;
899 if (sizeof(struct smb2_encryption_neg_context) + cphs_size >
901 pr_err("Invalid cipher count(%d)\n", cph_cnt);
905 if (!(server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION))
908 for (i = 0; i < cph_cnt; i++) {
909 if (pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_GCM ||
910 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_CCM ||
911 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_CCM ||
912 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_GCM) {
913 ksmbd_debug(SMB, "Cipher ID = 0x%x\n",
914 pneg_ctxt->Ciphers[i]);
915 conn->cipher_type = pneg_ctxt->Ciphers[i];
922 * smb3_encryption_negotiated() - checks if server and client agreed on enabling encryption
923 * @conn: smb connection
925 * Return: true if connection should be encrypted, else false
927 static bool smb3_encryption_negotiated(struct ksmbd_conn *conn)
929 if (!conn->ops->generate_encryptionkey)
933 * SMB 3.0 and 3.0.2 dialects use the SMB2_GLOBAL_CAP_ENCRYPTION flag.
934 * SMB 3.1.1 uses the cipher_type field.
936 return (conn->vals->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION) ||
940 static void decode_compress_ctxt(struct ksmbd_conn *conn,
941 struct smb2_compression_capabilities_context *pneg_ctxt)
943 conn->compress_algorithm = SMB3_COMPRESS_NONE;
946 static void decode_sign_cap_ctxt(struct ksmbd_conn *conn,
947 struct smb2_signing_capabilities *pneg_ctxt,
950 int sign_algo_cnt = le16_to_cpu(pneg_ctxt->SigningAlgorithmCount);
951 int i, sign_alos_size = sign_algo_cnt * sizeof(__le16);
953 conn->signing_negotiated = false;
955 if (sizeof(struct smb2_signing_capabilities) + sign_alos_size >
957 pr_err("Invalid signing algorithm count(%d)\n", sign_algo_cnt);
961 for (i = 0; i < sign_algo_cnt; i++) {
962 if (pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_HMAC_SHA256_LE ||
963 pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_AES_CMAC_LE) {
964 ksmbd_debug(SMB, "Signing Algorithm ID = 0x%x\n",
965 pneg_ctxt->SigningAlgorithms[i]);
966 conn->signing_negotiated = true;
967 conn->signing_algorithm =
968 pneg_ctxt->SigningAlgorithms[i];
974 static __le32 deassemble_neg_contexts(struct ksmbd_conn *conn,
975 struct smb2_negotiate_req *req,
978 /* +4 is to account for the RFC1001 len field */
979 struct smb2_neg_context *pctx = (struct smb2_neg_context *)req;
980 int i = 0, len_of_ctxts;
981 int offset = le32_to_cpu(req->NegotiateContextOffset);
982 int neg_ctxt_cnt = le16_to_cpu(req->NegotiateContextCount);
983 __le32 status = STATUS_INVALID_PARAMETER;
985 ksmbd_debug(SMB, "decoding %d negotiate contexts\n", neg_ctxt_cnt);
986 if (len_of_smb <= offset) {
987 ksmbd_debug(SMB, "Invalid response: negotiate context offset\n");
991 len_of_ctxts = len_of_smb - offset;
993 while (i++ < neg_ctxt_cnt) {
996 /* check that offset is not beyond end of SMB */
997 if (len_of_ctxts == 0)
1000 if (len_of_ctxts < sizeof(struct smb2_neg_context))
1003 pctx = (struct smb2_neg_context *)((char *)pctx + offset);
1004 clen = le16_to_cpu(pctx->DataLength);
1005 if (clen + sizeof(struct smb2_neg_context) > len_of_ctxts)
1008 if (pctx->ContextType == SMB2_PREAUTH_INTEGRITY_CAPABILITIES) {
1010 "deassemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
1011 if (conn->preauth_info->Preauth_HashId)
1014 status = decode_preauth_ctxt(conn,
1015 (struct smb2_preauth_neg_context *)pctx);
1016 if (status != STATUS_SUCCESS)
1018 } else if (pctx->ContextType == SMB2_ENCRYPTION_CAPABILITIES) {
1020 "deassemble SMB2_ENCRYPTION_CAPABILITIES context\n");
1021 if (conn->cipher_type)
1024 decode_encrypt_ctxt(conn,
1025 (struct smb2_encryption_neg_context *)pctx,
1027 } else if (pctx->ContextType == SMB2_COMPRESSION_CAPABILITIES) {
1029 "deassemble SMB2_COMPRESSION_CAPABILITIES context\n");
1030 if (conn->compress_algorithm)
1033 decode_compress_ctxt(conn,
1034 (struct smb2_compression_capabilities_context *)pctx);
1035 } else if (pctx->ContextType == SMB2_NETNAME_NEGOTIATE_CONTEXT_ID) {
1037 "deassemble SMB2_NETNAME_NEGOTIATE_CONTEXT_ID context\n");
1038 } else if (pctx->ContextType == SMB2_POSIX_EXTENSIONS_AVAILABLE) {
1040 "deassemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
1041 conn->posix_ext_supported = true;
1042 } else if (pctx->ContextType == SMB2_SIGNING_CAPABILITIES) {
1044 "deassemble SMB2_SIGNING_CAPABILITIES context\n");
1045 decode_sign_cap_ctxt(conn,
1046 (struct smb2_signing_capabilities *)pctx,
1050 /* offsets must be 8 byte aligned */
1051 clen = (clen + 7) & ~0x7;
1052 offset = clen + sizeof(struct smb2_neg_context);
1053 len_of_ctxts -= clen + sizeof(struct smb2_neg_context);
1059 * smb2_handle_negotiate() - handler for smb2 negotiate command
1060 * @work: smb work containing smb request buffer
1064 int smb2_handle_negotiate(struct ksmbd_work *work)
1066 struct ksmbd_conn *conn = work->conn;
1067 struct smb2_negotiate_req *req = smb2_get_msg(work->request_buf);
1068 struct smb2_negotiate_rsp *rsp = smb2_get_msg(work->response_buf);
1070 unsigned int smb2_buf_len, smb2_neg_size;
1073 ksmbd_debug(SMB, "Received negotiate request\n");
1074 conn->need_neg = false;
1075 if (ksmbd_conn_good(work)) {
1076 pr_err("conn->tcp_status is already in CifsGood State\n");
1077 work->send_no_response = 1;
1081 if (req->DialectCount == 0) {
1082 pr_err("malformed packet\n");
1083 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1088 smb2_buf_len = get_rfc1002_len(work->request_buf);
1089 smb2_neg_size = offsetof(struct smb2_negotiate_req, Dialects);
1090 if (smb2_neg_size > smb2_buf_len) {
1091 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1096 if (conn->dialect == SMB311_PROT_ID) {
1097 unsigned int nego_ctxt_off = le32_to_cpu(req->NegotiateContextOffset);
1099 if (smb2_buf_len < nego_ctxt_off) {
1100 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1105 if (smb2_neg_size > nego_ctxt_off) {
1106 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1111 if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
1113 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1118 if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
1120 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1126 conn->cli_cap = le32_to_cpu(req->Capabilities);
1127 switch (conn->dialect) {
1128 case SMB311_PROT_ID:
1129 conn->preauth_info =
1130 kzalloc(sizeof(struct preauth_integrity_info),
1132 if (!conn->preauth_info) {
1134 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1138 status = deassemble_neg_contexts(conn, req,
1139 get_rfc1002_len(work->request_buf));
1140 if (status != STATUS_SUCCESS) {
1141 pr_err("deassemble_neg_contexts error(0x%x)\n",
1143 rsp->hdr.Status = status;
1148 rc = init_smb3_11_server(conn);
1150 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1154 ksmbd_gen_preauth_integrity_hash(conn,
1156 conn->preauth_info->Preauth_HashValue);
1157 rsp->NegotiateContextOffset =
1158 cpu_to_le32(OFFSET_OF_NEG_CONTEXT);
1159 assemble_neg_contexts(conn, rsp, work->response_buf);
1161 case SMB302_PROT_ID:
1162 init_smb3_02_server(conn);
1165 init_smb3_0_server(conn);
1168 init_smb2_1_server(conn);
1173 ksmbd_debug(SMB, "Server dialect :0x%x not supported\n",
1175 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
1179 rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
1182 conn->connection_type = conn->dialect;
1184 rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
1185 rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
1186 rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);
1188 memcpy(conn->ClientGUID, req->ClientGUID,
1189 SMB2_CLIENT_GUID_SIZE);
1190 conn->cli_sec_mode = le16_to_cpu(req->SecurityMode);
1192 rsp->StructureSize = cpu_to_le16(65);
1193 rsp->DialectRevision = cpu_to_le16(conn->dialect);
1194 /* Not setting conn guid rsp->ServerGUID, as it
1195 * not used by client for identifying server
1197 memset(rsp->ServerGUID, 0, SMB2_CLIENT_GUID_SIZE);
1199 rsp->SystemTime = cpu_to_le64(ksmbd_systime());
1200 rsp->ServerStartTime = 0;
1201 ksmbd_debug(SMB, "negotiate context offset %d, count %d\n",
1202 le32_to_cpu(rsp->NegotiateContextOffset),
1203 le16_to_cpu(rsp->NegotiateContextCount));
1205 rsp->SecurityBufferOffset = cpu_to_le16(128);
1206 rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
1207 ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) +
1208 le16_to_cpu(rsp->SecurityBufferOffset));
1209 inc_rfc1001_len(work->response_buf, sizeof(struct smb2_negotiate_rsp) -
1210 sizeof(struct smb2_hdr) - sizeof(rsp->Buffer) +
1212 rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
1213 conn->use_spnego = true;
1215 if ((server_conf.signing == KSMBD_CONFIG_OPT_AUTO ||
1216 server_conf.signing == KSMBD_CONFIG_OPT_DISABLED) &&
1217 req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED_LE)
1219 else if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY) {
1220 server_conf.enforced_signing = true;
1221 rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
1225 conn->srv_sec_mode = le16_to_cpu(rsp->SecurityMode);
1226 ksmbd_conn_set_need_negotiate(work);
1230 smb2_set_err_rsp(work);
1235 static int alloc_preauth_hash(struct ksmbd_session *sess,
1236 struct ksmbd_conn *conn)
1238 if (sess->Preauth_HashValue)
1241 sess->Preauth_HashValue = kmemdup(conn->preauth_info->Preauth_HashValue,
1242 PREAUTH_HASHVALUE_SIZE, GFP_KERNEL);
1243 if (!sess->Preauth_HashValue)
1249 static int generate_preauth_hash(struct ksmbd_work *work)
1251 struct ksmbd_conn *conn = work->conn;
1252 struct ksmbd_session *sess = work->sess;
1255 if (conn->dialect != SMB311_PROT_ID)
1258 if (conn->binding) {
1259 struct preauth_session *preauth_sess;
1261 preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
1262 if (!preauth_sess) {
1263 preauth_sess = ksmbd_preauth_session_alloc(conn, sess->id);
1268 preauth_hash = preauth_sess->Preauth_HashValue;
1270 if (!sess->Preauth_HashValue)
1271 if (alloc_preauth_hash(sess, conn))
1273 preauth_hash = sess->Preauth_HashValue;
1276 ksmbd_gen_preauth_integrity_hash(conn, work->request_buf, preauth_hash);
1280 static int decode_negotiation_token(struct ksmbd_conn *conn,
1281 struct negotiate_message *negblob,
1284 if (!conn->use_spnego)
1287 if (ksmbd_decode_negTokenInit((char *)negblob, sz, conn)) {
1288 if (ksmbd_decode_negTokenTarg((char *)negblob, sz, conn)) {
1289 conn->auth_mechs |= KSMBD_AUTH_NTLMSSP;
1290 conn->preferred_auth_mech = KSMBD_AUTH_NTLMSSP;
1291 conn->use_spnego = false;
1297 static int ntlm_negotiate(struct ksmbd_work *work,
1298 struct negotiate_message *negblob,
1301 struct smb2_sess_setup_rsp *rsp = smb2_get_msg(work->response_buf);
1302 struct challenge_message *chgblob;
1303 unsigned char *spnego_blob = NULL;
1304 u16 spnego_blob_len;
1308 ksmbd_debug(SMB, "negotiate phase\n");
1309 rc = ksmbd_decode_ntlmssp_neg_blob(negblob, negblob_len, work->conn);
1313 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1315 (struct challenge_message *)((char *)&rsp->hdr.ProtocolId + sz);
1316 memset(chgblob, 0, sizeof(struct challenge_message));
1318 if (!work->conn->use_spnego) {
1319 sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
1323 rsp->SecurityBufferLength = cpu_to_le16(sz);
1327 sz = sizeof(struct challenge_message);
1328 sz += (strlen(ksmbd_netbios_name()) * 2 + 1 + 4) * 6;
1330 neg_blob = kzalloc(sz, GFP_KERNEL);
1334 chgblob = (struct challenge_message *)neg_blob;
1335 sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
1341 rc = build_spnego_ntlmssp_neg_blob(&spnego_blob, &spnego_blob_len,
1348 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1349 memcpy((char *)&rsp->hdr.ProtocolId + sz, spnego_blob, spnego_blob_len);
1350 rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
1358 static struct authenticate_message *user_authblob(struct ksmbd_conn *conn,
1359 struct smb2_sess_setup_req *req)
1363 if (conn->use_spnego && conn->mechToken)
1364 return (struct authenticate_message *)conn->mechToken;
1366 sz = le16_to_cpu(req->SecurityBufferOffset);
1367 return (struct authenticate_message *)((char *)&req->hdr.ProtocolId
1371 static struct ksmbd_user *session_user(struct ksmbd_conn *conn,
1372 struct smb2_sess_setup_req *req)
1374 struct authenticate_message *authblob;
1375 struct ksmbd_user *user;
1377 unsigned int auth_msg_len, name_off, name_len, secbuf_len;
1379 secbuf_len = le16_to_cpu(req->SecurityBufferLength);
1380 if (secbuf_len < sizeof(struct authenticate_message)) {
1381 ksmbd_debug(SMB, "blob len %d too small\n", secbuf_len);
1384 authblob = user_authblob(conn, req);
1385 name_off = le32_to_cpu(authblob->UserName.BufferOffset);
1386 name_len = le16_to_cpu(authblob->UserName.Length);
1387 auth_msg_len = le16_to_cpu(req->SecurityBufferOffset) + secbuf_len;
1389 if (auth_msg_len < (u64)name_off + name_len)
1392 name = smb_strndup_from_utf16((const char *)authblob + name_off,
1397 pr_err("cannot allocate memory\n");
1401 ksmbd_debug(SMB, "session setup request for user %s\n", name);
1402 user = ksmbd_login_user(name);
1407 static int ntlm_authenticate(struct ksmbd_work *work)
1409 struct smb2_sess_setup_req *req = smb2_get_msg(work->request_buf);
1410 struct smb2_sess_setup_rsp *rsp = smb2_get_msg(work->response_buf);
1411 struct ksmbd_conn *conn = work->conn;
1412 struct ksmbd_session *sess = work->sess;
1413 struct channel *chann = NULL;
1414 struct ksmbd_user *user;
1418 ksmbd_debug(SMB, "authenticate phase\n");
1419 if (conn->use_spnego) {
1420 unsigned char *spnego_blob;
1421 u16 spnego_blob_len;
1423 rc = build_spnego_ntlmssp_auth_blob(&spnego_blob,
1429 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1430 memcpy((char *)&rsp->hdr.ProtocolId + sz, spnego_blob, spnego_blob_len);
1431 rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
1433 inc_rfc1001_len(work->response_buf, spnego_blob_len - 1);
1436 user = session_user(conn, req);
1438 ksmbd_debug(SMB, "Unknown user name or an error\n");
1442 /* Check for previous session */
1443 prev_id = le64_to_cpu(req->PreviousSessionId);
1444 if (prev_id && prev_id != sess->id)
1445 destroy_previous_session(conn, user, prev_id);
1447 if (sess->state == SMB2_SESSION_VALID) {
1449 * Reuse session if anonymous try to connect
1450 * on reauthetication.
1452 if (ksmbd_anonymous_user(user)) {
1453 ksmbd_free_user(user);
1457 if (!ksmbd_compare_user(sess->user, user)) {
1458 ksmbd_free_user(user);
1461 ksmbd_free_user(user);
1466 if (user_guest(sess->user)) {
1467 rsp->SessionFlags = SMB2_SESSION_FLAG_IS_GUEST_LE;
1469 struct authenticate_message *authblob;
1471 authblob = user_authblob(conn, req);
1472 sz = le16_to_cpu(req->SecurityBufferLength);
1473 rc = ksmbd_decode_ntlmssp_auth_blob(authblob, sz, conn, sess);
1475 set_user_flag(sess->user, KSMBD_USER_FLAG_BAD_PASSWORD);
1476 ksmbd_debug(SMB, "authentication failed\n");
1482 * If session state is SMB2_SESSION_VALID, We can assume
1483 * that it is reauthentication. And the user/password
1484 * has been verified, so return it here.
1486 if (sess->state == SMB2_SESSION_VALID) {
1488 goto binding_session;
1492 if ((rsp->SessionFlags != SMB2_SESSION_FLAG_IS_GUEST_LE &&
1493 (conn->sign || server_conf.enforced_signing)) ||
1494 (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
1497 if (smb3_encryption_negotiated(conn) &&
1498 !(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1499 rc = conn->ops->generate_encryptionkey(conn, sess);
1502 "SMB3 encryption key generation failed\n");
1506 rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
1508 * signing is disable if encryption is enable
1515 if (conn->dialect >= SMB30_PROT_ID) {
1516 read_lock(&sess->chann_lock);
1517 chann = lookup_chann_list(sess, conn);
1518 read_unlock(&sess->chann_lock);
1520 chann = kmalloc(sizeof(struct channel), GFP_KERNEL);
1525 INIT_LIST_HEAD(&chann->chann_list);
1526 write_lock(&sess->chann_lock);
1527 list_add(&chann->chann_list, &sess->ksmbd_chann_list);
1528 write_unlock(&sess->chann_lock);
1532 if (conn->ops->generate_signingkey) {
1533 rc = conn->ops->generate_signingkey(sess, conn);
1535 ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
1540 if (!ksmbd_conn_lookup_dialect(conn)) {
1541 pr_err("fail to verify the dialect\n");
1547 #ifdef CONFIG_SMB_SERVER_KERBEROS5
1548 static int krb5_authenticate(struct ksmbd_work *work)
1550 struct smb2_sess_setup_req *req = smb2_get_msg(work->request_buf);
1551 struct smb2_sess_setup_rsp *rsp = smb2_get_msg(work->response_buf);
1552 struct ksmbd_conn *conn = work->conn;
1553 struct ksmbd_session *sess = work->sess;
1554 char *in_blob, *out_blob;
1555 struct channel *chann = NULL;
1557 int in_len, out_len;
1560 in_blob = (char *)&req->hdr.ProtocolId +
1561 le16_to_cpu(req->SecurityBufferOffset);
1562 in_len = le16_to_cpu(req->SecurityBufferLength);
1563 out_blob = (char *)&rsp->hdr.ProtocolId +
1564 le16_to_cpu(rsp->SecurityBufferOffset);
1565 out_len = work->response_sz -
1566 (le16_to_cpu(rsp->SecurityBufferOffset) + 4);
1568 /* Check previous session */
1569 prev_sess_id = le64_to_cpu(req->PreviousSessionId);
1570 if (prev_sess_id && prev_sess_id != sess->id)
1571 destroy_previous_session(conn, sess->user, prev_sess_id);
1573 if (sess->state == SMB2_SESSION_VALID)
1574 ksmbd_free_user(sess->user);
1576 retval = ksmbd_krb5_authenticate(sess, in_blob, in_len,
1577 out_blob, &out_len);
1579 ksmbd_debug(SMB, "krb5 authentication failed\n");
1582 rsp->SecurityBufferLength = cpu_to_le16(out_len);
1583 inc_rfc1001_len(work->response_buf, out_len - 1);
1585 if ((conn->sign || server_conf.enforced_signing) ||
1586 (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
1589 if (smb3_encryption_negotiated(conn)) {
1590 retval = conn->ops->generate_encryptionkey(conn, sess);
1593 "SMB3 encryption key generation failed\n");
1597 rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
1601 if (conn->dialect >= SMB30_PROT_ID) {
1602 read_lock(&sess->chann_lock);
1603 chann = lookup_chann_list(sess, conn);
1604 read_unlock(&sess->chann_lock);
1606 chann = kmalloc(sizeof(struct channel), GFP_KERNEL);
1611 INIT_LIST_HEAD(&chann->chann_list);
1612 write_lock(&sess->chann_lock);
1613 list_add(&chann->chann_list, &sess->ksmbd_chann_list);
1614 write_unlock(&sess->chann_lock);
1618 if (conn->ops->generate_signingkey) {
1619 retval = conn->ops->generate_signingkey(sess, conn);
1621 ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
1626 if (!ksmbd_conn_lookup_dialect(conn)) {
1627 pr_err("fail to verify the dialect\n");
1633 static int krb5_authenticate(struct ksmbd_work *work)
1639 int smb2_sess_setup(struct ksmbd_work *work)
1641 struct ksmbd_conn *conn = work->conn;
1642 struct smb2_sess_setup_req *req = smb2_get_msg(work->request_buf);
1643 struct smb2_sess_setup_rsp *rsp = smb2_get_msg(work->response_buf);
1644 struct ksmbd_session *sess;
1645 struct negotiate_message *negblob;
1646 unsigned int negblob_len, negblob_off;
1649 ksmbd_debug(SMB, "Received request for session setup\n");
1651 rsp->StructureSize = cpu_to_le16(9);
1652 rsp->SessionFlags = 0;
1653 rsp->SecurityBufferOffset = cpu_to_le16(72);
1654 rsp->SecurityBufferLength = 0;
1655 inc_rfc1001_len(work->response_buf, 9);
1657 if (!req->hdr.SessionId) {
1658 sess = ksmbd_smb2_session_create();
1663 rsp->hdr.SessionId = cpu_to_le64(sess->id);
1664 rc = ksmbd_session_register(conn, sess);
1667 } else if (conn->dialect >= SMB30_PROT_ID &&
1668 (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
1669 req->Flags & SMB2_SESSION_REQ_FLAG_BINDING) {
1670 u64 sess_id = le64_to_cpu(req->hdr.SessionId);
1672 sess = ksmbd_session_lookup_slowpath(sess_id);
1678 if (conn->dialect != sess->dialect) {
1683 if (!(req->hdr.Flags & SMB2_FLAGS_SIGNED)) {
1688 if (strncmp(conn->ClientGUID, sess->ClientGUID,
1689 SMB2_CLIENT_GUID_SIZE)) {
1694 if (sess->state == SMB2_SESSION_IN_PROGRESS) {
1699 if (sess->state == SMB2_SESSION_EXPIRED) {
1704 if (ksmbd_session_lookup(conn, sess_id)) {
1709 conn->binding = true;
1710 } else if ((conn->dialect < SMB30_PROT_ID ||
1711 server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
1712 (req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1717 sess = ksmbd_session_lookup(conn,
1718 le64_to_cpu(req->hdr.SessionId));
1726 if (sess->state == SMB2_SESSION_EXPIRED)
1727 sess->state = SMB2_SESSION_IN_PROGRESS;
1729 negblob_off = le16_to_cpu(req->SecurityBufferOffset);
1730 negblob_len = le16_to_cpu(req->SecurityBufferLength);
1731 if (negblob_off < offsetof(struct smb2_sess_setup_req, Buffer) ||
1732 negblob_len < offsetof(struct negotiate_message, NegotiateFlags)) {
1737 negblob = (struct negotiate_message *)((char *)&req->hdr.ProtocolId +
1740 if (decode_negotiation_token(conn, negblob, negblob_len) == 0) {
1741 if (conn->mechToken)
1742 negblob = (struct negotiate_message *)conn->mechToken;
1745 if (server_conf.auth_mechs & conn->auth_mechs) {
1746 rc = generate_preauth_hash(work);
1750 if (conn->preferred_auth_mech &
1751 (KSMBD_AUTH_KRB5 | KSMBD_AUTH_MSKRB5)) {
1752 rc = krb5_authenticate(work);
1758 ksmbd_conn_set_good(work);
1759 sess->state = SMB2_SESSION_VALID;
1760 kfree(sess->Preauth_HashValue);
1761 sess->Preauth_HashValue = NULL;
1762 } else if (conn->preferred_auth_mech == KSMBD_AUTH_NTLMSSP) {
1763 if (negblob->MessageType == NtLmNegotiate) {
1764 rc = ntlm_negotiate(work, negblob, negblob_len);
1768 STATUS_MORE_PROCESSING_REQUIRED;
1770 * Note: here total size -1 is done as an
1771 * adjustment for 0 size blob
1773 inc_rfc1001_len(work->response_buf,
1774 le16_to_cpu(rsp->SecurityBufferLength) - 1);
1776 } else if (negblob->MessageType == NtLmAuthenticate) {
1777 rc = ntlm_authenticate(work);
1781 ksmbd_conn_set_good(work);
1782 sess->state = SMB2_SESSION_VALID;
1783 if (conn->binding) {
1784 struct preauth_session *preauth_sess;
1787 ksmbd_preauth_session_lookup(conn, sess->id);
1789 list_del(&preauth_sess->preauth_entry);
1790 kfree(preauth_sess);
1793 kfree(sess->Preauth_HashValue);
1794 sess->Preauth_HashValue = NULL;
1797 /* TODO: need one more negotiation */
1798 pr_err("Not support the preferred authentication\n");
1802 pr_err("Not support authentication\n");
1808 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1809 else if (rc == -ENOENT)
1810 rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
1811 else if (rc == -EACCES)
1812 rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
1813 else if (rc == -EFAULT)
1814 rsp->hdr.Status = STATUS_NETWORK_SESSION_EXPIRED;
1815 else if (rc == -ENOMEM)
1816 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
1818 rsp->hdr.Status = STATUS_LOGON_FAILURE;
1820 if (conn->use_spnego && conn->mechToken) {
1821 kfree(conn->mechToken);
1822 conn->mechToken = NULL;
1827 * SecurityBufferOffset should be set to zero
1828 * in session setup error response.
1830 rsp->SecurityBufferOffset = 0;
1833 bool try_delay = false;
1836 * To avoid dictionary attacks (repeated session setups rapidly sent) to
1837 * connect to server, ksmbd make a delay of a 5 seconds on session setup
1838 * failure to make it harder to send enough random connection requests
1839 * to break into a server.
1841 if (sess->user && sess->user->flags & KSMBD_USER_FLAG_DELAY_SESSION)
1844 xa_erase(&conn->sessions, sess->id);
1845 ksmbd_session_destroy(sess);
1856 * smb2_tree_connect() - handler for smb2 tree connect command
1857 * @work: smb work containing smb request buffer
1859 * Return: 0 on success, otherwise error
1861 int smb2_tree_connect(struct ksmbd_work *work)
1863 struct ksmbd_conn *conn = work->conn;
1864 struct smb2_tree_connect_req *req = smb2_get_msg(work->request_buf);
1865 struct smb2_tree_connect_rsp *rsp = smb2_get_msg(work->response_buf);
1866 struct ksmbd_session *sess = work->sess;
1867 char *treename = NULL, *name = NULL;
1868 struct ksmbd_tree_conn_status status;
1869 struct ksmbd_share_config *share;
1872 treename = smb_strndup_from_utf16(req->Buffer,
1873 le16_to_cpu(req->PathLength), true,
1875 if (IS_ERR(treename)) {
1876 pr_err("treename is NULL\n");
1877 status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
1881 name = ksmbd_extract_sharename(treename);
1883 status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
1887 ksmbd_debug(SMB, "tree connect request for tree %s treename %s\n",
1890 status = ksmbd_tree_conn_connect(conn, sess, name);
1891 if (status.ret == KSMBD_TREE_CONN_STATUS_OK)
1892 rsp->hdr.Id.SyncId.TreeId = cpu_to_le32(status.tree_conn->id);
1896 share = status.tree_conn->share_conf;
1897 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
1898 ksmbd_debug(SMB, "IPC share path request\n");
1899 rsp->ShareType = SMB2_SHARE_TYPE_PIPE;
1900 rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
1901 FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE |
1902 FILE_DELETE_LE | FILE_READ_CONTROL_LE |
1903 FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
1904 FILE_SYNCHRONIZE_LE;
1906 rsp->ShareType = SMB2_SHARE_TYPE_DISK;
1907 rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
1908 FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE;
1909 if (test_tree_conn_flag(status.tree_conn,
1910 KSMBD_TREE_CONN_FLAG_WRITABLE)) {
1911 rsp->MaximalAccess |= FILE_WRITE_DATA_LE |
1912 FILE_APPEND_DATA_LE | FILE_WRITE_EA_LE |
1913 FILE_DELETE_LE | FILE_WRITE_ATTRIBUTES_LE |
1914 FILE_DELETE_CHILD_LE | FILE_READ_CONTROL_LE |
1915 FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
1916 FILE_SYNCHRONIZE_LE;
1920 status.tree_conn->maximal_access = le32_to_cpu(rsp->MaximalAccess);
1921 if (conn->posix_ext_supported)
1922 status.tree_conn->posix_extensions = true;
1925 rsp->StructureSize = cpu_to_le16(16);
1926 rsp->Capabilities = 0;
1928 /* default manual caching */
1929 rsp->ShareFlags = SMB2_SHAREFLAG_MANUAL_CACHING;
1930 inc_rfc1001_len(work->response_buf, 16);
1932 if (!IS_ERR(treename))
1937 switch (status.ret) {
1938 case KSMBD_TREE_CONN_STATUS_OK:
1939 rsp->hdr.Status = STATUS_SUCCESS;
1942 case KSMBD_TREE_CONN_STATUS_NO_SHARE:
1943 rsp->hdr.Status = STATUS_BAD_NETWORK_PATH;
1946 case KSMBD_TREE_CONN_STATUS_NOMEM:
1947 rsp->hdr.Status = STATUS_NO_MEMORY;
1949 case KSMBD_TREE_CONN_STATUS_ERROR:
1950 case KSMBD_TREE_CONN_STATUS_TOO_MANY_CONNS:
1951 case KSMBD_TREE_CONN_STATUS_TOO_MANY_SESSIONS:
1952 rsp->hdr.Status = STATUS_ACCESS_DENIED;
1955 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1958 rsp->hdr.Status = STATUS_ACCESS_DENIED;
1965 * smb2_create_open_flags() - convert smb open flags to unix open flags
1966 * @file_present: is file already present
1967 * @access: file access flags
1968 * @disposition: file disposition flags
1969 * @may_flags: set with MAY_ flags
1971 * Return: file open flags
1973 static int smb2_create_open_flags(bool file_present, __le32 access,
1977 int oflags = O_NONBLOCK | O_LARGEFILE;
1979 if (access & FILE_READ_DESIRED_ACCESS_LE &&
1980 access & FILE_WRITE_DESIRE_ACCESS_LE) {
1982 *may_flags = MAY_OPEN | MAY_READ | MAY_WRITE;
1983 } else if (access & FILE_WRITE_DESIRE_ACCESS_LE) {
1985 *may_flags = MAY_OPEN | MAY_WRITE;
1988 *may_flags = MAY_OPEN | MAY_READ;
1991 if (access == FILE_READ_ATTRIBUTES_LE)
1995 switch (disposition & FILE_CREATE_MASK_LE) {
1997 case FILE_CREATE_LE:
1999 case FILE_SUPERSEDE_LE:
2000 case FILE_OVERWRITE_LE:
2001 case FILE_OVERWRITE_IF_LE:
2008 switch (disposition & FILE_CREATE_MASK_LE) {
2009 case FILE_SUPERSEDE_LE:
2010 case FILE_CREATE_LE:
2011 case FILE_OPEN_IF_LE:
2012 case FILE_OVERWRITE_IF_LE:
2016 case FILE_OVERWRITE_LE:
2028 * smb2_tree_disconnect() - handler for smb tree connect request
2029 * @work: smb work containing request buffer
2033 int smb2_tree_disconnect(struct ksmbd_work *work)
2035 struct smb2_tree_disconnect_rsp *rsp = smb2_get_msg(work->response_buf);
2036 struct ksmbd_session *sess = work->sess;
2037 struct ksmbd_tree_connect *tcon = work->tcon;
2039 rsp->StructureSize = cpu_to_le16(4);
2040 inc_rfc1001_len(work->response_buf, 4);
2042 ksmbd_debug(SMB, "request\n");
2045 struct smb2_tree_disconnect_req *req =
2046 smb2_get_msg(work->request_buf);
2048 ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
2049 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2050 smb2_set_err_rsp(work);
2054 ksmbd_close_tree_conn_fds(work);
2055 ksmbd_tree_conn_disconnect(sess, tcon);
2060 * smb2_session_logoff() - handler for session log off request
2061 * @work: smb work containing request buffer
2065 int smb2_session_logoff(struct ksmbd_work *work)
2067 struct ksmbd_conn *conn = work->conn;
2068 struct smb2_logoff_rsp *rsp = smb2_get_msg(work->response_buf);
2069 struct ksmbd_session *sess = work->sess;
2071 rsp->StructureSize = cpu_to_le16(4);
2072 inc_rfc1001_len(work->response_buf, 4);
2074 ksmbd_debug(SMB, "request\n");
2076 /* setting CifsExiting here may race with start_tcp_sess */
2077 ksmbd_conn_set_need_reconnect(work);
2078 ksmbd_close_session_fds(work);
2079 ksmbd_conn_wait_idle(conn);
2081 if (ksmbd_tree_conn_session_logoff(sess)) {
2082 struct smb2_logoff_req *req = smb2_get_msg(work->request_buf);
2084 ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
2085 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2086 smb2_set_err_rsp(work);
2090 ksmbd_destroy_file_table(&sess->file_table);
2091 sess->state = SMB2_SESSION_EXPIRED;
2093 ksmbd_free_user(sess->user);
2096 /* let start_tcp_sess free connection info now */
2097 ksmbd_conn_set_need_negotiate(work);
2102 * create_smb2_pipe() - create IPC pipe
2103 * @work: smb work containing request buffer
2105 * Return: 0 on success, otherwise error
2107 static noinline int create_smb2_pipe(struct ksmbd_work *work)
2109 struct smb2_create_rsp *rsp = smb2_get_msg(work->response_buf);
2110 struct smb2_create_req *req = smb2_get_msg(work->request_buf);
2115 name = smb_strndup_from_utf16(req->Buffer, le16_to_cpu(req->NameLength),
2116 1, work->conn->local_nls);
2118 rsp->hdr.Status = STATUS_NO_MEMORY;
2119 err = PTR_ERR(name);
2123 id = ksmbd_session_rpc_open(work->sess, name);
2125 pr_err("Unable to open RPC pipe: %d\n", id);
2130 rsp->hdr.Status = STATUS_SUCCESS;
2131 rsp->StructureSize = cpu_to_le16(89);
2132 rsp->OplockLevel = SMB2_OPLOCK_LEVEL_NONE;
2134 rsp->CreateAction = cpu_to_le32(FILE_OPENED);
2136 rsp->CreationTime = cpu_to_le64(0);
2137 rsp->LastAccessTime = cpu_to_le64(0);
2138 rsp->ChangeTime = cpu_to_le64(0);
2139 rsp->AllocationSize = cpu_to_le64(0);
2140 rsp->EndofFile = cpu_to_le64(0);
2141 rsp->FileAttributes = FILE_ATTRIBUTE_NORMAL_LE;
2143 rsp->VolatileFileId = id;
2144 rsp->PersistentFileId = 0;
2145 rsp->CreateContextsOffset = 0;
2146 rsp->CreateContextsLength = 0;
2148 inc_rfc1001_len(work->response_buf, 88); /* StructureSize - 1*/
2155 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2159 rsp->hdr.Status = STATUS_NO_MEMORY;
2166 smb2_set_err_rsp(work);
2171 * smb2_set_ea() - handler for setting extended attributes using set
2173 * @eabuf: set info command buffer
2174 * @buf_len: set info command buffer length
2175 * @path: dentry path for get ea
2177 * Return: 0 on success, otherwise error
2179 static int smb2_set_ea(struct smb2_ea_info *eabuf, unsigned int buf_len,
2182 struct user_namespace *user_ns = mnt_user_ns(path->mnt);
2183 char *attr_name = NULL, *value;
2185 unsigned int next = 0;
2187 if (buf_len < sizeof(struct smb2_ea_info) + eabuf->EaNameLength +
2188 le16_to_cpu(eabuf->EaValueLength))
2191 attr_name = kmalloc(XATTR_NAME_MAX + 1, GFP_KERNEL);
2196 if (!eabuf->EaNameLength)
2200 "name : <%s>, name_len : %u, value_len : %u, next : %u\n",
2201 eabuf->name, eabuf->EaNameLength,
2202 le16_to_cpu(eabuf->EaValueLength),
2203 le32_to_cpu(eabuf->NextEntryOffset));
2205 if (eabuf->EaNameLength >
2206 (XATTR_NAME_MAX - XATTR_USER_PREFIX_LEN)) {
2211 memcpy(attr_name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN);
2212 memcpy(&attr_name[XATTR_USER_PREFIX_LEN], eabuf->name,
2213 eabuf->EaNameLength);
2214 attr_name[XATTR_USER_PREFIX_LEN + eabuf->EaNameLength] = '\0';
2215 value = (char *)&eabuf->name + eabuf->EaNameLength + 1;
2217 if (!eabuf->EaValueLength) {
2218 rc = ksmbd_vfs_casexattr_len(user_ns,
2221 XATTR_USER_PREFIX_LEN +
2222 eabuf->EaNameLength);
2224 /* delete the EA only when it exits */
2226 rc = ksmbd_vfs_remove_xattr(user_ns,
2232 "remove xattr failed(%d)\n",
2238 /* if the EA doesn't exist, just do nothing. */
2241 rc = ksmbd_vfs_setxattr(user_ns,
2242 path->dentry, attr_name, value,
2243 le16_to_cpu(eabuf->EaValueLength), 0);
2246 "ksmbd_vfs_setxattr is failed(%d)\n",
2253 next = le32_to_cpu(eabuf->NextEntryOffset);
2254 if (next == 0 || buf_len < next)
2257 eabuf = (struct smb2_ea_info *)((char *)eabuf + next);
2258 if (next < (u32)eabuf->EaNameLength + le16_to_cpu(eabuf->EaValueLength))
2261 } while (next != 0);
2267 static noinline int smb2_set_stream_name_xattr(struct path *path,
2268 struct ksmbd_file *fp,
2269 char *stream_name, int s_type)
2271 struct user_namespace *user_ns = mnt_user_ns(path->mnt);
2272 size_t xattr_stream_size;
2273 char *xattr_stream_name;
2276 rc = ksmbd_vfs_xattr_stream_name(stream_name,
2283 fp->stream.name = xattr_stream_name;
2284 fp->stream.size = xattr_stream_size;
2286 /* Check if there is stream prefix in xattr space */
2287 rc = ksmbd_vfs_casexattr_len(user_ns,
2294 if (fp->cdoption == FILE_OPEN_LE) {
2295 ksmbd_debug(SMB, "XATTR stream name lookup failed: %d\n", rc);
2299 rc = ksmbd_vfs_setxattr(user_ns, path->dentry,
2300 xattr_stream_name, NULL, 0, 0);
2302 pr_err("Failed to store XATTR stream name :%d\n", rc);
2306 static int smb2_remove_smb_xattrs(struct path *path)
2308 struct user_namespace *user_ns = mnt_user_ns(path->mnt);
2309 char *name, *xattr_list = NULL;
2310 ssize_t xattr_list_len;
2313 xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
2314 if (xattr_list_len < 0) {
2316 } else if (!xattr_list_len) {
2317 ksmbd_debug(SMB, "empty xattr in the file\n");
2321 for (name = xattr_list; name - xattr_list < xattr_list_len;
2322 name += strlen(name) + 1) {
2323 ksmbd_debug(SMB, "%s, len %zd\n", name, strlen(name));
2325 if (strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN) &&
2326 strncmp(&name[XATTR_USER_PREFIX_LEN], DOS_ATTRIBUTE_PREFIX,
2327 DOS_ATTRIBUTE_PREFIX_LEN) &&
2328 strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX, STREAM_PREFIX_LEN))
2331 err = ksmbd_vfs_remove_xattr(user_ns, path->dentry, name);
2333 ksmbd_debug(SMB, "remove xattr failed : %s\n", name);
2340 static int smb2_create_truncate(struct path *path)
2342 int rc = vfs_truncate(path, 0);
2345 pr_err("vfs_truncate failed, rc %d\n", rc);
2349 rc = smb2_remove_smb_xattrs(path);
2350 if (rc == -EOPNOTSUPP)
2354 "ksmbd_truncate_stream_name_xattr failed, rc %d\n",
2359 static void smb2_new_xattrs(struct ksmbd_tree_connect *tcon, struct path *path,
2360 struct ksmbd_file *fp)
2362 struct xattr_dos_attrib da = {0};
2365 if (!test_share_config_flag(tcon->share_conf,
2366 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2370 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
2371 da.itime = da.create_time = fp->create_time;
2372 da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
2373 XATTR_DOSINFO_ITIME;
2375 rc = ksmbd_vfs_set_dos_attrib_xattr(mnt_user_ns(path->mnt),
2378 ksmbd_debug(SMB, "failed to store file attribute into xattr\n");
2381 static void smb2_update_xattrs(struct ksmbd_tree_connect *tcon,
2382 struct path *path, struct ksmbd_file *fp)
2384 struct xattr_dos_attrib da;
2387 fp->f_ci->m_fattr &= ~(FILE_ATTRIBUTE_HIDDEN_LE | FILE_ATTRIBUTE_SYSTEM_LE);
2389 /* get FileAttributes from XATTR_NAME_DOS_ATTRIBUTE */
2390 if (!test_share_config_flag(tcon->share_conf,
2391 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2394 rc = ksmbd_vfs_get_dos_attrib_xattr(mnt_user_ns(path->mnt),
2397 fp->f_ci->m_fattr = cpu_to_le32(da.attr);
2398 fp->create_time = da.create_time;
2399 fp->itime = da.itime;
2403 static int smb2_creat(struct ksmbd_work *work, struct path *path, char *name,
2404 int open_flags, umode_t posix_mode, bool is_dir)
2406 struct ksmbd_tree_connect *tcon = work->tcon;
2407 struct ksmbd_share_config *share = tcon->share_conf;
2411 if (!(open_flags & O_CREAT))
2414 ksmbd_debug(SMB, "file does not exist, so creating\n");
2415 if (is_dir == true) {
2416 ksmbd_debug(SMB, "creating directory\n");
2418 mode = share_config_directory_mode(share, posix_mode);
2419 rc = ksmbd_vfs_mkdir(work, name, mode);
2423 ksmbd_debug(SMB, "creating regular file\n");
2425 mode = share_config_create_mode(share, posix_mode);
2426 rc = ksmbd_vfs_create(work, name, mode);
2431 rc = ksmbd_vfs_kern_path(work, name, 0, path, 0);
2433 pr_err("cannot get linux path (%s), err = %d\n",
2440 static int smb2_create_sd_buffer(struct ksmbd_work *work,
2441 struct smb2_create_req *req,
2444 struct create_context *context;
2445 struct create_sd_buf_req *sd_buf;
2447 if (!req->CreateContextsOffset)
2450 /* Parse SD BUFFER create contexts */
2451 context = smb2_find_context_vals(req, SMB2_CREATE_SD_BUFFER);
2454 else if (IS_ERR(context))
2455 return PTR_ERR(context);
2458 "Set ACLs using SMB2_CREATE_SD_BUFFER context\n");
2459 sd_buf = (struct create_sd_buf_req *)context;
2460 if (le16_to_cpu(context->DataOffset) +
2461 le32_to_cpu(context->DataLength) <
2462 sizeof(struct create_sd_buf_req))
2464 return set_info_sec(work->conn, work->tcon, path, &sd_buf->ntsd,
2465 le32_to_cpu(sd_buf->ccontext.DataLength), true);
2468 static void ksmbd_acls_fattr(struct smb_fattr *fattr,
2469 struct user_namespace *mnt_userns,
2470 struct inode *inode)
2472 fattr->cf_uid = i_uid_into_mnt(mnt_userns, inode);
2473 fattr->cf_gid = i_gid_into_mnt(mnt_userns, inode);
2474 fattr->cf_mode = inode->i_mode;
2475 fattr->cf_acls = NULL;
2476 fattr->cf_dacls = NULL;
2478 if (IS_ENABLED(CONFIG_FS_POSIX_ACL)) {
2479 fattr->cf_acls = get_acl(inode, ACL_TYPE_ACCESS);
2480 if (S_ISDIR(inode->i_mode))
2481 fattr->cf_dacls = get_acl(inode, ACL_TYPE_DEFAULT);
2486 * smb2_open() - handler for smb file open request
2487 * @work: smb work containing request buffer
2489 * Return: 0 on success, otherwise error
2491 int smb2_open(struct ksmbd_work *work)
2493 struct ksmbd_conn *conn = work->conn;
2494 struct ksmbd_session *sess = work->sess;
2495 struct ksmbd_tree_connect *tcon = work->tcon;
2496 struct smb2_create_req *req;
2497 struct smb2_create_rsp *rsp;
2499 struct ksmbd_share_config *share = tcon->share_conf;
2500 struct ksmbd_file *fp = NULL;
2501 struct file *filp = NULL;
2502 struct user_namespace *user_ns = NULL;
2504 struct create_context *context;
2505 struct lease_ctx_info *lc = NULL;
2506 struct create_ea_buf_req *ea_buf = NULL;
2507 struct oplock_info *opinfo;
2508 __le32 *next_ptr = NULL;
2509 int req_op_level = 0, open_flags = 0, may_flags = 0, file_info = 0;
2511 int contxt_cnt = 0, query_disk_id = 0;
2512 int maximal_access_ctxt = 0, posix_ctxt = 0;
2516 char *stream_name = NULL;
2517 bool file_present = false, created = false, already_permitted = false;
2518 int share_ret, need_truncate = 0;
2520 umode_t posix_mode = 0;
2521 __le32 daccess, maximal_access = 0;
2523 WORK_BUFFERS(work, req, rsp);
2525 if (req->hdr.NextCommand && !work->next_smb2_rcv_hdr_off &&
2526 (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
2527 ksmbd_debug(SMB, "invalid flag in chained command\n");
2528 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2529 smb2_set_err_rsp(work);
2533 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
2534 ksmbd_debug(SMB, "IPC pipe create request\n");
2535 return create_smb2_pipe(work);
2538 if (req->NameLength) {
2539 if ((req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
2540 *(char *)req->Buffer == '\\') {
2541 pr_err("not allow directory name included leading slash\n");
2546 name = smb2_get_name(req->Buffer,
2547 le16_to_cpu(req->NameLength),
2548 work->conn->local_nls);
2557 ksmbd_debug(SMB, "converted name = %s\n", name);
2558 if (strchr(name, ':')) {
2559 if (!test_share_config_flag(work->tcon->share_conf,
2560 KSMBD_SHARE_FLAG_STREAMS)) {
2564 rc = parse_stream_name(name, &stream_name, &s_type);
2569 rc = ksmbd_validate_filename(name);
2573 if (ksmbd_share_veto_filename(share, name)) {
2575 ksmbd_debug(SMB, "Reject open(), vetoed file: %s\n",
2580 name = kstrdup("", GFP_KERNEL);
2587 req_op_level = req->RequestedOplockLevel;
2588 if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE)
2589 lc = parse_lease_state(req);
2591 if (le32_to_cpu(req->ImpersonationLevel) > le32_to_cpu(IL_DELEGATE)) {
2592 pr_err("Invalid impersonationlevel : 0x%x\n",
2593 le32_to_cpu(req->ImpersonationLevel));
2595 rsp->hdr.Status = STATUS_BAD_IMPERSONATION_LEVEL;
2599 if (req->CreateOptions && !(req->CreateOptions & CREATE_OPTIONS_MASK_LE)) {
2600 pr_err("Invalid create options : 0x%x\n",
2601 le32_to_cpu(req->CreateOptions));
2605 if (req->CreateOptions & FILE_SEQUENTIAL_ONLY_LE &&
2606 req->CreateOptions & FILE_RANDOM_ACCESS_LE)
2607 req->CreateOptions = ~(FILE_SEQUENTIAL_ONLY_LE);
2609 if (req->CreateOptions &
2610 (FILE_OPEN_BY_FILE_ID_LE | CREATE_TREE_CONNECTION |
2611 FILE_RESERVE_OPFILTER_LE)) {
2616 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
2617 if (req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE) {
2620 } else if (req->CreateOptions & FILE_NO_COMPRESSION_LE) {
2621 req->CreateOptions = ~(FILE_NO_COMPRESSION_LE);
2626 if (le32_to_cpu(req->CreateDisposition) >
2627 le32_to_cpu(FILE_OVERWRITE_IF_LE)) {
2628 pr_err("Invalid create disposition : 0x%x\n",
2629 le32_to_cpu(req->CreateDisposition));
2634 if (!(req->DesiredAccess & DESIRED_ACCESS_MASK)) {
2635 pr_err("Invalid desired access : 0x%x\n",
2636 le32_to_cpu(req->DesiredAccess));
2641 if (req->FileAttributes && !(req->FileAttributes & FILE_ATTRIBUTE_MASK_LE)) {
2642 pr_err("Invalid file attribute : 0x%x\n",
2643 le32_to_cpu(req->FileAttributes));
2648 if (req->CreateContextsOffset) {
2649 /* Parse non-durable handle create contexts */
2650 context = smb2_find_context_vals(req, SMB2_CREATE_EA_BUFFER);
2651 if (IS_ERR(context)) {
2652 rc = PTR_ERR(context);
2654 } else if (context) {
2655 ea_buf = (struct create_ea_buf_req *)context;
2656 if (le16_to_cpu(context->DataOffset) +
2657 le32_to_cpu(context->DataLength) <
2658 sizeof(struct create_ea_buf_req)) {
2662 if (req->CreateOptions & FILE_NO_EA_KNOWLEDGE_LE) {
2663 rsp->hdr.Status = STATUS_ACCESS_DENIED;
2669 context = smb2_find_context_vals(req,
2670 SMB2_CREATE_QUERY_MAXIMAL_ACCESS_REQUEST);
2671 if (IS_ERR(context)) {
2672 rc = PTR_ERR(context);
2674 } else if (context) {
2676 "get query maximal access context\n");
2677 maximal_access_ctxt = 1;
2680 context = smb2_find_context_vals(req,
2681 SMB2_CREATE_TIMEWARP_REQUEST);
2682 if (IS_ERR(context)) {
2683 rc = PTR_ERR(context);
2685 } else if (context) {
2686 ksmbd_debug(SMB, "get timewarp context\n");
2691 if (tcon->posix_extensions) {
2692 context = smb2_find_context_vals(req,
2693 SMB2_CREATE_TAG_POSIX);
2694 if (IS_ERR(context)) {
2695 rc = PTR_ERR(context);
2697 } else if (context) {
2698 struct create_posix *posix =
2699 (struct create_posix *)context;
2700 if (le16_to_cpu(context->DataOffset) +
2701 le32_to_cpu(context->DataLength) <
2702 sizeof(struct create_posix) - 4) {
2706 ksmbd_debug(SMB, "get posix context\n");
2708 posix_mode = le32_to_cpu(posix->Mode);
2714 if (ksmbd_override_fsids(work)) {
2719 rc = ksmbd_vfs_kern_path(work, name, LOOKUP_NO_SYMLINKS, &path, 1);
2721 if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE) {
2723 * If file exists with under flags, return access
2726 if (req->CreateDisposition == FILE_OVERWRITE_IF_LE ||
2727 req->CreateDisposition == FILE_OPEN_IF_LE) {
2733 if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
2735 "User does not have write permission\n");
2740 } else if (d_is_symlink(path.dentry)) {
2750 ksmbd_debug(SMB, "can not get linux path for %s, rc = %d\n",
2754 file_present = true;
2755 user_ns = mnt_user_ns(path.mnt);
2756 generic_fillattr(user_ns, d_inode(path.dentry), &stat);
2759 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
2760 if (s_type == DATA_STREAM) {
2762 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2765 if (S_ISDIR(stat.mode) && s_type == DATA_STREAM) {
2767 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
2771 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE &&
2772 req->FileAttributes & FILE_ATTRIBUTE_NORMAL_LE) {
2773 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2781 if (file_present && req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE &&
2782 S_ISDIR(stat.mode) && !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2783 ksmbd_debug(SMB, "open() argument is a directory: %s, %x\n",
2784 name, req->CreateOptions);
2785 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
2790 if (file_present && (req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
2791 !(req->CreateDisposition == FILE_CREATE_LE) &&
2792 !S_ISDIR(stat.mode)) {
2793 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2798 if (!stream_name && file_present &&
2799 req->CreateDisposition == FILE_CREATE_LE) {
2804 daccess = smb_map_generic_desired_access(req->DesiredAccess);
2806 if (file_present && !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2807 rc = smb_check_perm_dacl(conn, &path, &daccess,
2813 if (daccess & FILE_MAXIMAL_ACCESS_LE) {
2814 if (!file_present) {
2815 daccess = cpu_to_le32(GENERIC_ALL_FLAGS);
2817 rc = ksmbd_vfs_query_maximal_access(user_ns,
2822 already_permitted = true;
2824 maximal_access = daccess;
2827 open_flags = smb2_create_open_flags(file_present, daccess,
2828 req->CreateDisposition,
2831 if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
2832 if (open_flags & O_CREAT) {
2834 "User does not have write permission\n");
2840 /*create file if not present */
2841 if (!file_present) {
2842 rc = smb2_creat(work, &path, name, open_flags, posix_mode,
2843 req->CreateOptions & FILE_DIRECTORY_FILE_LE);
2845 if (rc == -ENOENT) {
2847 rsp->hdr.Status = STATUS_OBJECT_PATH_NOT_FOUND;
2853 user_ns = mnt_user_ns(path.mnt);
2855 if (le32_to_cpu(ea_buf->ccontext.DataLength) <
2856 sizeof(struct smb2_ea_info)) {
2861 rc = smb2_set_ea(&ea_buf->ea,
2862 le32_to_cpu(ea_buf->ccontext.DataLength),
2864 if (rc == -EOPNOTSUPP)
2869 } else if (!already_permitted) {
2870 /* FILE_READ_ATTRIBUTE is allowed without inode_permission,
2871 * because execute(search) permission on a parent directory,
2872 * is already granted.
2874 if (daccess & ~(FILE_READ_ATTRIBUTES_LE | FILE_READ_CONTROL_LE)) {
2875 rc = inode_permission(user_ns,
2876 d_inode(path.dentry),
2881 if ((daccess & FILE_DELETE_LE) ||
2882 (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2883 rc = ksmbd_vfs_may_delete(user_ns,
2891 rc = ksmbd_query_inode_status(d_inode(path.dentry->d_parent));
2892 if (rc == KSMBD_INODE_STATUS_PENDING_DELETE) {
2898 filp = dentry_open(&path, open_flags, current_cred());
2901 pr_err("dentry open for dir failed, rc %d\n", rc);
2906 if (!(open_flags & O_TRUNC))
2907 file_info = FILE_OPENED;
2909 file_info = FILE_OVERWRITTEN;
2911 if ((req->CreateDisposition & FILE_CREATE_MASK_LE) ==
2913 file_info = FILE_SUPERSEDED;
2914 } else if (open_flags & O_CREAT) {
2915 file_info = FILE_CREATED;
2918 ksmbd_vfs_set_fadvise(filp, req->CreateOptions);
2920 /* Obtain Volatile-ID */
2921 fp = ksmbd_open_fd(work, filp);
2929 /* Get Persistent-ID */
2930 ksmbd_open_durable_fd(fp);
2931 if (!has_file_id(fp->persistent_id)) {
2936 fp->cdoption = req->CreateDisposition;
2937 fp->daccess = daccess;
2938 fp->saccess = req->ShareAccess;
2939 fp->coption = req->CreateOptions;
2941 /* Set default windows and posix acls if creating new file */
2944 struct inode *inode = d_inode(path.dentry);
2946 posix_acl_rc = ksmbd_vfs_inherit_posix_acl(user_ns,
2948 d_inode(path.dentry->d_parent));
2950 ksmbd_debug(SMB, "inherit posix acl failed : %d\n", posix_acl_rc);
2952 if (test_share_config_flag(work->tcon->share_conf,
2953 KSMBD_SHARE_FLAG_ACL_XATTR)) {
2954 rc = smb_inherit_dacl(conn, &path, sess->user->uid,
2959 rc = smb2_create_sd_buffer(work, req, &path);
2962 ksmbd_vfs_set_init_posix_acl(user_ns,
2965 if (test_share_config_flag(work->tcon->share_conf,
2966 KSMBD_SHARE_FLAG_ACL_XATTR)) {
2967 struct smb_fattr fattr;
2968 struct smb_ntsd *pntsd;
2969 int pntsd_size, ace_num = 0;
2971 ksmbd_acls_fattr(&fattr, user_ns, inode);
2973 ace_num = fattr.cf_acls->a_count;
2975 ace_num += fattr.cf_dacls->a_count;
2977 pntsd = kmalloc(sizeof(struct smb_ntsd) +
2978 sizeof(struct smb_sid) * 3 +
2979 sizeof(struct smb_acl) +
2980 sizeof(struct smb_ace) * ace_num * 2,
2985 rc = build_sec_desc(user_ns,
2990 &pntsd_size, &fattr);
2991 posix_acl_release(fattr.cf_acls);
2992 posix_acl_release(fattr.cf_dacls);
2998 rc = ksmbd_vfs_set_sd_xattr(conn,
3005 pr_err("failed to store ntacl in xattr : %d\n",
3014 rc = smb2_set_stream_name_xattr(&path,
3020 file_info = FILE_CREATED;
3023 fp->attrib_only = !(req->DesiredAccess & ~(FILE_READ_ATTRIBUTES_LE |
3024 FILE_WRITE_ATTRIBUTES_LE | FILE_SYNCHRONIZE_LE));
3025 if (!S_ISDIR(file_inode(filp)->i_mode) && open_flags & O_TRUNC &&
3026 !fp->attrib_only && !stream_name) {
3027 smb_break_all_oplock(work, fp);
3031 /* fp should be searchable through ksmbd_inode.m_fp_list
3032 * after daccess, saccess, attrib_only, and stream are
3035 write_lock(&fp->f_ci->m_lock);
3036 list_add(&fp->node, &fp->f_ci->m_fp_list);
3037 write_unlock(&fp->f_ci->m_lock);
3039 rc = ksmbd_vfs_getattr(&path, &stat);
3041 generic_fillattr(user_ns, d_inode(path.dentry), &stat);
3045 /* Check delete pending among previous fp before oplock break */
3046 if (ksmbd_inode_pending_delete(fp)) {
3051 share_ret = ksmbd_smb_check_shared_mode(fp->filp, fp);
3052 if (!test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_OPLOCKS) ||
3053 (req_op_level == SMB2_OPLOCK_LEVEL_LEASE &&
3054 !(conn->vals->capabilities & SMB2_GLOBAL_CAP_LEASING))) {
3055 if (share_ret < 0 && !S_ISDIR(file_inode(fp->filp)->i_mode)) {
3060 if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE) {
3061 req_op_level = smb2_map_lease_to_oplock(lc->req_state);
3063 "lease req for(%s) req oplock state 0x%x, lease state 0x%x\n",
3064 name, req_op_level, lc->req_state);
3065 rc = find_same_lease_key(sess, fp->f_ci, lc);
3068 } else if (open_flags == O_RDONLY &&
3069 (req_op_level == SMB2_OPLOCK_LEVEL_BATCH ||
3070 req_op_level == SMB2_OPLOCK_LEVEL_EXCLUSIVE))
3071 req_op_level = SMB2_OPLOCK_LEVEL_II;
3073 rc = smb_grant_oplock(work, req_op_level,
3074 fp->persistent_id, fp,
3075 le32_to_cpu(req->hdr.Id.SyncId.TreeId),
3081 if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)
3082 ksmbd_fd_set_delete_on_close(fp, file_info);
3084 if (need_truncate) {
3085 rc = smb2_create_truncate(&path);
3090 if (req->CreateContextsOffset) {
3091 struct create_alloc_size_req *az_req;
3093 az_req = (struct create_alloc_size_req *)smb2_find_context_vals(req,
3094 SMB2_CREATE_ALLOCATION_SIZE);
3095 if (IS_ERR(az_req)) {
3096 rc = PTR_ERR(az_req);
3098 } else if (az_req) {
3102 if (le16_to_cpu(az_req->ccontext.DataOffset) +
3103 le32_to_cpu(az_req->ccontext.DataLength) <
3104 sizeof(struct create_alloc_size_req)) {
3108 alloc_size = le64_to_cpu(az_req->AllocationSize);
3110 "request smb2 create allocate size : %llu\n",
3112 smb_break_all_levII_oplock(work, fp, 1);
3113 err = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
3117 "vfs_fallocate is failed : %d\n",
3121 context = smb2_find_context_vals(req, SMB2_CREATE_QUERY_ON_DISK_ID);
3122 if (IS_ERR(context)) {
3123 rc = PTR_ERR(context);
3125 } else if (context) {
3126 ksmbd_debug(SMB, "get query on disk id context\n");
3131 if (stat.result_mask & STATX_BTIME)
3132 fp->create_time = ksmbd_UnixTimeToNT(stat.btime);
3134 fp->create_time = ksmbd_UnixTimeToNT(stat.ctime);
3135 if (req->FileAttributes || fp->f_ci->m_fattr == 0)
3137 cpu_to_le32(smb2_get_dos_mode(&stat, le32_to_cpu(req->FileAttributes)));
3140 smb2_update_xattrs(tcon, &path, fp);
3142 smb2_new_xattrs(tcon, &path, fp);
3144 memcpy(fp->client_guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE);
3146 generic_fillattr(user_ns, file_inode(fp->filp),
3149 rsp->StructureSize = cpu_to_le16(89);
3151 opinfo = rcu_dereference(fp->f_opinfo);
3152 rsp->OplockLevel = opinfo != NULL ? opinfo->level : 0;
3155 rsp->CreateAction = cpu_to_le32(file_info);
3156 rsp->CreationTime = cpu_to_le64(fp->create_time);
3157 time = ksmbd_UnixTimeToNT(stat.atime);
3158 rsp->LastAccessTime = cpu_to_le64(time);
3159 time = ksmbd_UnixTimeToNT(stat.mtime);
3160 rsp->LastWriteTime = cpu_to_le64(time);
3161 time = ksmbd_UnixTimeToNT(stat.ctime);
3162 rsp->ChangeTime = cpu_to_le64(time);
3163 rsp->AllocationSize = S_ISDIR(stat.mode) ? 0 :
3164 cpu_to_le64(stat.blocks << 9);
3165 rsp->EndofFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
3166 rsp->FileAttributes = fp->f_ci->m_fattr;
3170 rsp->PersistentFileId = fp->persistent_id;
3171 rsp->VolatileFileId = fp->volatile_id;
3173 rsp->CreateContextsOffset = 0;
3174 rsp->CreateContextsLength = 0;
3175 inc_rfc1001_len(work->response_buf, 88); /* StructureSize - 1*/
3177 /* If lease is request send lease context response */
3178 if (opinfo && opinfo->is_lease) {
3179 struct create_context *lease_ccontext;
3181 ksmbd_debug(SMB, "lease granted on(%s) lease state 0x%x\n",
3182 name, opinfo->o_lease->state);
3183 rsp->OplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
3185 lease_ccontext = (struct create_context *)rsp->Buffer;
3187 create_lease_buf(rsp->Buffer, opinfo->o_lease);
3188 le32_add_cpu(&rsp->CreateContextsLength,
3189 conn->vals->create_lease_size);
3190 inc_rfc1001_len(work->response_buf,
3191 conn->vals->create_lease_size);
3192 next_ptr = &lease_ccontext->Next;
3193 next_off = conn->vals->create_lease_size;
3196 if (maximal_access_ctxt) {
3197 struct create_context *mxac_ccontext;
3199 if (maximal_access == 0)
3200 ksmbd_vfs_query_maximal_access(user_ns,
3203 mxac_ccontext = (struct create_context *)(rsp->Buffer +
3204 le32_to_cpu(rsp->CreateContextsLength));
3206 create_mxac_rsp_buf(rsp->Buffer +
3207 le32_to_cpu(rsp->CreateContextsLength),
3208 le32_to_cpu(maximal_access));
3209 le32_add_cpu(&rsp->CreateContextsLength,
3210 conn->vals->create_mxac_size);
3211 inc_rfc1001_len(work->response_buf,
3212 conn->vals->create_mxac_size);
3214 *next_ptr = cpu_to_le32(next_off);
3215 next_ptr = &mxac_ccontext->Next;
3216 next_off = conn->vals->create_mxac_size;
3219 if (query_disk_id) {
3220 struct create_context *disk_id_ccontext;
3222 disk_id_ccontext = (struct create_context *)(rsp->Buffer +
3223 le32_to_cpu(rsp->CreateContextsLength));
3225 create_disk_id_rsp_buf(rsp->Buffer +
3226 le32_to_cpu(rsp->CreateContextsLength),
3227 stat.ino, tcon->id);
3228 le32_add_cpu(&rsp->CreateContextsLength,
3229 conn->vals->create_disk_id_size);
3230 inc_rfc1001_len(work->response_buf,
3231 conn->vals->create_disk_id_size);
3233 *next_ptr = cpu_to_le32(next_off);
3234 next_ptr = &disk_id_ccontext->Next;
3235 next_off = conn->vals->create_disk_id_size;
3240 create_posix_rsp_buf(rsp->Buffer +
3241 le32_to_cpu(rsp->CreateContextsLength),
3243 le32_add_cpu(&rsp->CreateContextsLength,
3244 conn->vals->create_posix_size);
3245 inc_rfc1001_len(work->response_buf,
3246 conn->vals->create_posix_size);
3248 *next_ptr = cpu_to_le32(next_off);
3251 if (contxt_cnt > 0) {
3252 rsp->CreateContextsOffset =
3253 cpu_to_le32(offsetof(struct smb2_create_rsp, Buffer));
3257 if (file_present || created)
3259 ksmbd_revert_fsids(work);
3263 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
3264 else if (rc == -EOPNOTSUPP)
3265 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
3266 else if (rc == -EACCES || rc == -ESTALE || rc == -EXDEV)
3267 rsp->hdr.Status = STATUS_ACCESS_DENIED;
3268 else if (rc == -ENOENT)
3269 rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
3270 else if (rc == -EPERM)
3271 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
3272 else if (rc == -EBUSY)
3273 rsp->hdr.Status = STATUS_DELETE_PENDING;
3274 else if (rc == -EBADF)
3275 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
3276 else if (rc == -ENOEXEC)
3277 rsp->hdr.Status = STATUS_DUPLICATE_OBJECTID;
3278 else if (rc == -ENXIO)
3279 rsp->hdr.Status = STATUS_NO_SUCH_DEVICE;
3280 else if (rc == -EEXIST)
3281 rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
3282 else if (rc == -EMFILE)
3283 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
3284 if (!rsp->hdr.Status)
3285 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
3288 ksmbd_fd_put(work, fp);
3289 smb2_set_err_rsp(work);
3290 ksmbd_debug(SMB, "Error response: %x\n", rsp->hdr.Status);
3299 static int readdir_info_level_struct_sz(int info_level)
3301 switch (info_level) {
3302 case FILE_FULL_DIRECTORY_INFORMATION:
3303 return sizeof(struct file_full_directory_info);
3304 case FILE_BOTH_DIRECTORY_INFORMATION:
3305 return sizeof(struct file_both_directory_info);
3306 case FILE_DIRECTORY_INFORMATION:
3307 return sizeof(struct file_directory_info);
3308 case FILE_NAMES_INFORMATION:
3309 return sizeof(struct file_names_info);
3310 case FILEID_FULL_DIRECTORY_INFORMATION:
3311 return sizeof(struct file_id_full_dir_info);
3312 case FILEID_BOTH_DIRECTORY_INFORMATION:
3313 return sizeof(struct file_id_both_directory_info);
3314 case SMB_FIND_FILE_POSIX_INFO:
3315 return sizeof(struct smb2_posix_info);
3321 static int dentry_name(struct ksmbd_dir_info *d_info, int info_level)
3323 switch (info_level) {
3324 case FILE_FULL_DIRECTORY_INFORMATION:
3326 struct file_full_directory_info *ffdinfo;
3328 ffdinfo = (struct file_full_directory_info *)d_info->rptr;
3329 d_info->rptr += le32_to_cpu(ffdinfo->NextEntryOffset);
3330 d_info->name = ffdinfo->FileName;
3331 d_info->name_len = le32_to_cpu(ffdinfo->FileNameLength);
3334 case FILE_BOTH_DIRECTORY_INFORMATION:
3336 struct file_both_directory_info *fbdinfo;
3338 fbdinfo = (struct file_both_directory_info *)d_info->rptr;
3339 d_info->rptr += le32_to_cpu(fbdinfo->NextEntryOffset);
3340 d_info->name = fbdinfo->FileName;
3341 d_info->name_len = le32_to_cpu(fbdinfo->FileNameLength);
3344 case FILE_DIRECTORY_INFORMATION:
3346 struct file_directory_info *fdinfo;
3348 fdinfo = (struct file_directory_info *)d_info->rptr;
3349 d_info->rptr += le32_to_cpu(fdinfo->NextEntryOffset);
3350 d_info->name = fdinfo->FileName;
3351 d_info->name_len = le32_to_cpu(fdinfo->FileNameLength);
3354 case FILE_NAMES_INFORMATION:
3356 struct file_names_info *fninfo;
3358 fninfo = (struct file_names_info *)d_info->rptr;
3359 d_info->rptr += le32_to_cpu(fninfo->NextEntryOffset);
3360 d_info->name = fninfo->FileName;
3361 d_info->name_len = le32_to_cpu(fninfo->FileNameLength);
3364 case FILEID_FULL_DIRECTORY_INFORMATION:
3366 struct file_id_full_dir_info *dinfo;
3368 dinfo = (struct file_id_full_dir_info *)d_info->rptr;
3369 d_info->rptr += le32_to_cpu(dinfo->NextEntryOffset);
3370 d_info->name = dinfo->FileName;
3371 d_info->name_len = le32_to_cpu(dinfo->FileNameLength);
3374 case FILEID_BOTH_DIRECTORY_INFORMATION:
3376 struct file_id_both_directory_info *fibdinfo;
3378 fibdinfo = (struct file_id_both_directory_info *)d_info->rptr;
3379 d_info->rptr += le32_to_cpu(fibdinfo->NextEntryOffset);
3380 d_info->name = fibdinfo->FileName;
3381 d_info->name_len = le32_to_cpu(fibdinfo->FileNameLength);
3384 case SMB_FIND_FILE_POSIX_INFO:
3386 struct smb2_posix_info *posix_info;
3388 posix_info = (struct smb2_posix_info *)d_info->rptr;
3389 d_info->rptr += le32_to_cpu(posix_info->NextEntryOffset);
3390 d_info->name = posix_info->name;
3391 d_info->name_len = le32_to_cpu(posix_info->name_len);
3400 * smb2_populate_readdir_entry() - encode directory entry in smb2 response
3402 * @conn: connection instance
3403 * @info_level: smb information level
3404 * @d_info: structure included variables for query dir
3405 * @ksmbd_kstat: ksmbd wrapper of dirent stat information
3407 * if directory has many entries, find first can't read it fully.
3408 * find next might be called multiple times to read remaining dir entries
3410 * Return: 0 on success, otherwise error
3412 static int smb2_populate_readdir_entry(struct ksmbd_conn *conn, int info_level,
3413 struct ksmbd_dir_info *d_info,
3414 struct ksmbd_kstat *ksmbd_kstat)
3416 int next_entry_offset = 0;
3420 int struct_sz, rc = 0;
3422 conv_name = ksmbd_convert_dir_info_name(d_info,
3428 /* Somehow the name has only terminating NULL bytes */
3431 goto free_conv_name;
3434 struct_sz = readdir_info_level_struct_sz(info_level) - 1 + conv_len;
3435 next_entry_offset = ALIGN(struct_sz, KSMBD_DIR_INFO_ALIGNMENT);
3436 d_info->last_entry_off_align = next_entry_offset - struct_sz;
3438 if (next_entry_offset > d_info->out_buf_len) {
3439 d_info->out_buf_len = 0;
3441 goto free_conv_name;
3444 kstat = d_info->wptr;
3445 if (info_level != FILE_NAMES_INFORMATION)
3446 kstat = ksmbd_vfs_init_kstat(&d_info->wptr, ksmbd_kstat);
3448 switch (info_level) {
3449 case FILE_FULL_DIRECTORY_INFORMATION:
3451 struct file_full_directory_info *ffdinfo;
3453 ffdinfo = (struct file_full_directory_info *)kstat;
3454 ffdinfo->FileNameLength = cpu_to_le32(conv_len);
3456 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3457 if (ffdinfo->EaSize)
3458 ffdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3459 if (d_info->hide_dot_file && d_info->name[0] == '.')
3460 ffdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3461 memcpy(ffdinfo->FileName, conv_name, conv_len);
3462 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3465 case FILE_BOTH_DIRECTORY_INFORMATION:
3467 struct file_both_directory_info *fbdinfo;
3469 fbdinfo = (struct file_both_directory_info *)kstat;
3470 fbdinfo->FileNameLength = cpu_to_le32(conv_len);
3472 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3473 if (fbdinfo->EaSize)
3474 fbdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3475 fbdinfo->ShortNameLength = 0;
3476 fbdinfo->Reserved = 0;
3477 if (d_info->hide_dot_file && d_info->name[0] == '.')
3478 fbdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3479 memcpy(fbdinfo->FileName, conv_name, conv_len);
3480 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3483 case FILE_DIRECTORY_INFORMATION:
3485 struct file_directory_info *fdinfo;
3487 fdinfo = (struct file_directory_info *)kstat;
3488 fdinfo->FileNameLength = cpu_to_le32(conv_len);
3489 if (d_info->hide_dot_file && d_info->name[0] == '.')
3490 fdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3491 memcpy(fdinfo->FileName, conv_name, conv_len);
3492 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3495 case FILE_NAMES_INFORMATION:
3497 struct file_names_info *fninfo;
3499 fninfo = (struct file_names_info *)kstat;
3500 fninfo->FileNameLength = cpu_to_le32(conv_len);
3501 memcpy(fninfo->FileName, conv_name, conv_len);
3502 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3505 case FILEID_FULL_DIRECTORY_INFORMATION:
3507 struct file_id_full_dir_info *dinfo;
3509 dinfo = (struct file_id_full_dir_info *)kstat;
3510 dinfo->FileNameLength = cpu_to_le32(conv_len);
3512 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3514 dinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3515 dinfo->Reserved = 0;
3516 dinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
3517 if (d_info->hide_dot_file && d_info->name[0] == '.')
3518 dinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3519 memcpy(dinfo->FileName, conv_name, conv_len);
3520 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3523 case FILEID_BOTH_DIRECTORY_INFORMATION:
3525 struct file_id_both_directory_info *fibdinfo;
3527 fibdinfo = (struct file_id_both_directory_info *)kstat;
3528 fibdinfo->FileNameLength = cpu_to_le32(conv_len);
3530 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3531 if (fibdinfo->EaSize)
3532 fibdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3533 fibdinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
3534 fibdinfo->ShortNameLength = 0;
3535 fibdinfo->Reserved = 0;
3536 fibdinfo->Reserved2 = cpu_to_le16(0);
3537 if (d_info->hide_dot_file && d_info->name[0] == '.')
3538 fibdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3539 memcpy(fibdinfo->FileName, conv_name, conv_len);
3540 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3543 case SMB_FIND_FILE_POSIX_INFO:
3545 struct smb2_posix_info *posix_info;
3548 posix_info = (struct smb2_posix_info *)kstat;
3549 posix_info->Ignored = 0;
3550 posix_info->CreationTime = cpu_to_le64(ksmbd_kstat->create_time);
3551 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->ctime);
3552 posix_info->ChangeTime = cpu_to_le64(time);
3553 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->atime);
3554 posix_info->LastAccessTime = cpu_to_le64(time);
3555 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->mtime);
3556 posix_info->LastWriteTime = cpu_to_le64(time);
3557 posix_info->EndOfFile = cpu_to_le64(ksmbd_kstat->kstat->size);
3558 posix_info->AllocationSize = cpu_to_le64(ksmbd_kstat->kstat->blocks << 9);
3559 posix_info->DeviceId = cpu_to_le32(ksmbd_kstat->kstat->rdev);
3560 posix_info->HardLinks = cpu_to_le32(ksmbd_kstat->kstat->nlink);
3561 posix_info->Mode = cpu_to_le32(ksmbd_kstat->kstat->mode);
3562 posix_info->Inode = cpu_to_le64(ksmbd_kstat->kstat->ino);
3563 posix_info->DosAttributes =
3564 S_ISDIR(ksmbd_kstat->kstat->mode) ?
3565 FILE_ATTRIBUTE_DIRECTORY_LE : FILE_ATTRIBUTE_ARCHIVE_LE;
3566 if (d_info->hide_dot_file && d_info->name[0] == '.')
3567 posix_info->DosAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3568 id_to_sid(from_kuid_munged(&init_user_ns, ksmbd_kstat->kstat->uid),
3569 SIDNFS_USER, (struct smb_sid *)&posix_info->SidBuffer[0]);
3570 id_to_sid(from_kgid_munged(&init_user_ns, ksmbd_kstat->kstat->gid),
3571 SIDNFS_GROUP, (struct smb_sid *)&posix_info->SidBuffer[20]);
3572 memcpy(posix_info->name, conv_name, conv_len);
3573 posix_info->name_len = cpu_to_le32(conv_len);
3574 posix_info->NextEntryOffset = cpu_to_le32(next_entry_offset);
3578 } /* switch (info_level) */
3580 d_info->last_entry_offset = d_info->data_count;
3581 d_info->data_count += next_entry_offset;
3582 d_info->out_buf_len -= next_entry_offset;
3583 d_info->wptr += next_entry_offset;
3586 "info_level : %d, buf_len :%d, next_offset : %d, data_count : %d\n",
3587 info_level, d_info->out_buf_len,
3588 next_entry_offset, d_info->data_count);
3595 struct smb2_query_dir_private {
3596 struct ksmbd_work *work;
3597 char *search_pattern;
3598 struct ksmbd_file *dir_fp;
3600 struct ksmbd_dir_info *d_info;
3604 static void lock_dir(struct ksmbd_file *dir_fp)
3606 struct dentry *dir = dir_fp->filp->f_path.dentry;
3608 inode_lock_nested(d_inode(dir), I_MUTEX_PARENT);
3611 static void unlock_dir(struct ksmbd_file *dir_fp)
3613 struct dentry *dir = dir_fp->filp->f_path.dentry;
3615 inode_unlock(d_inode(dir));
3618 static int process_query_dir_entries(struct smb2_query_dir_private *priv)
3620 struct user_namespace *user_ns = file_mnt_user_ns(priv->dir_fp->filp);
3622 struct ksmbd_kstat ksmbd_kstat;
3626 for (i = 0; i < priv->d_info->num_entry; i++) {
3627 struct dentry *dent;
3629 if (dentry_name(priv->d_info, priv->info_level))
3632 lock_dir(priv->dir_fp);
3633 dent = lookup_one(user_ns, priv->d_info->name,
3634 priv->dir_fp->filp->f_path.dentry,
3635 priv->d_info->name_len);
3636 unlock_dir(priv->dir_fp);
3639 ksmbd_debug(SMB, "Cannot lookup `%s' [%ld]\n",
3644 if (unlikely(d_is_negative(dent))) {
3646 ksmbd_debug(SMB, "Negative dentry `%s'\n",
3647 priv->d_info->name);
3651 ksmbd_kstat.kstat = &kstat;
3652 if (priv->info_level != FILE_NAMES_INFORMATION)
3653 ksmbd_vfs_fill_dentry_attrs(priv->work,
3658 rc = smb2_populate_readdir_entry(priv->work->conn,
3669 static int reserve_populate_dentry(struct ksmbd_dir_info *d_info,
3674 int next_entry_offset;
3676 struct_sz = readdir_info_level_struct_sz(info_level);
3677 if (struct_sz == -EOPNOTSUPP)
3680 conv_len = (d_info->name_len + 1) * 2;
3681 next_entry_offset = ALIGN(struct_sz - 1 + conv_len,
3682 KSMBD_DIR_INFO_ALIGNMENT);
3684 if (next_entry_offset > d_info->out_buf_len) {
3685 d_info->out_buf_len = 0;
3689 switch (info_level) {
3690 case FILE_FULL_DIRECTORY_INFORMATION:
3692 struct file_full_directory_info *ffdinfo;
3694 ffdinfo = (struct file_full_directory_info *)d_info->wptr;
3695 memcpy(ffdinfo->FileName, d_info->name, d_info->name_len);
3696 ffdinfo->FileName[d_info->name_len] = 0x00;
3697 ffdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3698 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3701 case FILE_BOTH_DIRECTORY_INFORMATION:
3703 struct file_both_directory_info *fbdinfo;
3705 fbdinfo = (struct file_both_directory_info *)d_info->wptr;
3706 memcpy(fbdinfo->FileName, d_info->name, d_info->name_len);
3707 fbdinfo->FileName[d_info->name_len] = 0x00;
3708 fbdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3709 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3712 case FILE_DIRECTORY_INFORMATION:
3714 struct file_directory_info *fdinfo;
3716 fdinfo = (struct file_directory_info *)d_info->wptr;
3717 memcpy(fdinfo->FileName, d_info->name, d_info->name_len);
3718 fdinfo->FileName[d_info->name_len] = 0x00;
3719 fdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3720 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3723 case FILE_NAMES_INFORMATION:
3725 struct file_names_info *fninfo;
3727 fninfo = (struct file_names_info *)d_info->wptr;
3728 memcpy(fninfo->FileName, d_info->name, d_info->name_len);
3729 fninfo->FileName[d_info->name_len] = 0x00;
3730 fninfo->FileNameLength = cpu_to_le32(d_info->name_len);
3731 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3734 case FILEID_FULL_DIRECTORY_INFORMATION:
3736 struct file_id_full_dir_info *dinfo;
3738 dinfo = (struct file_id_full_dir_info *)d_info->wptr;
3739 memcpy(dinfo->FileName, d_info->name, d_info->name_len);
3740 dinfo->FileName[d_info->name_len] = 0x00;
3741 dinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3742 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3745 case FILEID_BOTH_DIRECTORY_INFORMATION:
3747 struct file_id_both_directory_info *fibdinfo;
3749 fibdinfo = (struct file_id_both_directory_info *)d_info->wptr;
3750 memcpy(fibdinfo->FileName, d_info->name, d_info->name_len);
3751 fibdinfo->FileName[d_info->name_len] = 0x00;
3752 fibdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3753 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3756 case SMB_FIND_FILE_POSIX_INFO:
3758 struct smb2_posix_info *posix_info;
3760 posix_info = (struct smb2_posix_info *)d_info->wptr;
3761 memcpy(posix_info->name, d_info->name, d_info->name_len);
3762 posix_info->name[d_info->name_len] = 0x00;
3763 posix_info->name_len = cpu_to_le32(d_info->name_len);
3764 posix_info->NextEntryOffset =
3765 cpu_to_le32(next_entry_offset);
3768 } /* switch (info_level) */
3770 d_info->num_entry++;
3771 d_info->out_buf_len -= next_entry_offset;
3772 d_info->wptr += next_entry_offset;
3776 static int __query_dir(struct dir_context *ctx, const char *name, int namlen,
3777 loff_t offset, u64 ino, unsigned int d_type)
3779 struct ksmbd_readdir_data *buf;
3780 struct smb2_query_dir_private *priv;
3781 struct ksmbd_dir_info *d_info;
3784 buf = container_of(ctx, struct ksmbd_readdir_data, ctx);
3785 priv = buf->private;
3786 d_info = priv->d_info;
3788 /* dot and dotdot entries are already reserved */
3789 if (!strcmp(".", name) || !strcmp("..", name))
3791 if (ksmbd_share_veto_filename(priv->work->tcon->share_conf, name))
3793 if (!match_pattern(name, namlen, priv->search_pattern))
3796 d_info->name = name;
3797 d_info->name_len = namlen;
3798 rc = reserve_populate_dentry(d_info, priv->info_level);
3801 if (d_info->flags & SMB2_RETURN_SINGLE_ENTRY) {
3802 d_info->out_buf_len = 0;
3808 static void restart_ctx(struct dir_context *ctx)
3813 static int verify_info_level(int info_level)
3815 switch (info_level) {
3816 case FILE_FULL_DIRECTORY_INFORMATION:
3817 case FILE_BOTH_DIRECTORY_INFORMATION:
3818 case FILE_DIRECTORY_INFORMATION:
3819 case FILE_NAMES_INFORMATION:
3820 case FILEID_FULL_DIRECTORY_INFORMATION:
3821 case FILEID_BOTH_DIRECTORY_INFORMATION:
3822 case SMB_FIND_FILE_POSIX_INFO:
3831 static int smb2_calc_max_out_buf_len(struct ksmbd_work *work,
3832 unsigned short hdr2_len,
3833 unsigned int out_buf_len)
3837 if (out_buf_len > work->conn->vals->max_trans_size)
3840 free_len = (int)(work->response_sz -
3841 (get_rfc1002_len(work->response_buf) + 4)) -
3846 return min_t(int, out_buf_len, free_len);
3849 int smb2_query_dir(struct ksmbd_work *work)
3851 struct ksmbd_conn *conn = work->conn;
3852 struct smb2_query_directory_req *req;
3853 struct smb2_query_directory_rsp *rsp;
3854 struct ksmbd_share_config *share = work->tcon->share_conf;
3855 struct ksmbd_file *dir_fp = NULL;
3856 struct ksmbd_dir_info d_info;
3858 char *srch_ptr = NULL;
3859 unsigned char srch_flag;
3861 struct smb2_query_dir_private query_dir_private = {NULL, };
3863 WORK_BUFFERS(work, req, rsp);
3865 if (ksmbd_override_fsids(work)) {
3866 rsp->hdr.Status = STATUS_NO_MEMORY;
3867 smb2_set_err_rsp(work);
3871 rc = verify_info_level(req->FileInformationClass);
3877 dir_fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
3883 if (!(dir_fp->daccess & FILE_LIST_DIRECTORY_LE) ||
3884 inode_permission(file_mnt_user_ns(dir_fp->filp),
3885 file_inode(dir_fp->filp),
3886 MAY_READ | MAY_EXEC)) {
3887 pr_err("no right to enumerate directory (%pd)\n",
3888 dir_fp->filp->f_path.dentry);
3893 if (!S_ISDIR(file_inode(dir_fp->filp)->i_mode)) {
3894 pr_err("can't do query dir for a file\n");
3899 srch_flag = req->Flags;
3900 srch_ptr = smb_strndup_from_utf16(req->Buffer,
3901 le16_to_cpu(req->FileNameLength), 1,
3903 if (IS_ERR(srch_ptr)) {
3904 ksmbd_debug(SMB, "Search Pattern not found\n");
3908 ksmbd_debug(SMB, "Search pattern is %s\n", srch_ptr);
3911 if (srch_flag & SMB2_REOPEN || srch_flag & SMB2_RESTART_SCANS) {
3912 ksmbd_debug(SMB, "Restart directory scan\n");
3913 generic_file_llseek(dir_fp->filp, 0, SEEK_SET);
3914 restart_ctx(&dir_fp->readdir_data.ctx);
3917 memset(&d_info, 0, sizeof(struct ksmbd_dir_info));
3918 d_info.wptr = (char *)rsp->Buffer;
3919 d_info.rptr = (char *)rsp->Buffer;
3920 d_info.out_buf_len =
3921 smb2_calc_max_out_buf_len(work, 8,
3922 le32_to_cpu(req->OutputBufferLength));
3923 if (d_info.out_buf_len < 0) {
3927 d_info.flags = srch_flag;
3930 * reserve dot and dotdot entries in head of buffer
3933 rc = ksmbd_populate_dot_dotdot_entries(work, req->FileInformationClass,
3934 dir_fp, &d_info, srch_ptr,
3935 smb2_populate_readdir_entry);
3941 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_HIDE_DOT_FILES))
3942 d_info.hide_dot_file = true;
3944 buffer_sz = d_info.out_buf_len;
3945 d_info.rptr = d_info.wptr;
3946 query_dir_private.work = work;
3947 query_dir_private.search_pattern = srch_ptr;
3948 query_dir_private.dir_fp = dir_fp;
3949 query_dir_private.d_info = &d_info;
3950 query_dir_private.info_level = req->FileInformationClass;
3951 dir_fp->readdir_data.private = &query_dir_private;
3952 set_ctx_actor(&dir_fp->readdir_data.ctx, __query_dir);
3954 rc = iterate_dir(dir_fp->filp, &dir_fp->readdir_data.ctx);
3956 * req->OutputBufferLength is too small to contain even one entry.
3957 * In this case, it immediately returns OutputBufferLength 0 to client.
3959 if (!d_info.out_buf_len && !d_info.num_entry)
3962 restart_ctx(&dir_fp->readdir_data.ctx);
3968 d_info.wptr = d_info.rptr;
3969 d_info.out_buf_len = buffer_sz;
3970 rc = process_query_dir_entries(&query_dir_private);
3974 if (!d_info.data_count && d_info.out_buf_len >= 0) {
3975 if (srch_flag & SMB2_RETURN_SINGLE_ENTRY && !is_asterisk(srch_ptr)) {
3976 rsp->hdr.Status = STATUS_NO_SUCH_FILE;
3978 dir_fp->dot_dotdot[0] = dir_fp->dot_dotdot[1] = 0;
3979 rsp->hdr.Status = STATUS_NO_MORE_FILES;
3981 rsp->StructureSize = cpu_to_le16(9);
3982 rsp->OutputBufferOffset = cpu_to_le16(0);
3983 rsp->OutputBufferLength = cpu_to_le32(0);
3985 inc_rfc1001_len(work->response_buf, 9);
3988 ((struct file_directory_info *)
3989 ((char *)rsp->Buffer + d_info.last_entry_offset))
3990 ->NextEntryOffset = 0;
3991 if (d_info.data_count >= d_info.last_entry_off_align)
3992 d_info.data_count -= d_info.last_entry_off_align;
3994 rsp->StructureSize = cpu_to_le16(9);
3995 rsp->OutputBufferOffset = cpu_to_le16(72);
3996 rsp->OutputBufferLength = cpu_to_le32(d_info.data_count);
3997 inc_rfc1001_len(work->response_buf, 8 + d_info.data_count);
4001 ksmbd_fd_put(work, dir_fp);
4002 ksmbd_revert_fsids(work);
4006 pr_err("error while processing smb2 query dir rc = %d\n", rc);
4011 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
4012 else if (rc == -EACCES)
4013 rsp->hdr.Status = STATUS_ACCESS_DENIED;
4014 else if (rc == -ENOENT)
4015 rsp->hdr.Status = STATUS_NO_SUCH_FILE;
4016 else if (rc == -EBADF)
4017 rsp->hdr.Status = STATUS_FILE_CLOSED;
4018 else if (rc == -ENOMEM)
4019 rsp->hdr.Status = STATUS_NO_MEMORY;
4020 else if (rc == -EFAULT)
4021 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
4022 if (!rsp->hdr.Status)
4023 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
4025 smb2_set_err_rsp(work);
4026 ksmbd_fd_put(work, dir_fp);
4027 ksmbd_revert_fsids(work);
4032 * buffer_check_err() - helper function to check buffer errors
4033 * @reqOutputBufferLength: max buffer length expected in command response
4034 * @rsp: query info response buffer contains output buffer length
4035 * @rsp_org: base response buffer pointer in case of chained response
4036 * @infoclass_size: query info class response buffer size
4038 * Return: 0 on success, otherwise error
4040 static int buffer_check_err(int reqOutputBufferLength,
4041 struct smb2_query_info_rsp *rsp,
4042 void *rsp_org, int infoclass_size)
4044 if (reqOutputBufferLength < le32_to_cpu(rsp->OutputBufferLength)) {
4045 if (reqOutputBufferLength < infoclass_size) {
4046 pr_err("Invalid Buffer Size Requested\n");
4047 rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
4048 *(__be32 *)rsp_org = cpu_to_be32(sizeof(struct smb2_hdr));
4052 ksmbd_debug(SMB, "Buffer Overflow\n");
4053 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
4054 *(__be32 *)rsp_org = cpu_to_be32(sizeof(struct smb2_hdr) +
4055 reqOutputBufferLength);
4056 rsp->OutputBufferLength = cpu_to_le32(reqOutputBufferLength);
4061 static void get_standard_info_pipe(struct smb2_query_info_rsp *rsp,
4064 struct smb2_file_standard_info *sinfo;
4066 sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
4068 sinfo->AllocationSize = cpu_to_le64(4096);
4069 sinfo->EndOfFile = cpu_to_le64(0);
4070 sinfo->NumberOfLinks = cpu_to_le32(1);
4071 sinfo->DeletePending = 1;
4072 sinfo->Directory = 0;
4073 rsp->OutputBufferLength =
4074 cpu_to_le32(sizeof(struct smb2_file_standard_info));
4075 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_standard_info));
4078 static void get_internal_info_pipe(struct smb2_query_info_rsp *rsp, u64 num,
4081 struct smb2_file_internal_info *file_info;
4083 file_info = (struct smb2_file_internal_info *)rsp->Buffer;
4085 /* any unique number */
4086 file_info->IndexNumber = cpu_to_le64(num | (1ULL << 63));
4087 rsp->OutputBufferLength =
4088 cpu_to_le32(sizeof(struct smb2_file_internal_info));
4089 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_internal_info));
4092 static int smb2_get_info_file_pipe(struct ksmbd_session *sess,
4093 struct smb2_query_info_req *req,
4094 struct smb2_query_info_rsp *rsp,
4101 * Windows can sometime send query file info request on
4102 * pipe without opening it, checking error condition here
4104 id = req->VolatileFileId;
4105 if (!ksmbd_session_rpc_method(sess, id))
4108 ksmbd_debug(SMB, "FileInfoClass %u, FileId 0x%llx\n",
4109 req->FileInfoClass, req->VolatileFileId);
4111 switch (req->FileInfoClass) {
4112 case FILE_STANDARD_INFORMATION:
4113 get_standard_info_pipe(rsp, rsp_org);
4114 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4116 FILE_STANDARD_INFORMATION_SIZE);
4118 case FILE_INTERNAL_INFORMATION:
4119 get_internal_info_pipe(rsp, id, rsp_org);
4120 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4122 FILE_INTERNAL_INFORMATION_SIZE);
4125 ksmbd_debug(SMB, "smb2_info_file_pipe for %u not supported\n",
4126 req->FileInfoClass);
4133 * smb2_get_ea() - handler for smb2 get extended attribute command
4134 * @work: smb work containing query info command buffer
4135 * @fp: ksmbd_file pointer
4136 * @req: get extended attribute request
4137 * @rsp: response buffer pointer
4138 * @rsp_org: base response buffer pointer in case of chained response
4140 * Return: 0 on success, otherwise error
4142 static int smb2_get_ea(struct ksmbd_work *work, struct ksmbd_file *fp,
4143 struct smb2_query_info_req *req,
4144 struct smb2_query_info_rsp *rsp, void *rsp_org)
4146 struct smb2_ea_info *eainfo, *prev_eainfo;
4147 char *name, *ptr, *xattr_list = NULL, *buf;
4148 int rc, name_len, value_len, xattr_list_len, idx;
4149 ssize_t buf_free_len, alignment_bytes, next_offset, rsp_data_cnt = 0;
4150 struct smb2_ea_info_req *ea_req = NULL;
4152 struct user_namespace *user_ns = file_mnt_user_ns(fp->filp);
4154 if (!(fp->daccess & FILE_READ_EA_LE)) {
4155 pr_err("Not permitted to read ext attr : 0x%x\n",
4160 path = &fp->filp->f_path;
4161 /* single EA entry is requested with given user.* name */
4162 if (req->InputBufferLength) {
4163 if (le32_to_cpu(req->InputBufferLength) <
4164 sizeof(struct smb2_ea_info_req))
4167 ea_req = (struct smb2_ea_info_req *)req->Buffer;
4169 /* need to send all EAs, if no specific EA is requested*/
4170 if (le32_to_cpu(req->Flags) & SL_RETURN_SINGLE_ENTRY)
4172 "All EAs are requested but need to send single EA entry in rsp flags 0x%x\n",
4173 le32_to_cpu(req->Flags));
4177 smb2_calc_max_out_buf_len(work, 8,
4178 le32_to_cpu(req->OutputBufferLength));
4179 if (buf_free_len < 0)
4182 rc = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
4184 rsp->hdr.Status = STATUS_INVALID_HANDLE;
4186 } else if (!rc) { /* there is no EA in the file */
4187 ksmbd_debug(SMB, "no ea data in the file\n");
4190 xattr_list_len = rc;
4192 ptr = (char *)rsp->Buffer;
4193 eainfo = (struct smb2_ea_info *)ptr;
4194 prev_eainfo = eainfo;
4197 while (idx < xattr_list_len) {
4198 name = xattr_list + idx;
4199 name_len = strlen(name);
4201 ksmbd_debug(SMB, "%s, len %d\n", name, name_len);
4202 idx += name_len + 1;
4205 * CIFS does not support EA other than user.* namespace,
4206 * still keep the framework generic, to list other attrs
4209 if (strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4212 if (!strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
4216 if (req->InputBufferLength &&
4217 strncmp(&name[XATTR_USER_PREFIX_LEN], ea_req->name,
4218 ea_req->EaNameLength))
4221 if (!strncmp(&name[XATTR_USER_PREFIX_LEN],
4222 DOS_ATTRIBUTE_PREFIX, DOS_ATTRIBUTE_PREFIX_LEN))
4225 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4226 name_len -= XATTR_USER_PREFIX_LEN;
4228 ptr = (char *)(&eainfo->name + name_len + 1);
4229 buf_free_len -= (offsetof(struct smb2_ea_info, name) +
4231 /* bailout if xattr can't fit in buf_free_len */
4232 value_len = ksmbd_vfs_getxattr(user_ns, path->dentry,
4234 if (value_len <= 0) {
4236 rsp->hdr.Status = STATUS_INVALID_HANDLE;
4240 buf_free_len -= value_len;
4241 if (buf_free_len < 0) {
4246 memcpy(ptr, buf, value_len);
4251 eainfo->EaNameLength = name_len;
4253 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4254 memcpy(eainfo->name, &name[XATTR_USER_PREFIX_LEN],
4257 memcpy(eainfo->name, name, name_len);
4259 eainfo->name[name_len] = '\0';
4260 eainfo->EaValueLength = cpu_to_le16(value_len);
4261 next_offset = offsetof(struct smb2_ea_info, name) +
4262 name_len + 1 + value_len;
4264 /* align next xattr entry at 4 byte bundary */
4265 alignment_bytes = ((next_offset + 3) & ~3) - next_offset;
4266 if (alignment_bytes) {
4267 memset(ptr, '\0', alignment_bytes);
4268 ptr += alignment_bytes;
4269 next_offset += alignment_bytes;
4270 buf_free_len -= alignment_bytes;
4272 eainfo->NextEntryOffset = cpu_to_le32(next_offset);
4273 prev_eainfo = eainfo;
4274 eainfo = (struct smb2_ea_info *)ptr;
4275 rsp_data_cnt += next_offset;
4277 if (req->InputBufferLength) {
4278 ksmbd_debug(SMB, "single entry requested\n");
4283 /* no more ea entries */
4284 prev_eainfo->NextEntryOffset = 0;
4287 if (rsp_data_cnt == 0)
4288 rsp->hdr.Status = STATUS_NO_EAS_ON_FILE;
4289 rsp->OutputBufferLength = cpu_to_le32(rsp_data_cnt);
4290 inc_rfc1001_len(rsp_org, rsp_data_cnt);
4296 static void get_file_access_info(struct smb2_query_info_rsp *rsp,
4297 struct ksmbd_file *fp, void *rsp_org)
4299 struct smb2_file_access_info *file_info;
4301 file_info = (struct smb2_file_access_info *)rsp->Buffer;
4302 file_info->AccessFlags = fp->daccess;
4303 rsp->OutputBufferLength =
4304 cpu_to_le32(sizeof(struct smb2_file_access_info));
4305 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_access_info));
4308 static int get_file_basic_info(struct smb2_query_info_rsp *rsp,
4309 struct ksmbd_file *fp, void *rsp_org)
4311 struct smb2_file_basic_info *basic_info;
4315 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4316 pr_err("no right to read the attributes : 0x%x\n",
4321 basic_info = (struct smb2_file_basic_info *)rsp->Buffer;
4322 generic_fillattr(file_mnt_user_ns(fp->filp), file_inode(fp->filp),
4324 basic_info->CreationTime = cpu_to_le64(fp->create_time);
4325 time = ksmbd_UnixTimeToNT(stat.atime);
4326 basic_info->LastAccessTime = cpu_to_le64(time);
4327 time = ksmbd_UnixTimeToNT(stat.mtime);
4328 basic_info->LastWriteTime = cpu_to_le64(time);
4329 time = ksmbd_UnixTimeToNT(stat.ctime);
4330 basic_info->ChangeTime = cpu_to_le64(time);
4331 basic_info->Attributes = fp->f_ci->m_fattr;
4332 basic_info->Pad1 = 0;
4333 rsp->OutputBufferLength =
4334 cpu_to_le32(sizeof(struct smb2_file_basic_info));
4335 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_basic_info));
4339 static unsigned long long get_allocation_size(struct inode *inode,
4342 unsigned long long alloc_size = 0;
4344 if (!S_ISDIR(stat->mode)) {
4345 if ((inode->i_blocks << 9) <= stat->size)
4346 alloc_size = stat->size;
4348 alloc_size = inode->i_blocks << 9;
4354 static void get_file_standard_info(struct smb2_query_info_rsp *rsp,
4355 struct ksmbd_file *fp, void *rsp_org)
4357 struct smb2_file_standard_info *sinfo;
4358 unsigned int delete_pending;
4359 struct inode *inode;
4362 inode = file_inode(fp->filp);
4363 generic_fillattr(file_mnt_user_ns(fp->filp), inode, &stat);
4365 sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
4366 delete_pending = ksmbd_inode_pending_delete(fp);
4368 sinfo->AllocationSize = cpu_to_le64(get_allocation_size(inode, &stat));
4369 sinfo->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4370 sinfo->NumberOfLinks = cpu_to_le32(get_nlink(&stat) - delete_pending);
4371 sinfo->DeletePending = delete_pending;
4372 sinfo->Directory = S_ISDIR(stat.mode) ? 1 : 0;
4373 rsp->OutputBufferLength =
4374 cpu_to_le32(sizeof(struct smb2_file_standard_info));
4375 inc_rfc1001_len(rsp_org,
4376 sizeof(struct smb2_file_standard_info));
4379 static void get_file_alignment_info(struct smb2_query_info_rsp *rsp,
4382 struct smb2_file_alignment_info *file_info;
4384 file_info = (struct smb2_file_alignment_info *)rsp->Buffer;
4385 file_info->AlignmentRequirement = 0;
4386 rsp->OutputBufferLength =
4387 cpu_to_le32(sizeof(struct smb2_file_alignment_info));
4388 inc_rfc1001_len(rsp_org,
4389 sizeof(struct smb2_file_alignment_info));
4392 static int get_file_all_info(struct ksmbd_work *work,
4393 struct smb2_query_info_rsp *rsp,
4394 struct ksmbd_file *fp,
4397 struct ksmbd_conn *conn = work->conn;
4398 struct smb2_file_all_info *file_info;
4399 unsigned int delete_pending;
4400 struct inode *inode;
4406 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4407 ksmbd_debug(SMB, "no right to read the attributes : 0x%x\n",
4412 filename = convert_to_nt_pathname(work->tcon->share_conf, &fp->filp->f_path);
4413 if (IS_ERR(filename))
4414 return PTR_ERR(filename);
4416 inode = file_inode(fp->filp);
4417 generic_fillattr(file_mnt_user_ns(fp->filp), inode, &stat);
4419 ksmbd_debug(SMB, "filename = %s\n", filename);
4420 delete_pending = ksmbd_inode_pending_delete(fp);
4421 file_info = (struct smb2_file_all_info *)rsp->Buffer;
4423 file_info->CreationTime = cpu_to_le64(fp->create_time);
4424 time = ksmbd_UnixTimeToNT(stat.atime);
4425 file_info->LastAccessTime = cpu_to_le64(time);
4426 time = ksmbd_UnixTimeToNT(stat.mtime);
4427 file_info->LastWriteTime = cpu_to_le64(time);
4428 time = ksmbd_UnixTimeToNT(stat.ctime);
4429 file_info->ChangeTime = cpu_to_le64(time);
4430 file_info->Attributes = fp->f_ci->m_fattr;
4431 file_info->Pad1 = 0;
4432 file_info->AllocationSize =
4433 cpu_to_le64(get_allocation_size(inode, &stat));
4434 file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4435 file_info->NumberOfLinks =
4436 cpu_to_le32(get_nlink(&stat) - delete_pending);
4437 file_info->DeletePending = delete_pending;
4438 file_info->Directory = S_ISDIR(stat.mode) ? 1 : 0;
4439 file_info->Pad2 = 0;
4440 file_info->IndexNumber = cpu_to_le64(stat.ino);
4441 file_info->EASize = 0;
4442 file_info->AccessFlags = fp->daccess;
4443 file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
4444 file_info->Mode = fp->coption;
4445 file_info->AlignmentRequirement = 0;
4446 conv_len = smbConvertToUTF16((__le16 *)file_info->FileName, filename,
4447 PATH_MAX, conn->local_nls, 0);
4449 file_info->FileNameLength = cpu_to_le32(conv_len);
4450 rsp->OutputBufferLength =
4451 cpu_to_le32(sizeof(struct smb2_file_all_info) + conv_len - 1);
4453 inc_rfc1001_len(rsp_org, le32_to_cpu(rsp->OutputBufferLength));
4457 static void get_file_alternate_info(struct ksmbd_work *work,
4458 struct smb2_query_info_rsp *rsp,
4459 struct ksmbd_file *fp,
4462 struct ksmbd_conn *conn = work->conn;
4463 struct smb2_file_alt_name_info *file_info;
4464 struct dentry *dentry = fp->filp->f_path.dentry;
4467 spin_lock(&dentry->d_lock);
4468 file_info = (struct smb2_file_alt_name_info *)rsp->Buffer;
4469 conv_len = ksmbd_extract_shortname(conn,
4470 dentry->d_name.name,
4471 file_info->FileName);
4472 spin_unlock(&dentry->d_lock);
4473 file_info->FileNameLength = cpu_to_le32(conv_len);
4474 rsp->OutputBufferLength =
4475 cpu_to_le32(sizeof(struct smb2_file_alt_name_info) + conv_len);
4476 inc_rfc1001_len(rsp_org, le32_to_cpu(rsp->OutputBufferLength));
4479 static void get_file_stream_info(struct ksmbd_work *work,
4480 struct smb2_query_info_rsp *rsp,
4481 struct ksmbd_file *fp,
4484 struct ksmbd_conn *conn = work->conn;
4485 struct smb2_file_stream_info *file_info;
4486 char *stream_name, *xattr_list = NULL, *stream_buf;
4488 struct path *path = &fp->filp->f_path;
4489 ssize_t xattr_list_len;
4490 int nbytes = 0, streamlen, stream_name_len, next, idx = 0;
4492 struct smb2_query_info_req *req = ksmbd_req_buf_next(work);
4494 generic_fillattr(file_mnt_user_ns(fp->filp), file_inode(fp->filp),
4496 file_info = (struct smb2_file_stream_info *)rsp->Buffer;
4499 smb2_calc_max_out_buf_len(work, 8,
4500 le32_to_cpu(req->OutputBufferLength));
4501 if (buf_free_len < 0)
4504 xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
4505 if (xattr_list_len < 0) {
4507 } else if (!xattr_list_len) {
4508 ksmbd_debug(SMB, "empty xattr in the file\n");
4512 while (idx < xattr_list_len) {
4513 stream_name = xattr_list + idx;
4514 streamlen = strlen(stream_name);
4515 idx += streamlen + 1;
4517 ksmbd_debug(SMB, "%s, len %d\n", stream_name, streamlen);
4519 if (strncmp(&stream_name[XATTR_USER_PREFIX_LEN],
4520 STREAM_PREFIX, STREAM_PREFIX_LEN))
4523 stream_name_len = streamlen - (XATTR_USER_PREFIX_LEN +
4525 streamlen = stream_name_len;
4529 stream_buf = kmalloc(streamlen + 1, GFP_KERNEL);
4533 streamlen = snprintf(stream_buf, streamlen + 1,
4534 ":%s", &stream_name[XATTR_NAME_STREAM_LEN]);
4536 next = sizeof(struct smb2_file_stream_info) + streamlen * 2;
4537 if (next > buf_free_len) {
4542 file_info = (struct smb2_file_stream_info *)&rsp->Buffer[nbytes];
4543 streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
4544 stream_buf, streamlen,
4545 conn->local_nls, 0);
4548 file_info->StreamNameLength = cpu_to_le32(streamlen);
4549 file_info->StreamSize = cpu_to_le64(stream_name_len);
4550 file_info->StreamAllocationSize = cpu_to_le64(stream_name_len);
4553 buf_free_len -= next;
4554 file_info->NextEntryOffset = cpu_to_le32(next);
4558 if (!S_ISDIR(stat.mode) &&
4559 buf_free_len >= sizeof(struct smb2_file_stream_info) + 7 * 2) {
4560 file_info = (struct smb2_file_stream_info *)
4561 &rsp->Buffer[nbytes];
4562 streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
4563 "::$DATA", 7, conn->local_nls, 0);
4565 file_info->StreamNameLength = cpu_to_le32(streamlen);
4566 file_info->StreamSize = cpu_to_le64(stat.size);
4567 file_info->StreamAllocationSize = cpu_to_le64(stat.blocks << 9);
4568 nbytes += sizeof(struct smb2_file_stream_info) + streamlen;
4571 /* last entry offset should be 0 */
4572 file_info->NextEntryOffset = 0;
4575 rsp->OutputBufferLength = cpu_to_le32(nbytes);
4576 inc_rfc1001_len(rsp_org, nbytes);
4579 static void get_file_internal_info(struct smb2_query_info_rsp *rsp,
4580 struct ksmbd_file *fp, void *rsp_org)
4582 struct smb2_file_internal_info *file_info;
4585 generic_fillattr(file_mnt_user_ns(fp->filp), file_inode(fp->filp),
4587 file_info = (struct smb2_file_internal_info *)rsp->Buffer;
4588 file_info->IndexNumber = cpu_to_le64(stat.ino);
4589 rsp->OutputBufferLength =
4590 cpu_to_le32(sizeof(struct smb2_file_internal_info));
4591 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_internal_info));
4594 static int get_file_network_open_info(struct smb2_query_info_rsp *rsp,
4595 struct ksmbd_file *fp, void *rsp_org)
4597 struct smb2_file_ntwrk_info *file_info;
4598 struct inode *inode;
4602 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4603 pr_err("no right to read the attributes : 0x%x\n",
4608 file_info = (struct smb2_file_ntwrk_info *)rsp->Buffer;
4610 inode = file_inode(fp->filp);
4611 generic_fillattr(file_mnt_user_ns(fp->filp), inode, &stat);
4613 file_info->CreationTime = cpu_to_le64(fp->create_time);
4614 time = ksmbd_UnixTimeToNT(stat.atime);
4615 file_info->LastAccessTime = cpu_to_le64(time);
4616 time = ksmbd_UnixTimeToNT(stat.mtime);
4617 file_info->LastWriteTime = cpu_to_le64(time);
4618 time = ksmbd_UnixTimeToNT(stat.ctime);
4619 file_info->ChangeTime = cpu_to_le64(time);
4620 file_info->Attributes = fp->f_ci->m_fattr;
4621 file_info->AllocationSize =
4622 cpu_to_le64(get_allocation_size(inode, &stat));
4623 file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4624 file_info->Reserved = cpu_to_le32(0);
4625 rsp->OutputBufferLength =
4626 cpu_to_le32(sizeof(struct smb2_file_ntwrk_info));
4627 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_ntwrk_info));
4631 static void get_file_ea_info(struct smb2_query_info_rsp *rsp, void *rsp_org)
4633 struct smb2_file_ea_info *file_info;
4635 file_info = (struct smb2_file_ea_info *)rsp->Buffer;
4636 file_info->EASize = 0;
4637 rsp->OutputBufferLength =
4638 cpu_to_le32(sizeof(struct smb2_file_ea_info));
4639 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_ea_info));
4642 static void get_file_position_info(struct smb2_query_info_rsp *rsp,
4643 struct ksmbd_file *fp, void *rsp_org)
4645 struct smb2_file_pos_info *file_info;
4647 file_info = (struct smb2_file_pos_info *)rsp->Buffer;
4648 file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
4649 rsp->OutputBufferLength =
4650 cpu_to_le32(sizeof(struct smb2_file_pos_info));
4651 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_pos_info));
4654 static void get_file_mode_info(struct smb2_query_info_rsp *rsp,
4655 struct ksmbd_file *fp, void *rsp_org)
4657 struct smb2_file_mode_info *file_info;
4659 file_info = (struct smb2_file_mode_info *)rsp->Buffer;
4660 file_info->Mode = fp->coption & FILE_MODE_INFO_MASK;
4661 rsp->OutputBufferLength =
4662 cpu_to_le32(sizeof(struct smb2_file_mode_info));
4663 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_mode_info));
4666 static void get_file_compression_info(struct smb2_query_info_rsp *rsp,
4667 struct ksmbd_file *fp, void *rsp_org)
4669 struct smb2_file_comp_info *file_info;
4672 generic_fillattr(file_mnt_user_ns(fp->filp), file_inode(fp->filp),
4675 file_info = (struct smb2_file_comp_info *)rsp->Buffer;
4676 file_info->CompressedFileSize = cpu_to_le64(stat.blocks << 9);
4677 file_info->CompressionFormat = COMPRESSION_FORMAT_NONE;
4678 file_info->CompressionUnitShift = 0;
4679 file_info->ChunkShift = 0;
4680 file_info->ClusterShift = 0;
4681 memset(&file_info->Reserved[0], 0, 3);
4683 rsp->OutputBufferLength =
4684 cpu_to_le32(sizeof(struct smb2_file_comp_info));
4685 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_comp_info));
4688 static int get_file_attribute_tag_info(struct smb2_query_info_rsp *rsp,
4689 struct ksmbd_file *fp, void *rsp_org)
4691 struct smb2_file_attr_tag_info *file_info;
4693 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4694 pr_err("no right to read the attributes : 0x%x\n",
4699 file_info = (struct smb2_file_attr_tag_info *)rsp->Buffer;
4700 file_info->FileAttributes = fp->f_ci->m_fattr;
4701 file_info->ReparseTag = 0;
4702 rsp->OutputBufferLength =
4703 cpu_to_le32(sizeof(struct smb2_file_attr_tag_info));
4704 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_attr_tag_info));
4708 static int find_file_posix_info(struct smb2_query_info_rsp *rsp,
4709 struct ksmbd_file *fp, void *rsp_org)
4711 struct smb311_posix_qinfo *file_info;
4712 struct inode *inode = file_inode(fp->filp);
4715 file_info = (struct smb311_posix_qinfo *)rsp->Buffer;
4716 file_info->CreationTime = cpu_to_le64(fp->create_time);
4717 time = ksmbd_UnixTimeToNT(inode->i_atime);
4718 file_info->LastAccessTime = cpu_to_le64(time);
4719 time = ksmbd_UnixTimeToNT(inode->i_mtime);
4720 file_info->LastWriteTime = cpu_to_le64(time);
4721 time = ksmbd_UnixTimeToNT(inode->i_ctime);
4722 file_info->ChangeTime = cpu_to_le64(time);
4723 file_info->DosAttributes = fp->f_ci->m_fattr;
4724 file_info->Inode = cpu_to_le64(inode->i_ino);
4725 file_info->EndOfFile = cpu_to_le64(inode->i_size);
4726 file_info->AllocationSize = cpu_to_le64(inode->i_blocks << 9);
4727 file_info->HardLinks = cpu_to_le32(inode->i_nlink);
4728 file_info->Mode = cpu_to_le32(inode->i_mode);
4729 file_info->DeviceId = cpu_to_le32(inode->i_rdev);
4730 rsp->OutputBufferLength =
4731 cpu_to_le32(sizeof(struct smb311_posix_qinfo));
4732 inc_rfc1001_len(rsp_org, sizeof(struct smb311_posix_qinfo));
4736 static int smb2_get_info_file(struct ksmbd_work *work,
4737 struct smb2_query_info_req *req,
4738 struct smb2_query_info_rsp *rsp)
4740 struct ksmbd_file *fp;
4741 int fileinfoclass = 0;
4743 int file_infoclass_size;
4744 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
4746 if (test_share_config_flag(work->tcon->share_conf,
4747 KSMBD_SHARE_FLAG_PIPE)) {
4748 /* smb2 info file called for pipe */
4749 return smb2_get_info_file_pipe(work->sess, req, rsp,
4750 work->response_buf);
4753 if (work->next_smb2_rcv_hdr_off) {
4754 if (!has_file_id(req->VolatileFileId)) {
4755 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
4756 work->compound_fid);
4757 id = work->compound_fid;
4758 pid = work->compound_pfid;
4762 if (!has_file_id(id)) {
4763 id = req->VolatileFileId;
4764 pid = req->PersistentFileId;
4767 fp = ksmbd_lookup_fd_slow(work, id, pid);
4771 fileinfoclass = req->FileInfoClass;
4773 switch (fileinfoclass) {
4774 case FILE_ACCESS_INFORMATION:
4775 get_file_access_info(rsp, fp, work->response_buf);
4776 file_infoclass_size = FILE_ACCESS_INFORMATION_SIZE;
4779 case FILE_BASIC_INFORMATION:
4780 rc = get_file_basic_info(rsp, fp, work->response_buf);
4781 file_infoclass_size = FILE_BASIC_INFORMATION_SIZE;
4784 case FILE_STANDARD_INFORMATION:
4785 get_file_standard_info(rsp, fp, work->response_buf);
4786 file_infoclass_size = FILE_STANDARD_INFORMATION_SIZE;
4789 case FILE_ALIGNMENT_INFORMATION:
4790 get_file_alignment_info(rsp, work->response_buf);
4791 file_infoclass_size = FILE_ALIGNMENT_INFORMATION_SIZE;
4794 case FILE_ALL_INFORMATION:
4795 rc = get_file_all_info(work, rsp, fp, work->response_buf);
4796 file_infoclass_size = FILE_ALL_INFORMATION_SIZE;
4799 case FILE_ALTERNATE_NAME_INFORMATION:
4800 get_file_alternate_info(work, rsp, fp, work->response_buf);
4801 file_infoclass_size = FILE_ALTERNATE_NAME_INFORMATION_SIZE;
4804 case FILE_STREAM_INFORMATION:
4805 get_file_stream_info(work, rsp, fp, work->response_buf);
4806 file_infoclass_size = FILE_STREAM_INFORMATION_SIZE;
4809 case FILE_INTERNAL_INFORMATION:
4810 get_file_internal_info(rsp, fp, work->response_buf);
4811 file_infoclass_size = FILE_INTERNAL_INFORMATION_SIZE;
4814 case FILE_NETWORK_OPEN_INFORMATION:
4815 rc = get_file_network_open_info(rsp, fp, work->response_buf);
4816 file_infoclass_size = FILE_NETWORK_OPEN_INFORMATION_SIZE;
4819 case FILE_EA_INFORMATION:
4820 get_file_ea_info(rsp, work->response_buf);
4821 file_infoclass_size = FILE_EA_INFORMATION_SIZE;
4824 case FILE_FULL_EA_INFORMATION:
4825 rc = smb2_get_ea(work, fp, req, rsp, work->response_buf);
4826 file_infoclass_size = FILE_FULL_EA_INFORMATION_SIZE;
4829 case FILE_POSITION_INFORMATION:
4830 get_file_position_info(rsp, fp, work->response_buf);
4831 file_infoclass_size = FILE_POSITION_INFORMATION_SIZE;
4834 case FILE_MODE_INFORMATION:
4835 get_file_mode_info(rsp, fp, work->response_buf);
4836 file_infoclass_size = FILE_MODE_INFORMATION_SIZE;
4839 case FILE_COMPRESSION_INFORMATION:
4840 get_file_compression_info(rsp, fp, work->response_buf);
4841 file_infoclass_size = FILE_COMPRESSION_INFORMATION_SIZE;
4844 case FILE_ATTRIBUTE_TAG_INFORMATION:
4845 rc = get_file_attribute_tag_info(rsp, fp, work->response_buf);
4846 file_infoclass_size = FILE_ATTRIBUTE_TAG_INFORMATION_SIZE;
4848 case SMB_FIND_FILE_POSIX_INFO:
4849 if (!work->tcon->posix_extensions) {
4850 pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
4853 rc = find_file_posix_info(rsp, fp, work->response_buf);
4854 file_infoclass_size = sizeof(struct smb311_posix_qinfo);
4858 ksmbd_debug(SMB, "fileinfoclass %d not supported yet\n",
4863 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4864 rsp, work->response_buf,
4865 file_infoclass_size);
4866 ksmbd_fd_put(work, fp);
4870 static int smb2_get_info_filesystem(struct ksmbd_work *work,
4871 struct smb2_query_info_req *req,
4872 struct smb2_query_info_rsp *rsp)
4874 struct ksmbd_session *sess = work->sess;
4875 struct ksmbd_conn *conn = work->conn;
4876 struct ksmbd_share_config *share = work->tcon->share_conf;
4877 int fsinfoclass = 0;
4878 struct kstatfs stfs;
4881 int fs_infoclass_size = 0;
4883 rc = kern_path(share->path, LOOKUP_NO_SYMLINKS, &path);
4885 pr_err("cannot create vfs path\n");
4889 rc = vfs_statfs(&path, &stfs);
4891 pr_err("cannot do stat of path %s\n", share->path);
4896 fsinfoclass = req->FileInfoClass;
4898 switch (fsinfoclass) {
4899 case FS_DEVICE_INFORMATION:
4901 struct filesystem_device_info *info;
4903 info = (struct filesystem_device_info *)rsp->Buffer;
4905 info->DeviceType = cpu_to_le32(stfs.f_type);
4906 info->DeviceCharacteristics = cpu_to_le32(0x00000020);
4907 rsp->OutputBufferLength = cpu_to_le32(8);
4908 inc_rfc1001_len(work->response_buf, 8);
4909 fs_infoclass_size = FS_DEVICE_INFORMATION_SIZE;
4912 case FS_ATTRIBUTE_INFORMATION:
4914 struct filesystem_attribute_info *info;
4917 info = (struct filesystem_attribute_info *)rsp->Buffer;
4918 info->Attributes = cpu_to_le32(FILE_SUPPORTS_OBJECT_IDS |
4919 FILE_PERSISTENT_ACLS |
4920 FILE_UNICODE_ON_DISK |
4921 FILE_CASE_PRESERVED_NAMES |
4922 FILE_CASE_SENSITIVE_SEARCH |
4923 FILE_SUPPORTS_BLOCK_REFCOUNTING);
4925 info->Attributes |= cpu_to_le32(server_conf.share_fake_fscaps);
4927 info->MaxPathNameComponentLength = cpu_to_le32(stfs.f_namelen);
4928 len = smbConvertToUTF16((__le16 *)info->FileSystemName,
4929 "NTFS", PATH_MAX, conn->local_nls, 0);
4931 info->FileSystemNameLen = cpu_to_le32(len);
4932 sz = sizeof(struct filesystem_attribute_info) - 2 + len;
4933 rsp->OutputBufferLength = cpu_to_le32(sz);
4934 inc_rfc1001_len(work->response_buf, sz);
4935 fs_infoclass_size = FS_ATTRIBUTE_INFORMATION_SIZE;
4938 case FS_VOLUME_INFORMATION:
4940 struct filesystem_vol_info *info;
4942 unsigned int serial_crc = 0;
4944 info = (struct filesystem_vol_info *)(rsp->Buffer);
4945 info->VolumeCreationTime = 0;
4946 serial_crc = crc32_le(serial_crc, share->name,
4947 strlen(share->name));
4948 serial_crc = crc32_le(serial_crc, share->path,
4949 strlen(share->path));
4950 serial_crc = crc32_le(serial_crc, ksmbd_netbios_name(),
4951 strlen(ksmbd_netbios_name()));
4952 /* Taking dummy value of serial number*/
4953 info->SerialNumber = cpu_to_le32(serial_crc);
4954 len = smbConvertToUTF16((__le16 *)info->VolumeLabel,
4955 share->name, PATH_MAX,
4956 conn->local_nls, 0);
4958 info->VolumeLabelSize = cpu_to_le32(len);
4960 sz = sizeof(struct filesystem_vol_info) - 2 + len;
4961 rsp->OutputBufferLength = cpu_to_le32(sz);
4962 inc_rfc1001_len(work->response_buf, sz);
4963 fs_infoclass_size = FS_VOLUME_INFORMATION_SIZE;
4966 case FS_SIZE_INFORMATION:
4968 struct filesystem_info *info;
4970 info = (struct filesystem_info *)(rsp->Buffer);
4971 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
4972 info->FreeAllocationUnits = cpu_to_le64(stfs.f_bfree);
4973 info->SectorsPerAllocationUnit = cpu_to_le32(1);
4974 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
4975 rsp->OutputBufferLength = cpu_to_le32(24);
4976 inc_rfc1001_len(work->response_buf, 24);
4977 fs_infoclass_size = FS_SIZE_INFORMATION_SIZE;
4980 case FS_FULL_SIZE_INFORMATION:
4982 struct smb2_fs_full_size_info *info;
4984 info = (struct smb2_fs_full_size_info *)(rsp->Buffer);
4985 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
4986 info->CallerAvailableAllocationUnits =
4987 cpu_to_le64(stfs.f_bavail);
4988 info->ActualAvailableAllocationUnits =
4989 cpu_to_le64(stfs.f_bfree);
4990 info->SectorsPerAllocationUnit = cpu_to_le32(1);
4991 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
4992 rsp->OutputBufferLength = cpu_to_le32(32);
4993 inc_rfc1001_len(work->response_buf, 32);
4994 fs_infoclass_size = FS_FULL_SIZE_INFORMATION_SIZE;
4997 case FS_OBJECT_ID_INFORMATION:
4999 struct object_id_info *info;
5001 info = (struct object_id_info *)(rsp->Buffer);
5003 if (!user_guest(sess->user))
5004 memcpy(info->objid, user_passkey(sess->user), 16);
5006 memset(info->objid, 0, 16);
5008 info->extended_info.magic = cpu_to_le32(EXTENDED_INFO_MAGIC);
5009 info->extended_info.version = cpu_to_le32(1);
5010 info->extended_info.release = cpu_to_le32(1);
5011 info->extended_info.rel_date = 0;
5012 memcpy(info->extended_info.version_string, "1.1.0", strlen("1.1.0"));
5013 rsp->OutputBufferLength = cpu_to_le32(64);
5014 inc_rfc1001_len(work->response_buf, 64);
5015 fs_infoclass_size = FS_OBJECT_ID_INFORMATION_SIZE;
5018 case FS_SECTOR_SIZE_INFORMATION:
5020 struct smb3_fs_ss_info *info;
5021 unsigned int sector_size =
5022 min_t(unsigned int, path.mnt->mnt_sb->s_blocksize, 4096);
5024 info = (struct smb3_fs_ss_info *)(rsp->Buffer);
5026 info->LogicalBytesPerSector = cpu_to_le32(sector_size);
5027 info->PhysicalBytesPerSectorForAtomicity =
5028 cpu_to_le32(sector_size);
5029 info->PhysicalBytesPerSectorForPerf = cpu_to_le32(sector_size);
5030 info->FSEffPhysicalBytesPerSectorForAtomicity =
5031 cpu_to_le32(sector_size);
5032 info->Flags = cpu_to_le32(SSINFO_FLAGS_ALIGNED_DEVICE |
5033 SSINFO_FLAGS_PARTITION_ALIGNED_ON_DEVICE);
5034 info->ByteOffsetForSectorAlignment = 0;
5035 info->ByteOffsetForPartitionAlignment = 0;
5036 rsp->OutputBufferLength = cpu_to_le32(28);
5037 inc_rfc1001_len(work->response_buf, 28);
5038 fs_infoclass_size = FS_SECTOR_SIZE_INFORMATION_SIZE;
5041 case FS_CONTROL_INFORMATION:
5044 * TODO : The current implementation is based on
5045 * test result with win7(NTFS) server. It's need to
5046 * modify this to get valid Quota values
5049 struct smb2_fs_control_info *info;
5051 info = (struct smb2_fs_control_info *)(rsp->Buffer);
5052 info->FreeSpaceStartFiltering = 0;
5053 info->FreeSpaceThreshold = 0;
5054 info->FreeSpaceStopFiltering = 0;
5055 info->DefaultQuotaThreshold = cpu_to_le64(SMB2_NO_FID);
5056 info->DefaultQuotaLimit = cpu_to_le64(SMB2_NO_FID);
5058 rsp->OutputBufferLength = cpu_to_le32(48);
5059 inc_rfc1001_len(work->response_buf, 48);
5060 fs_infoclass_size = FS_CONTROL_INFORMATION_SIZE;
5063 case FS_POSIX_INFORMATION:
5065 struct filesystem_posix_info *info;
5067 if (!work->tcon->posix_extensions) {
5068 pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
5071 info = (struct filesystem_posix_info *)(rsp->Buffer);
5072 info->OptimalTransferSize = cpu_to_le32(stfs.f_bsize);
5073 info->BlockSize = cpu_to_le32(stfs.f_bsize);
5074 info->TotalBlocks = cpu_to_le64(stfs.f_blocks);
5075 info->BlocksAvail = cpu_to_le64(stfs.f_bfree);
5076 info->UserBlocksAvail = cpu_to_le64(stfs.f_bavail);
5077 info->TotalFileNodes = cpu_to_le64(stfs.f_files);
5078 info->FreeFileNodes = cpu_to_le64(stfs.f_ffree);
5079 rsp->OutputBufferLength = cpu_to_le32(56);
5080 inc_rfc1001_len(work->response_buf, 56);
5081 fs_infoclass_size = FS_POSIX_INFORMATION_SIZE;
5089 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
5090 rsp, work->response_buf,
5096 static int smb2_get_info_sec(struct ksmbd_work *work,
5097 struct smb2_query_info_req *req,
5098 struct smb2_query_info_rsp *rsp)
5100 struct ksmbd_file *fp;
5101 struct user_namespace *user_ns;
5102 struct smb_ntsd *pntsd = (struct smb_ntsd *)rsp->Buffer, *ppntsd = NULL;
5103 struct smb_fattr fattr = {{0}};
5104 struct inode *inode;
5106 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
5107 int addition_info = le32_to_cpu(req->AdditionalInformation);
5110 if (addition_info & ~(OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO |
5111 PROTECTED_DACL_SECINFO |
5112 UNPROTECTED_DACL_SECINFO)) {
5113 ksmbd_debug(SMB, "Unsupported addition info: 0x%x)\n",
5116 pntsd->revision = cpu_to_le16(1);
5117 pntsd->type = cpu_to_le16(SELF_RELATIVE | DACL_PROTECTED);
5118 pntsd->osidoffset = 0;
5119 pntsd->gsidoffset = 0;
5120 pntsd->sacloffset = 0;
5121 pntsd->dacloffset = 0;
5123 secdesclen = sizeof(struct smb_ntsd);
5124 rsp->OutputBufferLength = cpu_to_le32(secdesclen);
5125 inc_rfc1001_len(work->response_buf, secdesclen);
5130 if (work->next_smb2_rcv_hdr_off) {
5131 if (!has_file_id(req->VolatileFileId)) {
5132 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
5133 work->compound_fid);
5134 id = work->compound_fid;
5135 pid = work->compound_pfid;
5139 if (!has_file_id(id)) {
5140 id = req->VolatileFileId;
5141 pid = req->PersistentFileId;
5144 fp = ksmbd_lookup_fd_slow(work, id, pid);
5148 user_ns = file_mnt_user_ns(fp->filp);
5149 inode = file_inode(fp->filp);
5150 ksmbd_acls_fattr(&fattr, user_ns, inode);
5152 if (test_share_config_flag(work->tcon->share_conf,
5153 KSMBD_SHARE_FLAG_ACL_XATTR))
5154 ksmbd_vfs_get_sd_xattr(work->conn, user_ns,
5155 fp->filp->f_path.dentry, &ppntsd);
5157 rc = build_sec_desc(user_ns, pntsd, ppntsd, addition_info,
5158 &secdesclen, &fattr);
5159 posix_acl_release(fattr.cf_acls);
5160 posix_acl_release(fattr.cf_dacls);
5162 ksmbd_fd_put(work, fp);
5166 rsp->OutputBufferLength = cpu_to_le32(secdesclen);
5167 inc_rfc1001_len(work->response_buf, secdesclen);
5172 * smb2_query_info() - handler for smb2 query info command
5173 * @work: smb work containing query info request buffer
5175 * Return: 0 on success, otherwise error
5177 int smb2_query_info(struct ksmbd_work *work)
5179 struct smb2_query_info_req *req;
5180 struct smb2_query_info_rsp *rsp;
5183 WORK_BUFFERS(work, req, rsp);
5185 ksmbd_debug(SMB, "GOT query info request\n");
5187 switch (req->InfoType) {
5188 case SMB2_O_INFO_FILE:
5189 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
5190 rc = smb2_get_info_file(work, req, rsp);
5192 case SMB2_O_INFO_FILESYSTEM:
5193 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILESYSTEM\n");
5194 rc = smb2_get_info_filesystem(work, req, rsp);
5196 case SMB2_O_INFO_SECURITY:
5197 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
5198 rc = smb2_get_info_sec(work, req, rsp);
5201 ksmbd_debug(SMB, "InfoType %d not supported yet\n",
5208 rsp->hdr.Status = STATUS_ACCESS_DENIED;
5209 else if (rc == -ENOENT)
5210 rsp->hdr.Status = STATUS_FILE_CLOSED;
5211 else if (rc == -EIO)
5212 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
5213 else if (rc == -EOPNOTSUPP || rsp->hdr.Status == 0)
5214 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
5215 smb2_set_err_rsp(work);
5217 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n",
5221 rsp->StructureSize = cpu_to_le16(9);
5222 rsp->OutputBufferOffset = cpu_to_le16(72);
5223 inc_rfc1001_len(work->response_buf, 8);
5228 * smb2_close_pipe() - handler for closing IPC pipe
5229 * @work: smb work containing close request buffer
5233 static noinline int smb2_close_pipe(struct ksmbd_work *work)
5236 struct smb2_close_req *req = smb2_get_msg(work->request_buf);
5237 struct smb2_close_rsp *rsp = smb2_get_msg(work->response_buf);
5239 id = req->VolatileFileId;
5240 ksmbd_session_rpc_close(work->sess, id);
5242 rsp->StructureSize = cpu_to_le16(60);
5245 rsp->CreationTime = 0;
5246 rsp->LastAccessTime = 0;
5247 rsp->LastWriteTime = 0;
5248 rsp->ChangeTime = 0;
5249 rsp->AllocationSize = 0;
5251 rsp->Attributes = 0;
5252 inc_rfc1001_len(work->response_buf, 60);
5257 * smb2_close() - handler for smb2 close file command
5258 * @work: smb work containing close request buffer
5262 int smb2_close(struct ksmbd_work *work)
5264 u64 volatile_id = KSMBD_NO_FID;
5266 struct smb2_close_req *req;
5267 struct smb2_close_rsp *rsp;
5268 struct ksmbd_conn *conn = work->conn;
5269 struct ksmbd_file *fp;
5270 struct inode *inode;
5274 WORK_BUFFERS(work, req, rsp);
5276 if (test_share_config_flag(work->tcon->share_conf,
5277 KSMBD_SHARE_FLAG_PIPE)) {
5278 ksmbd_debug(SMB, "IPC pipe close request\n");
5279 return smb2_close_pipe(work);
5282 sess_id = le64_to_cpu(req->hdr.SessionId);
5283 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5284 sess_id = work->compound_sid;
5286 work->compound_sid = 0;
5287 if (check_session_id(conn, sess_id)) {
5288 work->compound_sid = sess_id;
5290 rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
5291 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5292 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
5297 if (work->next_smb2_rcv_hdr_off &&
5298 !has_file_id(req->VolatileFileId)) {
5299 if (!has_file_id(work->compound_fid)) {
5300 /* file already closed, return FILE_CLOSED */
5301 ksmbd_debug(SMB, "file already closed\n");
5302 rsp->hdr.Status = STATUS_FILE_CLOSED;
5307 "Compound request set FID = %llu:%llu\n",
5309 work->compound_pfid);
5310 volatile_id = work->compound_fid;
5312 /* file closed, stored id is not valid anymore */
5313 work->compound_fid = KSMBD_NO_FID;
5314 work->compound_pfid = KSMBD_NO_FID;
5317 volatile_id = req->VolatileFileId;
5319 ksmbd_debug(SMB, "volatile_id = %llu\n", volatile_id);
5321 rsp->StructureSize = cpu_to_le16(60);
5324 if (req->Flags == SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB) {
5325 fp = ksmbd_lookup_fd_fast(work, volatile_id);
5331 inode = file_inode(fp->filp);
5332 rsp->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB;
5333 rsp->AllocationSize = S_ISDIR(inode->i_mode) ? 0 :
5334 cpu_to_le64(inode->i_blocks << 9);
5335 rsp->EndOfFile = cpu_to_le64(inode->i_size);
5336 rsp->Attributes = fp->f_ci->m_fattr;
5337 rsp->CreationTime = cpu_to_le64(fp->create_time);
5338 time = ksmbd_UnixTimeToNT(inode->i_atime);
5339 rsp->LastAccessTime = cpu_to_le64(time);
5340 time = ksmbd_UnixTimeToNT(inode->i_mtime);
5341 rsp->LastWriteTime = cpu_to_le64(time);
5342 time = ksmbd_UnixTimeToNT(inode->i_ctime);
5343 rsp->ChangeTime = cpu_to_le64(time);
5344 ksmbd_fd_put(work, fp);
5347 rsp->AllocationSize = 0;
5349 rsp->Attributes = 0;
5350 rsp->CreationTime = 0;
5351 rsp->LastAccessTime = 0;
5352 rsp->LastWriteTime = 0;
5353 rsp->ChangeTime = 0;
5356 err = ksmbd_close_fd(work, volatile_id);
5359 if (rsp->hdr.Status == 0)
5360 rsp->hdr.Status = STATUS_FILE_CLOSED;
5361 smb2_set_err_rsp(work);
5363 inc_rfc1001_len(work->response_buf, 60);
5370 * smb2_echo() - handler for smb2 echo(ping) command
5371 * @work: smb work containing echo request buffer
5375 int smb2_echo(struct ksmbd_work *work)
5377 struct smb2_echo_rsp *rsp = smb2_get_msg(work->response_buf);
5379 rsp->StructureSize = cpu_to_le16(4);
5381 inc_rfc1001_len(work->response_buf, 4);
5385 static int smb2_rename(struct ksmbd_work *work,
5386 struct ksmbd_file *fp,
5387 struct user_namespace *user_ns,
5388 struct smb2_file_rename_info *file_info,
5389 struct nls_table *local_nls)
5391 struct ksmbd_share_config *share = fp->tcon->share_conf;
5392 char *new_name = NULL, *abs_oldname = NULL, *old_name = NULL;
5393 char *pathname = NULL;
5395 bool file_present = true;
5398 ksmbd_debug(SMB, "setting FILE_RENAME_INFO\n");
5399 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
5403 abs_oldname = d_path(&fp->filp->f_path, pathname, PATH_MAX);
5404 if (IS_ERR(abs_oldname)) {
5408 old_name = strrchr(abs_oldname, '/');
5409 if (old_name && old_name[1] != '\0') {
5412 ksmbd_debug(SMB, "can't get last component in path %s\n",
5418 new_name = smb2_get_name(file_info->FileName,
5419 le32_to_cpu(file_info->FileNameLength),
5421 if (IS_ERR(new_name)) {
5422 rc = PTR_ERR(new_name);
5426 if (strchr(new_name, ':')) {
5428 char *xattr_stream_name, *stream_name = NULL;
5429 size_t xattr_stream_size;
5432 rc = parse_stream_name(new_name, &stream_name, &s_type);
5436 len = strlen(new_name);
5437 if (len > 0 && new_name[len - 1] != '/') {
5438 pr_err("not allow base filename in rename\n");
5443 rc = ksmbd_vfs_xattr_stream_name(stream_name,
5450 rc = ksmbd_vfs_setxattr(user_ns,
5451 fp->filp->f_path.dentry,
5455 pr_err("failed to store stream name in xattr: %d\n",
5464 ksmbd_debug(SMB, "new name %s\n", new_name);
5465 rc = ksmbd_vfs_kern_path(work, new_name, LOOKUP_NO_SYMLINKS, &path, 1);
5469 file_present = false;
5474 if (ksmbd_share_veto_filename(share, new_name)) {
5476 ksmbd_debug(SMB, "Can't rename vetoed file: %s\n", new_name);
5480 if (file_info->ReplaceIfExists) {
5482 rc = ksmbd_vfs_remove_file(work, new_name);
5484 if (rc != -ENOTEMPTY)
5486 ksmbd_debug(SMB, "cannot delete %s, rc %d\n",
5493 strncmp(old_name, path.dentry->d_name.name, strlen(old_name))) {
5496 "cannot rename already existing file\n");
5501 rc = ksmbd_vfs_fp_rename(work, fp, new_name);
5504 if (!IS_ERR(new_name))
5509 static int smb2_create_link(struct ksmbd_work *work,
5510 struct ksmbd_share_config *share,
5511 struct smb2_file_link_info *file_info,
5512 unsigned int buf_len, struct file *filp,
5513 struct nls_table *local_nls)
5515 char *link_name = NULL, *target_name = NULL, *pathname = NULL;
5517 bool file_present = true;
5520 if (buf_len < (u64)sizeof(struct smb2_file_link_info) +
5521 le32_to_cpu(file_info->FileNameLength))
5524 ksmbd_debug(SMB, "setting FILE_LINK_INFORMATION\n");
5525 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
5529 link_name = smb2_get_name(file_info->FileName,
5530 le32_to_cpu(file_info->FileNameLength),
5532 if (IS_ERR(link_name) || S_ISDIR(file_inode(filp)->i_mode)) {
5537 ksmbd_debug(SMB, "link name is %s\n", link_name);
5538 target_name = d_path(&filp->f_path, pathname, PATH_MAX);
5539 if (IS_ERR(target_name)) {
5544 ksmbd_debug(SMB, "target name is %s\n", target_name);
5545 rc = ksmbd_vfs_kern_path(work, link_name, LOOKUP_NO_SYMLINKS, &path, 0);
5549 file_present = false;
5554 if (file_info->ReplaceIfExists) {
5556 rc = ksmbd_vfs_remove_file(work, link_name);
5559 ksmbd_debug(SMB, "cannot delete %s\n",
5567 ksmbd_debug(SMB, "link already exists\n");
5572 rc = ksmbd_vfs_link(work, target_name, link_name);
5576 if (!IS_ERR(link_name))
5582 static int set_file_basic_info(struct ksmbd_file *fp,
5583 struct smb2_file_basic_info *file_info,
5584 struct ksmbd_share_config *share)
5588 struct inode *inode;
5589 struct user_namespace *user_ns;
5592 if (!(fp->daccess & FILE_WRITE_ATTRIBUTES_LE))
5597 inode = file_inode(filp);
5598 user_ns = file_mnt_user_ns(filp);
5600 if (file_info->CreationTime)
5601 fp->create_time = le64_to_cpu(file_info->CreationTime);
5603 if (file_info->LastAccessTime) {
5604 attrs.ia_atime = ksmbd_NTtimeToUnix(file_info->LastAccessTime);
5605 attrs.ia_valid |= (ATTR_ATIME | ATTR_ATIME_SET);
5608 attrs.ia_valid |= ATTR_CTIME;
5609 if (file_info->ChangeTime)
5610 attrs.ia_ctime = ksmbd_NTtimeToUnix(file_info->ChangeTime);
5612 attrs.ia_ctime = inode->i_ctime;
5614 if (file_info->LastWriteTime) {
5615 attrs.ia_mtime = ksmbd_NTtimeToUnix(file_info->LastWriteTime);
5616 attrs.ia_valid |= (ATTR_MTIME | ATTR_MTIME_SET);
5619 if (file_info->Attributes) {
5620 if (!S_ISDIR(inode->i_mode) &&
5621 file_info->Attributes & FILE_ATTRIBUTE_DIRECTORY_LE) {
5622 pr_err("can't change a file to a directory\n");
5626 if (!(S_ISDIR(inode->i_mode) && file_info->Attributes == FILE_ATTRIBUTE_NORMAL_LE))
5627 fp->f_ci->m_fattr = file_info->Attributes |
5628 (fp->f_ci->m_fattr & FILE_ATTRIBUTE_DIRECTORY_LE);
5631 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_STORE_DOS_ATTRS) &&
5632 (file_info->CreationTime || file_info->Attributes)) {
5633 struct xattr_dos_attrib da = {0};
5636 da.itime = fp->itime;
5637 da.create_time = fp->create_time;
5638 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
5639 da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
5640 XATTR_DOSINFO_ITIME;
5642 rc = ksmbd_vfs_set_dos_attrib_xattr(user_ns,
5643 filp->f_path.dentry, &da);
5646 "failed to restore file attribute in EA\n");
5650 if (attrs.ia_valid) {
5651 struct dentry *dentry = filp->f_path.dentry;
5652 struct inode *inode = d_inode(dentry);
5654 if (IS_IMMUTABLE(inode) || IS_APPEND(inode))
5658 inode->i_ctime = attrs.ia_ctime;
5659 attrs.ia_valid &= ~ATTR_CTIME;
5660 rc = notify_change(user_ns, dentry, &attrs, NULL);
5661 inode_unlock(inode);
5666 static int set_file_allocation_info(struct ksmbd_work *work,
5667 struct ksmbd_file *fp,
5668 struct smb2_file_alloc_info *file_alloc_info)
5671 * TODO : It's working fine only when store dos attributes
5672 * is not yes. need to implement a logic which works
5673 * properly with any smb.conf option
5677 struct inode *inode;
5680 if (!(fp->daccess & FILE_WRITE_DATA_LE))
5683 alloc_blks = (le64_to_cpu(file_alloc_info->AllocationSize) + 511) >> 9;
5684 inode = file_inode(fp->filp);
5686 if (alloc_blks > inode->i_blocks) {
5687 smb_break_all_levII_oplock(work, fp, 1);
5688 rc = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
5690 if (rc && rc != -EOPNOTSUPP) {
5691 pr_err("vfs_fallocate is failed : %d\n", rc);
5694 } else if (alloc_blks < inode->i_blocks) {
5698 * Allocation size could be smaller than original one
5699 * which means allocated blocks in file should be
5700 * deallocated. use truncate to cut out it, but inode
5701 * size is also updated with truncate offset.
5702 * inode size is retained by backup inode size.
5704 size = i_size_read(inode);
5705 rc = ksmbd_vfs_truncate(work, fp, alloc_blks * 512);
5707 pr_err("truncate failed!, err %d\n", rc);
5710 if (size < alloc_blks * 512)
5711 i_size_write(inode, size);
5716 static int set_end_of_file_info(struct ksmbd_work *work, struct ksmbd_file *fp,
5717 struct smb2_file_eof_info *file_eof_info)
5720 struct inode *inode;
5723 if (!(fp->daccess & FILE_WRITE_DATA_LE))
5726 newsize = le64_to_cpu(file_eof_info->EndOfFile);
5727 inode = file_inode(fp->filp);
5730 * If FILE_END_OF_FILE_INFORMATION of set_info_file is called
5731 * on FAT32 shared device, truncate execution time is too long
5732 * and network error could cause from windows client. because
5733 * truncate of some filesystem like FAT32 fill zero data in
5736 if (inode->i_sb->s_magic != MSDOS_SUPER_MAGIC) {
5737 ksmbd_debug(SMB, "truncated to newsize %lld\n", newsize);
5738 rc = ksmbd_vfs_truncate(work, fp, newsize);
5740 ksmbd_debug(SMB, "truncate failed!, err %d\n", rc);
5749 static int set_rename_info(struct ksmbd_work *work, struct ksmbd_file *fp,
5750 struct smb2_file_rename_info *rename_info,
5751 unsigned int buf_len)
5753 struct user_namespace *user_ns;
5754 struct ksmbd_file *parent_fp;
5755 struct dentry *parent;
5756 struct dentry *dentry = fp->filp->f_path.dentry;
5759 if (!(fp->daccess & FILE_DELETE_LE)) {
5760 pr_err("no right to delete : 0x%x\n", fp->daccess);
5764 if (buf_len < (u64)sizeof(struct smb2_file_rename_info) +
5765 le32_to_cpu(rename_info->FileNameLength))
5768 user_ns = file_mnt_user_ns(fp->filp);
5769 if (ksmbd_stream_fd(fp))
5772 parent = dget_parent(dentry);
5773 ret = ksmbd_vfs_lock_parent(user_ns, parent, dentry);
5779 parent_fp = ksmbd_lookup_fd_inode(d_inode(parent));
5780 inode_unlock(d_inode(parent));
5784 if (parent_fp->daccess & FILE_DELETE_LE) {
5785 pr_err("parent dir is opened with delete access\n");
5786 ksmbd_fd_put(work, parent_fp);
5789 ksmbd_fd_put(work, parent_fp);
5792 return smb2_rename(work, fp, user_ns, rename_info,
5793 work->conn->local_nls);
5796 static int set_file_disposition_info(struct ksmbd_file *fp,
5797 struct smb2_file_disposition_info *file_info)
5799 struct inode *inode;
5801 if (!(fp->daccess & FILE_DELETE_LE)) {
5802 pr_err("no right to delete : 0x%x\n", fp->daccess);
5806 inode = file_inode(fp->filp);
5807 if (file_info->DeletePending) {
5808 if (S_ISDIR(inode->i_mode) &&
5809 ksmbd_vfs_empty_dir(fp) == -ENOTEMPTY)
5811 ksmbd_set_inode_pending_delete(fp);
5813 ksmbd_clear_inode_pending_delete(fp);
5818 static int set_file_position_info(struct ksmbd_file *fp,
5819 struct smb2_file_pos_info *file_info)
5821 loff_t current_byte_offset;
5822 unsigned long sector_size;
5823 struct inode *inode;
5825 inode = file_inode(fp->filp);
5826 current_byte_offset = le64_to_cpu(file_info->CurrentByteOffset);
5827 sector_size = inode->i_sb->s_blocksize;
5829 if (current_byte_offset < 0 ||
5830 (fp->coption == FILE_NO_INTERMEDIATE_BUFFERING_LE &&
5831 current_byte_offset & (sector_size - 1))) {
5832 pr_err("CurrentByteOffset is not valid : %llu\n",
5833 current_byte_offset);
5837 fp->filp->f_pos = current_byte_offset;
5841 static int set_file_mode_info(struct ksmbd_file *fp,
5842 struct smb2_file_mode_info *file_info)
5846 mode = file_info->Mode;
5848 if ((mode & ~FILE_MODE_INFO_MASK)) {
5849 pr_err("Mode is not valid : 0x%x\n", le32_to_cpu(mode));
5854 * TODO : need to implement consideration for
5855 * FILE_SYNCHRONOUS_IO_ALERT and FILE_SYNCHRONOUS_IO_NONALERT
5857 ksmbd_vfs_set_fadvise(fp->filp, mode);
5863 * smb2_set_info_file() - handler for smb2 set info command
5864 * @work: smb work containing set info command buffer
5865 * @fp: ksmbd_file pointer
5866 * @req: request buffer pointer
5867 * @share: ksmbd_share_config pointer
5869 * Return: 0 on success, otherwise error
5870 * TODO: need to implement an error handling for STATUS_INFO_LENGTH_MISMATCH
5872 static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp,
5873 struct smb2_set_info_req *req,
5874 struct ksmbd_share_config *share)
5876 unsigned int buf_len = le32_to_cpu(req->BufferLength);
5878 switch (req->FileInfoClass) {
5879 case FILE_BASIC_INFORMATION:
5881 if (buf_len < sizeof(struct smb2_file_basic_info))
5884 return set_file_basic_info(fp, (struct smb2_file_basic_info *)req->Buffer, share);
5886 case FILE_ALLOCATION_INFORMATION:
5888 if (buf_len < sizeof(struct smb2_file_alloc_info))
5891 return set_file_allocation_info(work, fp,
5892 (struct smb2_file_alloc_info *)req->Buffer);
5894 case FILE_END_OF_FILE_INFORMATION:
5896 if (buf_len < sizeof(struct smb2_file_eof_info))
5899 return set_end_of_file_info(work, fp,
5900 (struct smb2_file_eof_info *)req->Buffer);
5902 case FILE_RENAME_INFORMATION:
5904 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
5906 "User does not have write permission\n");
5910 if (buf_len < sizeof(struct smb2_file_rename_info))
5913 return set_rename_info(work, fp,
5914 (struct smb2_file_rename_info *)req->Buffer,
5917 case FILE_LINK_INFORMATION:
5919 if (buf_len < sizeof(struct smb2_file_link_info))
5922 return smb2_create_link(work, work->tcon->share_conf,
5923 (struct smb2_file_link_info *)req->Buffer,
5925 work->conn->local_nls);
5927 case FILE_DISPOSITION_INFORMATION:
5929 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
5931 "User does not have write permission\n");
5935 if (buf_len < sizeof(struct smb2_file_disposition_info))
5938 return set_file_disposition_info(fp,
5939 (struct smb2_file_disposition_info *)req->Buffer);
5941 case FILE_FULL_EA_INFORMATION:
5943 if (!(fp->daccess & FILE_WRITE_EA_LE)) {
5944 pr_err("Not permitted to write ext attr: 0x%x\n",
5949 if (buf_len < sizeof(struct smb2_ea_info))
5952 return smb2_set_ea((struct smb2_ea_info *)req->Buffer,
5953 buf_len, &fp->filp->f_path);
5955 case FILE_POSITION_INFORMATION:
5957 if (buf_len < sizeof(struct smb2_file_pos_info))
5960 return set_file_position_info(fp, (struct smb2_file_pos_info *)req->Buffer);
5962 case FILE_MODE_INFORMATION:
5964 if (buf_len < sizeof(struct smb2_file_mode_info))
5967 return set_file_mode_info(fp, (struct smb2_file_mode_info *)req->Buffer);
5971 pr_err("Unimplemented Fileinfoclass :%d\n", req->FileInfoClass);
5975 static int smb2_set_info_sec(struct ksmbd_file *fp, int addition_info,
5976 char *buffer, int buf_len)
5978 struct smb_ntsd *pntsd = (struct smb_ntsd *)buffer;
5980 fp->saccess |= FILE_SHARE_DELETE_LE;
5982 return set_info_sec(fp->conn, fp->tcon, &fp->filp->f_path, pntsd,
5987 * smb2_set_info() - handler for smb2 set info command handler
5988 * @work: smb work containing set info request buffer
5990 * Return: 0 on success, otherwise error
5992 int smb2_set_info(struct ksmbd_work *work)
5994 struct smb2_set_info_req *req;
5995 struct smb2_set_info_rsp *rsp;
5996 struct ksmbd_file *fp;
5998 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
6000 ksmbd_debug(SMB, "Received set info request\n");
6002 if (work->next_smb2_rcv_hdr_off) {
6003 req = ksmbd_req_buf_next(work);
6004 rsp = ksmbd_resp_buf_next(work);
6005 if (!has_file_id(req->VolatileFileId)) {
6006 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
6007 work->compound_fid);
6008 id = work->compound_fid;
6009 pid = work->compound_pfid;
6012 req = smb2_get_msg(work->request_buf);
6013 rsp = smb2_get_msg(work->response_buf);
6016 if (!has_file_id(id)) {
6017 id = req->VolatileFileId;
6018 pid = req->PersistentFileId;
6021 fp = ksmbd_lookup_fd_slow(work, id, pid);
6023 ksmbd_debug(SMB, "Invalid id for close: %u\n", id);
6028 switch (req->InfoType) {
6029 case SMB2_O_INFO_FILE:
6030 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
6031 rc = smb2_set_info_file(work, fp, req, work->tcon->share_conf);
6033 case SMB2_O_INFO_SECURITY:
6034 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
6035 if (ksmbd_override_fsids(work)) {
6039 rc = smb2_set_info_sec(fp,
6040 le32_to_cpu(req->AdditionalInformation),
6042 le32_to_cpu(req->BufferLength));
6043 ksmbd_revert_fsids(work);
6052 rsp->StructureSize = cpu_to_le16(2);
6053 inc_rfc1001_len(work->response_buf, 2);
6054 ksmbd_fd_put(work, fp);
6058 if (rc == -EACCES || rc == -EPERM || rc == -EXDEV)
6059 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6060 else if (rc == -EINVAL)
6061 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6062 else if (rc == -ESHARE)
6063 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6064 else if (rc == -ENOENT)
6065 rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
6066 else if (rc == -EBUSY || rc == -ENOTEMPTY)
6067 rsp->hdr.Status = STATUS_DIRECTORY_NOT_EMPTY;
6068 else if (rc == -EAGAIN)
6069 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6070 else if (rc == -EBADF || rc == -ESTALE)
6071 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6072 else if (rc == -EEXIST)
6073 rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
6074 else if (rsp->hdr.Status == 0 || rc == -EOPNOTSUPP)
6075 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
6076 smb2_set_err_rsp(work);
6077 ksmbd_fd_put(work, fp);
6078 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n", rc);
6083 * smb2_read_pipe() - handler for smb2 read from IPC pipe
6084 * @work: smb work containing read IPC pipe command buffer
6086 * Return: 0 on success, otherwise error
6088 static noinline int smb2_read_pipe(struct ksmbd_work *work)
6090 int nbytes = 0, err;
6092 struct ksmbd_rpc_command *rpc_resp;
6093 struct smb2_read_req *req = smb2_get_msg(work->request_buf);
6094 struct smb2_read_rsp *rsp = smb2_get_msg(work->response_buf);
6096 id = req->VolatileFileId;
6098 inc_rfc1001_len(work->response_buf, 16);
6099 rpc_resp = ksmbd_rpc_read(work->sess, id);
6101 if (rpc_resp->flags != KSMBD_RPC_OK) {
6106 work->aux_payload_buf =
6107 kvmalloc(rpc_resp->payload_sz, GFP_KERNEL | __GFP_ZERO);
6108 if (!work->aux_payload_buf) {
6113 memcpy(work->aux_payload_buf, rpc_resp->payload,
6114 rpc_resp->payload_sz);
6116 nbytes = rpc_resp->payload_sz;
6117 work->resp_hdr_sz = get_rfc1002_len(work->response_buf) + 4;
6118 work->aux_payload_sz = nbytes;
6122 rsp->StructureSize = cpu_to_le16(17);
6123 rsp->DataOffset = 80;
6125 rsp->DataLength = cpu_to_le32(nbytes);
6126 rsp->DataRemaining = 0;
6128 inc_rfc1001_len(work->response_buf, nbytes);
6132 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
6133 smb2_set_err_rsp(work);
6138 static int smb2_set_remote_key_for_rdma(struct ksmbd_work *work,
6139 struct smb2_buffer_desc_v1 *desc,
6141 __le16 ChannelInfoLength)
6143 unsigned int i, ch_count;
6145 if (work->conn->dialect == SMB30_PROT_ID &&
6146 Channel != SMB2_CHANNEL_RDMA_V1)
6149 ch_count = le16_to_cpu(ChannelInfoLength) / sizeof(*desc);
6150 if (ksmbd_debug_types & KSMBD_DEBUG_RDMA) {
6151 for (i = 0; i < ch_count; i++) {
6152 pr_info("RDMA r/w request %#x: token %#x, length %#x\n",
6154 le32_to_cpu(desc[i].token),
6155 le32_to_cpu(desc[i].length));
6161 work->need_invalidate_rkey =
6162 (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE);
6163 if (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE)
6164 work->remote_key = le32_to_cpu(desc->token);
6168 static ssize_t smb2_read_rdma_channel(struct ksmbd_work *work,
6169 struct smb2_read_req *req, void *data_buf,
6174 err = ksmbd_conn_rdma_write(work->conn, data_buf, length,
6175 (struct smb2_buffer_desc_v1 *)
6176 ((char *)req + le16_to_cpu(req->ReadChannelInfoOffset)),
6177 le16_to_cpu(req->ReadChannelInfoLength));
6185 * smb2_read() - handler for smb2 read from file
6186 * @work: smb work containing read command buffer
6188 * Return: 0 on success, otherwise error
6190 int smb2_read(struct ksmbd_work *work)
6192 struct ksmbd_conn *conn = work->conn;
6193 struct smb2_read_req *req;
6194 struct smb2_read_rsp *rsp;
6195 struct ksmbd_file *fp = NULL;
6197 size_t length, mincount;
6198 ssize_t nbytes = 0, remain_bytes = 0;
6200 bool is_rdma_channel = false;
6201 unsigned int max_read_size = conn->vals->max_read_size;
6203 WORK_BUFFERS(work, req, rsp);
6205 if (test_share_config_flag(work->tcon->share_conf,
6206 KSMBD_SHARE_FLAG_PIPE)) {
6207 ksmbd_debug(SMB, "IPC pipe read request\n");
6208 return smb2_read_pipe(work);
6211 if (req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE ||
6212 req->Channel == SMB2_CHANNEL_RDMA_V1) {
6213 is_rdma_channel = true;
6214 max_read_size = get_smbd_max_read_write_size();
6217 if (is_rdma_channel == true) {
6218 unsigned int ch_offset = le16_to_cpu(req->ReadChannelInfoOffset);
6220 if (ch_offset < offsetof(struct smb2_read_req, Buffer)) {
6224 err = smb2_set_remote_key_for_rdma(work,
6225 (struct smb2_buffer_desc_v1 *)
6226 ((char *)req + ch_offset),
6228 req->ReadChannelInfoLength);
6233 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
6239 if (!(fp->daccess & (FILE_READ_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
6240 pr_err("Not permitted to read : 0x%x\n", fp->daccess);
6245 offset = le64_to_cpu(req->Offset);
6246 length = le32_to_cpu(req->Length);
6247 mincount = le32_to_cpu(req->MinimumCount);
6249 if (length > max_read_size) {
6250 ksmbd_debug(SMB, "limiting read size to max size(%u)\n",
6256 ksmbd_debug(SMB, "filename %pd, offset %lld, len %zu\n",
6257 fp->filp->f_path.dentry, offset, length);
6259 work->aux_payload_buf = kvmalloc(length, GFP_KERNEL | __GFP_ZERO);
6260 if (!work->aux_payload_buf) {
6265 nbytes = ksmbd_vfs_read(work, fp, length, &offset);
6271 if ((nbytes == 0 && length != 0) || nbytes < mincount) {
6272 kvfree(work->aux_payload_buf);
6273 work->aux_payload_buf = NULL;
6274 rsp->hdr.Status = STATUS_END_OF_FILE;
6275 smb2_set_err_rsp(work);
6276 ksmbd_fd_put(work, fp);
6280 ksmbd_debug(SMB, "nbytes %zu, offset %lld mincount %zu\n",
6281 nbytes, offset, mincount);
6283 if (is_rdma_channel == true) {
6284 /* write data to the client using rdma channel */
6285 remain_bytes = smb2_read_rdma_channel(work, req,
6286 work->aux_payload_buf,
6288 kvfree(work->aux_payload_buf);
6289 work->aux_payload_buf = NULL;
6292 if (remain_bytes < 0) {
6293 err = (int)remain_bytes;
6298 rsp->StructureSize = cpu_to_le16(17);
6299 rsp->DataOffset = 80;
6301 rsp->DataLength = cpu_to_le32(nbytes);
6302 rsp->DataRemaining = cpu_to_le32(remain_bytes);
6304 inc_rfc1001_len(work->response_buf, 16);
6305 work->resp_hdr_sz = get_rfc1002_len(work->response_buf) + 4;
6306 work->aux_payload_sz = nbytes;
6307 inc_rfc1001_len(work->response_buf, nbytes);
6308 ksmbd_fd_put(work, fp);
6314 rsp->hdr.Status = STATUS_INVALID_DEVICE_REQUEST;
6315 else if (err == -EAGAIN)
6316 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6317 else if (err == -ENOENT)
6318 rsp->hdr.Status = STATUS_FILE_CLOSED;
6319 else if (err == -EACCES)
6320 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6321 else if (err == -ESHARE)
6322 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6323 else if (err == -EINVAL)
6324 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6326 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6328 smb2_set_err_rsp(work);
6330 ksmbd_fd_put(work, fp);
6335 * smb2_write_pipe() - handler for smb2 write on IPC pipe
6336 * @work: smb work containing write IPC pipe command buffer
6338 * Return: 0 on success, otherwise error
6340 static noinline int smb2_write_pipe(struct ksmbd_work *work)
6342 struct smb2_write_req *req = smb2_get_msg(work->request_buf);
6343 struct smb2_write_rsp *rsp = smb2_get_msg(work->response_buf);
6344 struct ksmbd_rpc_command *rpc_resp;
6346 int err = 0, ret = 0;
6350 length = le32_to_cpu(req->Length);
6351 id = req->VolatileFileId;
6353 if ((u64)le16_to_cpu(req->DataOffset) + length >
6354 get_rfc1002_len(work->request_buf)) {
6355 pr_err("invalid write data offset %u, smb_len %u\n",
6356 le16_to_cpu(req->DataOffset),
6357 get_rfc1002_len(work->request_buf));
6362 data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
6363 le16_to_cpu(req->DataOffset));
6365 rpc_resp = ksmbd_rpc_write(work->sess, id, data_buf, length);
6367 if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
6368 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
6370 smb2_set_err_rsp(work);
6373 if (rpc_resp->flags != KSMBD_RPC_OK) {
6374 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6375 smb2_set_err_rsp(work);
6382 rsp->StructureSize = cpu_to_le16(17);
6383 rsp->DataOffset = 0;
6385 rsp->DataLength = cpu_to_le32(length);
6386 rsp->DataRemaining = 0;
6388 inc_rfc1001_len(work->response_buf, 16);
6392 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6393 smb2_set_err_rsp(work);
6399 static ssize_t smb2_write_rdma_channel(struct ksmbd_work *work,
6400 struct smb2_write_req *req,
6401 struct ksmbd_file *fp,
6402 loff_t offset, size_t length, bool sync)
6408 data_buf = kvmalloc(length, GFP_KERNEL | __GFP_ZERO);
6412 ret = ksmbd_conn_rdma_read(work->conn, data_buf, length,
6413 (struct smb2_buffer_desc_v1 *)
6414 ((char *)req + le16_to_cpu(req->WriteChannelInfoOffset)),
6415 le16_to_cpu(req->WriteChannelInfoLength));
6421 ret = ksmbd_vfs_write(work, fp, data_buf, length, &offset, sync, &nbytes);
6430 * smb2_write() - handler for smb2 write from file
6431 * @work: smb work containing write command buffer
6433 * Return: 0 on success, otherwise error
6435 int smb2_write(struct ksmbd_work *work)
6437 struct smb2_write_req *req;
6438 struct smb2_write_rsp *rsp;
6439 struct ksmbd_file *fp = NULL;
6444 bool writethrough = false, is_rdma_channel = false;
6446 unsigned int max_write_size = work->conn->vals->max_write_size;
6448 WORK_BUFFERS(work, req, rsp);
6450 if (test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_PIPE)) {
6451 ksmbd_debug(SMB, "IPC pipe write request\n");
6452 return smb2_write_pipe(work);
6455 offset = le64_to_cpu(req->Offset);
6456 length = le32_to_cpu(req->Length);
6458 if (req->Channel == SMB2_CHANNEL_RDMA_V1 ||
6459 req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE) {
6460 is_rdma_channel = true;
6461 max_write_size = get_smbd_max_read_write_size();
6462 length = le32_to_cpu(req->RemainingBytes);
6465 if (is_rdma_channel == true) {
6466 unsigned int ch_offset = le16_to_cpu(req->WriteChannelInfoOffset);
6468 if (req->Length != 0 || req->DataOffset != 0 ||
6469 ch_offset < offsetof(struct smb2_write_req, Buffer)) {
6473 err = smb2_set_remote_key_for_rdma(work,
6474 (struct smb2_buffer_desc_v1 *)
6475 ((char *)req + ch_offset),
6477 req->WriteChannelInfoLength);
6482 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
6483 ksmbd_debug(SMB, "User does not have write permission\n");
6488 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
6494 if (!(fp->daccess & (FILE_WRITE_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
6495 pr_err("Not permitted to write : 0x%x\n", fp->daccess);
6500 if (length > max_write_size) {
6501 ksmbd_debug(SMB, "limiting write size to max size(%u)\n",
6507 ksmbd_debug(SMB, "flags %u\n", le32_to_cpu(req->Flags));
6508 if (le32_to_cpu(req->Flags) & SMB2_WRITEFLAG_WRITE_THROUGH)
6509 writethrough = true;
6511 if (is_rdma_channel == false) {
6512 if ((u64)le16_to_cpu(req->DataOffset) + length >
6513 get_rfc1002_len(work->request_buf)) {
6514 pr_err("invalid write data offset %u, smb_len %u\n",
6515 le16_to_cpu(req->DataOffset),
6516 get_rfc1002_len(work->request_buf));
6520 data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
6521 le16_to_cpu(req->DataOffset));
6523 ksmbd_debug(SMB, "filename %pd, offset %lld, len %zu\n",
6524 fp->filp->f_path.dentry, offset, length);
6525 err = ksmbd_vfs_write(work, fp, data_buf, length, &offset,
6526 writethrough, &nbytes);
6530 /* read data from the client using rdma channel, and
6533 nbytes = smb2_write_rdma_channel(work, req, fp, offset, length,
6541 rsp->StructureSize = cpu_to_le16(17);
6542 rsp->DataOffset = 0;
6544 rsp->DataLength = cpu_to_le32(nbytes);
6545 rsp->DataRemaining = 0;
6547 inc_rfc1001_len(work->response_buf, 16);
6548 ksmbd_fd_put(work, fp);
6553 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6554 else if (err == -ENOSPC || err == -EFBIG)
6555 rsp->hdr.Status = STATUS_DISK_FULL;
6556 else if (err == -ENOENT)
6557 rsp->hdr.Status = STATUS_FILE_CLOSED;
6558 else if (err == -EACCES)
6559 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6560 else if (err == -ESHARE)
6561 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6562 else if (err == -EINVAL)
6563 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6565 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6567 smb2_set_err_rsp(work);
6568 ksmbd_fd_put(work, fp);
6573 * smb2_flush() - handler for smb2 flush file - fsync
6574 * @work: smb work containing flush command buffer
6576 * Return: 0 on success, otherwise error
6578 int smb2_flush(struct ksmbd_work *work)
6580 struct smb2_flush_req *req;
6581 struct smb2_flush_rsp *rsp;
6584 WORK_BUFFERS(work, req, rsp);
6586 ksmbd_debug(SMB, "SMB2_FLUSH called for fid %llu\n", req->VolatileFileId);
6588 err = ksmbd_vfs_fsync(work, req->VolatileFileId, req->PersistentFileId);
6592 rsp->StructureSize = cpu_to_le16(4);
6594 inc_rfc1001_len(work->response_buf, 4);
6599 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6600 smb2_set_err_rsp(work);
6607 * smb2_cancel() - handler for smb2 cancel command
6608 * @work: smb work containing cancel command buffer
6610 * Return: 0 on success, otherwise error
6612 int smb2_cancel(struct ksmbd_work *work)
6614 struct ksmbd_conn *conn = work->conn;
6615 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
6616 struct smb2_hdr *chdr;
6617 struct ksmbd_work *cancel_work = NULL, *iter;
6618 struct list_head *command_list;
6620 ksmbd_debug(SMB, "smb2 cancel called on mid %llu, async flags 0x%x\n",
6621 hdr->MessageId, hdr->Flags);
6623 if (hdr->Flags & SMB2_FLAGS_ASYNC_COMMAND) {
6624 command_list = &conn->async_requests;
6626 spin_lock(&conn->request_lock);
6627 list_for_each_entry(iter, command_list,
6628 async_request_entry) {
6629 chdr = smb2_get_msg(iter->request_buf);
6631 if (iter->async_id !=
6632 le64_to_cpu(hdr->Id.AsyncId))
6636 "smb2 with AsyncId %llu cancelled command = 0x%x\n",
6637 le64_to_cpu(hdr->Id.AsyncId),
6638 le16_to_cpu(chdr->Command));
6642 spin_unlock(&conn->request_lock);
6644 command_list = &conn->requests;
6646 spin_lock(&conn->request_lock);
6647 list_for_each_entry(iter, command_list, request_entry) {
6648 chdr = smb2_get_msg(iter->request_buf);
6650 if (chdr->MessageId != hdr->MessageId ||
6655 "smb2 with mid %llu cancelled command = 0x%x\n",
6656 le64_to_cpu(hdr->MessageId),
6657 le16_to_cpu(chdr->Command));
6661 spin_unlock(&conn->request_lock);
6665 cancel_work->state = KSMBD_WORK_CANCELLED;
6666 if (cancel_work->cancel_fn)
6667 cancel_work->cancel_fn(cancel_work->cancel_argv);
6670 /* For SMB2_CANCEL command itself send no response*/
6671 work->send_no_response = 1;
6675 struct file_lock *smb_flock_init(struct file *f)
6677 struct file_lock *fl;
6679 fl = locks_alloc_lock();
6683 locks_init_lock(fl);
6686 fl->fl_pid = current->tgid;
6688 fl->fl_flags = FL_POSIX;
6690 fl->fl_lmops = NULL;
6696 static int smb2_set_flock_flags(struct file_lock *flock, int flags)
6700 /* Checking for wrong flag combination during lock request*/
6702 case SMB2_LOCKFLAG_SHARED:
6703 ksmbd_debug(SMB, "received shared request\n");
6705 flock->fl_type = F_RDLCK;
6706 flock->fl_flags |= FL_SLEEP;
6708 case SMB2_LOCKFLAG_EXCLUSIVE:
6709 ksmbd_debug(SMB, "received exclusive request\n");
6711 flock->fl_type = F_WRLCK;
6712 flock->fl_flags |= FL_SLEEP;
6714 case SMB2_LOCKFLAG_SHARED | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
6716 "received shared & fail immediately request\n");
6718 flock->fl_type = F_RDLCK;
6720 case SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
6722 "received exclusive & fail immediately request\n");
6724 flock->fl_type = F_WRLCK;
6726 case SMB2_LOCKFLAG_UNLOCK:
6727 ksmbd_debug(SMB, "received unlock request\n");
6728 flock->fl_type = F_UNLCK;
6736 static struct ksmbd_lock *smb2_lock_init(struct file_lock *flock,
6737 unsigned int cmd, int flags,
6738 struct list_head *lock_list)
6740 struct ksmbd_lock *lock;
6742 lock = kzalloc(sizeof(struct ksmbd_lock), GFP_KERNEL);
6748 lock->start = flock->fl_start;
6749 lock->end = flock->fl_end;
6750 lock->flags = flags;
6751 if (lock->start == lock->end)
6753 INIT_LIST_HEAD(&lock->clist);
6754 INIT_LIST_HEAD(&lock->flist);
6755 INIT_LIST_HEAD(&lock->llist);
6756 list_add_tail(&lock->llist, lock_list);
6761 static void smb2_remove_blocked_lock(void **argv)
6763 struct file_lock *flock = (struct file_lock *)argv[0];
6765 ksmbd_vfs_posix_lock_unblock(flock);
6766 wake_up(&flock->fl_wait);
6769 static inline bool lock_defer_pending(struct file_lock *fl)
6771 /* check pending lock waiters */
6772 return waitqueue_active(&fl->fl_wait);
6776 * smb2_lock() - handler for smb2 file lock command
6777 * @work: smb work containing lock command buffer
6779 * Return: 0 on success, otherwise error
6781 int smb2_lock(struct ksmbd_work *work)
6783 struct smb2_lock_req *req = smb2_get_msg(work->request_buf);
6784 struct smb2_lock_rsp *rsp = smb2_get_msg(work->response_buf);
6785 struct smb2_lock_element *lock_ele;
6786 struct ksmbd_file *fp = NULL;
6787 struct file_lock *flock = NULL;
6788 struct file *filp = NULL;
6792 int err = -EIO, i, rc = 0;
6793 u64 lock_start, lock_length;
6794 struct ksmbd_lock *smb_lock = NULL, *cmp_lock, *tmp, *tmp2;
6795 struct ksmbd_conn *conn;
6797 LIST_HEAD(lock_list);
6798 LIST_HEAD(rollback_list);
6801 ksmbd_debug(SMB, "Received lock request\n");
6802 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
6804 ksmbd_debug(SMB, "Invalid file id for lock : %llu\n", req->VolatileFileId);
6810 lock_count = le16_to_cpu(req->LockCount);
6811 lock_ele = req->locks;
6813 ksmbd_debug(SMB, "lock count is %d\n", lock_count);
6819 for (i = 0; i < lock_count; i++) {
6820 flags = le32_to_cpu(lock_ele[i].Flags);
6822 flock = smb_flock_init(filp);
6826 cmd = smb2_set_flock_flags(flock, flags);
6828 lock_start = le64_to_cpu(lock_ele[i].Offset);
6829 lock_length = le64_to_cpu(lock_ele[i].Length);
6830 if (lock_start > U64_MAX - lock_length) {
6831 pr_err("Invalid lock range requested\n");
6832 rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
6836 if (lock_start > OFFSET_MAX)
6837 flock->fl_start = OFFSET_MAX;
6839 flock->fl_start = lock_start;
6841 lock_length = le64_to_cpu(lock_ele[i].Length);
6842 if (lock_length > OFFSET_MAX - flock->fl_start)
6843 lock_length = OFFSET_MAX - flock->fl_start;
6845 flock->fl_end = flock->fl_start + lock_length;
6847 if (flock->fl_end < flock->fl_start) {
6849 "the end offset(%llx) is smaller than the start offset(%llx)\n",
6850 flock->fl_end, flock->fl_start);
6851 rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
6855 /* Check conflict locks in one request */
6856 list_for_each_entry(cmp_lock, &lock_list, llist) {
6857 if (cmp_lock->fl->fl_start <= flock->fl_start &&
6858 cmp_lock->fl->fl_end >= flock->fl_end) {
6859 if (cmp_lock->fl->fl_type != F_UNLCK &&
6860 flock->fl_type != F_UNLCK) {
6861 pr_err("conflict two locks in one request\n");
6868 smb_lock = smb2_lock_init(flock, cmd, flags, &lock_list);
6875 list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
6876 if (smb_lock->cmd < 0) {
6881 if (!(smb_lock->flags & SMB2_LOCKFLAG_MASK)) {
6886 if ((prior_lock & (SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_SHARED) &&
6887 smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) ||
6888 (prior_lock == SMB2_LOCKFLAG_UNLOCK &&
6889 !(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK))) {
6894 prior_lock = smb_lock->flags;
6896 if (!(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) &&
6897 !(smb_lock->flags & SMB2_LOCKFLAG_FAIL_IMMEDIATELY))
6901 /* check locks in connection list */
6902 read_lock(&conn_list_lock);
6903 list_for_each_entry(conn, &conn_list, conns_list) {
6904 spin_lock(&conn->llist_lock);
6905 list_for_each_entry_safe(cmp_lock, tmp2, &conn->lock_list, clist) {
6906 if (file_inode(cmp_lock->fl->fl_file) !=
6907 file_inode(smb_lock->fl->fl_file))
6910 if (smb_lock->fl->fl_type == F_UNLCK) {
6911 if (cmp_lock->fl->fl_file == smb_lock->fl->fl_file &&
6912 cmp_lock->start == smb_lock->start &&
6913 cmp_lock->end == smb_lock->end &&
6914 !lock_defer_pending(cmp_lock->fl)) {
6916 list_del(&cmp_lock->flist);
6917 list_del(&cmp_lock->clist);
6918 spin_unlock(&conn->llist_lock);
6919 read_unlock(&conn_list_lock);
6921 locks_free_lock(cmp_lock->fl);
6928 if (cmp_lock->fl->fl_file == smb_lock->fl->fl_file) {
6929 if (smb_lock->flags & SMB2_LOCKFLAG_SHARED)
6932 if (cmp_lock->flags & SMB2_LOCKFLAG_SHARED)
6936 /* check zero byte lock range */
6937 if (cmp_lock->zero_len && !smb_lock->zero_len &&
6938 cmp_lock->start > smb_lock->start &&
6939 cmp_lock->start < smb_lock->end) {
6940 spin_unlock(&conn->llist_lock);
6941 read_unlock(&conn_list_lock);
6942 pr_err("previous lock conflict with zero byte lock range\n");
6946 if (smb_lock->zero_len && !cmp_lock->zero_len &&
6947 smb_lock->start > cmp_lock->start &&
6948 smb_lock->start < cmp_lock->end) {
6949 spin_unlock(&conn->llist_lock);
6950 read_unlock(&conn_list_lock);
6951 pr_err("current lock conflict with zero byte lock range\n");
6955 if (((cmp_lock->start <= smb_lock->start &&
6956 cmp_lock->end > smb_lock->start) ||
6957 (cmp_lock->start < smb_lock->end &&
6958 cmp_lock->end >= smb_lock->end)) &&
6959 !cmp_lock->zero_len && !smb_lock->zero_len) {
6960 spin_unlock(&conn->llist_lock);
6961 read_unlock(&conn_list_lock);
6962 pr_err("Not allow lock operation on exclusive lock range\n");
6966 spin_unlock(&conn->llist_lock);
6968 read_unlock(&conn_list_lock);
6970 if (smb_lock->fl->fl_type == F_UNLCK && nolock) {
6971 pr_err("Try to unlock nolocked range\n");
6972 rsp->hdr.Status = STATUS_RANGE_NOT_LOCKED;
6977 if (smb_lock->zero_len) {
6982 flock = smb_lock->fl;
6983 list_del(&smb_lock->llist);
6985 rc = vfs_lock_file(filp, smb_lock->cmd, flock, NULL);
6987 if (flags & SMB2_LOCKFLAG_UNLOCK) {
6989 ksmbd_debug(SMB, "File unlocked\n");
6990 } else if (rc == -ENOENT) {
6991 rsp->hdr.Status = STATUS_NOT_LOCKED;
6994 locks_free_lock(flock);
6997 if (rc == FILE_LOCK_DEFERRED) {
7001 "would have to wait for getting lock\n");
7002 spin_lock(&work->conn->llist_lock);
7003 list_add_tail(&smb_lock->clist,
7004 &work->conn->lock_list);
7005 spin_unlock(&work->conn->llist_lock);
7006 list_add(&smb_lock->llist, &rollback_list);
7008 argv = kmalloc(sizeof(void *), GFP_KERNEL);
7015 rc = setup_async_work(work,
7016 smb2_remove_blocked_lock,
7022 spin_lock(&fp->f_lock);
7023 list_add(&work->fp_entry, &fp->blocked_works);
7024 spin_unlock(&fp->f_lock);
7026 smb2_send_interim_resp(work, STATUS_PENDING);
7028 ksmbd_vfs_posix_lock_wait(flock);
7030 if (work->state != KSMBD_WORK_ACTIVE) {
7031 list_del(&smb_lock->llist);
7032 spin_lock(&work->conn->llist_lock);
7033 list_del(&smb_lock->clist);
7034 spin_unlock(&work->conn->llist_lock);
7035 locks_free_lock(flock);
7037 if (work->state == KSMBD_WORK_CANCELLED) {
7038 spin_lock(&fp->f_lock);
7039 list_del(&work->fp_entry);
7040 spin_unlock(&fp->f_lock);
7044 smb2_send_interim_resp(work,
7046 work->send_no_response = 1;
7049 init_smb2_rsp_hdr(work);
7050 smb2_set_err_rsp(work);
7052 STATUS_RANGE_NOT_LOCKED;
7057 list_del(&smb_lock->llist);
7058 spin_lock(&work->conn->llist_lock);
7059 list_del(&smb_lock->clist);
7060 spin_unlock(&work->conn->llist_lock);
7062 spin_lock(&fp->f_lock);
7063 list_del(&work->fp_entry);
7064 spin_unlock(&fp->f_lock);
7067 spin_lock(&work->conn->llist_lock);
7068 list_add_tail(&smb_lock->clist,
7069 &work->conn->lock_list);
7070 list_add_tail(&smb_lock->flist,
7072 spin_unlock(&work->conn->llist_lock);
7073 list_add(&smb_lock->llist, &rollback_list);
7074 ksmbd_debug(SMB, "successful in taking lock\n");
7081 if (atomic_read(&fp->f_ci->op_count) > 1)
7082 smb_break_all_oplock(work, fp);
7084 rsp->StructureSize = cpu_to_le16(4);
7085 ksmbd_debug(SMB, "successful in taking lock\n");
7086 rsp->hdr.Status = STATUS_SUCCESS;
7088 inc_rfc1001_len(work->response_buf, 4);
7089 ksmbd_fd_put(work, fp);
7093 list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
7094 locks_free_lock(smb_lock->fl);
7095 list_del(&smb_lock->llist);
7099 list_for_each_entry_safe(smb_lock, tmp, &rollback_list, llist) {
7100 struct file_lock *rlock = NULL;
7102 rlock = smb_flock_init(filp);
7103 rlock->fl_type = F_UNLCK;
7104 rlock->fl_start = smb_lock->start;
7105 rlock->fl_end = smb_lock->end;
7107 rc = vfs_lock_file(filp, 0, rlock, NULL);
7109 pr_err("rollback unlock fail : %d\n", rc);
7111 list_del(&smb_lock->llist);
7112 spin_lock(&work->conn->llist_lock);
7113 if (!list_empty(&smb_lock->flist))
7114 list_del(&smb_lock->flist);
7115 list_del(&smb_lock->clist);
7116 spin_unlock(&work->conn->llist_lock);
7118 locks_free_lock(smb_lock->fl);
7119 locks_free_lock(rlock);
7123 ksmbd_debug(SMB, "failed in taking lock(flags : %x), err : %d\n", flags, err);
7125 if (!rsp->hdr.Status) {
7127 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7128 else if (err == -ENOMEM)
7129 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
7130 else if (err == -ENOENT)
7131 rsp->hdr.Status = STATUS_FILE_CLOSED;
7133 rsp->hdr.Status = STATUS_LOCK_NOT_GRANTED;
7136 smb2_set_err_rsp(work);
7137 ksmbd_fd_put(work, fp);
7141 static int fsctl_copychunk(struct ksmbd_work *work,
7142 struct copychunk_ioctl_req *ci_req,
7143 unsigned int cnt_code,
7144 unsigned int input_count,
7145 unsigned long long volatile_id,
7146 unsigned long long persistent_id,
7147 struct smb2_ioctl_rsp *rsp)
7149 struct copychunk_ioctl_rsp *ci_rsp;
7150 struct ksmbd_file *src_fp = NULL, *dst_fp = NULL;
7151 struct srv_copychunk *chunks;
7152 unsigned int i, chunk_count, chunk_count_written = 0;
7153 unsigned int chunk_size_written = 0;
7154 loff_t total_size_written = 0;
7157 ci_rsp = (struct copychunk_ioctl_rsp *)&rsp->Buffer[0];
7159 rsp->VolatileFileId = volatile_id;
7160 rsp->PersistentFileId = persistent_id;
7161 ci_rsp->ChunksWritten =
7162 cpu_to_le32(ksmbd_server_side_copy_max_chunk_count());
7163 ci_rsp->ChunkBytesWritten =
7164 cpu_to_le32(ksmbd_server_side_copy_max_chunk_size());
7165 ci_rsp->TotalBytesWritten =
7166 cpu_to_le32(ksmbd_server_side_copy_max_total_size());
7168 chunks = (struct srv_copychunk *)&ci_req->Chunks[0];
7169 chunk_count = le32_to_cpu(ci_req->ChunkCount);
7170 if (chunk_count == 0)
7172 total_size_written = 0;
7174 /* verify the SRV_COPYCHUNK_COPY packet */
7175 if (chunk_count > ksmbd_server_side_copy_max_chunk_count() ||
7176 input_count < offsetof(struct copychunk_ioctl_req, Chunks) +
7177 chunk_count * sizeof(struct srv_copychunk)) {
7178 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7182 for (i = 0; i < chunk_count; i++) {
7183 if (le32_to_cpu(chunks[i].Length) == 0 ||
7184 le32_to_cpu(chunks[i].Length) > ksmbd_server_side_copy_max_chunk_size())
7186 total_size_written += le32_to_cpu(chunks[i].Length);
7189 if (i < chunk_count ||
7190 total_size_written > ksmbd_server_side_copy_max_total_size()) {
7191 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7195 src_fp = ksmbd_lookup_foreign_fd(work,
7196 le64_to_cpu(ci_req->ResumeKey[0]));
7197 dst_fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
7200 src_fp->persistent_id != le64_to_cpu(ci_req->ResumeKey[1])) {
7201 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
7206 rsp->hdr.Status = STATUS_FILE_CLOSED;
7211 * FILE_READ_DATA should only be included in
7212 * the FSCTL_COPYCHUNK case
7214 if (cnt_code == FSCTL_COPYCHUNK &&
7215 !(dst_fp->daccess & (FILE_READ_DATA_LE | FILE_GENERIC_READ_LE))) {
7216 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7220 ret = ksmbd_vfs_copy_file_ranges(work, src_fp, dst_fp,
7221 chunks, chunk_count,
7222 &chunk_count_written,
7223 &chunk_size_written,
7224 &total_size_written);
7227 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7229 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
7230 else if (ret == -EBADF)
7231 rsp->hdr.Status = STATUS_INVALID_HANDLE;
7232 else if (ret == -EFBIG || ret == -ENOSPC)
7233 rsp->hdr.Status = STATUS_DISK_FULL;
7234 else if (ret == -EINVAL)
7235 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7236 else if (ret == -EISDIR)
7237 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
7238 else if (ret == -E2BIG)
7239 rsp->hdr.Status = STATUS_INVALID_VIEW_SIZE;
7241 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
7244 ci_rsp->ChunksWritten = cpu_to_le32(chunk_count_written);
7245 ci_rsp->ChunkBytesWritten = cpu_to_le32(chunk_size_written);
7246 ci_rsp->TotalBytesWritten = cpu_to_le32(total_size_written);
7248 ksmbd_fd_put(work, src_fp);
7249 ksmbd_fd_put(work, dst_fp);
7253 static __be32 idev_ipv4_address(struct in_device *idev)
7257 struct in_ifaddr *ifa;
7260 in_dev_for_each_ifa_rcu(ifa, idev) {
7261 if (ifa->ifa_flags & IFA_F_SECONDARY)
7264 addr = ifa->ifa_address;
7271 static int fsctl_query_iface_info_ioctl(struct ksmbd_conn *conn,
7272 struct smb2_ioctl_rsp *rsp,
7273 unsigned int out_buf_len)
7275 struct network_interface_info_ioctl_rsp *nii_rsp = NULL;
7277 struct net_device *netdev;
7278 struct sockaddr_storage_rsp *sockaddr_storage;
7280 unsigned long long speed;
7283 for_each_netdev(&init_net, netdev) {
7284 bool ipv4_set = false;
7286 if (netdev->type == ARPHRD_LOOPBACK)
7289 flags = dev_get_flags(netdev);
7290 if (!(flags & IFF_RUNNING))
7294 nbytes + sizeof(struct network_interface_info_ioctl_rsp)) {
7299 nii_rsp = (struct network_interface_info_ioctl_rsp *)
7300 &rsp->Buffer[nbytes];
7301 nii_rsp->IfIndex = cpu_to_le32(netdev->ifindex);
7303 nii_rsp->Capability = 0;
7304 if (netdev->real_num_tx_queues > 1)
7305 nii_rsp->Capability |= cpu_to_le32(RSS_CAPABLE);
7306 if (ksmbd_rdma_capable_netdev(netdev))
7307 nii_rsp->Capability |= cpu_to_le32(RDMA_CAPABLE);
7309 nii_rsp->Next = cpu_to_le32(152);
7310 nii_rsp->Reserved = 0;
7312 if (netdev->ethtool_ops->get_link_ksettings) {
7313 struct ethtool_link_ksettings cmd;
7315 netdev->ethtool_ops->get_link_ksettings(netdev, &cmd);
7316 speed = cmd.base.speed;
7318 ksmbd_debug(SMB, "%s %s\n", netdev->name,
7319 "speed is unknown, defaulting to 1Gb/sec");
7324 nii_rsp->LinkSpeed = cpu_to_le64(speed);
7326 sockaddr_storage = (struct sockaddr_storage_rsp *)
7327 nii_rsp->SockAddr_Storage;
7328 memset(sockaddr_storage, 0, 128);
7331 struct in_device *idev;
7333 sockaddr_storage->Family = cpu_to_le16(INTERNETWORK);
7334 sockaddr_storage->addr4.Port = 0;
7336 idev = __in_dev_get_rtnl(netdev);
7339 sockaddr_storage->addr4.IPv4address =
7340 idev_ipv4_address(idev);
7341 nbytes += sizeof(struct network_interface_info_ioctl_rsp);
7345 struct inet6_dev *idev6;
7346 struct inet6_ifaddr *ifa;
7347 __u8 *ipv6_addr = sockaddr_storage->addr6.IPv6address;
7349 sockaddr_storage->Family = cpu_to_le16(INTERNETWORKV6);
7350 sockaddr_storage->addr6.Port = 0;
7351 sockaddr_storage->addr6.FlowInfo = 0;
7353 idev6 = __in6_dev_get(netdev);
7357 list_for_each_entry(ifa, &idev6->addr_list, if_list) {
7358 if (ifa->flags & (IFA_F_TENTATIVE |
7361 memcpy(ipv6_addr, ifa->addr.s6_addr, 16);
7364 sockaddr_storage->addr6.ScopeId = 0;
7365 nbytes += sizeof(struct network_interface_info_ioctl_rsp);
7370 /* zero if this is last one */
7374 rsp->PersistentFileId = SMB2_NO_FID;
7375 rsp->VolatileFileId = SMB2_NO_FID;
7379 static int fsctl_validate_negotiate_info(struct ksmbd_conn *conn,
7380 struct validate_negotiate_info_req *neg_req,
7381 struct validate_negotiate_info_rsp *neg_rsp,
7382 unsigned int in_buf_len)
7387 if (in_buf_len < offsetof(struct validate_negotiate_info_req, Dialects) +
7388 le16_to_cpu(neg_req->DialectCount) * sizeof(__le16))
7391 dialect = ksmbd_lookup_dialect_by_id(neg_req->Dialects,
7392 neg_req->DialectCount);
7393 if (dialect == BAD_PROT_ID || dialect != conn->dialect) {
7398 if (strncmp(neg_req->Guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE)) {
7403 if (le16_to_cpu(neg_req->SecurityMode) != conn->cli_sec_mode) {
7408 if (le32_to_cpu(neg_req->Capabilities) != conn->cli_cap) {
7413 neg_rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
7414 memset(neg_rsp->Guid, 0, SMB2_CLIENT_GUID_SIZE);
7415 neg_rsp->SecurityMode = cpu_to_le16(conn->srv_sec_mode);
7416 neg_rsp->Dialect = cpu_to_le16(conn->dialect);
7421 static int fsctl_query_allocated_ranges(struct ksmbd_work *work, u64 id,
7422 struct file_allocated_range_buffer *qar_req,
7423 struct file_allocated_range_buffer *qar_rsp,
7424 unsigned int in_count, unsigned int *out_count)
7426 struct ksmbd_file *fp;
7427 loff_t start, length;
7434 fp = ksmbd_lookup_fd_fast(work, id);
7438 start = le64_to_cpu(qar_req->file_offset);
7439 length = le64_to_cpu(qar_req->length);
7441 ret = ksmbd_vfs_fqar_lseek(fp, start, length,
7442 qar_rsp, in_count, out_count);
7443 if (ret && ret != -E2BIG)
7446 ksmbd_fd_put(work, fp);
7450 static int fsctl_pipe_transceive(struct ksmbd_work *work, u64 id,
7451 unsigned int out_buf_len,
7452 struct smb2_ioctl_req *req,
7453 struct smb2_ioctl_rsp *rsp)
7455 struct ksmbd_rpc_command *rpc_resp;
7456 char *data_buf = (char *)&req->Buffer[0];
7459 rpc_resp = ksmbd_rpc_ioctl(work->sess, id, data_buf,
7460 le32_to_cpu(req->InputCount));
7462 if (rpc_resp->flags == KSMBD_RPC_SOME_NOT_MAPPED) {
7464 * set STATUS_SOME_NOT_MAPPED response
7465 * for unknown domain sid.
7467 rsp->hdr.Status = STATUS_SOME_NOT_MAPPED;
7468 } else if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
7469 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7471 } else if (rpc_resp->flags != KSMBD_RPC_OK) {
7472 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7476 nbytes = rpc_resp->payload_sz;
7477 if (rpc_resp->payload_sz > out_buf_len) {
7478 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
7479 nbytes = out_buf_len;
7482 if (!rpc_resp->payload_sz) {
7484 STATUS_UNEXPECTED_IO_ERROR;
7488 memcpy((char *)rsp->Buffer, rpc_resp->payload, nbytes);
7495 static inline int fsctl_set_sparse(struct ksmbd_work *work, u64 id,
7496 struct file_sparse *sparse)
7498 struct ksmbd_file *fp;
7499 struct user_namespace *user_ns;
7503 fp = ksmbd_lookup_fd_fast(work, id);
7506 user_ns = file_mnt_user_ns(fp->filp);
7508 old_fattr = fp->f_ci->m_fattr;
7509 if (sparse->SetSparse)
7510 fp->f_ci->m_fattr |= FILE_ATTRIBUTE_SPARSE_FILE_LE;
7512 fp->f_ci->m_fattr &= ~FILE_ATTRIBUTE_SPARSE_FILE_LE;
7514 if (fp->f_ci->m_fattr != old_fattr &&
7515 test_share_config_flag(work->tcon->share_conf,
7516 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS)) {
7517 struct xattr_dos_attrib da;
7519 ret = ksmbd_vfs_get_dos_attrib_xattr(user_ns,
7520 fp->filp->f_path.dentry, &da);
7524 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
7525 ret = ksmbd_vfs_set_dos_attrib_xattr(user_ns,
7526 fp->filp->f_path.dentry, &da);
7528 fp->f_ci->m_fattr = old_fattr;
7532 ksmbd_fd_put(work, fp);
7536 static int fsctl_request_resume_key(struct ksmbd_work *work,
7537 struct smb2_ioctl_req *req,
7538 struct resume_key_ioctl_rsp *key_rsp)
7540 struct ksmbd_file *fp;
7542 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
7546 memset(key_rsp, 0, sizeof(*key_rsp));
7547 key_rsp->ResumeKey[0] = req->VolatileFileId;
7548 key_rsp->ResumeKey[1] = req->PersistentFileId;
7549 ksmbd_fd_put(work, fp);
7555 * smb2_ioctl() - handler for smb2 ioctl command
7556 * @work: smb work containing ioctl command buffer
7558 * Return: 0 on success, otherwise error
7560 int smb2_ioctl(struct ksmbd_work *work)
7562 struct smb2_ioctl_req *req;
7563 struct smb2_ioctl_rsp *rsp;
7564 unsigned int cnt_code, nbytes = 0, out_buf_len, in_buf_len;
7565 u64 id = KSMBD_NO_FID;
7566 struct ksmbd_conn *conn = work->conn;
7569 if (work->next_smb2_rcv_hdr_off) {
7570 req = ksmbd_req_buf_next(work);
7571 rsp = ksmbd_resp_buf_next(work);
7572 if (!has_file_id(req->VolatileFileId)) {
7573 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
7574 work->compound_fid);
7575 id = work->compound_fid;
7578 req = smb2_get_msg(work->request_buf);
7579 rsp = smb2_get_msg(work->response_buf);
7582 if (!has_file_id(id))
7583 id = req->VolatileFileId;
7585 if (req->Flags != cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL)) {
7586 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7590 cnt_code = le32_to_cpu(req->CtlCode);
7591 ret = smb2_calc_max_out_buf_len(work, 48,
7592 le32_to_cpu(req->MaxOutputResponse));
7594 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7597 out_buf_len = (unsigned int)ret;
7598 in_buf_len = le32_to_cpu(req->InputCount);
7601 case FSCTL_DFS_GET_REFERRALS:
7602 case FSCTL_DFS_GET_REFERRALS_EX:
7603 /* Not support DFS yet */
7604 rsp->hdr.Status = STATUS_FS_DRIVER_REQUIRED;
7606 case FSCTL_CREATE_OR_GET_OBJECT_ID:
7608 struct file_object_buf_type1_ioctl_rsp *obj_buf;
7610 nbytes = sizeof(struct file_object_buf_type1_ioctl_rsp);
7611 obj_buf = (struct file_object_buf_type1_ioctl_rsp *)
7615 * TODO: This is dummy implementation to pass smbtorture
7616 * Need to check correct response later
7618 memset(obj_buf->ObjectId, 0x0, 16);
7619 memset(obj_buf->BirthVolumeId, 0x0, 16);
7620 memset(obj_buf->BirthObjectId, 0x0, 16);
7621 memset(obj_buf->DomainId, 0x0, 16);
7625 case FSCTL_PIPE_TRANSCEIVE:
7626 out_buf_len = min_t(u32, KSMBD_IPC_MAX_PAYLOAD, out_buf_len);
7627 nbytes = fsctl_pipe_transceive(work, id, out_buf_len, req, rsp);
7629 case FSCTL_VALIDATE_NEGOTIATE_INFO:
7630 if (conn->dialect < SMB30_PROT_ID) {
7635 if (in_buf_len < sizeof(struct validate_negotiate_info_req))
7638 if (out_buf_len < sizeof(struct validate_negotiate_info_rsp))
7641 ret = fsctl_validate_negotiate_info(conn,
7642 (struct validate_negotiate_info_req *)&req->Buffer[0],
7643 (struct validate_negotiate_info_rsp *)&rsp->Buffer[0],
7648 nbytes = sizeof(struct validate_negotiate_info_rsp);
7649 rsp->PersistentFileId = SMB2_NO_FID;
7650 rsp->VolatileFileId = SMB2_NO_FID;
7652 case FSCTL_QUERY_NETWORK_INTERFACE_INFO:
7653 ret = fsctl_query_iface_info_ioctl(conn, rsp, out_buf_len);
7658 case FSCTL_REQUEST_RESUME_KEY:
7659 if (out_buf_len < sizeof(struct resume_key_ioctl_rsp)) {
7664 ret = fsctl_request_resume_key(work, req,
7665 (struct resume_key_ioctl_rsp *)&rsp->Buffer[0]);
7668 rsp->PersistentFileId = req->PersistentFileId;
7669 rsp->VolatileFileId = req->VolatileFileId;
7670 nbytes = sizeof(struct resume_key_ioctl_rsp);
7672 case FSCTL_COPYCHUNK:
7673 case FSCTL_COPYCHUNK_WRITE:
7674 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7676 "User does not have write permission\n");
7681 if (in_buf_len < sizeof(struct copychunk_ioctl_req)) {
7686 if (out_buf_len < sizeof(struct copychunk_ioctl_rsp)) {
7691 nbytes = sizeof(struct copychunk_ioctl_rsp);
7692 rsp->VolatileFileId = req->VolatileFileId;
7693 rsp->PersistentFileId = req->PersistentFileId;
7694 fsctl_copychunk(work,
7695 (struct copychunk_ioctl_req *)&req->Buffer[0],
7696 le32_to_cpu(req->CtlCode),
7697 le32_to_cpu(req->InputCount),
7698 req->VolatileFileId,
7699 req->PersistentFileId,
7702 case FSCTL_SET_SPARSE:
7703 if (in_buf_len < sizeof(struct file_sparse)) {
7708 ret = fsctl_set_sparse(work, id,
7709 (struct file_sparse *)&req->Buffer[0]);
7713 case FSCTL_SET_ZERO_DATA:
7715 struct file_zero_data_information *zero_data;
7716 struct ksmbd_file *fp;
7717 loff_t off, len, bfz;
7719 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7721 "User does not have write permission\n");
7726 if (in_buf_len < sizeof(struct file_zero_data_information)) {
7732 (struct file_zero_data_information *)&req->Buffer[0];
7734 off = le64_to_cpu(zero_data->FileOffset);
7735 bfz = le64_to_cpu(zero_data->BeyondFinalZero);
7743 fp = ksmbd_lookup_fd_fast(work, id);
7749 ret = ksmbd_vfs_zero_data(work, fp, off, len);
7750 ksmbd_fd_put(work, fp);
7756 case FSCTL_QUERY_ALLOCATED_RANGES:
7757 if (in_buf_len < sizeof(struct file_allocated_range_buffer)) {
7762 ret = fsctl_query_allocated_ranges(work, id,
7763 (struct file_allocated_range_buffer *)&req->Buffer[0],
7764 (struct file_allocated_range_buffer *)&rsp->Buffer[0],
7766 sizeof(struct file_allocated_range_buffer), &nbytes);
7767 if (ret == -E2BIG) {
7768 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
7769 } else if (ret < 0) {
7774 nbytes *= sizeof(struct file_allocated_range_buffer);
7776 case FSCTL_GET_REPARSE_POINT:
7778 struct reparse_data_buffer *reparse_ptr;
7779 struct ksmbd_file *fp;
7781 reparse_ptr = (struct reparse_data_buffer *)&rsp->Buffer[0];
7782 fp = ksmbd_lookup_fd_fast(work, id);
7784 pr_err("not found fp!!\n");
7789 reparse_ptr->ReparseTag =
7790 smb2_get_reparse_tag_special_file(file_inode(fp->filp)->i_mode);
7791 reparse_ptr->ReparseDataLength = 0;
7792 ksmbd_fd_put(work, fp);
7793 nbytes = sizeof(struct reparse_data_buffer);
7796 case FSCTL_DUPLICATE_EXTENTS_TO_FILE:
7798 struct ksmbd_file *fp_in, *fp_out = NULL;
7799 struct duplicate_extents_to_file *dup_ext;
7800 loff_t src_off, dst_off, length, cloned;
7802 if (in_buf_len < sizeof(struct duplicate_extents_to_file)) {
7807 dup_ext = (struct duplicate_extents_to_file *)&req->Buffer[0];
7809 fp_in = ksmbd_lookup_fd_slow(work, dup_ext->VolatileFileHandle,
7810 dup_ext->PersistentFileHandle);
7812 pr_err("not found file handle in duplicate extent to file\n");
7817 fp_out = ksmbd_lookup_fd_fast(work, id);
7819 pr_err("not found fp\n");
7824 src_off = le64_to_cpu(dup_ext->SourceFileOffset);
7825 dst_off = le64_to_cpu(dup_ext->TargetFileOffset);
7826 length = le64_to_cpu(dup_ext->ByteCount);
7828 * XXX: It is not clear if FSCTL_DUPLICATE_EXTENTS_TO_FILE
7829 * should fall back to vfs_copy_file_range(). This could be
7830 * beneficial when re-exporting nfs/smb mount, but note that
7831 * this can result in partial copy that returns an error status.
7832 * If/when FSCTL_DUPLICATE_EXTENTS_TO_FILE_EX is implemented,
7833 * fall back to vfs_copy_file_range(), should be avoided when
7834 * the flag DUPLICATE_EXTENTS_DATA_EX_SOURCE_ATOMIC is set.
7836 cloned = vfs_clone_file_range(fp_in->filp, src_off,
7837 fp_out->filp, dst_off, length, 0);
7838 if (cloned == -EXDEV || cloned == -EOPNOTSUPP) {
7841 } else if (cloned != length) {
7842 cloned = vfs_copy_file_range(fp_in->filp, src_off,
7843 fp_out->filp, dst_off,
7845 if (cloned != length) {
7854 ksmbd_fd_put(work, fp_in);
7855 ksmbd_fd_put(work, fp_out);
7861 ksmbd_debug(SMB, "not implemented yet ioctl command 0x%x\n",
7867 rsp->CtlCode = cpu_to_le32(cnt_code);
7868 rsp->InputCount = cpu_to_le32(0);
7869 rsp->InputOffset = cpu_to_le32(112);
7870 rsp->OutputOffset = cpu_to_le32(112);
7871 rsp->OutputCount = cpu_to_le32(nbytes);
7872 rsp->StructureSize = cpu_to_le16(49);
7873 rsp->Reserved = cpu_to_le16(0);
7874 rsp->Flags = cpu_to_le32(0);
7875 rsp->Reserved2 = cpu_to_le32(0);
7876 inc_rfc1001_len(work->response_buf, 48 + nbytes);
7882 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7883 else if (ret == -ENOENT)
7884 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
7885 else if (ret == -EOPNOTSUPP)
7886 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7887 else if (ret == -ENOSPC)
7888 rsp->hdr.Status = STATUS_BUFFER_TOO_SMALL;
7889 else if (ret < 0 || rsp->hdr.Status == 0)
7890 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7891 smb2_set_err_rsp(work);
7896 * smb20_oplock_break_ack() - handler for smb2.0 oplock break command
7897 * @work: smb work containing oplock break command buffer
7901 static void smb20_oplock_break_ack(struct ksmbd_work *work)
7903 struct smb2_oplock_break *req = smb2_get_msg(work->request_buf);
7904 struct smb2_oplock_break *rsp = smb2_get_msg(work->response_buf);
7905 struct ksmbd_file *fp;
7906 struct oplock_info *opinfo = NULL;
7909 u64 volatile_id, persistent_id;
7910 char req_oplevel = 0, rsp_oplevel = 0;
7911 unsigned int oplock_change_type;
7913 volatile_id = req->VolatileFid;
7914 persistent_id = req->PersistentFid;
7915 req_oplevel = req->OplockLevel;
7916 ksmbd_debug(OPLOCK, "v_id %llu, p_id %llu request oplock level %d\n",
7917 volatile_id, persistent_id, req_oplevel);
7919 fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
7921 rsp->hdr.Status = STATUS_FILE_CLOSED;
7922 smb2_set_err_rsp(work);
7926 opinfo = opinfo_get(fp);
7928 pr_err("unexpected null oplock_info\n");
7929 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
7930 smb2_set_err_rsp(work);
7931 ksmbd_fd_put(work, fp);
7935 if (opinfo->level == SMB2_OPLOCK_LEVEL_NONE) {
7936 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
7940 if (opinfo->op_state == OPLOCK_STATE_NONE) {
7941 ksmbd_debug(SMB, "unexpected oplock state 0x%x\n", opinfo->op_state);
7942 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
7946 if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
7947 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
7948 (req_oplevel != SMB2_OPLOCK_LEVEL_II &&
7949 req_oplevel != SMB2_OPLOCK_LEVEL_NONE)) {
7950 err = STATUS_INVALID_OPLOCK_PROTOCOL;
7951 oplock_change_type = OPLOCK_WRITE_TO_NONE;
7952 } else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
7953 req_oplevel != SMB2_OPLOCK_LEVEL_NONE) {
7954 err = STATUS_INVALID_OPLOCK_PROTOCOL;
7955 oplock_change_type = OPLOCK_READ_TO_NONE;
7956 } else if (req_oplevel == SMB2_OPLOCK_LEVEL_II ||
7957 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
7958 err = STATUS_INVALID_DEVICE_STATE;
7959 if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
7960 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
7961 req_oplevel == SMB2_OPLOCK_LEVEL_II) {
7962 oplock_change_type = OPLOCK_WRITE_TO_READ;
7963 } else if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
7964 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
7965 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
7966 oplock_change_type = OPLOCK_WRITE_TO_NONE;
7967 } else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
7968 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
7969 oplock_change_type = OPLOCK_READ_TO_NONE;
7971 oplock_change_type = 0;
7974 oplock_change_type = 0;
7977 switch (oplock_change_type) {
7978 case OPLOCK_WRITE_TO_READ:
7979 ret = opinfo_write_to_read(opinfo);
7980 rsp_oplevel = SMB2_OPLOCK_LEVEL_II;
7982 case OPLOCK_WRITE_TO_NONE:
7983 ret = opinfo_write_to_none(opinfo);
7984 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
7986 case OPLOCK_READ_TO_NONE:
7987 ret = opinfo_read_to_none(opinfo);
7988 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
7991 pr_err("unknown oplock change 0x%x -> 0x%x\n",
7992 opinfo->level, rsp_oplevel);
7996 rsp->hdr.Status = err;
8001 ksmbd_fd_put(work, fp);
8002 opinfo->op_state = OPLOCK_STATE_NONE;
8003 wake_up_interruptible_all(&opinfo->oplock_q);
8005 rsp->StructureSize = cpu_to_le16(24);
8006 rsp->OplockLevel = rsp_oplevel;
8009 rsp->VolatileFid = volatile_id;
8010 rsp->PersistentFid = persistent_id;
8011 inc_rfc1001_len(work->response_buf, 24);
8015 opinfo->op_state = OPLOCK_STATE_NONE;
8016 wake_up_interruptible_all(&opinfo->oplock_q);
8019 ksmbd_fd_put(work, fp);
8020 smb2_set_err_rsp(work);
8023 static int check_lease_state(struct lease *lease, __le32 req_state)
8025 if ((lease->new_state ==
8026 (SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE)) &&
8027 !(req_state & SMB2_LEASE_WRITE_CACHING_LE)) {
8028 lease->new_state = req_state;
8032 if (lease->new_state == req_state)
8039 * smb21_lease_break_ack() - handler for smb2.1 lease break command
8040 * @work: smb work containing lease break command buffer
8044 static void smb21_lease_break_ack(struct ksmbd_work *work)
8046 struct ksmbd_conn *conn = work->conn;
8047 struct smb2_lease_ack *req = smb2_get_msg(work->request_buf);
8048 struct smb2_lease_ack *rsp = smb2_get_msg(work->response_buf);
8049 struct oplock_info *opinfo;
8052 unsigned int lease_change_type;
8054 struct lease *lease;
8056 ksmbd_debug(OPLOCK, "smb21 lease break, lease state(0x%x)\n",
8057 le32_to_cpu(req->LeaseState));
8058 opinfo = lookup_lease_in_table(conn, req->LeaseKey);
8060 ksmbd_debug(OPLOCK, "file not opened\n");
8061 smb2_set_err_rsp(work);
8062 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8065 lease = opinfo->o_lease;
8067 if (opinfo->op_state == OPLOCK_STATE_NONE) {
8068 pr_err("unexpected lease break state 0x%x\n",
8070 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8074 if (check_lease_state(lease, req->LeaseState)) {
8075 rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
8077 "req lease state: 0x%x, expected state: 0x%x\n",
8078 req->LeaseState, lease->new_state);
8082 if (!atomic_read(&opinfo->breaking_cnt)) {
8083 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8087 /* check for bad lease state */
8088 if (req->LeaseState &
8089 (~(SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE))) {
8090 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8091 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8092 lease_change_type = OPLOCK_WRITE_TO_NONE;
8094 lease_change_type = OPLOCK_READ_TO_NONE;
8095 ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8096 le32_to_cpu(lease->state),
8097 le32_to_cpu(req->LeaseState));
8098 } else if (lease->state == SMB2_LEASE_READ_CACHING_LE &&
8099 req->LeaseState != SMB2_LEASE_NONE_LE) {
8100 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8101 lease_change_type = OPLOCK_READ_TO_NONE;
8102 ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8103 le32_to_cpu(lease->state),
8104 le32_to_cpu(req->LeaseState));
8106 /* valid lease state changes */
8107 err = STATUS_INVALID_DEVICE_STATE;
8108 if (req->LeaseState == SMB2_LEASE_NONE_LE) {
8109 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8110 lease_change_type = OPLOCK_WRITE_TO_NONE;
8112 lease_change_type = OPLOCK_READ_TO_NONE;
8113 } else if (req->LeaseState & SMB2_LEASE_READ_CACHING_LE) {
8114 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8115 lease_change_type = OPLOCK_WRITE_TO_READ;
8117 lease_change_type = OPLOCK_READ_HANDLE_TO_READ;
8119 lease_change_type = 0;
8123 switch (lease_change_type) {
8124 case OPLOCK_WRITE_TO_READ:
8125 ret = opinfo_write_to_read(opinfo);
8127 case OPLOCK_READ_HANDLE_TO_READ:
8128 ret = opinfo_read_handle_to_read(opinfo);
8130 case OPLOCK_WRITE_TO_NONE:
8131 ret = opinfo_write_to_none(opinfo);
8133 case OPLOCK_READ_TO_NONE:
8134 ret = opinfo_read_to_none(opinfo);
8137 ksmbd_debug(OPLOCK, "unknown lease change 0x%x -> 0x%x\n",
8138 le32_to_cpu(lease->state),
8139 le32_to_cpu(req->LeaseState));
8142 lease_state = lease->state;
8143 opinfo->op_state = OPLOCK_STATE_NONE;
8144 wake_up_interruptible_all(&opinfo->oplock_q);
8145 atomic_dec(&opinfo->breaking_cnt);
8146 wake_up_interruptible_all(&opinfo->oplock_brk);
8150 rsp->hdr.Status = err;
8154 rsp->StructureSize = cpu_to_le16(36);
8157 memcpy(rsp->LeaseKey, req->LeaseKey, 16);
8158 rsp->LeaseState = lease_state;
8159 rsp->LeaseDuration = 0;
8160 inc_rfc1001_len(work->response_buf, 36);
8164 opinfo->op_state = OPLOCK_STATE_NONE;
8165 wake_up_interruptible_all(&opinfo->oplock_q);
8166 atomic_dec(&opinfo->breaking_cnt);
8167 wake_up_interruptible_all(&opinfo->oplock_brk);
8170 smb2_set_err_rsp(work);
8174 * smb2_oplock_break() - dispatcher for smb2.0 and 2.1 oplock/lease break
8175 * @work: smb work containing oplock/lease break command buffer
8179 int smb2_oplock_break(struct ksmbd_work *work)
8181 struct smb2_oplock_break *req = smb2_get_msg(work->request_buf);
8182 struct smb2_oplock_break *rsp = smb2_get_msg(work->response_buf);
8184 switch (le16_to_cpu(req->StructureSize)) {
8185 case OP_BREAK_STRUCT_SIZE_20:
8186 smb20_oplock_break_ack(work);
8188 case OP_BREAK_STRUCT_SIZE_21:
8189 smb21_lease_break_ack(work);
8192 ksmbd_debug(OPLOCK, "invalid break cmd %d\n",
8193 le16_to_cpu(req->StructureSize));
8194 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8195 smb2_set_err_rsp(work);
8202 * smb2_notify() - handler for smb2 notify request
8203 * @work: smb work containing notify command buffer
8207 int smb2_notify(struct ksmbd_work *work)
8209 struct smb2_change_notify_req *req;
8210 struct smb2_change_notify_rsp *rsp;
8212 WORK_BUFFERS(work, req, rsp);
8214 if (work->next_smb2_rcv_hdr_off && req->hdr.NextCommand) {
8215 rsp->hdr.Status = STATUS_INTERNAL_ERROR;
8216 smb2_set_err_rsp(work);
8220 smb2_set_err_rsp(work);
8221 rsp->hdr.Status = STATUS_NOT_IMPLEMENTED;
8226 * smb2_is_sign_req() - handler for checking packet signing status
8227 * @work: smb work containing notify command buffer
8228 * @command: SMB2 command id
8230 * Return: true if packed is signed, false otherwise
8232 bool smb2_is_sign_req(struct ksmbd_work *work, unsigned int command)
8234 struct smb2_hdr *rcv_hdr2 = smb2_get_msg(work->request_buf);
8236 if ((rcv_hdr2->Flags & SMB2_FLAGS_SIGNED) &&
8237 command != SMB2_NEGOTIATE_HE &&
8238 command != SMB2_SESSION_SETUP_HE &&
8239 command != SMB2_OPLOCK_BREAK_HE)
8246 * smb2_check_sign_req() - handler for req packet sign processing
8247 * @work: smb work containing notify command buffer
8249 * Return: 1 on success, 0 otherwise
8251 int smb2_check_sign_req(struct ksmbd_work *work)
8253 struct smb2_hdr *hdr;
8254 char signature_req[SMB2_SIGNATURE_SIZE];
8255 char signature[SMB2_HMACSHA256_SIZE];
8259 hdr = smb2_get_msg(work->request_buf);
8260 if (work->next_smb2_rcv_hdr_off)
8261 hdr = ksmbd_req_buf_next(work);
8263 if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8264 len = get_rfc1002_len(work->request_buf);
8265 else if (hdr->NextCommand)
8266 len = le32_to_cpu(hdr->NextCommand);
8268 len = get_rfc1002_len(work->request_buf) -
8269 work->next_smb2_rcv_hdr_off;
8271 memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8272 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8274 iov[0].iov_base = (char *)&hdr->ProtocolId;
8275 iov[0].iov_len = len;
8277 if (ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, 1,
8281 if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8282 pr_err("bad smb2 signature\n");
8290 * smb2_set_sign_rsp() - handler for rsp packet sign processing
8291 * @work: smb work containing notify command buffer
8294 void smb2_set_sign_rsp(struct ksmbd_work *work)
8296 struct smb2_hdr *hdr;
8297 struct smb2_hdr *req_hdr;
8298 char signature[SMB2_HMACSHA256_SIZE];
8303 hdr = smb2_get_msg(work->response_buf);
8304 if (work->next_smb2_rsp_hdr_off)
8305 hdr = ksmbd_resp_buf_next(work);
8307 req_hdr = ksmbd_req_buf_next(work);
8309 if (!work->next_smb2_rsp_hdr_off) {
8310 len = get_rfc1002_len(work->response_buf);
8311 if (req_hdr->NextCommand)
8312 len = ALIGN(len, 8);
8314 len = get_rfc1002_len(work->response_buf) -
8315 work->next_smb2_rsp_hdr_off;
8316 len = ALIGN(len, 8);
8319 if (req_hdr->NextCommand)
8320 hdr->NextCommand = cpu_to_le32(len);
8322 hdr->Flags |= SMB2_FLAGS_SIGNED;
8323 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8325 iov[0].iov_base = (char *)&hdr->ProtocolId;
8326 iov[0].iov_len = len;
8328 if (work->aux_payload_sz) {
8329 iov[0].iov_len -= work->aux_payload_sz;
8331 iov[1].iov_base = work->aux_payload_buf;
8332 iov[1].iov_len = work->aux_payload_sz;
8336 if (!ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, n_vec,
8338 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
8342 * smb3_check_sign_req() - handler for req packet sign processing
8343 * @work: smb work containing notify command buffer
8345 * Return: 1 on success, 0 otherwise
8347 int smb3_check_sign_req(struct ksmbd_work *work)
8349 struct ksmbd_conn *conn = work->conn;
8351 struct smb2_hdr *hdr;
8352 struct channel *chann;
8353 char signature_req[SMB2_SIGNATURE_SIZE];
8354 char signature[SMB2_CMACAES_SIZE];
8358 hdr = smb2_get_msg(work->request_buf);
8359 if (work->next_smb2_rcv_hdr_off)
8360 hdr = ksmbd_req_buf_next(work);
8362 if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8363 len = get_rfc1002_len(work->request_buf);
8364 else if (hdr->NextCommand)
8365 len = le32_to_cpu(hdr->NextCommand);
8367 len = get_rfc1002_len(work->request_buf) -
8368 work->next_smb2_rcv_hdr_off;
8370 if (le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8371 signing_key = work->sess->smb3signingkey;
8373 read_lock(&work->sess->chann_lock);
8374 chann = lookup_chann_list(work->sess, conn);
8376 read_unlock(&work->sess->chann_lock);
8379 signing_key = chann->smb3signingkey;
8380 read_unlock(&work->sess->chann_lock);
8384 pr_err("SMB3 signing key is not generated\n");
8388 memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8389 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8390 iov[0].iov_base = (char *)&hdr->ProtocolId;
8391 iov[0].iov_len = len;
8393 if (ksmbd_sign_smb3_pdu(conn, signing_key, iov, 1, signature))
8396 if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8397 pr_err("bad smb2 signature\n");
8405 * smb3_set_sign_rsp() - handler for rsp packet sign processing
8406 * @work: smb work containing notify command buffer
8409 void smb3_set_sign_rsp(struct ksmbd_work *work)
8411 struct ksmbd_conn *conn = work->conn;
8412 struct smb2_hdr *req_hdr, *hdr;
8413 struct channel *chann;
8414 char signature[SMB2_CMACAES_SIZE];
8420 hdr = smb2_get_msg(work->response_buf);
8421 if (work->next_smb2_rsp_hdr_off)
8422 hdr = ksmbd_resp_buf_next(work);
8424 req_hdr = ksmbd_req_buf_next(work);
8426 if (!work->next_smb2_rsp_hdr_off) {
8427 len = get_rfc1002_len(work->response_buf);
8428 if (req_hdr->NextCommand)
8429 len = ALIGN(len, 8);
8431 len = get_rfc1002_len(work->response_buf) -
8432 work->next_smb2_rsp_hdr_off;
8433 len = ALIGN(len, 8);
8436 if (conn->binding == false &&
8437 le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8438 signing_key = work->sess->smb3signingkey;
8440 read_lock(&work->sess->chann_lock);
8441 chann = lookup_chann_list(work->sess, work->conn);
8443 read_unlock(&work->sess->chann_lock);
8446 signing_key = chann->smb3signingkey;
8447 read_unlock(&work->sess->chann_lock);
8453 if (req_hdr->NextCommand)
8454 hdr->NextCommand = cpu_to_le32(len);
8456 hdr->Flags |= SMB2_FLAGS_SIGNED;
8457 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8458 iov[0].iov_base = (char *)&hdr->ProtocolId;
8459 iov[0].iov_len = len;
8460 if (work->aux_payload_sz) {
8461 iov[0].iov_len -= work->aux_payload_sz;
8462 iov[1].iov_base = work->aux_payload_buf;
8463 iov[1].iov_len = work->aux_payload_sz;
8467 if (!ksmbd_sign_smb3_pdu(conn, signing_key, iov, n_vec, signature))
8468 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
8472 * smb3_preauth_hash_rsp() - handler for computing preauth hash on response
8473 * @work: smb work containing response buffer
8476 void smb3_preauth_hash_rsp(struct ksmbd_work *work)
8478 struct ksmbd_conn *conn = work->conn;
8479 struct ksmbd_session *sess = work->sess;
8480 struct smb2_hdr *req, *rsp;
8482 if (conn->dialect != SMB311_PROT_ID)
8485 WORK_BUFFERS(work, req, rsp);
8487 if (le16_to_cpu(req->Command) == SMB2_NEGOTIATE_HE &&
8489 ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
8490 conn->preauth_info->Preauth_HashValue);
8492 if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE && sess) {
8495 if (conn->binding) {
8496 struct preauth_session *preauth_sess;
8498 preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
8501 hash_value = preauth_sess->Preauth_HashValue;
8503 hash_value = sess->Preauth_HashValue;
8507 ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
8512 static void fill_transform_hdr(void *tr_buf, char *old_buf, __le16 cipher_type)
8514 struct smb2_transform_hdr *tr_hdr = tr_buf + 4;
8515 struct smb2_hdr *hdr = smb2_get_msg(old_buf);
8516 unsigned int orig_len = get_rfc1002_len(old_buf);
8518 /* tr_buf must be cleared by the caller */
8519 tr_hdr->ProtocolId = SMB2_TRANSFORM_PROTO_NUM;
8520 tr_hdr->OriginalMessageSize = cpu_to_le32(orig_len);
8521 tr_hdr->Flags = cpu_to_le16(TRANSFORM_FLAG_ENCRYPTED);
8522 if (cipher_type == SMB2_ENCRYPTION_AES128_GCM ||
8523 cipher_type == SMB2_ENCRYPTION_AES256_GCM)
8524 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_GCM_NONCE);
8526 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_CCM_NONCE);
8527 memcpy(&tr_hdr->SessionId, &hdr->SessionId, 8);
8528 inc_rfc1001_len(tr_buf, sizeof(struct smb2_transform_hdr));
8529 inc_rfc1001_len(tr_buf, orig_len);
8532 int smb3_encrypt_resp(struct ksmbd_work *work)
8534 char *buf = work->response_buf;
8537 int buf_size = 0, rq_nvec = 2 + (work->aux_payload_sz ? 1 : 0);
8539 if (ARRAY_SIZE(iov) < rq_nvec)
8542 work->tr_buf = kzalloc(sizeof(struct smb2_transform_hdr) + 4, GFP_KERNEL);
8546 /* fill transform header */
8547 fill_transform_hdr(work->tr_buf, buf, work->conn->cipher_type);
8549 iov[0].iov_base = work->tr_buf;
8550 iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
8551 buf_size += iov[0].iov_len - 4;
8553 iov[1].iov_base = buf + 4;
8554 iov[1].iov_len = get_rfc1002_len(buf);
8555 if (work->aux_payload_sz) {
8556 iov[1].iov_len = work->resp_hdr_sz - 4;
8558 iov[2].iov_base = work->aux_payload_buf;
8559 iov[2].iov_len = work->aux_payload_sz;
8560 buf_size += iov[2].iov_len;
8562 buf_size += iov[1].iov_len;
8563 work->resp_hdr_sz = iov[1].iov_len;
8565 rc = ksmbd_crypt_message(work->conn, iov, rq_nvec, 1);
8569 memmove(buf, iov[1].iov_base, iov[1].iov_len);
8570 *(__be32 *)work->tr_buf = cpu_to_be32(buf_size);
8575 bool smb3_is_transform_hdr(void *buf)
8577 struct smb2_transform_hdr *trhdr = smb2_get_msg(buf);
8579 return trhdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM;
8582 int smb3_decrypt_req(struct ksmbd_work *work)
8584 struct ksmbd_conn *conn = work->conn;
8585 struct ksmbd_session *sess;
8586 char *buf = work->request_buf;
8587 unsigned int pdu_length = get_rfc1002_len(buf);
8589 int buf_data_size = pdu_length - sizeof(struct smb2_transform_hdr);
8590 struct smb2_transform_hdr *tr_hdr = smb2_get_msg(buf);
8593 if (buf_data_size < sizeof(struct smb2_hdr)) {
8594 pr_err("Transform message is too small (%u)\n",
8596 return -ECONNABORTED;
8599 if (buf_data_size < le32_to_cpu(tr_hdr->OriginalMessageSize)) {
8600 pr_err("Transform message is broken\n");
8601 return -ECONNABORTED;
8604 sess = ksmbd_session_lookup_all(conn, le64_to_cpu(tr_hdr->SessionId));
8606 pr_err("invalid session id(%llx) in transform header\n",
8607 le64_to_cpu(tr_hdr->SessionId));
8608 return -ECONNABORTED;
8611 iov[0].iov_base = buf;
8612 iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
8613 iov[1].iov_base = buf + sizeof(struct smb2_transform_hdr) + 4;
8614 iov[1].iov_len = buf_data_size;
8615 rc = ksmbd_crypt_message(conn, iov, 2, 0);
8619 memmove(buf + 4, iov[1].iov_base, buf_data_size);
8620 *(__be32 *)buf = cpu_to_be32(buf_data_size);
8625 bool smb3_11_final_sess_setup_resp(struct ksmbd_work *work)
8627 struct ksmbd_conn *conn = work->conn;
8628 struct smb2_hdr *rsp = smb2_get_msg(work->response_buf);
8630 if (conn->dialect < SMB30_PROT_ID)
8633 if (work->next_smb2_rcv_hdr_off)
8634 rsp = ksmbd_resp_buf_next(work);
8636 if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE &&
8637 rsp->Status == STATUS_SUCCESS)