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_user *user, u64 id)
593 struct ksmbd_session *prev_sess = ksmbd_session_lookup_slowpath(id);
594 struct ksmbd_user *prev_user;
599 prev_user = prev_sess->user;
602 strcmp(user->name, prev_user->name) ||
603 user->passkey_sz != prev_user->passkey_sz ||
604 memcmp(user->passkey, prev_user->passkey, user->passkey_sz)) {
605 put_session(prev_sess);
609 put_session(prev_sess);
610 ksmbd_session_destroy(prev_sess);
614 * smb2_get_name() - get filename string from on the wire smb format
615 * @src: source buffer
616 * @maxlen: maxlen of source string
617 * @local_nls: nls_table pointer
619 * Return: matching converted filename on success, otherwise error ptr
622 smb2_get_name(const char *src, const int maxlen, struct nls_table *local_nls)
626 name = smb_strndup_from_utf16(src, maxlen, 1, local_nls);
628 pr_err("failed to get name %ld\n", PTR_ERR(name));
632 ksmbd_conv_path_to_unix(name);
633 ksmbd_strip_last_slash(name);
637 int setup_async_work(struct ksmbd_work *work, void (*fn)(void **), void **arg)
639 struct smb2_hdr *rsp_hdr;
640 struct ksmbd_conn *conn = work->conn;
643 rsp_hdr = smb2_get_msg(work->response_buf);
644 rsp_hdr->Flags |= SMB2_FLAGS_ASYNC_COMMAND;
646 id = ksmbd_acquire_async_msg_id(&conn->async_ida);
648 pr_err("Failed to alloc async message id\n");
651 work->syncronous = false;
653 rsp_hdr->Id.AsyncId = cpu_to_le64(id);
656 "Send interim Response to inform async request id : %d\n",
659 work->cancel_fn = fn;
660 work->cancel_argv = arg;
662 if (list_empty(&work->async_request_entry)) {
663 spin_lock(&conn->request_lock);
664 list_add_tail(&work->async_request_entry, &conn->async_requests);
665 spin_unlock(&conn->request_lock);
671 void smb2_send_interim_resp(struct ksmbd_work *work, __le32 status)
673 struct smb2_hdr *rsp_hdr;
675 rsp_hdr = smb2_get_msg(work->response_buf);
676 smb2_set_err_rsp(work);
677 rsp_hdr->Status = status;
680 ksmbd_conn_write(work);
685 static __le32 smb2_get_reparse_tag_special_file(umode_t mode)
687 if (S_ISDIR(mode) || S_ISREG(mode))
691 return IO_REPARSE_TAG_LX_SYMLINK_LE;
692 else if (S_ISFIFO(mode))
693 return IO_REPARSE_TAG_LX_FIFO_LE;
694 else if (S_ISSOCK(mode))
695 return IO_REPARSE_TAG_AF_UNIX_LE;
696 else if (S_ISCHR(mode))
697 return IO_REPARSE_TAG_LX_CHR_LE;
698 else if (S_ISBLK(mode))
699 return IO_REPARSE_TAG_LX_BLK_LE;
705 * smb2_get_dos_mode() - get file mode in dos format from unix mode
706 * @stat: kstat containing file mode
707 * @attribute: attribute flags
709 * Return: converted dos mode
711 static int smb2_get_dos_mode(struct kstat *stat, int attribute)
715 if (S_ISDIR(stat->mode)) {
716 attr = FILE_ATTRIBUTE_DIRECTORY |
717 (attribute & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM));
719 attr = (attribute & 0x00005137) | FILE_ATTRIBUTE_ARCHIVE;
720 attr &= ~(FILE_ATTRIBUTE_DIRECTORY);
721 if (S_ISREG(stat->mode) && (server_conf.share_fake_fscaps &
722 FILE_SUPPORTS_SPARSE_FILES))
723 attr |= FILE_ATTRIBUTE_SPARSE_FILE;
725 if (smb2_get_reparse_tag_special_file(stat->mode))
726 attr |= FILE_ATTRIBUTE_REPARSE_POINT;
732 static void build_preauth_ctxt(struct smb2_preauth_neg_context *pneg_ctxt,
735 pneg_ctxt->ContextType = SMB2_PREAUTH_INTEGRITY_CAPABILITIES;
736 pneg_ctxt->DataLength = cpu_to_le16(38);
737 pneg_ctxt->HashAlgorithmCount = cpu_to_le16(1);
738 pneg_ctxt->Reserved = cpu_to_le32(0);
739 pneg_ctxt->SaltLength = cpu_to_le16(SMB311_SALT_SIZE);
740 get_random_bytes(pneg_ctxt->Salt, SMB311_SALT_SIZE);
741 pneg_ctxt->HashAlgorithms = hash_id;
744 static void build_encrypt_ctxt(struct smb2_encryption_neg_context *pneg_ctxt,
747 pneg_ctxt->ContextType = SMB2_ENCRYPTION_CAPABILITIES;
748 pneg_ctxt->DataLength = cpu_to_le16(4);
749 pneg_ctxt->Reserved = cpu_to_le32(0);
750 pneg_ctxt->CipherCount = cpu_to_le16(1);
751 pneg_ctxt->Ciphers[0] = cipher_type;
754 static void build_compression_ctxt(struct smb2_compression_capabilities_context *pneg_ctxt,
757 pneg_ctxt->ContextType = SMB2_COMPRESSION_CAPABILITIES;
758 pneg_ctxt->DataLength =
759 cpu_to_le16(sizeof(struct smb2_compression_capabilities_context)
760 - sizeof(struct smb2_neg_context));
761 pneg_ctxt->Reserved = cpu_to_le32(0);
762 pneg_ctxt->CompressionAlgorithmCount = cpu_to_le16(1);
763 pneg_ctxt->Flags = cpu_to_le32(0);
764 pneg_ctxt->CompressionAlgorithms[0] = comp_algo;
767 static void build_sign_cap_ctxt(struct smb2_signing_capabilities *pneg_ctxt,
770 pneg_ctxt->ContextType = SMB2_SIGNING_CAPABILITIES;
771 pneg_ctxt->DataLength =
772 cpu_to_le16((sizeof(struct smb2_signing_capabilities) + 2)
773 - sizeof(struct smb2_neg_context));
774 pneg_ctxt->Reserved = cpu_to_le32(0);
775 pneg_ctxt->SigningAlgorithmCount = cpu_to_le16(1);
776 pneg_ctxt->SigningAlgorithms[0] = sign_algo;
779 static void build_posix_ctxt(struct smb2_posix_neg_context *pneg_ctxt)
781 pneg_ctxt->ContextType = SMB2_POSIX_EXTENSIONS_AVAILABLE;
782 pneg_ctxt->DataLength = cpu_to_le16(POSIX_CTXT_DATA_LEN);
783 /* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */
784 pneg_ctxt->Name[0] = 0x93;
785 pneg_ctxt->Name[1] = 0xAD;
786 pneg_ctxt->Name[2] = 0x25;
787 pneg_ctxt->Name[3] = 0x50;
788 pneg_ctxt->Name[4] = 0x9C;
789 pneg_ctxt->Name[5] = 0xB4;
790 pneg_ctxt->Name[6] = 0x11;
791 pneg_ctxt->Name[7] = 0xE7;
792 pneg_ctxt->Name[8] = 0xB4;
793 pneg_ctxt->Name[9] = 0x23;
794 pneg_ctxt->Name[10] = 0x83;
795 pneg_ctxt->Name[11] = 0xDE;
796 pneg_ctxt->Name[12] = 0x96;
797 pneg_ctxt->Name[13] = 0x8B;
798 pneg_ctxt->Name[14] = 0xCD;
799 pneg_ctxt->Name[15] = 0x7C;
802 static void assemble_neg_contexts(struct ksmbd_conn *conn,
803 struct smb2_negotiate_rsp *rsp,
806 char *pneg_ctxt = (char *)rsp +
807 le32_to_cpu(rsp->NegotiateContextOffset);
808 int neg_ctxt_cnt = 1;
812 "assemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
813 build_preauth_ctxt((struct smb2_preauth_neg_context *)pneg_ctxt,
814 conn->preauth_info->Preauth_HashId);
815 rsp->NegotiateContextCount = cpu_to_le16(neg_ctxt_cnt);
816 inc_rfc1001_len(smb2_buf_len, AUTH_GSS_PADDING);
817 ctxt_size = sizeof(struct smb2_preauth_neg_context);
818 /* Round to 8 byte boundary */
819 pneg_ctxt += round_up(sizeof(struct smb2_preauth_neg_context), 8);
821 if (conn->cipher_type) {
822 ctxt_size = round_up(ctxt_size, 8);
824 "assemble SMB2_ENCRYPTION_CAPABILITIES context\n");
825 build_encrypt_ctxt((struct smb2_encryption_neg_context *)pneg_ctxt,
827 rsp->NegotiateContextCount = cpu_to_le16(++neg_ctxt_cnt);
828 ctxt_size += sizeof(struct smb2_encryption_neg_context) + 2;
829 /* Round to 8 byte boundary */
831 round_up(sizeof(struct smb2_encryption_neg_context) + 2,
835 if (conn->compress_algorithm) {
836 ctxt_size = round_up(ctxt_size, 8);
838 "assemble SMB2_COMPRESSION_CAPABILITIES context\n");
839 /* Temporarily set to SMB3_COMPRESS_NONE */
840 build_compression_ctxt((struct smb2_compression_capabilities_context *)pneg_ctxt,
841 conn->compress_algorithm);
842 rsp->NegotiateContextCount = cpu_to_le16(++neg_ctxt_cnt);
843 ctxt_size += sizeof(struct smb2_compression_capabilities_context) + 2;
844 /* Round to 8 byte boundary */
845 pneg_ctxt += round_up(sizeof(struct smb2_compression_capabilities_context) + 2,
849 if (conn->posix_ext_supported) {
850 ctxt_size = round_up(ctxt_size, 8);
852 "assemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
853 build_posix_ctxt((struct smb2_posix_neg_context *)pneg_ctxt);
854 rsp->NegotiateContextCount = cpu_to_le16(++neg_ctxt_cnt);
855 ctxt_size += sizeof(struct smb2_posix_neg_context);
856 /* Round to 8 byte boundary */
857 pneg_ctxt += round_up(sizeof(struct smb2_posix_neg_context), 8);
860 if (conn->signing_negotiated) {
861 ctxt_size = round_up(ctxt_size, 8);
863 "assemble SMB2_SIGNING_CAPABILITIES context\n");
864 build_sign_cap_ctxt((struct smb2_signing_capabilities *)pneg_ctxt,
865 conn->signing_algorithm);
866 rsp->NegotiateContextCount = cpu_to_le16(++neg_ctxt_cnt);
867 ctxt_size += sizeof(struct smb2_signing_capabilities) + 2;
870 inc_rfc1001_len(smb2_buf_len, ctxt_size);
873 static __le32 decode_preauth_ctxt(struct ksmbd_conn *conn,
874 struct smb2_preauth_neg_context *pneg_ctxt)
876 __le32 err = STATUS_NO_PREAUTH_INTEGRITY_HASH_OVERLAP;
878 if (pneg_ctxt->HashAlgorithms == SMB2_PREAUTH_INTEGRITY_SHA512) {
879 conn->preauth_info->Preauth_HashId =
880 SMB2_PREAUTH_INTEGRITY_SHA512;
881 err = STATUS_SUCCESS;
887 static void decode_encrypt_ctxt(struct ksmbd_conn *conn,
888 struct smb2_encryption_neg_context *pneg_ctxt,
891 int cph_cnt = le16_to_cpu(pneg_ctxt->CipherCount);
892 int i, cphs_size = cph_cnt * sizeof(__le16);
894 conn->cipher_type = 0;
896 if (sizeof(struct smb2_encryption_neg_context) + cphs_size >
898 pr_err("Invalid cipher count(%d)\n", cph_cnt);
902 if (!(server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION))
905 for (i = 0; i < cph_cnt; i++) {
906 if (pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_GCM ||
907 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_CCM ||
908 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_CCM ||
909 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_GCM) {
910 ksmbd_debug(SMB, "Cipher ID = 0x%x\n",
911 pneg_ctxt->Ciphers[i]);
912 conn->cipher_type = pneg_ctxt->Ciphers[i];
919 * smb3_encryption_negotiated() - checks if server and client agreed on enabling encryption
920 * @conn: smb connection
922 * Return: true if connection should be encrypted, else false
924 static bool smb3_encryption_negotiated(struct ksmbd_conn *conn)
926 if (!conn->ops->generate_encryptionkey)
930 * SMB 3.0 and 3.0.2 dialects use the SMB2_GLOBAL_CAP_ENCRYPTION flag.
931 * SMB 3.1.1 uses the cipher_type field.
933 return (conn->vals->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION) ||
937 static void decode_compress_ctxt(struct ksmbd_conn *conn,
938 struct smb2_compression_capabilities_context *pneg_ctxt)
940 conn->compress_algorithm = SMB3_COMPRESS_NONE;
943 static void decode_sign_cap_ctxt(struct ksmbd_conn *conn,
944 struct smb2_signing_capabilities *pneg_ctxt,
947 int sign_algo_cnt = le16_to_cpu(pneg_ctxt->SigningAlgorithmCount);
948 int i, sign_alos_size = sign_algo_cnt * sizeof(__le16);
950 conn->signing_negotiated = false;
952 if (sizeof(struct smb2_signing_capabilities) + sign_alos_size >
954 pr_err("Invalid signing algorithm count(%d)\n", sign_algo_cnt);
958 for (i = 0; i < sign_algo_cnt; i++) {
959 if (pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_HMAC_SHA256_LE ||
960 pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_AES_CMAC_LE) {
961 ksmbd_debug(SMB, "Signing Algorithm ID = 0x%x\n",
962 pneg_ctxt->SigningAlgorithms[i]);
963 conn->signing_negotiated = true;
964 conn->signing_algorithm =
965 pneg_ctxt->SigningAlgorithms[i];
971 static __le32 deassemble_neg_contexts(struct ksmbd_conn *conn,
972 struct smb2_negotiate_req *req,
975 /* +4 is to account for the RFC1001 len field */
976 struct smb2_neg_context *pctx = (struct smb2_neg_context *)req;
977 int i = 0, len_of_ctxts;
978 int offset = le32_to_cpu(req->NegotiateContextOffset);
979 int neg_ctxt_cnt = le16_to_cpu(req->NegotiateContextCount);
980 __le32 status = STATUS_INVALID_PARAMETER;
982 ksmbd_debug(SMB, "decoding %d negotiate contexts\n", neg_ctxt_cnt);
983 if (len_of_smb <= offset) {
984 ksmbd_debug(SMB, "Invalid response: negotiate context offset\n");
988 len_of_ctxts = len_of_smb - offset;
990 while (i++ < neg_ctxt_cnt) {
993 /* check that offset is not beyond end of SMB */
994 if (len_of_ctxts == 0)
997 if (len_of_ctxts < sizeof(struct smb2_neg_context))
1000 pctx = (struct smb2_neg_context *)((char *)pctx + offset);
1001 clen = le16_to_cpu(pctx->DataLength);
1002 if (clen + sizeof(struct smb2_neg_context) > len_of_ctxts)
1005 if (pctx->ContextType == SMB2_PREAUTH_INTEGRITY_CAPABILITIES) {
1007 "deassemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
1008 if (conn->preauth_info->Preauth_HashId)
1011 status = decode_preauth_ctxt(conn,
1012 (struct smb2_preauth_neg_context *)pctx);
1013 if (status != STATUS_SUCCESS)
1015 } else if (pctx->ContextType == SMB2_ENCRYPTION_CAPABILITIES) {
1017 "deassemble SMB2_ENCRYPTION_CAPABILITIES context\n");
1018 if (conn->cipher_type)
1021 decode_encrypt_ctxt(conn,
1022 (struct smb2_encryption_neg_context *)pctx,
1024 } else if (pctx->ContextType == SMB2_COMPRESSION_CAPABILITIES) {
1026 "deassemble SMB2_COMPRESSION_CAPABILITIES context\n");
1027 if (conn->compress_algorithm)
1030 decode_compress_ctxt(conn,
1031 (struct smb2_compression_capabilities_context *)pctx);
1032 } else if (pctx->ContextType == SMB2_NETNAME_NEGOTIATE_CONTEXT_ID) {
1034 "deassemble SMB2_NETNAME_NEGOTIATE_CONTEXT_ID context\n");
1035 } else if (pctx->ContextType == SMB2_POSIX_EXTENSIONS_AVAILABLE) {
1037 "deassemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
1038 conn->posix_ext_supported = true;
1039 } else if (pctx->ContextType == SMB2_SIGNING_CAPABILITIES) {
1041 "deassemble SMB2_SIGNING_CAPABILITIES context\n");
1042 decode_sign_cap_ctxt(conn,
1043 (struct smb2_signing_capabilities *)pctx,
1047 /* offsets must be 8 byte aligned */
1048 clen = (clen + 7) & ~0x7;
1049 offset = clen + sizeof(struct smb2_neg_context);
1050 len_of_ctxts -= clen + sizeof(struct smb2_neg_context);
1056 * smb2_handle_negotiate() - handler for smb2 negotiate command
1057 * @work: smb work containing smb request buffer
1061 int smb2_handle_negotiate(struct ksmbd_work *work)
1063 struct ksmbd_conn *conn = work->conn;
1064 struct smb2_negotiate_req *req = smb2_get_msg(work->request_buf);
1065 struct smb2_negotiate_rsp *rsp = smb2_get_msg(work->response_buf);
1067 unsigned int smb2_buf_len, smb2_neg_size;
1070 ksmbd_debug(SMB, "Received negotiate request\n");
1071 conn->need_neg = false;
1072 if (ksmbd_conn_good(work)) {
1073 pr_err("conn->tcp_status is already in CifsGood State\n");
1074 work->send_no_response = 1;
1078 if (req->DialectCount == 0) {
1079 pr_err("malformed packet\n");
1080 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1085 smb2_buf_len = get_rfc1002_len(work->request_buf);
1086 smb2_neg_size = offsetof(struct smb2_negotiate_req, Dialects);
1087 if (smb2_neg_size > smb2_buf_len) {
1088 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1093 if (conn->dialect == SMB311_PROT_ID) {
1094 unsigned int nego_ctxt_off = le32_to_cpu(req->NegotiateContextOffset);
1096 if (smb2_buf_len < nego_ctxt_off) {
1097 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1102 if (smb2_neg_size > nego_ctxt_off) {
1103 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1108 if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
1110 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1115 if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
1117 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1123 conn->cli_cap = le32_to_cpu(req->Capabilities);
1124 switch (conn->dialect) {
1125 case SMB311_PROT_ID:
1126 conn->preauth_info =
1127 kzalloc(sizeof(struct preauth_integrity_info),
1129 if (!conn->preauth_info) {
1131 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1135 status = deassemble_neg_contexts(conn, req,
1136 get_rfc1002_len(work->request_buf));
1137 if (status != STATUS_SUCCESS) {
1138 pr_err("deassemble_neg_contexts error(0x%x)\n",
1140 rsp->hdr.Status = status;
1145 rc = init_smb3_11_server(conn);
1147 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1151 ksmbd_gen_preauth_integrity_hash(conn,
1153 conn->preauth_info->Preauth_HashValue);
1154 rsp->NegotiateContextOffset =
1155 cpu_to_le32(OFFSET_OF_NEG_CONTEXT);
1156 assemble_neg_contexts(conn, rsp, work->response_buf);
1158 case SMB302_PROT_ID:
1159 init_smb3_02_server(conn);
1162 init_smb3_0_server(conn);
1165 init_smb2_1_server(conn);
1170 ksmbd_debug(SMB, "Server dialect :0x%x not supported\n",
1172 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
1176 rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
1179 conn->connection_type = conn->dialect;
1181 rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
1182 rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
1183 rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);
1185 memcpy(conn->ClientGUID, req->ClientGUID,
1186 SMB2_CLIENT_GUID_SIZE);
1187 conn->cli_sec_mode = le16_to_cpu(req->SecurityMode);
1189 rsp->StructureSize = cpu_to_le16(65);
1190 rsp->DialectRevision = cpu_to_le16(conn->dialect);
1191 /* Not setting conn guid rsp->ServerGUID, as it
1192 * not used by client for identifying server
1194 memset(rsp->ServerGUID, 0, SMB2_CLIENT_GUID_SIZE);
1196 rsp->SystemTime = cpu_to_le64(ksmbd_systime());
1197 rsp->ServerStartTime = 0;
1198 ksmbd_debug(SMB, "negotiate context offset %d, count %d\n",
1199 le32_to_cpu(rsp->NegotiateContextOffset),
1200 le16_to_cpu(rsp->NegotiateContextCount));
1202 rsp->SecurityBufferOffset = cpu_to_le16(128);
1203 rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
1204 ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) +
1205 le16_to_cpu(rsp->SecurityBufferOffset));
1206 inc_rfc1001_len(work->response_buf, sizeof(struct smb2_negotiate_rsp) -
1207 sizeof(struct smb2_hdr) - sizeof(rsp->Buffer) +
1209 rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
1210 conn->use_spnego = true;
1212 if ((server_conf.signing == KSMBD_CONFIG_OPT_AUTO ||
1213 server_conf.signing == KSMBD_CONFIG_OPT_DISABLED) &&
1214 req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED_LE)
1216 else if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY) {
1217 server_conf.enforced_signing = true;
1218 rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
1222 conn->srv_sec_mode = le16_to_cpu(rsp->SecurityMode);
1223 ksmbd_conn_set_need_negotiate(work);
1227 smb2_set_err_rsp(work);
1232 static int alloc_preauth_hash(struct ksmbd_session *sess,
1233 struct ksmbd_conn *conn)
1235 if (sess->Preauth_HashValue)
1238 sess->Preauth_HashValue = kmemdup(conn->preauth_info->Preauth_HashValue,
1239 PREAUTH_HASHVALUE_SIZE, GFP_KERNEL);
1240 if (!sess->Preauth_HashValue)
1246 static int generate_preauth_hash(struct ksmbd_work *work)
1248 struct ksmbd_conn *conn = work->conn;
1249 struct ksmbd_session *sess = work->sess;
1252 if (conn->dialect != SMB311_PROT_ID)
1255 if (conn->binding) {
1256 struct preauth_session *preauth_sess;
1258 preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
1259 if (!preauth_sess) {
1260 preauth_sess = ksmbd_preauth_session_alloc(conn, sess->id);
1265 preauth_hash = preauth_sess->Preauth_HashValue;
1267 if (!sess->Preauth_HashValue)
1268 if (alloc_preauth_hash(sess, conn))
1270 preauth_hash = sess->Preauth_HashValue;
1273 ksmbd_gen_preauth_integrity_hash(conn, work->request_buf, preauth_hash);
1277 static int decode_negotiation_token(struct ksmbd_conn *conn,
1278 struct negotiate_message *negblob,
1281 if (!conn->use_spnego)
1284 if (ksmbd_decode_negTokenInit((char *)negblob, sz, conn)) {
1285 if (ksmbd_decode_negTokenTarg((char *)negblob, sz, conn)) {
1286 conn->auth_mechs |= KSMBD_AUTH_NTLMSSP;
1287 conn->preferred_auth_mech = KSMBD_AUTH_NTLMSSP;
1288 conn->use_spnego = false;
1294 static int ntlm_negotiate(struct ksmbd_work *work,
1295 struct negotiate_message *negblob,
1298 struct smb2_sess_setup_rsp *rsp = smb2_get_msg(work->response_buf);
1299 struct challenge_message *chgblob;
1300 unsigned char *spnego_blob = NULL;
1301 u16 spnego_blob_len;
1305 ksmbd_debug(SMB, "negotiate phase\n");
1306 rc = ksmbd_decode_ntlmssp_neg_blob(negblob, negblob_len, work->conn);
1310 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1312 (struct challenge_message *)((char *)&rsp->hdr.ProtocolId + sz);
1313 memset(chgblob, 0, sizeof(struct challenge_message));
1315 if (!work->conn->use_spnego) {
1316 sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
1320 rsp->SecurityBufferLength = cpu_to_le16(sz);
1324 sz = sizeof(struct challenge_message);
1325 sz += (strlen(ksmbd_netbios_name()) * 2 + 1 + 4) * 6;
1327 neg_blob = kzalloc(sz, GFP_KERNEL);
1331 chgblob = (struct challenge_message *)neg_blob;
1332 sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
1338 rc = build_spnego_ntlmssp_neg_blob(&spnego_blob, &spnego_blob_len,
1345 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1346 memcpy((char *)&rsp->hdr.ProtocolId + sz, spnego_blob, spnego_blob_len);
1347 rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
1355 static struct authenticate_message *user_authblob(struct ksmbd_conn *conn,
1356 struct smb2_sess_setup_req *req)
1360 if (conn->use_spnego && conn->mechToken)
1361 return (struct authenticate_message *)conn->mechToken;
1363 sz = le16_to_cpu(req->SecurityBufferOffset);
1364 return (struct authenticate_message *)((char *)&req->hdr.ProtocolId
1368 static struct ksmbd_user *session_user(struct ksmbd_conn *conn,
1369 struct smb2_sess_setup_req *req)
1371 struct authenticate_message *authblob;
1372 struct ksmbd_user *user;
1374 unsigned int auth_msg_len, name_off, name_len, secbuf_len;
1376 secbuf_len = le16_to_cpu(req->SecurityBufferLength);
1377 if (secbuf_len < sizeof(struct authenticate_message)) {
1378 ksmbd_debug(SMB, "blob len %d too small\n", secbuf_len);
1381 authblob = user_authblob(conn, req);
1382 name_off = le32_to_cpu(authblob->UserName.BufferOffset);
1383 name_len = le16_to_cpu(authblob->UserName.Length);
1384 auth_msg_len = le16_to_cpu(req->SecurityBufferOffset) + secbuf_len;
1386 if (auth_msg_len < (u64)name_off + name_len)
1389 name = smb_strndup_from_utf16((const char *)authblob + name_off,
1394 pr_err("cannot allocate memory\n");
1398 ksmbd_debug(SMB, "session setup request for user %s\n", name);
1399 user = ksmbd_login_user(name);
1404 static int ntlm_authenticate(struct ksmbd_work *work)
1406 struct smb2_sess_setup_req *req = smb2_get_msg(work->request_buf);
1407 struct smb2_sess_setup_rsp *rsp = smb2_get_msg(work->response_buf);
1408 struct ksmbd_conn *conn = work->conn;
1409 struct ksmbd_session *sess = work->sess;
1410 struct channel *chann = NULL;
1411 struct ksmbd_user *user;
1415 ksmbd_debug(SMB, "authenticate phase\n");
1416 if (conn->use_spnego) {
1417 unsigned char *spnego_blob;
1418 u16 spnego_blob_len;
1420 rc = build_spnego_ntlmssp_auth_blob(&spnego_blob,
1426 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1427 memcpy((char *)&rsp->hdr.ProtocolId + sz, spnego_blob, spnego_blob_len);
1428 rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
1430 inc_rfc1001_len(work->response_buf, spnego_blob_len - 1);
1433 user = session_user(conn, req);
1435 ksmbd_debug(SMB, "Unknown user name or an error\n");
1439 /* Check for previous session */
1440 prev_id = le64_to_cpu(req->PreviousSessionId);
1441 if (prev_id && prev_id != sess->id)
1442 destroy_previous_session(user, prev_id);
1444 if (sess->state == SMB2_SESSION_VALID) {
1446 * Reuse session if anonymous try to connect
1447 * on reauthetication.
1449 if (ksmbd_anonymous_user(user)) {
1450 ksmbd_free_user(user);
1454 if (!ksmbd_compare_user(sess->user, user)) {
1455 ksmbd_free_user(user);
1458 ksmbd_free_user(user);
1463 if (user_guest(sess->user)) {
1464 rsp->SessionFlags = SMB2_SESSION_FLAG_IS_GUEST_LE;
1466 struct authenticate_message *authblob;
1468 authblob = user_authblob(conn, req);
1469 sz = le16_to_cpu(req->SecurityBufferLength);
1470 rc = ksmbd_decode_ntlmssp_auth_blob(authblob, sz, conn, sess);
1472 set_user_flag(sess->user, KSMBD_USER_FLAG_BAD_PASSWORD);
1473 ksmbd_debug(SMB, "authentication failed\n");
1479 * If session state is SMB2_SESSION_VALID, We can assume
1480 * that it is reauthentication. And the user/password
1481 * has been verified, so return it here.
1483 if (sess->state == SMB2_SESSION_VALID) {
1485 goto binding_session;
1489 if ((rsp->SessionFlags != SMB2_SESSION_FLAG_IS_GUEST_LE &&
1490 (conn->sign || server_conf.enforced_signing)) ||
1491 (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
1494 if (smb3_encryption_negotiated(conn) &&
1495 !(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1496 rc = conn->ops->generate_encryptionkey(sess);
1499 "SMB3 encryption key generation failed\n");
1503 rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
1505 * signing is disable if encryption is enable
1512 if (conn->dialect >= SMB30_PROT_ID) {
1513 chann = lookup_chann_list(sess, conn);
1515 chann = kmalloc(sizeof(struct channel), GFP_KERNEL);
1520 INIT_LIST_HEAD(&chann->chann_list);
1521 list_add(&chann->chann_list, &sess->ksmbd_chann_list);
1525 if (conn->ops->generate_signingkey) {
1526 rc = conn->ops->generate_signingkey(sess, conn);
1528 ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
1533 if (!ksmbd_conn_lookup_dialect(conn)) {
1534 pr_err("fail to verify the dialect\n");
1540 #ifdef CONFIG_SMB_SERVER_KERBEROS5
1541 static int krb5_authenticate(struct ksmbd_work *work)
1543 struct smb2_sess_setup_req *req = smb2_get_msg(work->request_buf);
1544 struct smb2_sess_setup_rsp *rsp = smb2_get_msg(work->response_buf);
1545 struct ksmbd_conn *conn = work->conn;
1546 struct ksmbd_session *sess = work->sess;
1547 char *in_blob, *out_blob;
1548 struct channel *chann = NULL;
1550 int in_len, out_len;
1553 in_blob = (char *)&req->hdr.ProtocolId +
1554 le16_to_cpu(req->SecurityBufferOffset);
1555 in_len = le16_to_cpu(req->SecurityBufferLength);
1556 out_blob = (char *)&rsp->hdr.ProtocolId +
1557 le16_to_cpu(rsp->SecurityBufferOffset);
1558 out_len = work->response_sz -
1559 (le16_to_cpu(rsp->SecurityBufferOffset) + 4);
1561 /* Check previous session */
1562 prev_sess_id = le64_to_cpu(req->PreviousSessionId);
1563 if (prev_sess_id && prev_sess_id != sess->id)
1564 destroy_previous_session(sess->user, prev_sess_id);
1566 if (sess->state == SMB2_SESSION_VALID)
1567 ksmbd_free_user(sess->user);
1569 retval = ksmbd_krb5_authenticate(sess, in_blob, in_len,
1570 out_blob, &out_len);
1572 ksmbd_debug(SMB, "krb5 authentication failed\n");
1575 rsp->SecurityBufferLength = cpu_to_le16(out_len);
1576 inc_rfc1001_len(work->response_buf, out_len - 1);
1578 if ((conn->sign || server_conf.enforced_signing) ||
1579 (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
1582 if (smb3_encryption_negotiated(conn)) {
1583 retval = conn->ops->generate_encryptionkey(sess);
1586 "SMB3 encryption key generation failed\n");
1590 rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
1594 if (conn->dialect >= SMB30_PROT_ID) {
1595 chann = lookup_chann_list(sess, conn);
1597 chann = kmalloc(sizeof(struct channel), GFP_KERNEL);
1602 INIT_LIST_HEAD(&chann->chann_list);
1603 list_add(&chann->chann_list, &sess->ksmbd_chann_list);
1607 if (conn->ops->generate_signingkey) {
1608 retval = conn->ops->generate_signingkey(sess, conn);
1610 ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
1615 if (!ksmbd_conn_lookup_dialect(conn)) {
1616 pr_err("fail to verify the dialect\n");
1622 static int krb5_authenticate(struct ksmbd_work *work)
1628 int smb2_sess_setup(struct ksmbd_work *work)
1630 struct ksmbd_conn *conn = work->conn;
1631 struct smb2_sess_setup_req *req = smb2_get_msg(work->request_buf);
1632 struct smb2_sess_setup_rsp *rsp = smb2_get_msg(work->response_buf);
1633 struct ksmbd_session *sess;
1634 struct negotiate_message *negblob;
1635 unsigned int negblob_len, negblob_off;
1638 ksmbd_debug(SMB, "Received request for session setup\n");
1640 rsp->StructureSize = cpu_to_le16(9);
1641 rsp->SessionFlags = 0;
1642 rsp->SecurityBufferOffset = cpu_to_le16(72);
1643 rsp->SecurityBufferLength = 0;
1644 inc_rfc1001_len(work->response_buf, 9);
1646 if (!req->hdr.SessionId) {
1647 sess = ksmbd_smb2_session_create();
1652 rsp->hdr.SessionId = cpu_to_le64(sess->id);
1653 ksmbd_session_register(conn, sess);
1654 } else if (conn->dialect >= SMB30_PROT_ID &&
1655 (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
1656 req->Flags & SMB2_SESSION_REQ_FLAG_BINDING) {
1657 u64 sess_id = le64_to_cpu(req->hdr.SessionId);
1659 sess = ksmbd_session_lookup_slowpath(sess_id);
1665 if (conn->dialect != sess->conn->dialect) {
1670 if (!(req->hdr.Flags & SMB2_FLAGS_SIGNED)) {
1675 if (strncmp(conn->ClientGUID, sess->conn->ClientGUID,
1676 SMB2_CLIENT_GUID_SIZE)) {
1681 if (sess->state == SMB2_SESSION_IN_PROGRESS) {
1686 if (sess->state == SMB2_SESSION_EXPIRED) {
1691 if (ksmbd_session_lookup(conn, sess_id)) {
1696 conn->binding = true;
1697 } else if ((conn->dialect < SMB30_PROT_ID ||
1698 server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
1699 (req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1704 sess = ksmbd_session_lookup(conn,
1705 le64_to_cpu(req->hdr.SessionId));
1713 if (sess->state == SMB2_SESSION_EXPIRED)
1714 sess->state = SMB2_SESSION_IN_PROGRESS;
1716 negblob_off = le16_to_cpu(req->SecurityBufferOffset);
1717 negblob_len = le16_to_cpu(req->SecurityBufferLength);
1718 if (negblob_off < offsetof(struct smb2_sess_setup_req, Buffer) ||
1719 negblob_len < offsetof(struct negotiate_message, NegotiateFlags)) {
1724 negblob = (struct negotiate_message *)((char *)&req->hdr.ProtocolId +
1727 if (decode_negotiation_token(conn, negblob, negblob_len) == 0) {
1728 if (conn->mechToken)
1729 negblob = (struct negotiate_message *)conn->mechToken;
1732 if (server_conf.auth_mechs & conn->auth_mechs) {
1733 rc = generate_preauth_hash(work);
1737 if (conn->preferred_auth_mech &
1738 (KSMBD_AUTH_KRB5 | KSMBD_AUTH_MSKRB5)) {
1739 rc = krb5_authenticate(work);
1745 ksmbd_conn_set_good(work);
1746 sess->state = SMB2_SESSION_VALID;
1747 kfree(sess->Preauth_HashValue);
1748 sess->Preauth_HashValue = NULL;
1749 } else if (conn->preferred_auth_mech == KSMBD_AUTH_NTLMSSP) {
1750 if (negblob->MessageType == NtLmNegotiate) {
1751 rc = ntlm_negotiate(work, negblob, negblob_len);
1755 STATUS_MORE_PROCESSING_REQUIRED;
1757 * Note: here total size -1 is done as an
1758 * adjustment for 0 size blob
1760 inc_rfc1001_len(work->response_buf,
1761 le16_to_cpu(rsp->SecurityBufferLength) - 1);
1763 } else if (negblob->MessageType == NtLmAuthenticate) {
1764 rc = ntlm_authenticate(work);
1768 ksmbd_conn_set_good(work);
1769 sess->state = SMB2_SESSION_VALID;
1770 if (conn->binding) {
1771 struct preauth_session *preauth_sess;
1774 ksmbd_preauth_session_lookup(conn, sess->id);
1776 list_del(&preauth_sess->preauth_entry);
1777 kfree(preauth_sess);
1780 kfree(sess->Preauth_HashValue);
1781 sess->Preauth_HashValue = NULL;
1784 /* TODO: need one more negotiation */
1785 pr_err("Not support the preferred authentication\n");
1789 pr_err("Not support authentication\n");
1795 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1796 else if (rc == -ENOENT)
1797 rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
1798 else if (rc == -EACCES)
1799 rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
1800 else if (rc == -EFAULT)
1801 rsp->hdr.Status = STATUS_NETWORK_SESSION_EXPIRED;
1802 else if (rc == -ENOMEM)
1803 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
1805 rsp->hdr.Status = STATUS_LOGON_FAILURE;
1807 if (conn->use_spnego && conn->mechToken) {
1808 kfree(conn->mechToken);
1809 conn->mechToken = NULL;
1814 * SecurityBufferOffset should be set to zero
1815 * in session setup error response.
1817 rsp->SecurityBufferOffset = 0;
1820 bool try_delay = false;
1823 * To avoid dictionary attacks (repeated session setups rapidly sent) to
1824 * connect to server, ksmbd make a delay of a 5 seconds on session setup
1825 * failure to make it harder to send enough random connection requests
1826 * to break into a server.
1828 if (sess->user && sess->user->flags & KSMBD_USER_FLAG_DELAY_SESSION)
1831 ksmbd_session_destroy(sess);
1842 * smb2_tree_connect() - handler for smb2 tree connect command
1843 * @work: smb work containing smb request buffer
1845 * Return: 0 on success, otherwise error
1847 int smb2_tree_connect(struct ksmbd_work *work)
1849 struct ksmbd_conn *conn = work->conn;
1850 struct smb2_tree_connect_req *req = smb2_get_msg(work->request_buf);
1851 struct smb2_tree_connect_rsp *rsp = smb2_get_msg(work->response_buf);
1852 struct ksmbd_session *sess = work->sess;
1853 char *treename = NULL, *name = NULL;
1854 struct ksmbd_tree_conn_status status;
1855 struct ksmbd_share_config *share;
1858 treename = smb_strndup_from_utf16(req->Buffer,
1859 le16_to_cpu(req->PathLength), true,
1861 if (IS_ERR(treename)) {
1862 pr_err("treename is NULL\n");
1863 status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
1867 name = ksmbd_extract_sharename(treename);
1869 status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
1873 ksmbd_debug(SMB, "tree connect request for tree %s treename %s\n",
1876 status = ksmbd_tree_conn_connect(sess, name);
1877 if (status.ret == KSMBD_TREE_CONN_STATUS_OK)
1878 rsp->hdr.Id.SyncId.TreeId = cpu_to_le32(status.tree_conn->id);
1882 share = status.tree_conn->share_conf;
1883 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
1884 ksmbd_debug(SMB, "IPC share path request\n");
1885 rsp->ShareType = SMB2_SHARE_TYPE_PIPE;
1886 rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
1887 FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE |
1888 FILE_DELETE_LE | FILE_READ_CONTROL_LE |
1889 FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
1890 FILE_SYNCHRONIZE_LE;
1892 rsp->ShareType = SMB2_SHARE_TYPE_DISK;
1893 rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
1894 FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE;
1895 if (test_tree_conn_flag(status.tree_conn,
1896 KSMBD_TREE_CONN_FLAG_WRITABLE)) {
1897 rsp->MaximalAccess |= FILE_WRITE_DATA_LE |
1898 FILE_APPEND_DATA_LE | FILE_WRITE_EA_LE |
1899 FILE_DELETE_LE | FILE_WRITE_ATTRIBUTES_LE |
1900 FILE_DELETE_CHILD_LE | FILE_READ_CONTROL_LE |
1901 FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
1902 FILE_SYNCHRONIZE_LE;
1906 status.tree_conn->maximal_access = le32_to_cpu(rsp->MaximalAccess);
1907 if (conn->posix_ext_supported)
1908 status.tree_conn->posix_extensions = true;
1911 rsp->StructureSize = cpu_to_le16(16);
1912 rsp->Capabilities = 0;
1914 /* default manual caching */
1915 rsp->ShareFlags = SMB2_SHAREFLAG_MANUAL_CACHING;
1916 inc_rfc1001_len(work->response_buf, 16);
1918 if (!IS_ERR(treename))
1923 switch (status.ret) {
1924 case KSMBD_TREE_CONN_STATUS_OK:
1925 rsp->hdr.Status = STATUS_SUCCESS;
1928 case KSMBD_TREE_CONN_STATUS_NO_SHARE:
1929 rsp->hdr.Status = STATUS_BAD_NETWORK_PATH;
1932 case KSMBD_TREE_CONN_STATUS_NOMEM:
1933 rsp->hdr.Status = STATUS_NO_MEMORY;
1935 case KSMBD_TREE_CONN_STATUS_ERROR:
1936 case KSMBD_TREE_CONN_STATUS_TOO_MANY_CONNS:
1937 case KSMBD_TREE_CONN_STATUS_TOO_MANY_SESSIONS:
1938 rsp->hdr.Status = STATUS_ACCESS_DENIED;
1941 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1944 rsp->hdr.Status = STATUS_ACCESS_DENIED;
1951 * smb2_create_open_flags() - convert smb open flags to unix open flags
1952 * @file_present: is file already present
1953 * @access: file access flags
1954 * @disposition: file disposition flags
1955 * @may_flags: set with MAY_ flags
1957 * Return: file open flags
1959 static int smb2_create_open_flags(bool file_present, __le32 access,
1963 int oflags = O_NONBLOCK | O_LARGEFILE;
1965 if (access & FILE_READ_DESIRED_ACCESS_LE &&
1966 access & FILE_WRITE_DESIRE_ACCESS_LE) {
1968 *may_flags = MAY_OPEN | MAY_READ | MAY_WRITE;
1969 } else if (access & FILE_WRITE_DESIRE_ACCESS_LE) {
1971 *may_flags = MAY_OPEN | MAY_WRITE;
1974 *may_flags = MAY_OPEN | MAY_READ;
1977 if (access == FILE_READ_ATTRIBUTES_LE)
1981 switch (disposition & FILE_CREATE_MASK_LE) {
1983 case FILE_CREATE_LE:
1985 case FILE_SUPERSEDE_LE:
1986 case FILE_OVERWRITE_LE:
1987 case FILE_OVERWRITE_IF_LE:
1994 switch (disposition & FILE_CREATE_MASK_LE) {
1995 case FILE_SUPERSEDE_LE:
1996 case FILE_CREATE_LE:
1997 case FILE_OPEN_IF_LE:
1998 case FILE_OVERWRITE_IF_LE:
2002 case FILE_OVERWRITE_LE:
2014 * smb2_tree_disconnect() - handler for smb tree connect request
2015 * @work: smb work containing request buffer
2019 int smb2_tree_disconnect(struct ksmbd_work *work)
2021 struct smb2_tree_disconnect_rsp *rsp = smb2_get_msg(work->response_buf);
2022 struct ksmbd_session *sess = work->sess;
2023 struct ksmbd_tree_connect *tcon = work->tcon;
2025 rsp->StructureSize = cpu_to_le16(4);
2026 inc_rfc1001_len(work->response_buf, 4);
2028 ksmbd_debug(SMB, "request\n");
2031 struct smb2_tree_disconnect_req *req =
2032 smb2_get_msg(work->request_buf);
2034 ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
2035 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2036 smb2_set_err_rsp(work);
2040 ksmbd_close_tree_conn_fds(work);
2041 ksmbd_tree_conn_disconnect(sess, tcon);
2046 * smb2_session_logoff() - handler for session log off request
2047 * @work: smb work containing request buffer
2051 int smb2_session_logoff(struct ksmbd_work *work)
2053 struct ksmbd_conn *conn = work->conn;
2054 struct smb2_logoff_rsp *rsp = smb2_get_msg(work->response_buf);
2055 struct ksmbd_session *sess = work->sess;
2057 rsp->StructureSize = cpu_to_le16(4);
2058 inc_rfc1001_len(work->response_buf, 4);
2060 ksmbd_debug(SMB, "request\n");
2062 /* setting CifsExiting here may race with start_tcp_sess */
2063 ksmbd_conn_set_need_reconnect(work);
2064 ksmbd_close_session_fds(work);
2065 ksmbd_conn_wait_idle(conn);
2067 if (ksmbd_tree_conn_session_logoff(sess)) {
2068 struct smb2_logoff_req *req = smb2_get_msg(work->request_buf);
2070 ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
2071 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2072 smb2_set_err_rsp(work);
2076 ksmbd_destroy_file_table(&sess->file_table);
2077 sess->state = SMB2_SESSION_EXPIRED;
2079 ksmbd_free_user(sess->user);
2082 /* let start_tcp_sess free connection info now */
2083 ksmbd_conn_set_need_negotiate(work);
2088 * create_smb2_pipe() - create IPC pipe
2089 * @work: smb work containing request buffer
2091 * Return: 0 on success, otherwise error
2093 static noinline int create_smb2_pipe(struct ksmbd_work *work)
2095 struct smb2_create_rsp *rsp = smb2_get_msg(work->response_buf);
2096 struct smb2_create_req *req = smb2_get_msg(work->request_buf);
2101 name = smb_strndup_from_utf16(req->Buffer, le16_to_cpu(req->NameLength),
2102 1, work->conn->local_nls);
2104 rsp->hdr.Status = STATUS_NO_MEMORY;
2105 err = PTR_ERR(name);
2109 id = ksmbd_session_rpc_open(work->sess, name);
2111 pr_err("Unable to open RPC pipe: %d\n", id);
2116 rsp->hdr.Status = STATUS_SUCCESS;
2117 rsp->StructureSize = cpu_to_le16(89);
2118 rsp->OplockLevel = SMB2_OPLOCK_LEVEL_NONE;
2120 rsp->CreateAction = cpu_to_le32(FILE_OPENED);
2122 rsp->CreationTime = cpu_to_le64(0);
2123 rsp->LastAccessTime = cpu_to_le64(0);
2124 rsp->ChangeTime = cpu_to_le64(0);
2125 rsp->AllocationSize = cpu_to_le64(0);
2126 rsp->EndofFile = cpu_to_le64(0);
2127 rsp->FileAttributes = FILE_ATTRIBUTE_NORMAL_LE;
2129 rsp->VolatileFileId = id;
2130 rsp->PersistentFileId = 0;
2131 rsp->CreateContextsOffset = 0;
2132 rsp->CreateContextsLength = 0;
2134 inc_rfc1001_len(work->response_buf, 88); /* StructureSize - 1*/
2141 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2145 rsp->hdr.Status = STATUS_NO_MEMORY;
2152 smb2_set_err_rsp(work);
2157 * smb2_set_ea() - handler for setting extended attributes using set
2159 * @eabuf: set info command buffer
2160 * @buf_len: set info command buffer length
2161 * @path: dentry path for get ea
2163 * Return: 0 on success, otherwise error
2165 static int smb2_set_ea(struct smb2_ea_info *eabuf, unsigned int buf_len,
2168 struct user_namespace *user_ns = mnt_user_ns(path->mnt);
2169 char *attr_name = NULL, *value;
2171 unsigned int next = 0;
2173 if (buf_len < sizeof(struct smb2_ea_info) + eabuf->EaNameLength +
2174 le16_to_cpu(eabuf->EaValueLength))
2177 attr_name = kmalloc(XATTR_NAME_MAX + 1, GFP_KERNEL);
2182 if (!eabuf->EaNameLength)
2186 "name : <%s>, name_len : %u, value_len : %u, next : %u\n",
2187 eabuf->name, eabuf->EaNameLength,
2188 le16_to_cpu(eabuf->EaValueLength),
2189 le32_to_cpu(eabuf->NextEntryOffset));
2191 if (eabuf->EaNameLength >
2192 (XATTR_NAME_MAX - XATTR_USER_PREFIX_LEN)) {
2197 memcpy(attr_name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN);
2198 memcpy(&attr_name[XATTR_USER_PREFIX_LEN], eabuf->name,
2199 eabuf->EaNameLength);
2200 attr_name[XATTR_USER_PREFIX_LEN + eabuf->EaNameLength] = '\0';
2201 value = (char *)&eabuf->name + eabuf->EaNameLength + 1;
2203 if (!eabuf->EaValueLength) {
2204 rc = ksmbd_vfs_casexattr_len(user_ns,
2207 XATTR_USER_PREFIX_LEN +
2208 eabuf->EaNameLength);
2210 /* delete the EA only when it exits */
2212 rc = ksmbd_vfs_remove_xattr(user_ns,
2218 "remove xattr failed(%d)\n",
2224 /* if the EA doesn't exist, just do nothing. */
2227 rc = ksmbd_vfs_setxattr(user_ns,
2228 path->dentry, attr_name, value,
2229 le16_to_cpu(eabuf->EaValueLength), 0);
2232 "ksmbd_vfs_setxattr is failed(%d)\n",
2239 next = le32_to_cpu(eabuf->NextEntryOffset);
2240 if (next == 0 || buf_len < next)
2243 eabuf = (struct smb2_ea_info *)((char *)eabuf + next);
2244 if (next < (u32)eabuf->EaNameLength + le16_to_cpu(eabuf->EaValueLength))
2247 } while (next != 0);
2253 static noinline int smb2_set_stream_name_xattr(struct path *path,
2254 struct ksmbd_file *fp,
2255 char *stream_name, int s_type)
2257 struct user_namespace *user_ns = mnt_user_ns(path->mnt);
2258 size_t xattr_stream_size;
2259 char *xattr_stream_name;
2262 rc = ksmbd_vfs_xattr_stream_name(stream_name,
2269 fp->stream.name = xattr_stream_name;
2270 fp->stream.size = xattr_stream_size;
2272 /* Check if there is stream prefix in xattr space */
2273 rc = ksmbd_vfs_casexattr_len(user_ns,
2280 if (fp->cdoption == FILE_OPEN_LE) {
2281 ksmbd_debug(SMB, "XATTR stream name lookup failed: %d\n", rc);
2285 rc = ksmbd_vfs_setxattr(user_ns, path->dentry,
2286 xattr_stream_name, NULL, 0, 0);
2288 pr_err("Failed to store XATTR stream name :%d\n", rc);
2292 static int smb2_remove_smb_xattrs(struct path *path)
2294 struct user_namespace *user_ns = mnt_user_ns(path->mnt);
2295 char *name, *xattr_list = NULL;
2296 ssize_t xattr_list_len;
2299 xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
2300 if (xattr_list_len < 0) {
2302 } else if (!xattr_list_len) {
2303 ksmbd_debug(SMB, "empty xattr in the file\n");
2307 for (name = xattr_list; name - xattr_list < xattr_list_len;
2308 name += strlen(name) + 1) {
2309 ksmbd_debug(SMB, "%s, len %zd\n", name, strlen(name));
2311 if (strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN) &&
2312 strncmp(&name[XATTR_USER_PREFIX_LEN], DOS_ATTRIBUTE_PREFIX,
2313 DOS_ATTRIBUTE_PREFIX_LEN) &&
2314 strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX, STREAM_PREFIX_LEN))
2317 err = ksmbd_vfs_remove_xattr(user_ns, path->dentry, name);
2319 ksmbd_debug(SMB, "remove xattr failed : %s\n", name);
2326 static int smb2_create_truncate(struct path *path)
2328 int rc = vfs_truncate(path, 0);
2331 pr_err("vfs_truncate failed, rc %d\n", rc);
2335 rc = smb2_remove_smb_xattrs(path);
2336 if (rc == -EOPNOTSUPP)
2340 "ksmbd_truncate_stream_name_xattr failed, rc %d\n",
2345 static void smb2_new_xattrs(struct ksmbd_tree_connect *tcon, struct path *path,
2346 struct ksmbd_file *fp)
2348 struct xattr_dos_attrib da = {0};
2351 if (!test_share_config_flag(tcon->share_conf,
2352 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2356 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
2357 da.itime = da.create_time = fp->create_time;
2358 da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
2359 XATTR_DOSINFO_ITIME;
2361 rc = ksmbd_vfs_set_dos_attrib_xattr(mnt_user_ns(path->mnt),
2364 ksmbd_debug(SMB, "failed to store file attribute into xattr\n");
2367 static void smb2_update_xattrs(struct ksmbd_tree_connect *tcon,
2368 struct path *path, struct ksmbd_file *fp)
2370 struct xattr_dos_attrib da;
2373 fp->f_ci->m_fattr &= ~(FILE_ATTRIBUTE_HIDDEN_LE | FILE_ATTRIBUTE_SYSTEM_LE);
2375 /* get FileAttributes from XATTR_NAME_DOS_ATTRIBUTE */
2376 if (!test_share_config_flag(tcon->share_conf,
2377 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2380 rc = ksmbd_vfs_get_dos_attrib_xattr(mnt_user_ns(path->mnt),
2383 fp->f_ci->m_fattr = cpu_to_le32(da.attr);
2384 fp->create_time = da.create_time;
2385 fp->itime = da.itime;
2389 static int smb2_creat(struct ksmbd_work *work, struct path *path, char *name,
2390 int open_flags, umode_t posix_mode, bool is_dir)
2392 struct ksmbd_tree_connect *tcon = work->tcon;
2393 struct ksmbd_share_config *share = tcon->share_conf;
2397 if (!(open_flags & O_CREAT))
2400 ksmbd_debug(SMB, "file does not exist, so creating\n");
2401 if (is_dir == true) {
2402 ksmbd_debug(SMB, "creating directory\n");
2404 mode = share_config_directory_mode(share, posix_mode);
2405 rc = ksmbd_vfs_mkdir(work, name, mode);
2409 ksmbd_debug(SMB, "creating regular file\n");
2411 mode = share_config_create_mode(share, posix_mode);
2412 rc = ksmbd_vfs_create(work, name, mode);
2417 rc = ksmbd_vfs_kern_path(work, name, 0, path, 0);
2419 pr_err("cannot get linux path (%s), err = %d\n",
2426 static int smb2_create_sd_buffer(struct ksmbd_work *work,
2427 struct smb2_create_req *req,
2430 struct create_context *context;
2431 struct create_sd_buf_req *sd_buf;
2433 if (!req->CreateContextsOffset)
2436 /* Parse SD BUFFER create contexts */
2437 context = smb2_find_context_vals(req, SMB2_CREATE_SD_BUFFER);
2440 else if (IS_ERR(context))
2441 return PTR_ERR(context);
2444 "Set ACLs using SMB2_CREATE_SD_BUFFER context\n");
2445 sd_buf = (struct create_sd_buf_req *)context;
2446 if (le16_to_cpu(context->DataOffset) +
2447 le32_to_cpu(context->DataLength) <
2448 sizeof(struct create_sd_buf_req))
2450 return set_info_sec(work->conn, work->tcon, path, &sd_buf->ntsd,
2451 le32_to_cpu(sd_buf->ccontext.DataLength), true);
2454 static void ksmbd_acls_fattr(struct smb_fattr *fattr,
2455 struct user_namespace *mnt_userns,
2456 struct inode *inode)
2458 fattr->cf_uid = i_uid_into_mnt(mnt_userns, inode);
2459 fattr->cf_gid = i_gid_into_mnt(mnt_userns, inode);
2460 fattr->cf_mode = inode->i_mode;
2461 fattr->cf_acls = NULL;
2462 fattr->cf_dacls = NULL;
2464 if (IS_ENABLED(CONFIG_FS_POSIX_ACL)) {
2465 fattr->cf_acls = get_acl(inode, ACL_TYPE_ACCESS);
2466 if (S_ISDIR(inode->i_mode))
2467 fattr->cf_dacls = get_acl(inode, ACL_TYPE_DEFAULT);
2472 * smb2_open() - handler for smb file open request
2473 * @work: smb work containing request buffer
2475 * Return: 0 on success, otherwise error
2477 int smb2_open(struct ksmbd_work *work)
2479 struct ksmbd_conn *conn = work->conn;
2480 struct ksmbd_session *sess = work->sess;
2481 struct ksmbd_tree_connect *tcon = work->tcon;
2482 struct smb2_create_req *req;
2483 struct smb2_create_rsp *rsp;
2485 struct ksmbd_share_config *share = tcon->share_conf;
2486 struct ksmbd_file *fp = NULL;
2487 struct file *filp = NULL;
2488 struct user_namespace *user_ns = NULL;
2490 struct create_context *context;
2491 struct lease_ctx_info *lc = NULL;
2492 struct create_ea_buf_req *ea_buf = NULL;
2493 struct oplock_info *opinfo;
2494 __le32 *next_ptr = NULL;
2495 int req_op_level = 0, open_flags = 0, may_flags = 0, file_info = 0;
2497 int contxt_cnt = 0, query_disk_id = 0;
2498 int maximal_access_ctxt = 0, posix_ctxt = 0;
2502 char *stream_name = NULL;
2503 bool file_present = false, created = false, already_permitted = false;
2504 int share_ret, need_truncate = 0;
2506 umode_t posix_mode = 0;
2507 __le32 daccess, maximal_access = 0;
2509 WORK_BUFFERS(work, req, rsp);
2511 if (req->hdr.NextCommand && !work->next_smb2_rcv_hdr_off &&
2512 (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
2513 ksmbd_debug(SMB, "invalid flag in chained command\n");
2514 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2515 smb2_set_err_rsp(work);
2519 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
2520 ksmbd_debug(SMB, "IPC pipe create request\n");
2521 return create_smb2_pipe(work);
2524 if (req->NameLength) {
2525 if ((req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
2526 *(char *)req->Buffer == '\\') {
2527 pr_err("not allow directory name included leading slash\n");
2532 name = smb2_get_name(req->Buffer,
2533 le16_to_cpu(req->NameLength),
2534 work->conn->local_nls);
2543 ksmbd_debug(SMB, "converted name = %s\n", name);
2544 if (strchr(name, ':')) {
2545 if (!test_share_config_flag(work->tcon->share_conf,
2546 KSMBD_SHARE_FLAG_STREAMS)) {
2550 rc = parse_stream_name(name, &stream_name, &s_type);
2555 rc = ksmbd_validate_filename(name);
2559 if (ksmbd_share_veto_filename(share, name)) {
2561 ksmbd_debug(SMB, "Reject open(), vetoed file: %s\n",
2566 name = kstrdup("", GFP_KERNEL);
2573 req_op_level = req->RequestedOplockLevel;
2574 if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE)
2575 lc = parse_lease_state(req);
2577 if (le32_to_cpu(req->ImpersonationLevel) > le32_to_cpu(IL_DELEGATE)) {
2578 pr_err("Invalid impersonationlevel : 0x%x\n",
2579 le32_to_cpu(req->ImpersonationLevel));
2581 rsp->hdr.Status = STATUS_BAD_IMPERSONATION_LEVEL;
2585 if (req->CreateOptions && !(req->CreateOptions & CREATE_OPTIONS_MASK_LE)) {
2586 pr_err("Invalid create options : 0x%x\n",
2587 le32_to_cpu(req->CreateOptions));
2591 if (req->CreateOptions & FILE_SEQUENTIAL_ONLY_LE &&
2592 req->CreateOptions & FILE_RANDOM_ACCESS_LE)
2593 req->CreateOptions = ~(FILE_SEQUENTIAL_ONLY_LE);
2595 if (req->CreateOptions &
2596 (FILE_OPEN_BY_FILE_ID_LE | CREATE_TREE_CONNECTION |
2597 FILE_RESERVE_OPFILTER_LE)) {
2602 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
2603 if (req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE) {
2606 } else if (req->CreateOptions & FILE_NO_COMPRESSION_LE) {
2607 req->CreateOptions = ~(FILE_NO_COMPRESSION_LE);
2612 if (le32_to_cpu(req->CreateDisposition) >
2613 le32_to_cpu(FILE_OVERWRITE_IF_LE)) {
2614 pr_err("Invalid create disposition : 0x%x\n",
2615 le32_to_cpu(req->CreateDisposition));
2620 if (!(req->DesiredAccess & DESIRED_ACCESS_MASK)) {
2621 pr_err("Invalid desired access : 0x%x\n",
2622 le32_to_cpu(req->DesiredAccess));
2627 if (req->FileAttributes && !(req->FileAttributes & FILE_ATTRIBUTE_MASK_LE)) {
2628 pr_err("Invalid file attribute : 0x%x\n",
2629 le32_to_cpu(req->FileAttributes));
2634 if (req->CreateContextsOffset) {
2635 /* Parse non-durable handle create contexts */
2636 context = smb2_find_context_vals(req, SMB2_CREATE_EA_BUFFER);
2637 if (IS_ERR(context)) {
2638 rc = PTR_ERR(context);
2640 } else if (context) {
2641 ea_buf = (struct create_ea_buf_req *)context;
2642 if (le16_to_cpu(context->DataOffset) +
2643 le32_to_cpu(context->DataLength) <
2644 sizeof(struct create_ea_buf_req)) {
2648 if (req->CreateOptions & FILE_NO_EA_KNOWLEDGE_LE) {
2649 rsp->hdr.Status = STATUS_ACCESS_DENIED;
2655 context = smb2_find_context_vals(req,
2656 SMB2_CREATE_QUERY_MAXIMAL_ACCESS_REQUEST);
2657 if (IS_ERR(context)) {
2658 rc = PTR_ERR(context);
2660 } else if (context) {
2662 "get query maximal access context\n");
2663 maximal_access_ctxt = 1;
2666 context = smb2_find_context_vals(req,
2667 SMB2_CREATE_TIMEWARP_REQUEST);
2668 if (IS_ERR(context)) {
2669 rc = PTR_ERR(context);
2671 } else if (context) {
2672 ksmbd_debug(SMB, "get timewarp context\n");
2677 if (tcon->posix_extensions) {
2678 context = smb2_find_context_vals(req,
2679 SMB2_CREATE_TAG_POSIX);
2680 if (IS_ERR(context)) {
2681 rc = PTR_ERR(context);
2683 } else if (context) {
2684 struct create_posix *posix =
2685 (struct create_posix *)context;
2686 if (le16_to_cpu(context->DataOffset) +
2687 le32_to_cpu(context->DataLength) <
2688 sizeof(struct create_posix) - 4) {
2692 ksmbd_debug(SMB, "get posix context\n");
2694 posix_mode = le32_to_cpu(posix->Mode);
2700 if (ksmbd_override_fsids(work)) {
2705 rc = ksmbd_vfs_kern_path(work, name, LOOKUP_NO_SYMLINKS, &path, 1);
2707 if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE) {
2709 * If file exists with under flags, return access
2712 if (req->CreateDisposition == FILE_OVERWRITE_IF_LE ||
2713 req->CreateDisposition == FILE_OPEN_IF_LE) {
2719 if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
2721 "User does not have write permission\n");
2726 } else if (d_is_symlink(path.dentry)) {
2736 ksmbd_debug(SMB, "can not get linux path for %s, rc = %d\n",
2740 file_present = true;
2741 user_ns = mnt_user_ns(path.mnt);
2742 generic_fillattr(user_ns, d_inode(path.dentry), &stat);
2745 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
2746 if (s_type == DATA_STREAM) {
2748 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2751 if (S_ISDIR(stat.mode) && s_type == DATA_STREAM) {
2753 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
2757 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE &&
2758 req->FileAttributes & FILE_ATTRIBUTE_NORMAL_LE) {
2759 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2767 if (file_present && req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE &&
2768 S_ISDIR(stat.mode) && !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2769 ksmbd_debug(SMB, "open() argument is a directory: %s, %x\n",
2770 name, req->CreateOptions);
2771 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
2776 if (file_present && (req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
2777 !(req->CreateDisposition == FILE_CREATE_LE) &&
2778 !S_ISDIR(stat.mode)) {
2779 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2784 if (!stream_name && file_present &&
2785 req->CreateDisposition == FILE_CREATE_LE) {
2790 daccess = smb_map_generic_desired_access(req->DesiredAccess);
2792 if (file_present && !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2793 rc = smb_check_perm_dacl(conn, &path, &daccess,
2799 if (daccess & FILE_MAXIMAL_ACCESS_LE) {
2800 if (!file_present) {
2801 daccess = cpu_to_le32(GENERIC_ALL_FLAGS);
2803 rc = ksmbd_vfs_query_maximal_access(user_ns,
2808 already_permitted = true;
2810 maximal_access = daccess;
2813 open_flags = smb2_create_open_flags(file_present, daccess,
2814 req->CreateDisposition,
2817 if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
2818 if (open_flags & O_CREAT) {
2820 "User does not have write permission\n");
2826 /*create file if not present */
2827 if (!file_present) {
2828 rc = smb2_creat(work, &path, name, open_flags, posix_mode,
2829 req->CreateOptions & FILE_DIRECTORY_FILE_LE);
2831 if (rc == -ENOENT) {
2833 rsp->hdr.Status = STATUS_OBJECT_PATH_NOT_FOUND;
2839 user_ns = mnt_user_ns(path.mnt);
2841 if (le32_to_cpu(ea_buf->ccontext.DataLength) <
2842 sizeof(struct smb2_ea_info)) {
2847 rc = smb2_set_ea(&ea_buf->ea,
2848 le32_to_cpu(ea_buf->ccontext.DataLength),
2850 if (rc == -EOPNOTSUPP)
2855 } else if (!already_permitted) {
2856 /* FILE_READ_ATTRIBUTE is allowed without inode_permission,
2857 * because execute(search) permission on a parent directory,
2858 * is already granted.
2860 if (daccess & ~(FILE_READ_ATTRIBUTES_LE | FILE_READ_CONTROL_LE)) {
2861 rc = inode_permission(user_ns,
2862 d_inode(path.dentry),
2867 if ((daccess & FILE_DELETE_LE) ||
2868 (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2869 rc = ksmbd_vfs_may_delete(user_ns,
2877 rc = ksmbd_query_inode_status(d_inode(path.dentry->d_parent));
2878 if (rc == KSMBD_INODE_STATUS_PENDING_DELETE) {
2884 filp = dentry_open(&path, open_flags, current_cred());
2887 pr_err("dentry open for dir failed, rc %d\n", rc);
2892 if (!(open_flags & O_TRUNC))
2893 file_info = FILE_OPENED;
2895 file_info = FILE_OVERWRITTEN;
2897 if ((req->CreateDisposition & FILE_CREATE_MASK_LE) ==
2899 file_info = FILE_SUPERSEDED;
2900 } else if (open_flags & O_CREAT) {
2901 file_info = FILE_CREATED;
2904 ksmbd_vfs_set_fadvise(filp, req->CreateOptions);
2906 /* Obtain Volatile-ID */
2907 fp = ksmbd_open_fd(work, filp);
2915 /* Get Persistent-ID */
2916 ksmbd_open_durable_fd(fp);
2917 if (!has_file_id(fp->persistent_id)) {
2922 fp->cdoption = req->CreateDisposition;
2923 fp->daccess = daccess;
2924 fp->saccess = req->ShareAccess;
2925 fp->coption = req->CreateOptions;
2927 /* Set default windows and posix acls if creating new file */
2930 struct inode *inode = d_inode(path.dentry);
2932 posix_acl_rc = ksmbd_vfs_inherit_posix_acl(user_ns,
2934 d_inode(path.dentry->d_parent));
2936 ksmbd_debug(SMB, "inherit posix acl failed : %d\n", posix_acl_rc);
2938 if (test_share_config_flag(work->tcon->share_conf,
2939 KSMBD_SHARE_FLAG_ACL_XATTR)) {
2940 rc = smb_inherit_dacl(conn, &path, sess->user->uid,
2945 rc = smb2_create_sd_buffer(work, req, &path);
2948 ksmbd_vfs_set_init_posix_acl(user_ns,
2951 if (test_share_config_flag(work->tcon->share_conf,
2952 KSMBD_SHARE_FLAG_ACL_XATTR)) {
2953 struct smb_fattr fattr;
2954 struct smb_ntsd *pntsd;
2955 int pntsd_size, ace_num = 0;
2957 ksmbd_acls_fattr(&fattr, user_ns, inode);
2959 ace_num = fattr.cf_acls->a_count;
2961 ace_num += fattr.cf_dacls->a_count;
2963 pntsd = kmalloc(sizeof(struct smb_ntsd) +
2964 sizeof(struct smb_sid) * 3 +
2965 sizeof(struct smb_acl) +
2966 sizeof(struct smb_ace) * ace_num * 2,
2971 rc = build_sec_desc(user_ns,
2976 &pntsd_size, &fattr);
2977 posix_acl_release(fattr.cf_acls);
2978 posix_acl_release(fattr.cf_dacls);
2984 rc = ksmbd_vfs_set_sd_xattr(conn,
2991 pr_err("failed to store ntacl in xattr : %d\n",
3000 rc = smb2_set_stream_name_xattr(&path,
3006 file_info = FILE_CREATED;
3009 fp->attrib_only = !(req->DesiredAccess & ~(FILE_READ_ATTRIBUTES_LE |
3010 FILE_WRITE_ATTRIBUTES_LE | FILE_SYNCHRONIZE_LE));
3011 if (!S_ISDIR(file_inode(filp)->i_mode) && open_flags & O_TRUNC &&
3012 !fp->attrib_only && !stream_name) {
3013 smb_break_all_oplock(work, fp);
3017 /* fp should be searchable through ksmbd_inode.m_fp_list
3018 * after daccess, saccess, attrib_only, and stream are
3021 write_lock(&fp->f_ci->m_lock);
3022 list_add(&fp->node, &fp->f_ci->m_fp_list);
3023 write_unlock(&fp->f_ci->m_lock);
3025 rc = ksmbd_vfs_getattr(&path, &stat);
3027 generic_fillattr(user_ns, d_inode(path.dentry), &stat);
3031 /* Check delete pending among previous fp before oplock break */
3032 if (ksmbd_inode_pending_delete(fp)) {
3037 share_ret = ksmbd_smb_check_shared_mode(fp->filp, fp);
3038 if (!test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_OPLOCKS) ||
3039 (req_op_level == SMB2_OPLOCK_LEVEL_LEASE &&
3040 !(conn->vals->capabilities & SMB2_GLOBAL_CAP_LEASING))) {
3041 if (share_ret < 0 && !S_ISDIR(file_inode(fp->filp)->i_mode)) {
3046 if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE) {
3047 req_op_level = smb2_map_lease_to_oplock(lc->req_state);
3049 "lease req for(%s) req oplock state 0x%x, lease state 0x%x\n",
3050 name, req_op_level, lc->req_state);
3051 rc = find_same_lease_key(sess, fp->f_ci, lc);
3054 } else if (open_flags == O_RDONLY &&
3055 (req_op_level == SMB2_OPLOCK_LEVEL_BATCH ||
3056 req_op_level == SMB2_OPLOCK_LEVEL_EXCLUSIVE))
3057 req_op_level = SMB2_OPLOCK_LEVEL_II;
3059 rc = smb_grant_oplock(work, req_op_level,
3060 fp->persistent_id, fp,
3061 le32_to_cpu(req->hdr.Id.SyncId.TreeId),
3067 if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)
3068 ksmbd_fd_set_delete_on_close(fp, file_info);
3070 if (need_truncate) {
3071 rc = smb2_create_truncate(&path);
3076 if (req->CreateContextsOffset) {
3077 struct create_alloc_size_req *az_req;
3079 az_req = (struct create_alloc_size_req *)smb2_find_context_vals(req,
3080 SMB2_CREATE_ALLOCATION_SIZE);
3081 if (IS_ERR(az_req)) {
3082 rc = PTR_ERR(az_req);
3084 } else if (az_req) {
3088 if (le16_to_cpu(az_req->ccontext.DataOffset) +
3089 le32_to_cpu(az_req->ccontext.DataLength) <
3090 sizeof(struct create_alloc_size_req)) {
3094 alloc_size = le64_to_cpu(az_req->AllocationSize);
3096 "request smb2 create allocate size : %llu\n",
3098 smb_break_all_levII_oplock(work, fp, 1);
3099 err = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
3103 "vfs_fallocate is failed : %d\n",
3107 context = smb2_find_context_vals(req, SMB2_CREATE_QUERY_ON_DISK_ID);
3108 if (IS_ERR(context)) {
3109 rc = PTR_ERR(context);
3111 } else if (context) {
3112 ksmbd_debug(SMB, "get query on disk id context\n");
3117 if (stat.result_mask & STATX_BTIME)
3118 fp->create_time = ksmbd_UnixTimeToNT(stat.btime);
3120 fp->create_time = ksmbd_UnixTimeToNT(stat.ctime);
3121 if (req->FileAttributes || fp->f_ci->m_fattr == 0)
3123 cpu_to_le32(smb2_get_dos_mode(&stat, le32_to_cpu(req->FileAttributes)));
3126 smb2_update_xattrs(tcon, &path, fp);
3128 smb2_new_xattrs(tcon, &path, fp);
3130 memcpy(fp->client_guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE);
3132 generic_fillattr(user_ns, file_inode(fp->filp),
3135 rsp->StructureSize = cpu_to_le16(89);
3137 opinfo = rcu_dereference(fp->f_opinfo);
3138 rsp->OplockLevel = opinfo != NULL ? opinfo->level : 0;
3141 rsp->CreateAction = cpu_to_le32(file_info);
3142 rsp->CreationTime = cpu_to_le64(fp->create_time);
3143 time = ksmbd_UnixTimeToNT(stat.atime);
3144 rsp->LastAccessTime = cpu_to_le64(time);
3145 time = ksmbd_UnixTimeToNT(stat.mtime);
3146 rsp->LastWriteTime = cpu_to_le64(time);
3147 time = ksmbd_UnixTimeToNT(stat.ctime);
3148 rsp->ChangeTime = cpu_to_le64(time);
3149 rsp->AllocationSize = S_ISDIR(stat.mode) ? 0 :
3150 cpu_to_le64(stat.blocks << 9);
3151 rsp->EndofFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
3152 rsp->FileAttributes = fp->f_ci->m_fattr;
3156 rsp->PersistentFileId = fp->persistent_id;
3157 rsp->VolatileFileId = fp->volatile_id;
3159 rsp->CreateContextsOffset = 0;
3160 rsp->CreateContextsLength = 0;
3161 inc_rfc1001_len(work->response_buf, 88); /* StructureSize - 1*/
3163 /* If lease is request send lease context response */
3164 if (opinfo && opinfo->is_lease) {
3165 struct create_context *lease_ccontext;
3167 ksmbd_debug(SMB, "lease granted on(%s) lease state 0x%x\n",
3168 name, opinfo->o_lease->state);
3169 rsp->OplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
3171 lease_ccontext = (struct create_context *)rsp->Buffer;
3173 create_lease_buf(rsp->Buffer, opinfo->o_lease);
3174 le32_add_cpu(&rsp->CreateContextsLength,
3175 conn->vals->create_lease_size);
3176 inc_rfc1001_len(work->response_buf,
3177 conn->vals->create_lease_size);
3178 next_ptr = &lease_ccontext->Next;
3179 next_off = conn->vals->create_lease_size;
3182 if (maximal_access_ctxt) {
3183 struct create_context *mxac_ccontext;
3185 if (maximal_access == 0)
3186 ksmbd_vfs_query_maximal_access(user_ns,
3189 mxac_ccontext = (struct create_context *)(rsp->Buffer +
3190 le32_to_cpu(rsp->CreateContextsLength));
3192 create_mxac_rsp_buf(rsp->Buffer +
3193 le32_to_cpu(rsp->CreateContextsLength),
3194 le32_to_cpu(maximal_access));
3195 le32_add_cpu(&rsp->CreateContextsLength,
3196 conn->vals->create_mxac_size);
3197 inc_rfc1001_len(work->response_buf,
3198 conn->vals->create_mxac_size);
3200 *next_ptr = cpu_to_le32(next_off);
3201 next_ptr = &mxac_ccontext->Next;
3202 next_off = conn->vals->create_mxac_size;
3205 if (query_disk_id) {
3206 struct create_context *disk_id_ccontext;
3208 disk_id_ccontext = (struct create_context *)(rsp->Buffer +
3209 le32_to_cpu(rsp->CreateContextsLength));
3211 create_disk_id_rsp_buf(rsp->Buffer +
3212 le32_to_cpu(rsp->CreateContextsLength),
3213 stat.ino, tcon->id);
3214 le32_add_cpu(&rsp->CreateContextsLength,
3215 conn->vals->create_disk_id_size);
3216 inc_rfc1001_len(work->response_buf,
3217 conn->vals->create_disk_id_size);
3219 *next_ptr = cpu_to_le32(next_off);
3220 next_ptr = &disk_id_ccontext->Next;
3221 next_off = conn->vals->create_disk_id_size;
3226 create_posix_rsp_buf(rsp->Buffer +
3227 le32_to_cpu(rsp->CreateContextsLength),
3229 le32_add_cpu(&rsp->CreateContextsLength,
3230 conn->vals->create_posix_size);
3231 inc_rfc1001_len(work->response_buf,
3232 conn->vals->create_posix_size);
3234 *next_ptr = cpu_to_le32(next_off);
3237 if (contxt_cnt > 0) {
3238 rsp->CreateContextsOffset =
3239 cpu_to_le32(offsetof(struct smb2_create_rsp, Buffer));
3243 if (file_present || created)
3245 ksmbd_revert_fsids(work);
3249 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
3250 else if (rc == -EOPNOTSUPP)
3251 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
3252 else if (rc == -EACCES || rc == -ESTALE || rc == -EXDEV)
3253 rsp->hdr.Status = STATUS_ACCESS_DENIED;
3254 else if (rc == -ENOENT)
3255 rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
3256 else if (rc == -EPERM)
3257 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
3258 else if (rc == -EBUSY)
3259 rsp->hdr.Status = STATUS_DELETE_PENDING;
3260 else if (rc == -EBADF)
3261 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
3262 else if (rc == -ENOEXEC)
3263 rsp->hdr.Status = STATUS_DUPLICATE_OBJECTID;
3264 else if (rc == -ENXIO)
3265 rsp->hdr.Status = STATUS_NO_SUCH_DEVICE;
3266 else if (rc == -EEXIST)
3267 rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
3268 else if (rc == -EMFILE)
3269 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
3270 if (!rsp->hdr.Status)
3271 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
3274 ksmbd_fd_put(work, fp);
3275 smb2_set_err_rsp(work);
3276 ksmbd_debug(SMB, "Error response: %x\n", rsp->hdr.Status);
3285 static int readdir_info_level_struct_sz(int info_level)
3287 switch (info_level) {
3288 case FILE_FULL_DIRECTORY_INFORMATION:
3289 return sizeof(struct file_full_directory_info);
3290 case FILE_BOTH_DIRECTORY_INFORMATION:
3291 return sizeof(struct file_both_directory_info);
3292 case FILE_DIRECTORY_INFORMATION:
3293 return sizeof(struct file_directory_info);
3294 case FILE_NAMES_INFORMATION:
3295 return sizeof(struct file_names_info);
3296 case FILEID_FULL_DIRECTORY_INFORMATION:
3297 return sizeof(struct file_id_full_dir_info);
3298 case FILEID_BOTH_DIRECTORY_INFORMATION:
3299 return sizeof(struct file_id_both_directory_info);
3300 case SMB_FIND_FILE_POSIX_INFO:
3301 return sizeof(struct smb2_posix_info);
3307 static int dentry_name(struct ksmbd_dir_info *d_info, int info_level)
3309 switch (info_level) {
3310 case FILE_FULL_DIRECTORY_INFORMATION:
3312 struct file_full_directory_info *ffdinfo;
3314 ffdinfo = (struct file_full_directory_info *)d_info->rptr;
3315 d_info->rptr += le32_to_cpu(ffdinfo->NextEntryOffset);
3316 d_info->name = ffdinfo->FileName;
3317 d_info->name_len = le32_to_cpu(ffdinfo->FileNameLength);
3320 case FILE_BOTH_DIRECTORY_INFORMATION:
3322 struct file_both_directory_info *fbdinfo;
3324 fbdinfo = (struct file_both_directory_info *)d_info->rptr;
3325 d_info->rptr += le32_to_cpu(fbdinfo->NextEntryOffset);
3326 d_info->name = fbdinfo->FileName;
3327 d_info->name_len = le32_to_cpu(fbdinfo->FileNameLength);
3330 case FILE_DIRECTORY_INFORMATION:
3332 struct file_directory_info *fdinfo;
3334 fdinfo = (struct file_directory_info *)d_info->rptr;
3335 d_info->rptr += le32_to_cpu(fdinfo->NextEntryOffset);
3336 d_info->name = fdinfo->FileName;
3337 d_info->name_len = le32_to_cpu(fdinfo->FileNameLength);
3340 case FILE_NAMES_INFORMATION:
3342 struct file_names_info *fninfo;
3344 fninfo = (struct file_names_info *)d_info->rptr;
3345 d_info->rptr += le32_to_cpu(fninfo->NextEntryOffset);
3346 d_info->name = fninfo->FileName;
3347 d_info->name_len = le32_to_cpu(fninfo->FileNameLength);
3350 case FILEID_FULL_DIRECTORY_INFORMATION:
3352 struct file_id_full_dir_info *dinfo;
3354 dinfo = (struct file_id_full_dir_info *)d_info->rptr;
3355 d_info->rptr += le32_to_cpu(dinfo->NextEntryOffset);
3356 d_info->name = dinfo->FileName;
3357 d_info->name_len = le32_to_cpu(dinfo->FileNameLength);
3360 case FILEID_BOTH_DIRECTORY_INFORMATION:
3362 struct file_id_both_directory_info *fibdinfo;
3364 fibdinfo = (struct file_id_both_directory_info *)d_info->rptr;
3365 d_info->rptr += le32_to_cpu(fibdinfo->NextEntryOffset);
3366 d_info->name = fibdinfo->FileName;
3367 d_info->name_len = le32_to_cpu(fibdinfo->FileNameLength);
3370 case SMB_FIND_FILE_POSIX_INFO:
3372 struct smb2_posix_info *posix_info;
3374 posix_info = (struct smb2_posix_info *)d_info->rptr;
3375 d_info->rptr += le32_to_cpu(posix_info->NextEntryOffset);
3376 d_info->name = posix_info->name;
3377 d_info->name_len = le32_to_cpu(posix_info->name_len);
3386 * smb2_populate_readdir_entry() - encode directory entry in smb2 response
3388 * @conn: connection instance
3389 * @info_level: smb information level
3390 * @d_info: structure included variables for query dir
3391 * @ksmbd_kstat: ksmbd wrapper of dirent stat information
3393 * if directory has many entries, find first can't read it fully.
3394 * find next might be called multiple times to read remaining dir entries
3396 * Return: 0 on success, otherwise error
3398 static int smb2_populate_readdir_entry(struct ksmbd_conn *conn, int info_level,
3399 struct ksmbd_dir_info *d_info,
3400 struct ksmbd_kstat *ksmbd_kstat)
3402 int next_entry_offset = 0;
3406 int struct_sz, rc = 0;
3408 conv_name = ksmbd_convert_dir_info_name(d_info,
3414 /* Somehow the name has only terminating NULL bytes */
3417 goto free_conv_name;
3420 struct_sz = readdir_info_level_struct_sz(info_level) - 1 + conv_len;
3421 next_entry_offset = ALIGN(struct_sz, KSMBD_DIR_INFO_ALIGNMENT);
3422 d_info->last_entry_off_align = next_entry_offset - struct_sz;
3424 if (next_entry_offset > d_info->out_buf_len) {
3425 d_info->out_buf_len = 0;
3427 goto free_conv_name;
3430 kstat = d_info->wptr;
3431 if (info_level != FILE_NAMES_INFORMATION)
3432 kstat = ksmbd_vfs_init_kstat(&d_info->wptr, ksmbd_kstat);
3434 switch (info_level) {
3435 case FILE_FULL_DIRECTORY_INFORMATION:
3437 struct file_full_directory_info *ffdinfo;
3439 ffdinfo = (struct file_full_directory_info *)kstat;
3440 ffdinfo->FileNameLength = cpu_to_le32(conv_len);
3442 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3443 if (ffdinfo->EaSize)
3444 ffdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3445 if (d_info->hide_dot_file && d_info->name[0] == '.')
3446 ffdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3447 memcpy(ffdinfo->FileName, conv_name, conv_len);
3448 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3451 case FILE_BOTH_DIRECTORY_INFORMATION:
3453 struct file_both_directory_info *fbdinfo;
3455 fbdinfo = (struct file_both_directory_info *)kstat;
3456 fbdinfo->FileNameLength = cpu_to_le32(conv_len);
3458 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3459 if (fbdinfo->EaSize)
3460 fbdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3461 fbdinfo->ShortNameLength = 0;
3462 fbdinfo->Reserved = 0;
3463 if (d_info->hide_dot_file && d_info->name[0] == '.')
3464 fbdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3465 memcpy(fbdinfo->FileName, conv_name, conv_len);
3466 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3469 case FILE_DIRECTORY_INFORMATION:
3471 struct file_directory_info *fdinfo;
3473 fdinfo = (struct file_directory_info *)kstat;
3474 fdinfo->FileNameLength = cpu_to_le32(conv_len);
3475 if (d_info->hide_dot_file && d_info->name[0] == '.')
3476 fdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3477 memcpy(fdinfo->FileName, conv_name, conv_len);
3478 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3481 case FILE_NAMES_INFORMATION:
3483 struct file_names_info *fninfo;
3485 fninfo = (struct file_names_info *)kstat;
3486 fninfo->FileNameLength = cpu_to_le32(conv_len);
3487 memcpy(fninfo->FileName, conv_name, conv_len);
3488 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3491 case FILEID_FULL_DIRECTORY_INFORMATION:
3493 struct file_id_full_dir_info *dinfo;
3495 dinfo = (struct file_id_full_dir_info *)kstat;
3496 dinfo->FileNameLength = cpu_to_le32(conv_len);
3498 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3500 dinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3501 dinfo->Reserved = 0;
3502 dinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
3503 if (d_info->hide_dot_file && d_info->name[0] == '.')
3504 dinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3505 memcpy(dinfo->FileName, conv_name, conv_len);
3506 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3509 case FILEID_BOTH_DIRECTORY_INFORMATION:
3511 struct file_id_both_directory_info *fibdinfo;
3513 fibdinfo = (struct file_id_both_directory_info *)kstat;
3514 fibdinfo->FileNameLength = cpu_to_le32(conv_len);
3516 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3517 if (fibdinfo->EaSize)
3518 fibdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3519 fibdinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
3520 fibdinfo->ShortNameLength = 0;
3521 fibdinfo->Reserved = 0;
3522 fibdinfo->Reserved2 = cpu_to_le16(0);
3523 if (d_info->hide_dot_file && d_info->name[0] == '.')
3524 fibdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3525 memcpy(fibdinfo->FileName, conv_name, conv_len);
3526 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3529 case SMB_FIND_FILE_POSIX_INFO:
3531 struct smb2_posix_info *posix_info;
3534 posix_info = (struct smb2_posix_info *)kstat;
3535 posix_info->Ignored = 0;
3536 posix_info->CreationTime = cpu_to_le64(ksmbd_kstat->create_time);
3537 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->ctime);
3538 posix_info->ChangeTime = cpu_to_le64(time);
3539 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->atime);
3540 posix_info->LastAccessTime = cpu_to_le64(time);
3541 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->mtime);
3542 posix_info->LastWriteTime = cpu_to_le64(time);
3543 posix_info->EndOfFile = cpu_to_le64(ksmbd_kstat->kstat->size);
3544 posix_info->AllocationSize = cpu_to_le64(ksmbd_kstat->kstat->blocks << 9);
3545 posix_info->DeviceId = cpu_to_le32(ksmbd_kstat->kstat->rdev);
3546 posix_info->HardLinks = cpu_to_le32(ksmbd_kstat->kstat->nlink);
3547 posix_info->Mode = cpu_to_le32(ksmbd_kstat->kstat->mode);
3548 posix_info->Inode = cpu_to_le64(ksmbd_kstat->kstat->ino);
3549 posix_info->DosAttributes =
3550 S_ISDIR(ksmbd_kstat->kstat->mode) ?
3551 FILE_ATTRIBUTE_DIRECTORY_LE : FILE_ATTRIBUTE_ARCHIVE_LE;
3552 if (d_info->hide_dot_file && d_info->name[0] == '.')
3553 posix_info->DosAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3554 id_to_sid(from_kuid_munged(&init_user_ns, ksmbd_kstat->kstat->uid),
3555 SIDNFS_USER, (struct smb_sid *)&posix_info->SidBuffer[0]);
3556 id_to_sid(from_kgid_munged(&init_user_ns, ksmbd_kstat->kstat->gid),
3557 SIDNFS_GROUP, (struct smb_sid *)&posix_info->SidBuffer[20]);
3558 memcpy(posix_info->name, conv_name, conv_len);
3559 posix_info->name_len = cpu_to_le32(conv_len);
3560 posix_info->NextEntryOffset = cpu_to_le32(next_entry_offset);
3564 } /* switch (info_level) */
3566 d_info->last_entry_offset = d_info->data_count;
3567 d_info->data_count += next_entry_offset;
3568 d_info->out_buf_len -= next_entry_offset;
3569 d_info->wptr += next_entry_offset;
3572 "info_level : %d, buf_len :%d, next_offset : %d, data_count : %d\n",
3573 info_level, d_info->out_buf_len,
3574 next_entry_offset, d_info->data_count);
3581 struct smb2_query_dir_private {
3582 struct ksmbd_work *work;
3583 char *search_pattern;
3584 struct ksmbd_file *dir_fp;
3586 struct ksmbd_dir_info *d_info;
3590 static void lock_dir(struct ksmbd_file *dir_fp)
3592 struct dentry *dir = dir_fp->filp->f_path.dentry;
3594 inode_lock_nested(d_inode(dir), I_MUTEX_PARENT);
3597 static void unlock_dir(struct ksmbd_file *dir_fp)
3599 struct dentry *dir = dir_fp->filp->f_path.dentry;
3601 inode_unlock(d_inode(dir));
3604 static int process_query_dir_entries(struct smb2_query_dir_private *priv)
3606 struct user_namespace *user_ns = file_mnt_user_ns(priv->dir_fp->filp);
3608 struct ksmbd_kstat ksmbd_kstat;
3612 for (i = 0; i < priv->d_info->num_entry; i++) {
3613 struct dentry *dent;
3615 if (dentry_name(priv->d_info, priv->info_level))
3618 lock_dir(priv->dir_fp);
3619 dent = lookup_one(user_ns, priv->d_info->name,
3620 priv->dir_fp->filp->f_path.dentry,
3621 priv->d_info->name_len);
3622 unlock_dir(priv->dir_fp);
3625 ksmbd_debug(SMB, "Cannot lookup `%s' [%ld]\n",
3630 if (unlikely(d_is_negative(dent))) {
3632 ksmbd_debug(SMB, "Negative dentry `%s'\n",
3633 priv->d_info->name);
3637 ksmbd_kstat.kstat = &kstat;
3638 if (priv->info_level != FILE_NAMES_INFORMATION)
3639 ksmbd_vfs_fill_dentry_attrs(priv->work,
3644 rc = smb2_populate_readdir_entry(priv->work->conn,
3655 static int reserve_populate_dentry(struct ksmbd_dir_info *d_info,
3660 int next_entry_offset;
3662 struct_sz = readdir_info_level_struct_sz(info_level);
3663 if (struct_sz == -EOPNOTSUPP)
3666 conv_len = (d_info->name_len + 1) * 2;
3667 next_entry_offset = ALIGN(struct_sz - 1 + conv_len,
3668 KSMBD_DIR_INFO_ALIGNMENT);
3670 if (next_entry_offset > d_info->out_buf_len) {
3671 d_info->out_buf_len = 0;
3675 switch (info_level) {
3676 case FILE_FULL_DIRECTORY_INFORMATION:
3678 struct file_full_directory_info *ffdinfo;
3680 ffdinfo = (struct file_full_directory_info *)d_info->wptr;
3681 memcpy(ffdinfo->FileName, d_info->name, d_info->name_len);
3682 ffdinfo->FileName[d_info->name_len] = 0x00;
3683 ffdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3684 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3687 case FILE_BOTH_DIRECTORY_INFORMATION:
3689 struct file_both_directory_info *fbdinfo;
3691 fbdinfo = (struct file_both_directory_info *)d_info->wptr;
3692 memcpy(fbdinfo->FileName, d_info->name, d_info->name_len);
3693 fbdinfo->FileName[d_info->name_len] = 0x00;
3694 fbdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3695 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3698 case FILE_DIRECTORY_INFORMATION:
3700 struct file_directory_info *fdinfo;
3702 fdinfo = (struct file_directory_info *)d_info->wptr;
3703 memcpy(fdinfo->FileName, d_info->name, d_info->name_len);
3704 fdinfo->FileName[d_info->name_len] = 0x00;
3705 fdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3706 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3709 case FILE_NAMES_INFORMATION:
3711 struct file_names_info *fninfo;
3713 fninfo = (struct file_names_info *)d_info->wptr;
3714 memcpy(fninfo->FileName, d_info->name, d_info->name_len);
3715 fninfo->FileName[d_info->name_len] = 0x00;
3716 fninfo->FileNameLength = cpu_to_le32(d_info->name_len);
3717 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3720 case FILEID_FULL_DIRECTORY_INFORMATION:
3722 struct file_id_full_dir_info *dinfo;
3724 dinfo = (struct file_id_full_dir_info *)d_info->wptr;
3725 memcpy(dinfo->FileName, d_info->name, d_info->name_len);
3726 dinfo->FileName[d_info->name_len] = 0x00;
3727 dinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3728 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3731 case FILEID_BOTH_DIRECTORY_INFORMATION:
3733 struct file_id_both_directory_info *fibdinfo;
3735 fibdinfo = (struct file_id_both_directory_info *)d_info->wptr;
3736 memcpy(fibdinfo->FileName, d_info->name, d_info->name_len);
3737 fibdinfo->FileName[d_info->name_len] = 0x00;
3738 fibdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3739 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3742 case SMB_FIND_FILE_POSIX_INFO:
3744 struct smb2_posix_info *posix_info;
3746 posix_info = (struct smb2_posix_info *)d_info->wptr;
3747 memcpy(posix_info->name, d_info->name, d_info->name_len);
3748 posix_info->name[d_info->name_len] = 0x00;
3749 posix_info->name_len = cpu_to_le32(d_info->name_len);
3750 posix_info->NextEntryOffset =
3751 cpu_to_le32(next_entry_offset);
3754 } /* switch (info_level) */
3756 d_info->num_entry++;
3757 d_info->out_buf_len -= next_entry_offset;
3758 d_info->wptr += next_entry_offset;
3762 static int __query_dir(struct dir_context *ctx, const char *name, int namlen,
3763 loff_t offset, u64 ino, unsigned int d_type)
3765 struct ksmbd_readdir_data *buf;
3766 struct smb2_query_dir_private *priv;
3767 struct ksmbd_dir_info *d_info;
3770 buf = container_of(ctx, struct ksmbd_readdir_data, ctx);
3771 priv = buf->private;
3772 d_info = priv->d_info;
3774 /* dot and dotdot entries are already reserved */
3775 if (!strcmp(".", name) || !strcmp("..", name))
3777 if (ksmbd_share_veto_filename(priv->work->tcon->share_conf, name))
3779 if (!match_pattern(name, namlen, priv->search_pattern))
3782 d_info->name = name;
3783 d_info->name_len = namlen;
3784 rc = reserve_populate_dentry(d_info, priv->info_level);
3787 if (d_info->flags & SMB2_RETURN_SINGLE_ENTRY) {
3788 d_info->out_buf_len = 0;
3794 static void restart_ctx(struct dir_context *ctx)
3799 static int verify_info_level(int info_level)
3801 switch (info_level) {
3802 case FILE_FULL_DIRECTORY_INFORMATION:
3803 case FILE_BOTH_DIRECTORY_INFORMATION:
3804 case FILE_DIRECTORY_INFORMATION:
3805 case FILE_NAMES_INFORMATION:
3806 case FILEID_FULL_DIRECTORY_INFORMATION:
3807 case FILEID_BOTH_DIRECTORY_INFORMATION:
3808 case SMB_FIND_FILE_POSIX_INFO:
3817 static int smb2_calc_max_out_buf_len(struct ksmbd_work *work,
3818 unsigned short hdr2_len,
3819 unsigned int out_buf_len)
3823 if (out_buf_len > work->conn->vals->max_trans_size)
3826 free_len = (int)(work->response_sz -
3827 (get_rfc1002_len(work->response_buf) + 4)) -
3832 return min_t(int, out_buf_len, free_len);
3835 int smb2_query_dir(struct ksmbd_work *work)
3837 struct ksmbd_conn *conn = work->conn;
3838 struct smb2_query_directory_req *req;
3839 struct smb2_query_directory_rsp *rsp;
3840 struct ksmbd_share_config *share = work->tcon->share_conf;
3841 struct ksmbd_file *dir_fp = NULL;
3842 struct ksmbd_dir_info d_info;
3844 char *srch_ptr = NULL;
3845 unsigned char srch_flag;
3847 struct smb2_query_dir_private query_dir_private = {NULL, };
3849 WORK_BUFFERS(work, req, rsp);
3851 if (ksmbd_override_fsids(work)) {
3852 rsp->hdr.Status = STATUS_NO_MEMORY;
3853 smb2_set_err_rsp(work);
3857 rc = verify_info_level(req->FileInformationClass);
3863 dir_fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
3869 if (!(dir_fp->daccess & FILE_LIST_DIRECTORY_LE) ||
3870 inode_permission(file_mnt_user_ns(dir_fp->filp),
3871 file_inode(dir_fp->filp),
3872 MAY_READ | MAY_EXEC)) {
3873 pr_err("no right to enumerate directory (%pd)\n",
3874 dir_fp->filp->f_path.dentry);
3879 if (!S_ISDIR(file_inode(dir_fp->filp)->i_mode)) {
3880 pr_err("can't do query dir for a file\n");
3885 srch_flag = req->Flags;
3886 srch_ptr = smb_strndup_from_utf16(req->Buffer,
3887 le16_to_cpu(req->FileNameLength), 1,
3889 if (IS_ERR(srch_ptr)) {
3890 ksmbd_debug(SMB, "Search Pattern not found\n");
3894 ksmbd_debug(SMB, "Search pattern is %s\n", srch_ptr);
3897 if (srch_flag & SMB2_REOPEN || srch_flag & SMB2_RESTART_SCANS) {
3898 ksmbd_debug(SMB, "Restart directory scan\n");
3899 generic_file_llseek(dir_fp->filp, 0, SEEK_SET);
3900 restart_ctx(&dir_fp->readdir_data.ctx);
3903 memset(&d_info, 0, sizeof(struct ksmbd_dir_info));
3904 d_info.wptr = (char *)rsp->Buffer;
3905 d_info.rptr = (char *)rsp->Buffer;
3906 d_info.out_buf_len =
3907 smb2_calc_max_out_buf_len(work, 8,
3908 le32_to_cpu(req->OutputBufferLength));
3909 if (d_info.out_buf_len < 0) {
3913 d_info.flags = srch_flag;
3916 * reserve dot and dotdot entries in head of buffer
3919 rc = ksmbd_populate_dot_dotdot_entries(work, req->FileInformationClass,
3920 dir_fp, &d_info, srch_ptr,
3921 smb2_populate_readdir_entry);
3927 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_HIDE_DOT_FILES))
3928 d_info.hide_dot_file = true;
3930 buffer_sz = d_info.out_buf_len;
3931 d_info.rptr = d_info.wptr;
3932 query_dir_private.work = work;
3933 query_dir_private.search_pattern = srch_ptr;
3934 query_dir_private.dir_fp = dir_fp;
3935 query_dir_private.d_info = &d_info;
3936 query_dir_private.info_level = req->FileInformationClass;
3937 dir_fp->readdir_data.private = &query_dir_private;
3938 set_ctx_actor(&dir_fp->readdir_data.ctx, __query_dir);
3940 rc = iterate_dir(dir_fp->filp, &dir_fp->readdir_data.ctx);
3942 * req->OutputBufferLength is too small to contain even one entry.
3943 * In this case, it immediately returns OutputBufferLength 0 to client.
3945 if (!d_info.out_buf_len && !d_info.num_entry)
3948 restart_ctx(&dir_fp->readdir_data.ctx);
3954 d_info.wptr = d_info.rptr;
3955 d_info.out_buf_len = buffer_sz;
3956 rc = process_query_dir_entries(&query_dir_private);
3960 if (!d_info.data_count && d_info.out_buf_len >= 0) {
3961 if (srch_flag & SMB2_RETURN_SINGLE_ENTRY && !is_asterisk(srch_ptr)) {
3962 rsp->hdr.Status = STATUS_NO_SUCH_FILE;
3964 dir_fp->dot_dotdot[0] = dir_fp->dot_dotdot[1] = 0;
3965 rsp->hdr.Status = STATUS_NO_MORE_FILES;
3967 rsp->StructureSize = cpu_to_le16(9);
3968 rsp->OutputBufferOffset = cpu_to_le16(0);
3969 rsp->OutputBufferLength = cpu_to_le32(0);
3971 inc_rfc1001_len(work->response_buf, 9);
3974 ((struct file_directory_info *)
3975 ((char *)rsp->Buffer + d_info.last_entry_offset))
3976 ->NextEntryOffset = 0;
3977 if (d_info.data_count >= d_info.last_entry_off_align)
3978 d_info.data_count -= d_info.last_entry_off_align;
3980 rsp->StructureSize = cpu_to_le16(9);
3981 rsp->OutputBufferOffset = cpu_to_le16(72);
3982 rsp->OutputBufferLength = cpu_to_le32(d_info.data_count);
3983 inc_rfc1001_len(work->response_buf, 8 + d_info.data_count);
3987 ksmbd_fd_put(work, dir_fp);
3988 ksmbd_revert_fsids(work);
3992 pr_err("error while processing smb2 query dir rc = %d\n", rc);
3997 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
3998 else if (rc == -EACCES)
3999 rsp->hdr.Status = STATUS_ACCESS_DENIED;
4000 else if (rc == -ENOENT)
4001 rsp->hdr.Status = STATUS_NO_SUCH_FILE;
4002 else if (rc == -EBADF)
4003 rsp->hdr.Status = STATUS_FILE_CLOSED;
4004 else if (rc == -ENOMEM)
4005 rsp->hdr.Status = STATUS_NO_MEMORY;
4006 else if (rc == -EFAULT)
4007 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
4008 if (!rsp->hdr.Status)
4009 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
4011 smb2_set_err_rsp(work);
4012 ksmbd_fd_put(work, dir_fp);
4013 ksmbd_revert_fsids(work);
4018 * buffer_check_err() - helper function to check buffer errors
4019 * @reqOutputBufferLength: max buffer length expected in command response
4020 * @rsp: query info response buffer contains output buffer length
4021 * @rsp_org: base response buffer pointer in case of chained response
4022 * @infoclass_size: query info class response buffer size
4024 * Return: 0 on success, otherwise error
4026 static int buffer_check_err(int reqOutputBufferLength,
4027 struct smb2_query_info_rsp *rsp,
4028 void *rsp_org, int infoclass_size)
4030 if (reqOutputBufferLength < le32_to_cpu(rsp->OutputBufferLength)) {
4031 if (reqOutputBufferLength < infoclass_size) {
4032 pr_err("Invalid Buffer Size Requested\n");
4033 rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
4034 *(__be32 *)rsp_org = cpu_to_be32(sizeof(struct smb2_hdr));
4038 ksmbd_debug(SMB, "Buffer Overflow\n");
4039 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
4040 *(__be32 *)rsp_org = cpu_to_be32(sizeof(struct smb2_hdr) +
4041 reqOutputBufferLength);
4042 rsp->OutputBufferLength = cpu_to_le32(reqOutputBufferLength);
4047 static void get_standard_info_pipe(struct smb2_query_info_rsp *rsp,
4050 struct smb2_file_standard_info *sinfo;
4052 sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
4054 sinfo->AllocationSize = cpu_to_le64(4096);
4055 sinfo->EndOfFile = cpu_to_le64(0);
4056 sinfo->NumberOfLinks = cpu_to_le32(1);
4057 sinfo->DeletePending = 1;
4058 sinfo->Directory = 0;
4059 rsp->OutputBufferLength =
4060 cpu_to_le32(sizeof(struct smb2_file_standard_info));
4061 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_standard_info));
4064 static void get_internal_info_pipe(struct smb2_query_info_rsp *rsp, u64 num,
4067 struct smb2_file_internal_info *file_info;
4069 file_info = (struct smb2_file_internal_info *)rsp->Buffer;
4071 /* any unique number */
4072 file_info->IndexNumber = cpu_to_le64(num | (1ULL << 63));
4073 rsp->OutputBufferLength =
4074 cpu_to_le32(sizeof(struct smb2_file_internal_info));
4075 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_internal_info));
4078 static int smb2_get_info_file_pipe(struct ksmbd_session *sess,
4079 struct smb2_query_info_req *req,
4080 struct smb2_query_info_rsp *rsp,
4087 * Windows can sometime send query file info request on
4088 * pipe without opening it, checking error condition here
4090 id = req->VolatileFileId;
4091 if (!ksmbd_session_rpc_method(sess, id))
4094 ksmbd_debug(SMB, "FileInfoClass %u, FileId 0x%llx\n",
4095 req->FileInfoClass, req->VolatileFileId);
4097 switch (req->FileInfoClass) {
4098 case FILE_STANDARD_INFORMATION:
4099 get_standard_info_pipe(rsp, rsp_org);
4100 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4102 FILE_STANDARD_INFORMATION_SIZE);
4104 case FILE_INTERNAL_INFORMATION:
4105 get_internal_info_pipe(rsp, id, rsp_org);
4106 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4108 FILE_INTERNAL_INFORMATION_SIZE);
4111 ksmbd_debug(SMB, "smb2_info_file_pipe for %u not supported\n",
4112 req->FileInfoClass);
4119 * smb2_get_ea() - handler for smb2 get extended attribute command
4120 * @work: smb work containing query info command buffer
4121 * @fp: ksmbd_file pointer
4122 * @req: get extended attribute request
4123 * @rsp: response buffer pointer
4124 * @rsp_org: base response buffer pointer in case of chained response
4126 * Return: 0 on success, otherwise error
4128 static int smb2_get_ea(struct ksmbd_work *work, struct ksmbd_file *fp,
4129 struct smb2_query_info_req *req,
4130 struct smb2_query_info_rsp *rsp, void *rsp_org)
4132 struct smb2_ea_info *eainfo, *prev_eainfo;
4133 char *name, *ptr, *xattr_list = NULL, *buf;
4134 int rc, name_len, value_len, xattr_list_len, idx;
4135 ssize_t buf_free_len, alignment_bytes, next_offset, rsp_data_cnt = 0;
4136 struct smb2_ea_info_req *ea_req = NULL;
4138 struct user_namespace *user_ns = file_mnt_user_ns(fp->filp);
4140 if (!(fp->daccess & FILE_READ_EA_LE)) {
4141 pr_err("Not permitted to read ext attr : 0x%x\n",
4146 path = &fp->filp->f_path;
4147 /* single EA entry is requested with given user.* name */
4148 if (req->InputBufferLength) {
4149 if (le32_to_cpu(req->InputBufferLength) <
4150 sizeof(struct smb2_ea_info_req))
4153 ea_req = (struct smb2_ea_info_req *)req->Buffer;
4155 /* need to send all EAs, if no specific EA is requested*/
4156 if (le32_to_cpu(req->Flags) & SL_RETURN_SINGLE_ENTRY)
4158 "All EAs are requested but need to send single EA entry in rsp flags 0x%x\n",
4159 le32_to_cpu(req->Flags));
4163 smb2_calc_max_out_buf_len(work, 8,
4164 le32_to_cpu(req->OutputBufferLength));
4165 if (buf_free_len < 0)
4168 rc = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
4170 rsp->hdr.Status = STATUS_INVALID_HANDLE;
4172 } else if (!rc) { /* there is no EA in the file */
4173 ksmbd_debug(SMB, "no ea data in the file\n");
4176 xattr_list_len = rc;
4178 ptr = (char *)rsp->Buffer;
4179 eainfo = (struct smb2_ea_info *)ptr;
4180 prev_eainfo = eainfo;
4183 while (idx < xattr_list_len) {
4184 name = xattr_list + idx;
4185 name_len = strlen(name);
4187 ksmbd_debug(SMB, "%s, len %d\n", name, name_len);
4188 idx += name_len + 1;
4191 * CIFS does not support EA other than user.* namespace,
4192 * still keep the framework generic, to list other attrs
4195 if (strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4198 if (!strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
4202 if (req->InputBufferLength &&
4203 strncmp(&name[XATTR_USER_PREFIX_LEN], ea_req->name,
4204 ea_req->EaNameLength))
4207 if (!strncmp(&name[XATTR_USER_PREFIX_LEN],
4208 DOS_ATTRIBUTE_PREFIX, DOS_ATTRIBUTE_PREFIX_LEN))
4211 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4212 name_len -= XATTR_USER_PREFIX_LEN;
4214 ptr = (char *)(&eainfo->name + name_len + 1);
4215 buf_free_len -= (offsetof(struct smb2_ea_info, name) +
4217 /* bailout if xattr can't fit in buf_free_len */
4218 value_len = ksmbd_vfs_getxattr(user_ns, path->dentry,
4220 if (value_len <= 0) {
4222 rsp->hdr.Status = STATUS_INVALID_HANDLE;
4226 buf_free_len -= value_len;
4227 if (buf_free_len < 0) {
4232 memcpy(ptr, buf, value_len);
4237 eainfo->EaNameLength = name_len;
4239 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4240 memcpy(eainfo->name, &name[XATTR_USER_PREFIX_LEN],
4243 memcpy(eainfo->name, name, name_len);
4245 eainfo->name[name_len] = '\0';
4246 eainfo->EaValueLength = cpu_to_le16(value_len);
4247 next_offset = offsetof(struct smb2_ea_info, name) +
4248 name_len + 1 + value_len;
4250 /* align next xattr entry at 4 byte bundary */
4251 alignment_bytes = ((next_offset + 3) & ~3) - next_offset;
4252 if (alignment_bytes) {
4253 memset(ptr, '\0', alignment_bytes);
4254 ptr += alignment_bytes;
4255 next_offset += alignment_bytes;
4256 buf_free_len -= alignment_bytes;
4258 eainfo->NextEntryOffset = cpu_to_le32(next_offset);
4259 prev_eainfo = eainfo;
4260 eainfo = (struct smb2_ea_info *)ptr;
4261 rsp_data_cnt += next_offset;
4263 if (req->InputBufferLength) {
4264 ksmbd_debug(SMB, "single entry requested\n");
4269 /* no more ea entries */
4270 prev_eainfo->NextEntryOffset = 0;
4273 if (rsp_data_cnt == 0)
4274 rsp->hdr.Status = STATUS_NO_EAS_ON_FILE;
4275 rsp->OutputBufferLength = cpu_to_le32(rsp_data_cnt);
4276 inc_rfc1001_len(rsp_org, rsp_data_cnt);
4282 static void get_file_access_info(struct smb2_query_info_rsp *rsp,
4283 struct ksmbd_file *fp, void *rsp_org)
4285 struct smb2_file_access_info *file_info;
4287 file_info = (struct smb2_file_access_info *)rsp->Buffer;
4288 file_info->AccessFlags = fp->daccess;
4289 rsp->OutputBufferLength =
4290 cpu_to_le32(sizeof(struct smb2_file_access_info));
4291 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_access_info));
4294 static int get_file_basic_info(struct smb2_query_info_rsp *rsp,
4295 struct ksmbd_file *fp, void *rsp_org)
4297 struct smb2_file_basic_info *basic_info;
4301 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4302 pr_err("no right to read the attributes : 0x%x\n",
4307 basic_info = (struct smb2_file_basic_info *)rsp->Buffer;
4308 generic_fillattr(file_mnt_user_ns(fp->filp), file_inode(fp->filp),
4310 basic_info->CreationTime = cpu_to_le64(fp->create_time);
4311 time = ksmbd_UnixTimeToNT(stat.atime);
4312 basic_info->LastAccessTime = cpu_to_le64(time);
4313 time = ksmbd_UnixTimeToNT(stat.mtime);
4314 basic_info->LastWriteTime = cpu_to_le64(time);
4315 time = ksmbd_UnixTimeToNT(stat.ctime);
4316 basic_info->ChangeTime = cpu_to_le64(time);
4317 basic_info->Attributes = fp->f_ci->m_fattr;
4318 basic_info->Pad1 = 0;
4319 rsp->OutputBufferLength =
4320 cpu_to_le32(sizeof(struct smb2_file_basic_info));
4321 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_basic_info));
4325 static unsigned long long get_allocation_size(struct inode *inode,
4328 unsigned long long alloc_size = 0;
4330 if (!S_ISDIR(stat->mode)) {
4331 if ((inode->i_blocks << 9) <= stat->size)
4332 alloc_size = stat->size;
4334 alloc_size = inode->i_blocks << 9;
4340 static void get_file_standard_info(struct smb2_query_info_rsp *rsp,
4341 struct ksmbd_file *fp, void *rsp_org)
4343 struct smb2_file_standard_info *sinfo;
4344 unsigned int delete_pending;
4345 struct inode *inode;
4348 inode = file_inode(fp->filp);
4349 generic_fillattr(file_mnt_user_ns(fp->filp), inode, &stat);
4351 sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
4352 delete_pending = ksmbd_inode_pending_delete(fp);
4354 sinfo->AllocationSize = cpu_to_le64(get_allocation_size(inode, &stat));
4355 sinfo->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4356 sinfo->NumberOfLinks = cpu_to_le32(get_nlink(&stat) - delete_pending);
4357 sinfo->DeletePending = delete_pending;
4358 sinfo->Directory = S_ISDIR(stat.mode) ? 1 : 0;
4359 rsp->OutputBufferLength =
4360 cpu_to_le32(sizeof(struct smb2_file_standard_info));
4361 inc_rfc1001_len(rsp_org,
4362 sizeof(struct smb2_file_standard_info));
4365 static void get_file_alignment_info(struct smb2_query_info_rsp *rsp,
4368 struct smb2_file_alignment_info *file_info;
4370 file_info = (struct smb2_file_alignment_info *)rsp->Buffer;
4371 file_info->AlignmentRequirement = 0;
4372 rsp->OutputBufferLength =
4373 cpu_to_le32(sizeof(struct smb2_file_alignment_info));
4374 inc_rfc1001_len(rsp_org,
4375 sizeof(struct smb2_file_alignment_info));
4378 static int get_file_all_info(struct ksmbd_work *work,
4379 struct smb2_query_info_rsp *rsp,
4380 struct ksmbd_file *fp,
4383 struct ksmbd_conn *conn = work->conn;
4384 struct smb2_file_all_info *file_info;
4385 unsigned int delete_pending;
4386 struct inode *inode;
4392 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4393 ksmbd_debug(SMB, "no right to read the attributes : 0x%x\n",
4398 filename = convert_to_nt_pathname(work->tcon->share_conf, &fp->filp->f_path);
4399 if (IS_ERR(filename))
4400 return PTR_ERR(filename);
4402 inode = file_inode(fp->filp);
4403 generic_fillattr(file_mnt_user_ns(fp->filp), inode, &stat);
4405 ksmbd_debug(SMB, "filename = %s\n", filename);
4406 delete_pending = ksmbd_inode_pending_delete(fp);
4407 file_info = (struct smb2_file_all_info *)rsp->Buffer;
4409 file_info->CreationTime = cpu_to_le64(fp->create_time);
4410 time = ksmbd_UnixTimeToNT(stat.atime);
4411 file_info->LastAccessTime = cpu_to_le64(time);
4412 time = ksmbd_UnixTimeToNT(stat.mtime);
4413 file_info->LastWriteTime = cpu_to_le64(time);
4414 time = ksmbd_UnixTimeToNT(stat.ctime);
4415 file_info->ChangeTime = cpu_to_le64(time);
4416 file_info->Attributes = fp->f_ci->m_fattr;
4417 file_info->Pad1 = 0;
4418 file_info->AllocationSize =
4419 cpu_to_le64(get_allocation_size(inode, &stat));
4420 file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4421 file_info->NumberOfLinks =
4422 cpu_to_le32(get_nlink(&stat) - delete_pending);
4423 file_info->DeletePending = delete_pending;
4424 file_info->Directory = S_ISDIR(stat.mode) ? 1 : 0;
4425 file_info->Pad2 = 0;
4426 file_info->IndexNumber = cpu_to_le64(stat.ino);
4427 file_info->EASize = 0;
4428 file_info->AccessFlags = fp->daccess;
4429 file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
4430 file_info->Mode = fp->coption;
4431 file_info->AlignmentRequirement = 0;
4432 conv_len = smbConvertToUTF16((__le16 *)file_info->FileName, filename,
4433 PATH_MAX, conn->local_nls, 0);
4435 file_info->FileNameLength = cpu_to_le32(conv_len);
4436 rsp->OutputBufferLength =
4437 cpu_to_le32(sizeof(struct smb2_file_all_info) + conv_len - 1);
4439 inc_rfc1001_len(rsp_org, le32_to_cpu(rsp->OutputBufferLength));
4443 static void get_file_alternate_info(struct ksmbd_work *work,
4444 struct smb2_query_info_rsp *rsp,
4445 struct ksmbd_file *fp,
4448 struct ksmbd_conn *conn = work->conn;
4449 struct smb2_file_alt_name_info *file_info;
4450 struct dentry *dentry = fp->filp->f_path.dentry;
4453 spin_lock(&dentry->d_lock);
4454 file_info = (struct smb2_file_alt_name_info *)rsp->Buffer;
4455 conv_len = ksmbd_extract_shortname(conn,
4456 dentry->d_name.name,
4457 file_info->FileName);
4458 spin_unlock(&dentry->d_lock);
4459 file_info->FileNameLength = cpu_to_le32(conv_len);
4460 rsp->OutputBufferLength =
4461 cpu_to_le32(sizeof(struct smb2_file_alt_name_info) + conv_len);
4462 inc_rfc1001_len(rsp_org, le32_to_cpu(rsp->OutputBufferLength));
4465 static void get_file_stream_info(struct ksmbd_work *work,
4466 struct smb2_query_info_rsp *rsp,
4467 struct ksmbd_file *fp,
4470 struct ksmbd_conn *conn = work->conn;
4471 struct smb2_file_stream_info *file_info;
4472 char *stream_name, *xattr_list = NULL, *stream_buf;
4474 struct path *path = &fp->filp->f_path;
4475 ssize_t xattr_list_len;
4476 int nbytes = 0, streamlen, stream_name_len, next, idx = 0;
4478 struct smb2_query_info_req *req = ksmbd_req_buf_next(work);
4480 generic_fillattr(file_mnt_user_ns(fp->filp), file_inode(fp->filp),
4482 file_info = (struct smb2_file_stream_info *)rsp->Buffer;
4485 smb2_calc_max_out_buf_len(work, 8,
4486 le32_to_cpu(req->OutputBufferLength));
4487 if (buf_free_len < 0)
4490 xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
4491 if (xattr_list_len < 0) {
4493 } else if (!xattr_list_len) {
4494 ksmbd_debug(SMB, "empty xattr in the file\n");
4498 while (idx < xattr_list_len) {
4499 stream_name = xattr_list + idx;
4500 streamlen = strlen(stream_name);
4501 idx += streamlen + 1;
4503 ksmbd_debug(SMB, "%s, len %d\n", stream_name, streamlen);
4505 if (strncmp(&stream_name[XATTR_USER_PREFIX_LEN],
4506 STREAM_PREFIX, STREAM_PREFIX_LEN))
4509 stream_name_len = streamlen - (XATTR_USER_PREFIX_LEN +
4511 streamlen = stream_name_len;
4515 stream_buf = kmalloc(streamlen + 1, GFP_KERNEL);
4519 streamlen = snprintf(stream_buf, streamlen + 1,
4520 ":%s", &stream_name[XATTR_NAME_STREAM_LEN]);
4522 next = sizeof(struct smb2_file_stream_info) + streamlen * 2;
4523 if (next > buf_free_len) {
4528 file_info = (struct smb2_file_stream_info *)&rsp->Buffer[nbytes];
4529 streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
4530 stream_buf, streamlen,
4531 conn->local_nls, 0);
4534 file_info->StreamNameLength = cpu_to_le32(streamlen);
4535 file_info->StreamSize = cpu_to_le64(stream_name_len);
4536 file_info->StreamAllocationSize = cpu_to_le64(stream_name_len);
4539 buf_free_len -= next;
4540 file_info->NextEntryOffset = cpu_to_le32(next);
4544 if (!S_ISDIR(stat.mode) &&
4545 buf_free_len >= sizeof(struct smb2_file_stream_info) + 7 * 2) {
4546 file_info = (struct smb2_file_stream_info *)
4547 &rsp->Buffer[nbytes];
4548 streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
4549 "::$DATA", 7, conn->local_nls, 0);
4551 file_info->StreamNameLength = cpu_to_le32(streamlen);
4552 file_info->StreamSize = cpu_to_le64(stat.size);
4553 file_info->StreamAllocationSize = cpu_to_le64(stat.blocks << 9);
4554 nbytes += sizeof(struct smb2_file_stream_info) + streamlen;
4557 /* last entry offset should be 0 */
4558 file_info->NextEntryOffset = 0;
4561 rsp->OutputBufferLength = cpu_to_le32(nbytes);
4562 inc_rfc1001_len(rsp_org, nbytes);
4565 static void get_file_internal_info(struct smb2_query_info_rsp *rsp,
4566 struct ksmbd_file *fp, void *rsp_org)
4568 struct smb2_file_internal_info *file_info;
4571 generic_fillattr(file_mnt_user_ns(fp->filp), file_inode(fp->filp),
4573 file_info = (struct smb2_file_internal_info *)rsp->Buffer;
4574 file_info->IndexNumber = cpu_to_le64(stat.ino);
4575 rsp->OutputBufferLength =
4576 cpu_to_le32(sizeof(struct smb2_file_internal_info));
4577 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_internal_info));
4580 static int get_file_network_open_info(struct smb2_query_info_rsp *rsp,
4581 struct ksmbd_file *fp, void *rsp_org)
4583 struct smb2_file_ntwrk_info *file_info;
4584 struct inode *inode;
4588 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4589 pr_err("no right to read the attributes : 0x%x\n",
4594 file_info = (struct smb2_file_ntwrk_info *)rsp->Buffer;
4596 inode = file_inode(fp->filp);
4597 generic_fillattr(file_mnt_user_ns(fp->filp), inode, &stat);
4599 file_info->CreationTime = cpu_to_le64(fp->create_time);
4600 time = ksmbd_UnixTimeToNT(stat.atime);
4601 file_info->LastAccessTime = cpu_to_le64(time);
4602 time = ksmbd_UnixTimeToNT(stat.mtime);
4603 file_info->LastWriteTime = cpu_to_le64(time);
4604 time = ksmbd_UnixTimeToNT(stat.ctime);
4605 file_info->ChangeTime = cpu_to_le64(time);
4606 file_info->Attributes = fp->f_ci->m_fattr;
4607 file_info->AllocationSize =
4608 cpu_to_le64(get_allocation_size(inode, &stat));
4609 file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4610 file_info->Reserved = cpu_to_le32(0);
4611 rsp->OutputBufferLength =
4612 cpu_to_le32(sizeof(struct smb2_file_ntwrk_info));
4613 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_ntwrk_info));
4617 static void get_file_ea_info(struct smb2_query_info_rsp *rsp, void *rsp_org)
4619 struct smb2_file_ea_info *file_info;
4621 file_info = (struct smb2_file_ea_info *)rsp->Buffer;
4622 file_info->EASize = 0;
4623 rsp->OutputBufferLength =
4624 cpu_to_le32(sizeof(struct smb2_file_ea_info));
4625 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_ea_info));
4628 static void get_file_position_info(struct smb2_query_info_rsp *rsp,
4629 struct ksmbd_file *fp, void *rsp_org)
4631 struct smb2_file_pos_info *file_info;
4633 file_info = (struct smb2_file_pos_info *)rsp->Buffer;
4634 file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
4635 rsp->OutputBufferLength =
4636 cpu_to_le32(sizeof(struct smb2_file_pos_info));
4637 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_pos_info));
4640 static void get_file_mode_info(struct smb2_query_info_rsp *rsp,
4641 struct ksmbd_file *fp, void *rsp_org)
4643 struct smb2_file_mode_info *file_info;
4645 file_info = (struct smb2_file_mode_info *)rsp->Buffer;
4646 file_info->Mode = fp->coption & FILE_MODE_INFO_MASK;
4647 rsp->OutputBufferLength =
4648 cpu_to_le32(sizeof(struct smb2_file_mode_info));
4649 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_mode_info));
4652 static void get_file_compression_info(struct smb2_query_info_rsp *rsp,
4653 struct ksmbd_file *fp, void *rsp_org)
4655 struct smb2_file_comp_info *file_info;
4658 generic_fillattr(file_mnt_user_ns(fp->filp), file_inode(fp->filp),
4661 file_info = (struct smb2_file_comp_info *)rsp->Buffer;
4662 file_info->CompressedFileSize = cpu_to_le64(stat.blocks << 9);
4663 file_info->CompressionFormat = COMPRESSION_FORMAT_NONE;
4664 file_info->CompressionUnitShift = 0;
4665 file_info->ChunkShift = 0;
4666 file_info->ClusterShift = 0;
4667 memset(&file_info->Reserved[0], 0, 3);
4669 rsp->OutputBufferLength =
4670 cpu_to_le32(sizeof(struct smb2_file_comp_info));
4671 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_comp_info));
4674 static int get_file_attribute_tag_info(struct smb2_query_info_rsp *rsp,
4675 struct ksmbd_file *fp, void *rsp_org)
4677 struct smb2_file_attr_tag_info *file_info;
4679 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4680 pr_err("no right to read the attributes : 0x%x\n",
4685 file_info = (struct smb2_file_attr_tag_info *)rsp->Buffer;
4686 file_info->FileAttributes = fp->f_ci->m_fattr;
4687 file_info->ReparseTag = 0;
4688 rsp->OutputBufferLength =
4689 cpu_to_le32(sizeof(struct smb2_file_attr_tag_info));
4690 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_attr_tag_info));
4694 static int find_file_posix_info(struct smb2_query_info_rsp *rsp,
4695 struct ksmbd_file *fp, void *rsp_org)
4697 struct smb311_posix_qinfo *file_info;
4698 struct inode *inode = file_inode(fp->filp);
4701 file_info = (struct smb311_posix_qinfo *)rsp->Buffer;
4702 file_info->CreationTime = cpu_to_le64(fp->create_time);
4703 time = ksmbd_UnixTimeToNT(inode->i_atime);
4704 file_info->LastAccessTime = cpu_to_le64(time);
4705 time = ksmbd_UnixTimeToNT(inode->i_mtime);
4706 file_info->LastWriteTime = cpu_to_le64(time);
4707 time = ksmbd_UnixTimeToNT(inode->i_ctime);
4708 file_info->ChangeTime = cpu_to_le64(time);
4709 file_info->DosAttributes = fp->f_ci->m_fattr;
4710 file_info->Inode = cpu_to_le64(inode->i_ino);
4711 file_info->EndOfFile = cpu_to_le64(inode->i_size);
4712 file_info->AllocationSize = cpu_to_le64(inode->i_blocks << 9);
4713 file_info->HardLinks = cpu_to_le32(inode->i_nlink);
4714 file_info->Mode = cpu_to_le32(inode->i_mode);
4715 file_info->DeviceId = cpu_to_le32(inode->i_rdev);
4716 rsp->OutputBufferLength =
4717 cpu_to_le32(sizeof(struct smb311_posix_qinfo));
4718 inc_rfc1001_len(rsp_org, sizeof(struct smb311_posix_qinfo));
4722 static int smb2_get_info_file(struct ksmbd_work *work,
4723 struct smb2_query_info_req *req,
4724 struct smb2_query_info_rsp *rsp)
4726 struct ksmbd_file *fp;
4727 int fileinfoclass = 0;
4729 int file_infoclass_size;
4730 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
4732 if (test_share_config_flag(work->tcon->share_conf,
4733 KSMBD_SHARE_FLAG_PIPE)) {
4734 /* smb2 info file called for pipe */
4735 return smb2_get_info_file_pipe(work->sess, req, rsp,
4736 work->response_buf);
4739 if (work->next_smb2_rcv_hdr_off) {
4740 if (!has_file_id(req->VolatileFileId)) {
4741 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
4742 work->compound_fid);
4743 id = work->compound_fid;
4744 pid = work->compound_pfid;
4748 if (!has_file_id(id)) {
4749 id = req->VolatileFileId;
4750 pid = req->PersistentFileId;
4753 fp = ksmbd_lookup_fd_slow(work, id, pid);
4757 fileinfoclass = req->FileInfoClass;
4759 switch (fileinfoclass) {
4760 case FILE_ACCESS_INFORMATION:
4761 get_file_access_info(rsp, fp, work->response_buf);
4762 file_infoclass_size = FILE_ACCESS_INFORMATION_SIZE;
4765 case FILE_BASIC_INFORMATION:
4766 rc = get_file_basic_info(rsp, fp, work->response_buf);
4767 file_infoclass_size = FILE_BASIC_INFORMATION_SIZE;
4770 case FILE_STANDARD_INFORMATION:
4771 get_file_standard_info(rsp, fp, work->response_buf);
4772 file_infoclass_size = FILE_STANDARD_INFORMATION_SIZE;
4775 case FILE_ALIGNMENT_INFORMATION:
4776 get_file_alignment_info(rsp, work->response_buf);
4777 file_infoclass_size = FILE_ALIGNMENT_INFORMATION_SIZE;
4780 case FILE_ALL_INFORMATION:
4781 rc = get_file_all_info(work, rsp, fp, work->response_buf);
4782 file_infoclass_size = FILE_ALL_INFORMATION_SIZE;
4785 case FILE_ALTERNATE_NAME_INFORMATION:
4786 get_file_alternate_info(work, rsp, fp, work->response_buf);
4787 file_infoclass_size = FILE_ALTERNATE_NAME_INFORMATION_SIZE;
4790 case FILE_STREAM_INFORMATION:
4791 get_file_stream_info(work, rsp, fp, work->response_buf);
4792 file_infoclass_size = FILE_STREAM_INFORMATION_SIZE;
4795 case FILE_INTERNAL_INFORMATION:
4796 get_file_internal_info(rsp, fp, work->response_buf);
4797 file_infoclass_size = FILE_INTERNAL_INFORMATION_SIZE;
4800 case FILE_NETWORK_OPEN_INFORMATION:
4801 rc = get_file_network_open_info(rsp, fp, work->response_buf);
4802 file_infoclass_size = FILE_NETWORK_OPEN_INFORMATION_SIZE;
4805 case FILE_EA_INFORMATION:
4806 get_file_ea_info(rsp, work->response_buf);
4807 file_infoclass_size = FILE_EA_INFORMATION_SIZE;
4810 case FILE_FULL_EA_INFORMATION:
4811 rc = smb2_get_ea(work, fp, req, rsp, work->response_buf);
4812 file_infoclass_size = FILE_FULL_EA_INFORMATION_SIZE;
4815 case FILE_POSITION_INFORMATION:
4816 get_file_position_info(rsp, fp, work->response_buf);
4817 file_infoclass_size = FILE_POSITION_INFORMATION_SIZE;
4820 case FILE_MODE_INFORMATION:
4821 get_file_mode_info(rsp, fp, work->response_buf);
4822 file_infoclass_size = FILE_MODE_INFORMATION_SIZE;
4825 case FILE_COMPRESSION_INFORMATION:
4826 get_file_compression_info(rsp, fp, work->response_buf);
4827 file_infoclass_size = FILE_COMPRESSION_INFORMATION_SIZE;
4830 case FILE_ATTRIBUTE_TAG_INFORMATION:
4831 rc = get_file_attribute_tag_info(rsp, fp, work->response_buf);
4832 file_infoclass_size = FILE_ATTRIBUTE_TAG_INFORMATION_SIZE;
4834 case SMB_FIND_FILE_POSIX_INFO:
4835 if (!work->tcon->posix_extensions) {
4836 pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
4839 rc = find_file_posix_info(rsp, fp, work->response_buf);
4840 file_infoclass_size = sizeof(struct smb311_posix_qinfo);
4844 ksmbd_debug(SMB, "fileinfoclass %d not supported yet\n",
4849 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4850 rsp, work->response_buf,
4851 file_infoclass_size);
4852 ksmbd_fd_put(work, fp);
4856 static int smb2_get_info_filesystem(struct ksmbd_work *work,
4857 struct smb2_query_info_req *req,
4858 struct smb2_query_info_rsp *rsp)
4860 struct ksmbd_session *sess = work->sess;
4861 struct ksmbd_conn *conn = sess->conn;
4862 struct ksmbd_share_config *share = work->tcon->share_conf;
4863 int fsinfoclass = 0;
4864 struct kstatfs stfs;
4867 int fs_infoclass_size = 0;
4869 rc = kern_path(share->path, LOOKUP_NO_SYMLINKS, &path);
4871 pr_err("cannot create vfs path\n");
4875 rc = vfs_statfs(&path, &stfs);
4877 pr_err("cannot do stat of path %s\n", share->path);
4882 fsinfoclass = req->FileInfoClass;
4884 switch (fsinfoclass) {
4885 case FS_DEVICE_INFORMATION:
4887 struct filesystem_device_info *info;
4889 info = (struct filesystem_device_info *)rsp->Buffer;
4891 info->DeviceType = cpu_to_le32(stfs.f_type);
4892 info->DeviceCharacteristics = cpu_to_le32(0x00000020);
4893 rsp->OutputBufferLength = cpu_to_le32(8);
4894 inc_rfc1001_len(work->response_buf, 8);
4895 fs_infoclass_size = FS_DEVICE_INFORMATION_SIZE;
4898 case FS_ATTRIBUTE_INFORMATION:
4900 struct filesystem_attribute_info *info;
4903 info = (struct filesystem_attribute_info *)rsp->Buffer;
4904 info->Attributes = cpu_to_le32(FILE_SUPPORTS_OBJECT_IDS |
4905 FILE_PERSISTENT_ACLS |
4906 FILE_UNICODE_ON_DISK |
4907 FILE_CASE_PRESERVED_NAMES |
4908 FILE_CASE_SENSITIVE_SEARCH |
4909 FILE_SUPPORTS_BLOCK_REFCOUNTING);
4911 info->Attributes |= cpu_to_le32(server_conf.share_fake_fscaps);
4913 info->MaxPathNameComponentLength = cpu_to_le32(stfs.f_namelen);
4914 len = smbConvertToUTF16((__le16 *)info->FileSystemName,
4915 "NTFS", PATH_MAX, conn->local_nls, 0);
4917 info->FileSystemNameLen = cpu_to_le32(len);
4918 sz = sizeof(struct filesystem_attribute_info) - 2 + len;
4919 rsp->OutputBufferLength = cpu_to_le32(sz);
4920 inc_rfc1001_len(work->response_buf, sz);
4921 fs_infoclass_size = FS_ATTRIBUTE_INFORMATION_SIZE;
4924 case FS_VOLUME_INFORMATION:
4926 struct filesystem_vol_info *info;
4928 unsigned int serial_crc = 0;
4930 info = (struct filesystem_vol_info *)(rsp->Buffer);
4931 info->VolumeCreationTime = 0;
4932 serial_crc = crc32_le(serial_crc, share->name,
4933 strlen(share->name));
4934 serial_crc = crc32_le(serial_crc, share->path,
4935 strlen(share->path));
4936 serial_crc = crc32_le(serial_crc, ksmbd_netbios_name(),
4937 strlen(ksmbd_netbios_name()));
4938 /* Taking dummy value of serial number*/
4939 info->SerialNumber = cpu_to_le32(serial_crc);
4940 len = smbConvertToUTF16((__le16 *)info->VolumeLabel,
4941 share->name, PATH_MAX,
4942 conn->local_nls, 0);
4944 info->VolumeLabelSize = cpu_to_le32(len);
4946 sz = sizeof(struct filesystem_vol_info) - 2 + len;
4947 rsp->OutputBufferLength = cpu_to_le32(sz);
4948 inc_rfc1001_len(work->response_buf, sz);
4949 fs_infoclass_size = FS_VOLUME_INFORMATION_SIZE;
4952 case FS_SIZE_INFORMATION:
4954 struct filesystem_info *info;
4956 info = (struct filesystem_info *)(rsp->Buffer);
4957 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
4958 info->FreeAllocationUnits = cpu_to_le64(stfs.f_bfree);
4959 info->SectorsPerAllocationUnit = cpu_to_le32(1);
4960 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
4961 rsp->OutputBufferLength = cpu_to_le32(24);
4962 inc_rfc1001_len(work->response_buf, 24);
4963 fs_infoclass_size = FS_SIZE_INFORMATION_SIZE;
4966 case FS_FULL_SIZE_INFORMATION:
4968 struct smb2_fs_full_size_info *info;
4970 info = (struct smb2_fs_full_size_info *)(rsp->Buffer);
4971 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
4972 info->CallerAvailableAllocationUnits =
4973 cpu_to_le64(stfs.f_bavail);
4974 info->ActualAvailableAllocationUnits =
4975 cpu_to_le64(stfs.f_bfree);
4976 info->SectorsPerAllocationUnit = cpu_to_le32(1);
4977 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
4978 rsp->OutputBufferLength = cpu_to_le32(32);
4979 inc_rfc1001_len(work->response_buf, 32);
4980 fs_infoclass_size = FS_FULL_SIZE_INFORMATION_SIZE;
4983 case FS_OBJECT_ID_INFORMATION:
4985 struct object_id_info *info;
4987 info = (struct object_id_info *)(rsp->Buffer);
4989 if (!user_guest(sess->user))
4990 memcpy(info->objid, user_passkey(sess->user), 16);
4992 memset(info->objid, 0, 16);
4994 info->extended_info.magic = cpu_to_le32(EXTENDED_INFO_MAGIC);
4995 info->extended_info.version = cpu_to_le32(1);
4996 info->extended_info.release = cpu_to_le32(1);
4997 info->extended_info.rel_date = 0;
4998 memcpy(info->extended_info.version_string, "1.1.0", strlen("1.1.0"));
4999 rsp->OutputBufferLength = cpu_to_le32(64);
5000 inc_rfc1001_len(work->response_buf, 64);
5001 fs_infoclass_size = FS_OBJECT_ID_INFORMATION_SIZE;
5004 case FS_SECTOR_SIZE_INFORMATION:
5006 struct smb3_fs_ss_info *info;
5007 unsigned int sector_size =
5008 min_t(unsigned int, path.mnt->mnt_sb->s_blocksize, 4096);
5010 info = (struct smb3_fs_ss_info *)(rsp->Buffer);
5012 info->LogicalBytesPerSector = cpu_to_le32(sector_size);
5013 info->PhysicalBytesPerSectorForAtomicity =
5014 cpu_to_le32(sector_size);
5015 info->PhysicalBytesPerSectorForPerf = cpu_to_le32(sector_size);
5016 info->FSEffPhysicalBytesPerSectorForAtomicity =
5017 cpu_to_le32(sector_size);
5018 info->Flags = cpu_to_le32(SSINFO_FLAGS_ALIGNED_DEVICE |
5019 SSINFO_FLAGS_PARTITION_ALIGNED_ON_DEVICE);
5020 info->ByteOffsetForSectorAlignment = 0;
5021 info->ByteOffsetForPartitionAlignment = 0;
5022 rsp->OutputBufferLength = cpu_to_le32(28);
5023 inc_rfc1001_len(work->response_buf, 28);
5024 fs_infoclass_size = FS_SECTOR_SIZE_INFORMATION_SIZE;
5027 case FS_CONTROL_INFORMATION:
5030 * TODO : The current implementation is based on
5031 * test result with win7(NTFS) server. It's need to
5032 * modify this to get valid Quota values
5035 struct smb2_fs_control_info *info;
5037 info = (struct smb2_fs_control_info *)(rsp->Buffer);
5038 info->FreeSpaceStartFiltering = 0;
5039 info->FreeSpaceThreshold = 0;
5040 info->FreeSpaceStopFiltering = 0;
5041 info->DefaultQuotaThreshold = cpu_to_le64(SMB2_NO_FID);
5042 info->DefaultQuotaLimit = cpu_to_le64(SMB2_NO_FID);
5044 rsp->OutputBufferLength = cpu_to_le32(48);
5045 inc_rfc1001_len(work->response_buf, 48);
5046 fs_infoclass_size = FS_CONTROL_INFORMATION_SIZE;
5049 case FS_POSIX_INFORMATION:
5051 struct filesystem_posix_info *info;
5053 if (!work->tcon->posix_extensions) {
5054 pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
5057 info = (struct filesystem_posix_info *)(rsp->Buffer);
5058 info->OptimalTransferSize = cpu_to_le32(stfs.f_bsize);
5059 info->BlockSize = cpu_to_le32(stfs.f_bsize);
5060 info->TotalBlocks = cpu_to_le64(stfs.f_blocks);
5061 info->BlocksAvail = cpu_to_le64(stfs.f_bfree);
5062 info->UserBlocksAvail = cpu_to_le64(stfs.f_bavail);
5063 info->TotalFileNodes = cpu_to_le64(stfs.f_files);
5064 info->FreeFileNodes = cpu_to_le64(stfs.f_ffree);
5065 rsp->OutputBufferLength = cpu_to_le32(56);
5066 inc_rfc1001_len(work->response_buf, 56);
5067 fs_infoclass_size = FS_POSIX_INFORMATION_SIZE;
5075 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
5076 rsp, work->response_buf,
5082 static int smb2_get_info_sec(struct ksmbd_work *work,
5083 struct smb2_query_info_req *req,
5084 struct smb2_query_info_rsp *rsp)
5086 struct ksmbd_file *fp;
5087 struct user_namespace *user_ns;
5088 struct smb_ntsd *pntsd = (struct smb_ntsd *)rsp->Buffer, *ppntsd = NULL;
5089 struct smb_fattr fattr = {{0}};
5090 struct inode *inode;
5092 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
5093 int addition_info = le32_to_cpu(req->AdditionalInformation);
5096 if (addition_info & ~(OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO |
5097 PROTECTED_DACL_SECINFO |
5098 UNPROTECTED_DACL_SECINFO)) {
5099 ksmbd_debug(SMB, "Unsupported addition info: 0x%x)\n",
5102 pntsd->revision = cpu_to_le16(1);
5103 pntsd->type = cpu_to_le16(SELF_RELATIVE | DACL_PROTECTED);
5104 pntsd->osidoffset = 0;
5105 pntsd->gsidoffset = 0;
5106 pntsd->sacloffset = 0;
5107 pntsd->dacloffset = 0;
5109 secdesclen = sizeof(struct smb_ntsd);
5110 rsp->OutputBufferLength = cpu_to_le32(secdesclen);
5111 inc_rfc1001_len(work->response_buf, secdesclen);
5116 if (work->next_smb2_rcv_hdr_off) {
5117 if (!has_file_id(req->VolatileFileId)) {
5118 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
5119 work->compound_fid);
5120 id = work->compound_fid;
5121 pid = work->compound_pfid;
5125 if (!has_file_id(id)) {
5126 id = req->VolatileFileId;
5127 pid = req->PersistentFileId;
5130 fp = ksmbd_lookup_fd_slow(work, id, pid);
5134 user_ns = file_mnt_user_ns(fp->filp);
5135 inode = file_inode(fp->filp);
5136 ksmbd_acls_fattr(&fattr, user_ns, inode);
5138 if (test_share_config_flag(work->tcon->share_conf,
5139 KSMBD_SHARE_FLAG_ACL_XATTR))
5140 ksmbd_vfs_get_sd_xattr(work->conn, user_ns,
5141 fp->filp->f_path.dentry, &ppntsd);
5143 rc = build_sec_desc(user_ns, pntsd, ppntsd, addition_info,
5144 &secdesclen, &fattr);
5145 posix_acl_release(fattr.cf_acls);
5146 posix_acl_release(fattr.cf_dacls);
5148 ksmbd_fd_put(work, fp);
5152 rsp->OutputBufferLength = cpu_to_le32(secdesclen);
5153 inc_rfc1001_len(work->response_buf, secdesclen);
5158 * smb2_query_info() - handler for smb2 query info command
5159 * @work: smb work containing query info request buffer
5161 * Return: 0 on success, otherwise error
5163 int smb2_query_info(struct ksmbd_work *work)
5165 struct smb2_query_info_req *req;
5166 struct smb2_query_info_rsp *rsp;
5169 WORK_BUFFERS(work, req, rsp);
5171 ksmbd_debug(SMB, "GOT query info request\n");
5173 switch (req->InfoType) {
5174 case SMB2_O_INFO_FILE:
5175 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
5176 rc = smb2_get_info_file(work, req, rsp);
5178 case SMB2_O_INFO_FILESYSTEM:
5179 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILESYSTEM\n");
5180 rc = smb2_get_info_filesystem(work, req, rsp);
5182 case SMB2_O_INFO_SECURITY:
5183 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
5184 rc = smb2_get_info_sec(work, req, rsp);
5187 ksmbd_debug(SMB, "InfoType %d not supported yet\n",
5194 rsp->hdr.Status = STATUS_ACCESS_DENIED;
5195 else if (rc == -ENOENT)
5196 rsp->hdr.Status = STATUS_FILE_CLOSED;
5197 else if (rc == -EIO)
5198 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
5199 else if (rc == -EOPNOTSUPP || rsp->hdr.Status == 0)
5200 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
5201 smb2_set_err_rsp(work);
5203 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n",
5207 rsp->StructureSize = cpu_to_le16(9);
5208 rsp->OutputBufferOffset = cpu_to_le16(72);
5209 inc_rfc1001_len(work->response_buf, 8);
5214 * smb2_close_pipe() - handler for closing IPC pipe
5215 * @work: smb work containing close request buffer
5219 static noinline int smb2_close_pipe(struct ksmbd_work *work)
5222 struct smb2_close_req *req = smb2_get_msg(work->request_buf);
5223 struct smb2_close_rsp *rsp = smb2_get_msg(work->response_buf);
5225 id = req->VolatileFileId;
5226 ksmbd_session_rpc_close(work->sess, id);
5228 rsp->StructureSize = cpu_to_le16(60);
5231 rsp->CreationTime = 0;
5232 rsp->LastAccessTime = 0;
5233 rsp->LastWriteTime = 0;
5234 rsp->ChangeTime = 0;
5235 rsp->AllocationSize = 0;
5237 rsp->Attributes = 0;
5238 inc_rfc1001_len(work->response_buf, 60);
5243 * smb2_close() - handler for smb2 close file command
5244 * @work: smb work containing close request buffer
5248 int smb2_close(struct ksmbd_work *work)
5250 u64 volatile_id = KSMBD_NO_FID;
5252 struct smb2_close_req *req;
5253 struct smb2_close_rsp *rsp;
5254 struct ksmbd_conn *conn = work->conn;
5255 struct ksmbd_file *fp;
5256 struct inode *inode;
5260 WORK_BUFFERS(work, req, rsp);
5262 if (test_share_config_flag(work->tcon->share_conf,
5263 KSMBD_SHARE_FLAG_PIPE)) {
5264 ksmbd_debug(SMB, "IPC pipe close request\n");
5265 return smb2_close_pipe(work);
5268 sess_id = le64_to_cpu(req->hdr.SessionId);
5269 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5270 sess_id = work->compound_sid;
5272 work->compound_sid = 0;
5273 if (check_session_id(conn, sess_id)) {
5274 work->compound_sid = sess_id;
5276 rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
5277 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5278 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
5283 if (work->next_smb2_rcv_hdr_off &&
5284 !has_file_id(req->VolatileFileId)) {
5285 if (!has_file_id(work->compound_fid)) {
5286 /* file already closed, return FILE_CLOSED */
5287 ksmbd_debug(SMB, "file already closed\n");
5288 rsp->hdr.Status = STATUS_FILE_CLOSED;
5293 "Compound request set FID = %llu:%llu\n",
5295 work->compound_pfid);
5296 volatile_id = work->compound_fid;
5298 /* file closed, stored id is not valid anymore */
5299 work->compound_fid = KSMBD_NO_FID;
5300 work->compound_pfid = KSMBD_NO_FID;
5303 volatile_id = req->VolatileFileId;
5305 ksmbd_debug(SMB, "volatile_id = %llu\n", volatile_id);
5307 rsp->StructureSize = cpu_to_le16(60);
5310 if (req->Flags == SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB) {
5311 fp = ksmbd_lookup_fd_fast(work, volatile_id);
5317 inode = file_inode(fp->filp);
5318 rsp->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB;
5319 rsp->AllocationSize = S_ISDIR(inode->i_mode) ? 0 :
5320 cpu_to_le64(inode->i_blocks << 9);
5321 rsp->EndOfFile = cpu_to_le64(inode->i_size);
5322 rsp->Attributes = fp->f_ci->m_fattr;
5323 rsp->CreationTime = cpu_to_le64(fp->create_time);
5324 time = ksmbd_UnixTimeToNT(inode->i_atime);
5325 rsp->LastAccessTime = cpu_to_le64(time);
5326 time = ksmbd_UnixTimeToNT(inode->i_mtime);
5327 rsp->LastWriteTime = cpu_to_le64(time);
5328 time = ksmbd_UnixTimeToNT(inode->i_ctime);
5329 rsp->ChangeTime = cpu_to_le64(time);
5330 ksmbd_fd_put(work, fp);
5333 rsp->AllocationSize = 0;
5335 rsp->Attributes = 0;
5336 rsp->CreationTime = 0;
5337 rsp->LastAccessTime = 0;
5338 rsp->LastWriteTime = 0;
5339 rsp->ChangeTime = 0;
5342 err = ksmbd_close_fd(work, volatile_id);
5345 if (rsp->hdr.Status == 0)
5346 rsp->hdr.Status = STATUS_FILE_CLOSED;
5347 smb2_set_err_rsp(work);
5349 inc_rfc1001_len(work->response_buf, 60);
5356 * smb2_echo() - handler for smb2 echo(ping) command
5357 * @work: smb work containing echo request buffer
5361 int smb2_echo(struct ksmbd_work *work)
5363 struct smb2_echo_rsp *rsp = smb2_get_msg(work->response_buf);
5365 rsp->StructureSize = cpu_to_le16(4);
5367 inc_rfc1001_len(work->response_buf, 4);
5371 static int smb2_rename(struct ksmbd_work *work,
5372 struct ksmbd_file *fp,
5373 struct user_namespace *user_ns,
5374 struct smb2_file_rename_info *file_info,
5375 struct nls_table *local_nls)
5377 struct ksmbd_share_config *share = fp->tcon->share_conf;
5378 char *new_name = NULL, *abs_oldname = NULL, *old_name = NULL;
5379 char *pathname = NULL;
5381 bool file_present = true;
5384 ksmbd_debug(SMB, "setting FILE_RENAME_INFO\n");
5385 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
5389 abs_oldname = d_path(&fp->filp->f_path, pathname, PATH_MAX);
5390 if (IS_ERR(abs_oldname)) {
5394 old_name = strrchr(abs_oldname, '/');
5395 if (old_name && old_name[1] != '\0') {
5398 ksmbd_debug(SMB, "can't get last component in path %s\n",
5404 new_name = smb2_get_name(file_info->FileName,
5405 le32_to_cpu(file_info->FileNameLength),
5407 if (IS_ERR(new_name)) {
5408 rc = PTR_ERR(new_name);
5412 if (strchr(new_name, ':')) {
5414 char *xattr_stream_name, *stream_name = NULL;
5415 size_t xattr_stream_size;
5418 rc = parse_stream_name(new_name, &stream_name, &s_type);
5422 len = strlen(new_name);
5423 if (len > 0 && new_name[len - 1] != '/') {
5424 pr_err("not allow base filename in rename\n");
5429 rc = ksmbd_vfs_xattr_stream_name(stream_name,
5436 rc = ksmbd_vfs_setxattr(user_ns,
5437 fp->filp->f_path.dentry,
5441 pr_err("failed to store stream name in xattr: %d\n",
5450 ksmbd_debug(SMB, "new name %s\n", new_name);
5451 rc = ksmbd_vfs_kern_path(work, new_name, LOOKUP_NO_SYMLINKS, &path, 1);
5455 file_present = false;
5460 if (ksmbd_share_veto_filename(share, new_name)) {
5462 ksmbd_debug(SMB, "Can't rename vetoed file: %s\n", new_name);
5466 if (file_info->ReplaceIfExists) {
5468 rc = ksmbd_vfs_remove_file(work, new_name);
5470 if (rc != -ENOTEMPTY)
5472 ksmbd_debug(SMB, "cannot delete %s, rc %d\n",
5479 strncmp(old_name, path.dentry->d_name.name, strlen(old_name))) {
5482 "cannot rename already existing file\n");
5487 rc = ksmbd_vfs_fp_rename(work, fp, new_name);
5490 if (!IS_ERR(new_name))
5495 static int smb2_create_link(struct ksmbd_work *work,
5496 struct ksmbd_share_config *share,
5497 struct smb2_file_link_info *file_info,
5498 unsigned int buf_len, struct file *filp,
5499 struct nls_table *local_nls)
5501 char *link_name = NULL, *target_name = NULL, *pathname = NULL;
5503 bool file_present = true;
5506 if (buf_len < (u64)sizeof(struct smb2_file_link_info) +
5507 le32_to_cpu(file_info->FileNameLength))
5510 ksmbd_debug(SMB, "setting FILE_LINK_INFORMATION\n");
5511 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
5515 link_name = smb2_get_name(file_info->FileName,
5516 le32_to_cpu(file_info->FileNameLength),
5518 if (IS_ERR(link_name) || S_ISDIR(file_inode(filp)->i_mode)) {
5523 ksmbd_debug(SMB, "link name is %s\n", link_name);
5524 target_name = d_path(&filp->f_path, pathname, PATH_MAX);
5525 if (IS_ERR(target_name)) {
5530 ksmbd_debug(SMB, "target name is %s\n", target_name);
5531 rc = ksmbd_vfs_kern_path(work, link_name, LOOKUP_NO_SYMLINKS, &path, 0);
5535 file_present = false;
5540 if (file_info->ReplaceIfExists) {
5542 rc = ksmbd_vfs_remove_file(work, link_name);
5545 ksmbd_debug(SMB, "cannot delete %s\n",
5553 ksmbd_debug(SMB, "link already exists\n");
5558 rc = ksmbd_vfs_link(work, target_name, link_name);
5562 if (!IS_ERR(link_name))
5568 static int set_file_basic_info(struct ksmbd_file *fp,
5569 struct smb2_file_basic_info *file_info,
5570 struct ksmbd_share_config *share)
5574 struct inode *inode;
5575 struct user_namespace *user_ns;
5578 if (!(fp->daccess & FILE_WRITE_ATTRIBUTES_LE))
5583 inode = file_inode(filp);
5584 user_ns = file_mnt_user_ns(filp);
5586 if (file_info->CreationTime)
5587 fp->create_time = le64_to_cpu(file_info->CreationTime);
5589 if (file_info->LastAccessTime) {
5590 attrs.ia_atime = ksmbd_NTtimeToUnix(file_info->LastAccessTime);
5591 attrs.ia_valid |= (ATTR_ATIME | ATTR_ATIME_SET);
5594 attrs.ia_valid |= ATTR_CTIME;
5595 if (file_info->ChangeTime)
5596 attrs.ia_ctime = ksmbd_NTtimeToUnix(file_info->ChangeTime);
5598 attrs.ia_ctime = inode->i_ctime;
5600 if (file_info->LastWriteTime) {
5601 attrs.ia_mtime = ksmbd_NTtimeToUnix(file_info->LastWriteTime);
5602 attrs.ia_valid |= (ATTR_MTIME | ATTR_MTIME_SET);
5605 if (file_info->Attributes) {
5606 if (!S_ISDIR(inode->i_mode) &&
5607 file_info->Attributes & FILE_ATTRIBUTE_DIRECTORY_LE) {
5608 pr_err("can't change a file to a directory\n");
5612 if (!(S_ISDIR(inode->i_mode) && file_info->Attributes == FILE_ATTRIBUTE_NORMAL_LE))
5613 fp->f_ci->m_fattr = file_info->Attributes |
5614 (fp->f_ci->m_fattr & FILE_ATTRIBUTE_DIRECTORY_LE);
5617 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_STORE_DOS_ATTRS) &&
5618 (file_info->CreationTime || file_info->Attributes)) {
5619 struct xattr_dos_attrib da = {0};
5622 da.itime = fp->itime;
5623 da.create_time = fp->create_time;
5624 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
5625 da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
5626 XATTR_DOSINFO_ITIME;
5628 rc = ksmbd_vfs_set_dos_attrib_xattr(user_ns,
5629 filp->f_path.dentry, &da);
5632 "failed to restore file attribute in EA\n");
5636 if (attrs.ia_valid) {
5637 struct dentry *dentry = filp->f_path.dentry;
5638 struct inode *inode = d_inode(dentry);
5640 if (IS_IMMUTABLE(inode) || IS_APPEND(inode))
5644 inode->i_ctime = attrs.ia_ctime;
5645 attrs.ia_valid &= ~ATTR_CTIME;
5646 rc = notify_change(user_ns, dentry, &attrs, NULL);
5647 inode_unlock(inode);
5652 static int set_file_allocation_info(struct ksmbd_work *work,
5653 struct ksmbd_file *fp,
5654 struct smb2_file_alloc_info *file_alloc_info)
5657 * TODO : It's working fine only when store dos attributes
5658 * is not yes. need to implement a logic which works
5659 * properly with any smb.conf option
5663 struct inode *inode;
5666 if (!(fp->daccess & FILE_WRITE_DATA_LE))
5669 alloc_blks = (le64_to_cpu(file_alloc_info->AllocationSize) + 511) >> 9;
5670 inode = file_inode(fp->filp);
5672 if (alloc_blks > inode->i_blocks) {
5673 smb_break_all_levII_oplock(work, fp, 1);
5674 rc = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
5676 if (rc && rc != -EOPNOTSUPP) {
5677 pr_err("vfs_fallocate is failed : %d\n", rc);
5680 } else if (alloc_blks < inode->i_blocks) {
5684 * Allocation size could be smaller than original one
5685 * which means allocated blocks in file should be
5686 * deallocated. use truncate to cut out it, but inode
5687 * size is also updated with truncate offset.
5688 * inode size is retained by backup inode size.
5690 size = i_size_read(inode);
5691 rc = ksmbd_vfs_truncate(work, fp, alloc_blks * 512);
5693 pr_err("truncate failed!, err %d\n", rc);
5696 if (size < alloc_blks * 512)
5697 i_size_write(inode, size);
5702 static int set_end_of_file_info(struct ksmbd_work *work, struct ksmbd_file *fp,
5703 struct smb2_file_eof_info *file_eof_info)
5706 struct inode *inode;
5709 if (!(fp->daccess & FILE_WRITE_DATA_LE))
5712 newsize = le64_to_cpu(file_eof_info->EndOfFile);
5713 inode = file_inode(fp->filp);
5716 * If FILE_END_OF_FILE_INFORMATION of set_info_file is called
5717 * on FAT32 shared device, truncate execution time is too long
5718 * and network error could cause from windows client. because
5719 * truncate of some filesystem like FAT32 fill zero data in
5722 if (inode->i_sb->s_magic != MSDOS_SUPER_MAGIC) {
5723 ksmbd_debug(SMB, "truncated to newsize %lld\n", newsize);
5724 rc = ksmbd_vfs_truncate(work, fp, newsize);
5726 ksmbd_debug(SMB, "truncate failed!, err %d\n", rc);
5735 static int set_rename_info(struct ksmbd_work *work, struct ksmbd_file *fp,
5736 struct smb2_file_rename_info *rename_info,
5737 unsigned int buf_len)
5739 struct user_namespace *user_ns;
5740 struct ksmbd_file *parent_fp;
5741 struct dentry *parent;
5742 struct dentry *dentry = fp->filp->f_path.dentry;
5745 if (!(fp->daccess & FILE_DELETE_LE)) {
5746 pr_err("no right to delete : 0x%x\n", fp->daccess);
5750 if (buf_len < (u64)sizeof(struct smb2_file_rename_info) +
5751 le32_to_cpu(rename_info->FileNameLength))
5754 user_ns = file_mnt_user_ns(fp->filp);
5755 if (ksmbd_stream_fd(fp))
5758 parent = dget_parent(dentry);
5759 ret = ksmbd_vfs_lock_parent(user_ns, parent, dentry);
5765 parent_fp = ksmbd_lookup_fd_inode(d_inode(parent));
5766 inode_unlock(d_inode(parent));
5770 if (parent_fp->daccess & FILE_DELETE_LE) {
5771 pr_err("parent dir is opened with delete access\n");
5772 ksmbd_fd_put(work, parent_fp);
5775 ksmbd_fd_put(work, parent_fp);
5778 return smb2_rename(work, fp, user_ns, rename_info,
5779 work->sess->conn->local_nls);
5782 static int set_file_disposition_info(struct ksmbd_file *fp,
5783 struct smb2_file_disposition_info *file_info)
5785 struct inode *inode;
5787 if (!(fp->daccess & FILE_DELETE_LE)) {
5788 pr_err("no right to delete : 0x%x\n", fp->daccess);
5792 inode = file_inode(fp->filp);
5793 if (file_info->DeletePending) {
5794 if (S_ISDIR(inode->i_mode) &&
5795 ksmbd_vfs_empty_dir(fp) == -ENOTEMPTY)
5797 ksmbd_set_inode_pending_delete(fp);
5799 ksmbd_clear_inode_pending_delete(fp);
5804 static int set_file_position_info(struct ksmbd_file *fp,
5805 struct smb2_file_pos_info *file_info)
5807 loff_t current_byte_offset;
5808 unsigned long sector_size;
5809 struct inode *inode;
5811 inode = file_inode(fp->filp);
5812 current_byte_offset = le64_to_cpu(file_info->CurrentByteOffset);
5813 sector_size = inode->i_sb->s_blocksize;
5815 if (current_byte_offset < 0 ||
5816 (fp->coption == FILE_NO_INTERMEDIATE_BUFFERING_LE &&
5817 current_byte_offset & (sector_size - 1))) {
5818 pr_err("CurrentByteOffset is not valid : %llu\n",
5819 current_byte_offset);
5823 fp->filp->f_pos = current_byte_offset;
5827 static int set_file_mode_info(struct ksmbd_file *fp,
5828 struct smb2_file_mode_info *file_info)
5832 mode = file_info->Mode;
5834 if ((mode & ~FILE_MODE_INFO_MASK)) {
5835 pr_err("Mode is not valid : 0x%x\n", le32_to_cpu(mode));
5840 * TODO : need to implement consideration for
5841 * FILE_SYNCHRONOUS_IO_ALERT and FILE_SYNCHRONOUS_IO_NONALERT
5843 ksmbd_vfs_set_fadvise(fp->filp, mode);
5849 * smb2_set_info_file() - handler for smb2 set info command
5850 * @work: smb work containing set info command buffer
5851 * @fp: ksmbd_file pointer
5852 * @req: request buffer pointer
5853 * @share: ksmbd_share_config pointer
5855 * Return: 0 on success, otherwise error
5856 * TODO: need to implement an error handling for STATUS_INFO_LENGTH_MISMATCH
5858 static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp,
5859 struct smb2_set_info_req *req,
5860 struct ksmbd_share_config *share)
5862 unsigned int buf_len = le32_to_cpu(req->BufferLength);
5864 switch (req->FileInfoClass) {
5865 case FILE_BASIC_INFORMATION:
5867 if (buf_len < sizeof(struct smb2_file_basic_info))
5870 return set_file_basic_info(fp, (struct smb2_file_basic_info *)req->Buffer, share);
5872 case FILE_ALLOCATION_INFORMATION:
5874 if (buf_len < sizeof(struct smb2_file_alloc_info))
5877 return set_file_allocation_info(work, fp,
5878 (struct smb2_file_alloc_info *)req->Buffer);
5880 case FILE_END_OF_FILE_INFORMATION:
5882 if (buf_len < sizeof(struct smb2_file_eof_info))
5885 return set_end_of_file_info(work, fp,
5886 (struct smb2_file_eof_info *)req->Buffer);
5888 case FILE_RENAME_INFORMATION:
5890 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
5892 "User does not have write permission\n");
5896 if (buf_len < sizeof(struct smb2_file_rename_info))
5899 return set_rename_info(work, fp,
5900 (struct smb2_file_rename_info *)req->Buffer,
5903 case FILE_LINK_INFORMATION:
5905 if (buf_len < sizeof(struct smb2_file_link_info))
5908 return smb2_create_link(work, work->tcon->share_conf,
5909 (struct smb2_file_link_info *)req->Buffer,
5911 work->sess->conn->local_nls);
5913 case FILE_DISPOSITION_INFORMATION:
5915 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
5917 "User does not have write permission\n");
5921 if (buf_len < sizeof(struct smb2_file_disposition_info))
5924 return set_file_disposition_info(fp,
5925 (struct smb2_file_disposition_info *)req->Buffer);
5927 case FILE_FULL_EA_INFORMATION:
5929 if (!(fp->daccess & FILE_WRITE_EA_LE)) {
5930 pr_err("Not permitted to write ext attr: 0x%x\n",
5935 if (buf_len < sizeof(struct smb2_ea_info))
5938 return smb2_set_ea((struct smb2_ea_info *)req->Buffer,
5939 buf_len, &fp->filp->f_path);
5941 case FILE_POSITION_INFORMATION:
5943 if (buf_len < sizeof(struct smb2_file_pos_info))
5946 return set_file_position_info(fp, (struct smb2_file_pos_info *)req->Buffer);
5948 case FILE_MODE_INFORMATION:
5950 if (buf_len < sizeof(struct smb2_file_mode_info))
5953 return set_file_mode_info(fp, (struct smb2_file_mode_info *)req->Buffer);
5957 pr_err("Unimplemented Fileinfoclass :%d\n", req->FileInfoClass);
5961 static int smb2_set_info_sec(struct ksmbd_file *fp, int addition_info,
5962 char *buffer, int buf_len)
5964 struct smb_ntsd *pntsd = (struct smb_ntsd *)buffer;
5966 fp->saccess |= FILE_SHARE_DELETE_LE;
5968 return set_info_sec(fp->conn, fp->tcon, &fp->filp->f_path, pntsd,
5973 * smb2_set_info() - handler for smb2 set info command handler
5974 * @work: smb work containing set info request buffer
5976 * Return: 0 on success, otherwise error
5978 int smb2_set_info(struct ksmbd_work *work)
5980 struct smb2_set_info_req *req;
5981 struct smb2_set_info_rsp *rsp;
5982 struct ksmbd_file *fp;
5984 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
5986 ksmbd_debug(SMB, "Received set info request\n");
5988 if (work->next_smb2_rcv_hdr_off) {
5989 req = ksmbd_req_buf_next(work);
5990 rsp = ksmbd_resp_buf_next(work);
5991 if (!has_file_id(req->VolatileFileId)) {
5992 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
5993 work->compound_fid);
5994 id = work->compound_fid;
5995 pid = work->compound_pfid;
5998 req = smb2_get_msg(work->request_buf);
5999 rsp = smb2_get_msg(work->response_buf);
6002 if (!has_file_id(id)) {
6003 id = req->VolatileFileId;
6004 pid = req->PersistentFileId;
6007 fp = ksmbd_lookup_fd_slow(work, id, pid);
6009 ksmbd_debug(SMB, "Invalid id for close: %u\n", id);
6014 switch (req->InfoType) {
6015 case SMB2_O_INFO_FILE:
6016 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
6017 rc = smb2_set_info_file(work, fp, req, work->tcon->share_conf);
6019 case SMB2_O_INFO_SECURITY:
6020 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
6021 if (ksmbd_override_fsids(work)) {
6025 rc = smb2_set_info_sec(fp,
6026 le32_to_cpu(req->AdditionalInformation),
6028 le32_to_cpu(req->BufferLength));
6029 ksmbd_revert_fsids(work);
6038 rsp->StructureSize = cpu_to_le16(2);
6039 inc_rfc1001_len(work->response_buf, 2);
6040 ksmbd_fd_put(work, fp);
6044 if (rc == -EACCES || rc == -EPERM || rc == -EXDEV)
6045 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6046 else if (rc == -EINVAL)
6047 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6048 else if (rc == -ESHARE)
6049 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6050 else if (rc == -ENOENT)
6051 rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
6052 else if (rc == -EBUSY || rc == -ENOTEMPTY)
6053 rsp->hdr.Status = STATUS_DIRECTORY_NOT_EMPTY;
6054 else if (rc == -EAGAIN)
6055 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6056 else if (rc == -EBADF || rc == -ESTALE)
6057 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6058 else if (rc == -EEXIST)
6059 rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
6060 else if (rsp->hdr.Status == 0 || rc == -EOPNOTSUPP)
6061 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
6062 smb2_set_err_rsp(work);
6063 ksmbd_fd_put(work, fp);
6064 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n", rc);
6069 * smb2_read_pipe() - handler for smb2 read from IPC pipe
6070 * @work: smb work containing read IPC pipe command buffer
6072 * Return: 0 on success, otherwise error
6074 static noinline int smb2_read_pipe(struct ksmbd_work *work)
6076 int nbytes = 0, err;
6078 struct ksmbd_rpc_command *rpc_resp;
6079 struct smb2_read_req *req = smb2_get_msg(work->request_buf);
6080 struct smb2_read_rsp *rsp = smb2_get_msg(work->response_buf);
6082 id = req->VolatileFileId;
6084 inc_rfc1001_len(work->response_buf, 16);
6085 rpc_resp = ksmbd_rpc_read(work->sess, id);
6087 if (rpc_resp->flags != KSMBD_RPC_OK) {
6092 work->aux_payload_buf =
6093 kvmalloc(rpc_resp->payload_sz, GFP_KERNEL | __GFP_ZERO);
6094 if (!work->aux_payload_buf) {
6099 memcpy(work->aux_payload_buf, rpc_resp->payload,
6100 rpc_resp->payload_sz);
6102 nbytes = rpc_resp->payload_sz;
6103 work->resp_hdr_sz = get_rfc1002_len(work->response_buf) + 4;
6104 work->aux_payload_sz = nbytes;
6108 rsp->StructureSize = cpu_to_le16(17);
6109 rsp->DataOffset = 80;
6111 rsp->DataLength = cpu_to_le32(nbytes);
6112 rsp->DataRemaining = 0;
6114 inc_rfc1001_len(work->response_buf, nbytes);
6118 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
6119 smb2_set_err_rsp(work);
6124 static int smb2_set_remote_key_for_rdma(struct ksmbd_work *work,
6125 struct smb2_buffer_desc_v1 *desc,
6127 __le16 ChannelInfoLength)
6129 unsigned int i, ch_count;
6131 if (work->conn->dialect == SMB30_PROT_ID &&
6132 Channel != SMB2_CHANNEL_RDMA_V1)
6135 ch_count = le16_to_cpu(ChannelInfoLength) / sizeof(*desc);
6136 if (ksmbd_debug_types & KSMBD_DEBUG_RDMA) {
6137 for (i = 0; i < ch_count; i++) {
6138 pr_info("RDMA r/w request %#x: token %#x, length %#x\n",
6140 le32_to_cpu(desc[i].token),
6141 le32_to_cpu(desc[i].length));
6147 work->need_invalidate_rkey =
6148 (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE);
6149 if (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE)
6150 work->remote_key = le32_to_cpu(desc->token);
6154 static ssize_t smb2_read_rdma_channel(struct ksmbd_work *work,
6155 struct smb2_read_req *req, void *data_buf,
6160 err = ksmbd_conn_rdma_write(work->conn, data_buf, length,
6161 (struct smb2_buffer_desc_v1 *)
6162 ((char *)req + le16_to_cpu(req->ReadChannelInfoOffset)),
6163 le16_to_cpu(req->ReadChannelInfoLength));
6171 * smb2_read() - handler for smb2 read from file
6172 * @work: smb work containing read command buffer
6174 * Return: 0 on success, otherwise error
6176 int smb2_read(struct ksmbd_work *work)
6178 struct ksmbd_conn *conn = work->conn;
6179 struct smb2_read_req *req;
6180 struct smb2_read_rsp *rsp;
6181 struct ksmbd_file *fp = NULL;
6183 size_t length, mincount;
6184 ssize_t nbytes = 0, remain_bytes = 0;
6186 bool is_rdma_channel = false;
6187 unsigned int max_read_size = conn->vals->max_read_size;
6189 WORK_BUFFERS(work, req, rsp);
6191 if (test_share_config_flag(work->tcon->share_conf,
6192 KSMBD_SHARE_FLAG_PIPE)) {
6193 ksmbd_debug(SMB, "IPC pipe read request\n");
6194 return smb2_read_pipe(work);
6197 if (req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE ||
6198 req->Channel == SMB2_CHANNEL_RDMA_V1) {
6199 is_rdma_channel = true;
6200 max_read_size = get_smbd_max_read_write_size();
6203 if (is_rdma_channel == true) {
6204 unsigned int ch_offset = le16_to_cpu(req->ReadChannelInfoOffset);
6206 if (ch_offset < offsetof(struct smb2_read_req, Buffer)) {
6210 err = smb2_set_remote_key_for_rdma(work,
6211 (struct smb2_buffer_desc_v1 *)
6212 ((char *)req + ch_offset),
6214 req->ReadChannelInfoLength);
6219 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
6225 if (!(fp->daccess & (FILE_READ_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
6226 pr_err("Not permitted to read : 0x%x\n", fp->daccess);
6231 offset = le64_to_cpu(req->Offset);
6232 length = le32_to_cpu(req->Length);
6233 mincount = le32_to_cpu(req->MinimumCount);
6235 if (length > max_read_size) {
6236 ksmbd_debug(SMB, "limiting read size to max size(%u)\n",
6242 ksmbd_debug(SMB, "filename %pd, offset %lld, len %zu\n",
6243 fp->filp->f_path.dentry, offset, length);
6245 work->aux_payload_buf = kvmalloc(length, GFP_KERNEL | __GFP_ZERO);
6246 if (!work->aux_payload_buf) {
6251 nbytes = ksmbd_vfs_read(work, fp, length, &offset);
6257 if ((nbytes == 0 && length != 0) || nbytes < mincount) {
6258 kvfree(work->aux_payload_buf);
6259 work->aux_payload_buf = NULL;
6260 rsp->hdr.Status = STATUS_END_OF_FILE;
6261 smb2_set_err_rsp(work);
6262 ksmbd_fd_put(work, fp);
6266 ksmbd_debug(SMB, "nbytes %zu, offset %lld mincount %zu\n",
6267 nbytes, offset, mincount);
6269 if (is_rdma_channel == true) {
6270 /* write data to the client using rdma channel */
6271 remain_bytes = smb2_read_rdma_channel(work, req,
6272 work->aux_payload_buf,
6274 kvfree(work->aux_payload_buf);
6275 work->aux_payload_buf = NULL;
6278 if (remain_bytes < 0) {
6279 err = (int)remain_bytes;
6284 rsp->StructureSize = cpu_to_le16(17);
6285 rsp->DataOffset = 80;
6287 rsp->DataLength = cpu_to_le32(nbytes);
6288 rsp->DataRemaining = cpu_to_le32(remain_bytes);
6290 inc_rfc1001_len(work->response_buf, 16);
6291 work->resp_hdr_sz = get_rfc1002_len(work->response_buf) + 4;
6292 work->aux_payload_sz = nbytes;
6293 inc_rfc1001_len(work->response_buf, nbytes);
6294 ksmbd_fd_put(work, fp);
6300 rsp->hdr.Status = STATUS_INVALID_DEVICE_REQUEST;
6301 else if (err == -EAGAIN)
6302 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6303 else if (err == -ENOENT)
6304 rsp->hdr.Status = STATUS_FILE_CLOSED;
6305 else if (err == -EACCES)
6306 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6307 else if (err == -ESHARE)
6308 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6309 else if (err == -EINVAL)
6310 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6312 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6314 smb2_set_err_rsp(work);
6316 ksmbd_fd_put(work, fp);
6321 * smb2_write_pipe() - handler for smb2 write on IPC pipe
6322 * @work: smb work containing write IPC pipe command buffer
6324 * Return: 0 on success, otherwise error
6326 static noinline int smb2_write_pipe(struct ksmbd_work *work)
6328 struct smb2_write_req *req = smb2_get_msg(work->request_buf);
6329 struct smb2_write_rsp *rsp = smb2_get_msg(work->response_buf);
6330 struct ksmbd_rpc_command *rpc_resp;
6332 int err = 0, ret = 0;
6336 length = le32_to_cpu(req->Length);
6337 id = req->VolatileFileId;
6339 if ((u64)le16_to_cpu(req->DataOffset) + length >
6340 get_rfc1002_len(work->request_buf)) {
6341 pr_err("invalid write data offset %u, smb_len %u\n",
6342 le16_to_cpu(req->DataOffset),
6343 get_rfc1002_len(work->request_buf));
6348 data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
6349 le16_to_cpu(req->DataOffset));
6351 rpc_resp = ksmbd_rpc_write(work->sess, id, data_buf, length);
6353 if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
6354 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
6356 smb2_set_err_rsp(work);
6359 if (rpc_resp->flags != KSMBD_RPC_OK) {
6360 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6361 smb2_set_err_rsp(work);
6368 rsp->StructureSize = cpu_to_le16(17);
6369 rsp->DataOffset = 0;
6371 rsp->DataLength = cpu_to_le32(length);
6372 rsp->DataRemaining = 0;
6374 inc_rfc1001_len(work->response_buf, 16);
6378 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6379 smb2_set_err_rsp(work);
6385 static ssize_t smb2_write_rdma_channel(struct ksmbd_work *work,
6386 struct smb2_write_req *req,
6387 struct ksmbd_file *fp,
6388 loff_t offset, size_t length, bool sync)
6394 data_buf = kvmalloc(length, GFP_KERNEL | __GFP_ZERO);
6398 ret = ksmbd_conn_rdma_read(work->conn, data_buf, length,
6399 (struct smb2_buffer_desc_v1 *)
6400 ((char *)req + le16_to_cpu(req->WriteChannelInfoOffset)),
6401 le16_to_cpu(req->WriteChannelInfoLength));
6407 ret = ksmbd_vfs_write(work, fp, data_buf, length, &offset, sync, &nbytes);
6416 * smb2_write() - handler for smb2 write from file
6417 * @work: smb work containing write command buffer
6419 * Return: 0 on success, otherwise error
6421 int smb2_write(struct ksmbd_work *work)
6423 struct smb2_write_req *req;
6424 struct smb2_write_rsp *rsp;
6425 struct ksmbd_file *fp = NULL;
6430 bool writethrough = false, is_rdma_channel = false;
6432 unsigned int max_write_size = work->conn->vals->max_write_size;
6434 WORK_BUFFERS(work, req, rsp);
6436 if (test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_PIPE)) {
6437 ksmbd_debug(SMB, "IPC pipe write request\n");
6438 return smb2_write_pipe(work);
6441 offset = le64_to_cpu(req->Offset);
6442 length = le32_to_cpu(req->Length);
6444 if (req->Channel == SMB2_CHANNEL_RDMA_V1 ||
6445 req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE) {
6446 is_rdma_channel = true;
6447 max_write_size = get_smbd_max_read_write_size();
6448 length = le32_to_cpu(req->RemainingBytes);
6451 if (is_rdma_channel == true) {
6452 unsigned int ch_offset = le16_to_cpu(req->WriteChannelInfoOffset);
6454 if (req->Length != 0 || req->DataOffset != 0 ||
6455 ch_offset < offsetof(struct smb2_write_req, Buffer)) {
6459 err = smb2_set_remote_key_for_rdma(work,
6460 (struct smb2_buffer_desc_v1 *)
6461 ((char *)req + ch_offset),
6463 req->WriteChannelInfoLength);
6468 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
6469 ksmbd_debug(SMB, "User does not have write permission\n");
6474 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
6480 if (!(fp->daccess & (FILE_WRITE_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
6481 pr_err("Not permitted to write : 0x%x\n", fp->daccess);
6486 if (length > max_write_size) {
6487 ksmbd_debug(SMB, "limiting write size to max size(%u)\n",
6493 ksmbd_debug(SMB, "flags %u\n", le32_to_cpu(req->Flags));
6494 if (le32_to_cpu(req->Flags) & SMB2_WRITEFLAG_WRITE_THROUGH)
6495 writethrough = true;
6497 if (is_rdma_channel == false) {
6498 if ((u64)le16_to_cpu(req->DataOffset) + length >
6499 get_rfc1002_len(work->request_buf)) {
6500 pr_err("invalid write data offset %u, smb_len %u\n",
6501 le16_to_cpu(req->DataOffset),
6502 get_rfc1002_len(work->request_buf));
6506 data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
6507 le16_to_cpu(req->DataOffset));
6509 ksmbd_debug(SMB, "filename %pd, offset %lld, len %zu\n",
6510 fp->filp->f_path.dentry, offset, length);
6511 err = ksmbd_vfs_write(work, fp, data_buf, length, &offset,
6512 writethrough, &nbytes);
6516 /* read data from the client using rdma channel, and
6519 nbytes = smb2_write_rdma_channel(work, req, fp, offset, length,
6527 rsp->StructureSize = cpu_to_le16(17);
6528 rsp->DataOffset = 0;
6530 rsp->DataLength = cpu_to_le32(nbytes);
6531 rsp->DataRemaining = 0;
6533 inc_rfc1001_len(work->response_buf, 16);
6534 ksmbd_fd_put(work, fp);
6539 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6540 else if (err == -ENOSPC || err == -EFBIG)
6541 rsp->hdr.Status = STATUS_DISK_FULL;
6542 else if (err == -ENOENT)
6543 rsp->hdr.Status = STATUS_FILE_CLOSED;
6544 else if (err == -EACCES)
6545 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6546 else if (err == -ESHARE)
6547 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6548 else if (err == -EINVAL)
6549 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6551 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6553 smb2_set_err_rsp(work);
6554 ksmbd_fd_put(work, fp);
6559 * smb2_flush() - handler for smb2 flush file - fsync
6560 * @work: smb work containing flush command buffer
6562 * Return: 0 on success, otherwise error
6564 int smb2_flush(struct ksmbd_work *work)
6566 struct smb2_flush_req *req;
6567 struct smb2_flush_rsp *rsp;
6570 WORK_BUFFERS(work, req, rsp);
6572 ksmbd_debug(SMB, "SMB2_FLUSH called for fid %llu\n", req->VolatileFileId);
6574 err = ksmbd_vfs_fsync(work, req->VolatileFileId, req->PersistentFileId);
6578 rsp->StructureSize = cpu_to_le16(4);
6580 inc_rfc1001_len(work->response_buf, 4);
6585 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6586 smb2_set_err_rsp(work);
6593 * smb2_cancel() - handler for smb2 cancel command
6594 * @work: smb work containing cancel command buffer
6596 * Return: 0 on success, otherwise error
6598 int smb2_cancel(struct ksmbd_work *work)
6600 struct ksmbd_conn *conn = work->conn;
6601 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
6602 struct smb2_hdr *chdr;
6603 struct ksmbd_work *cancel_work = NULL, *iter;
6604 struct list_head *command_list;
6606 ksmbd_debug(SMB, "smb2 cancel called on mid %llu, async flags 0x%x\n",
6607 hdr->MessageId, hdr->Flags);
6609 if (hdr->Flags & SMB2_FLAGS_ASYNC_COMMAND) {
6610 command_list = &conn->async_requests;
6612 spin_lock(&conn->request_lock);
6613 list_for_each_entry(iter, command_list,
6614 async_request_entry) {
6615 chdr = smb2_get_msg(iter->request_buf);
6617 if (iter->async_id !=
6618 le64_to_cpu(hdr->Id.AsyncId))
6622 "smb2 with AsyncId %llu cancelled command = 0x%x\n",
6623 le64_to_cpu(hdr->Id.AsyncId),
6624 le16_to_cpu(chdr->Command));
6628 spin_unlock(&conn->request_lock);
6630 command_list = &conn->requests;
6632 spin_lock(&conn->request_lock);
6633 list_for_each_entry(iter, command_list, request_entry) {
6634 chdr = smb2_get_msg(iter->request_buf);
6636 if (chdr->MessageId != hdr->MessageId ||
6641 "smb2 with mid %llu cancelled command = 0x%x\n",
6642 le64_to_cpu(hdr->MessageId),
6643 le16_to_cpu(chdr->Command));
6647 spin_unlock(&conn->request_lock);
6651 cancel_work->state = KSMBD_WORK_CANCELLED;
6652 if (cancel_work->cancel_fn)
6653 cancel_work->cancel_fn(cancel_work->cancel_argv);
6656 /* For SMB2_CANCEL command itself send no response*/
6657 work->send_no_response = 1;
6661 struct file_lock *smb_flock_init(struct file *f)
6663 struct file_lock *fl;
6665 fl = locks_alloc_lock();
6669 locks_init_lock(fl);
6672 fl->fl_pid = current->tgid;
6674 fl->fl_flags = FL_POSIX;
6676 fl->fl_lmops = NULL;
6682 static int smb2_set_flock_flags(struct file_lock *flock, int flags)
6686 /* Checking for wrong flag combination during lock request*/
6688 case SMB2_LOCKFLAG_SHARED:
6689 ksmbd_debug(SMB, "received shared request\n");
6691 flock->fl_type = F_RDLCK;
6692 flock->fl_flags |= FL_SLEEP;
6694 case SMB2_LOCKFLAG_EXCLUSIVE:
6695 ksmbd_debug(SMB, "received exclusive request\n");
6697 flock->fl_type = F_WRLCK;
6698 flock->fl_flags |= FL_SLEEP;
6700 case SMB2_LOCKFLAG_SHARED | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
6702 "received shared & fail immediately request\n");
6704 flock->fl_type = F_RDLCK;
6706 case SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
6708 "received exclusive & fail immediately request\n");
6710 flock->fl_type = F_WRLCK;
6712 case SMB2_LOCKFLAG_UNLOCK:
6713 ksmbd_debug(SMB, "received unlock request\n");
6714 flock->fl_type = F_UNLCK;
6722 static struct ksmbd_lock *smb2_lock_init(struct file_lock *flock,
6723 unsigned int cmd, int flags,
6724 struct list_head *lock_list)
6726 struct ksmbd_lock *lock;
6728 lock = kzalloc(sizeof(struct ksmbd_lock), GFP_KERNEL);
6734 lock->start = flock->fl_start;
6735 lock->end = flock->fl_end;
6736 lock->flags = flags;
6737 if (lock->start == lock->end)
6739 INIT_LIST_HEAD(&lock->clist);
6740 INIT_LIST_HEAD(&lock->flist);
6741 INIT_LIST_HEAD(&lock->llist);
6742 list_add_tail(&lock->llist, lock_list);
6747 static void smb2_remove_blocked_lock(void **argv)
6749 struct file_lock *flock = (struct file_lock *)argv[0];
6751 ksmbd_vfs_posix_lock_unblock(flock);
6752 wake_up(&flock->fl_wait);
6755 static inline bool lock_defer_pending(struct file_lock *fl)
6757 /* check pending lock waiters */
6758 return waitqueue_active(&fl->fl_wait);
6762 * smb2_lock() - handler for smb2 file lock command
6763 * @work: smb work containing lock command buffer
6765 * Return: 0 on success, otherwise error
6767 int smb2_lock(struct ksmbd_work *work)
6769 struct smb2_lock_req *req = smb2_get_msg(work->request_buf);
6770 struct smb2_lock_rsp *rsp = smb2_get_msg(work->response_buf);
6771 struct smb2_lock_element *lock_ele;
6772 struct ksmbd_file *fp = NULL;
6773 struct file_lock *flock = NULL;
6774 struct file *filp = NULL;
6778 int err = -EIO, i, rc = 0;
6779 u64 lock_start, lock_length;
6780 struct ksmbd_lock *smb_lock = NULL, *cmp_lock, *tmp, *tmp2;
6781 struct ksmbd_conn *conn;
6783 LIST_HEAD(lock_list);
6784 LIST_HEAD(rollback_list);
6787 ksmbd_debug(SMB, "Received lock request\n");
6788 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
6790 ksmbd_debug(SMB, "Invalid file id for lock : %llu\n", req->VolatileFileId);
6796 lock_count = le16_to_cpu(req->LockCount);
6797 lock_ele = req->locks;
6799 ksmbd_debug(SMB, "lock count is %d\n", lock_count);
6805 for (i = 0; i < lock_count; i++) {
6806 flags = le32_to_cpu(lock_ele[i].Flags);
6808 flock = smb_flock_init(filp);
6812 cmd = smb2_set_flock_flags(flock, flags);
6814 lock_start = le64_to_cpu(lock_ele[i].Offset);
6815 lock_length = le64_to_cpu(lock_ele[i].Length);
6816 if (lock_start > U64_MAX - lock_length) {
6817 pr_err("Invalid lock range requested\n");
6818 rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
6822 if (lock_start > OFFSET_MAX)
6823 flock->fl_start = OFFSET_MAX;
6825 flock->fl_start = lock_start;
6827 lock_length = le64_to_cpu(lock_ele[i].Length);
6828 if (lock_length > OFFSET_MAX - flock->fl_start)
6829 lock_length = OFFSET_MAX - flock->fl_start;
6831 flock->fl_end = flock->fl_start + lock_length;
6833 if (flock->fl_end < flock->fl_start) {
6835 "the end offset(%llx) is smaller than the start offset(%llx)\n",
6836 flock->fl_end, flock->fl_start);
6837 rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
6841 /* Check conflict locks in one request */
6842 list_for_each_entry(cmp_lock, &lock_list, llist) {
6843 if (cmp_lock->fl->fl_start <= flock->fl_start &&
6844 cmp_lock->fl->fl_end >= flock->fl_end) {
6845 if (cmp_lock->fl->fl_type != F_UNLCK &&
6846 flock->fl_type != F_UNLCK) {
6847 pr_err("conflict two locks in one request\n");
6854 smb_lock = smb2_lock_init(flock, cmd, flags, &lock_list);
6861 list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
6862 if (smb_lock->cmd < 0) {
6867 if (!(smb_lock->flags & SMB2_LOCKFLAG_MASK)) {
6872 if ((prior_lock & (SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_SHARED) &&
6873 smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) ||
6874 (prior_lock == SMB2_LOCKFLAG_UNLOCK &&
6875 !(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK))) {
6880 prior_lock = smb_lock->flags;
6882 if (!(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) &&
6883 !(smb_lock->flags & SMB2_LOCKFLAG_FAIL_IMMEDIATELY))
6887 /* check locks in connection list */
6888 read_lock(&conn_list_lock);
6889 list_for_each_entry(conn, &conn_list, conns_list) {
6890 spin_lock(&conn->llist_lock);
6891 list_for_each_entry_safe(cmp_lock, tmp2, &conn->lock_list, clist) {
6892 if (file_inode(cmp_lock->fl->fl_file) !=
6893 file_inode(smb_lock->fl->fl_file))
6896 if (smb_lock->fl->fl_type == F_UNLCK) {
6897 if (cmp_lock->fl->fl_file == smb_lock->fl->fl_file &&
6898 cmp_lock->start == smb_lock->start &&
6899 cmp_lock->end == smb_lock->end &&
6900 !lock_defer_pending(cmp_lock->fl)) {
6902 list_del(&cmp_lock->flist);
6903 list_del(&cmp_lock->clist);
6904 spin_unlock(&conn->llist_lock);
6905 read_unlock(&conn_list_lock);
6907 locks_free_lock(cmp_lock->fl);
6914 if (cmp_lock->fl->fl_file == smb_lock->fl->fl_file) {
6915 if (smb_lock->flags & SMB2_LOCKFLAG_SHARED)
6918 if (cmp_lock->flags & SMB2_LOCKFLAG_SHARED)
6922 /* check zero byte lock range */
6923 if (cmp_lock->zero_len && !smb_lock->zero_len &&
6924 cmp_lock->start > smb_lock->start &&
6925 cmp_lock->start < smb_lock->end) {
6926 spin_unlock(&conn->llist_lock);
6927 read_unlock(&conn_list_lock);
6928 pr_err("previous lock conflict with zero byte lock range\n");
6932 if (smb_lock->zero_len && !cmp_lock->zero_len &&
6933 smb_lock->start > cmp_lock->start &&
6934 smb_lock->start < cmp_lock->end) {
6935 spin_unlock(&conn->llist_lock);
6936 read_unlock(&conn_list_lock);
6937 pr_err("current lock conflict with zero byte lock range\n");
6941 if (((cmp_lock->start <= smb_lock->start &&
6942 cmp_lock->end > smb_lock->start) ||
6943 (cmp_lock->start < smb_lock->end &&
6944 cmp_lock->end >= smb_lock->end)) &&
6945 !cmp_lock->zero_len && !smb_lock->zero_len) {
6946 spin_unlock(&conn->llist_lock);
6947 read_unlock(&conn_list_lock);
6948 pr_err("Not allow lock operation on exclusive lock range\n");
6952 spin_unlock(&conn->llist_lock);
6954 read_unlock(&conn_list_lock);
6956 if (smb_lock->fl->fl_type == F_UNLCK && nolock) {
6957 pr_err("Try to unlock nolocked range\n");
6958 rsp->hdr.Status = STATUS_RANGE_NOT_LOCKED;
6963 if (smb_lock->zero_len) {
6968 flock = smb_lock->fl;
6969 list_del(&smb_lock->llist);
6971 rc = vfs_lock_file(filp, smb_lock->cmd, flock, NULL);
6973 if (flags & SMB2_LOCKFLAG_UNLOCK) {
6975 ksmbd_debug(SMB, "File unlocked\n");
6976 } else if (rc == -ENOENT) {
6977 rsp->hdr.Status = STATUS_NOT_LOCKED;
6980 locks_free_lock(flock);
6983 if (rc == FILE_LOCK_DEFERRED) {
6987 "would have to wait for getting lock\n");
6988 spin_lock(&work->conn->llist_lock);
6989 list_add_tail(&smb_lock->clist,
6990 &work->conn->lock_list);
6991 spin_unlock(&work->conn->llist_lock);
6992 list_add(&smb_lock->llist, &rollback_list);
6994 argv = kmalloc(sizeof(void *), GFP_KERNEL);
7001 rc = setup_async_work(work,
7002 smb2_remove_blocked_lock,
7008 spin_lock(&fp->f_lock);
7009 list_add(&work->fp_entry, &fp->blocked_works);
7010 spin_unlock(&fp->f_lock);
7012 smb2_send_interim_resp(work, STATUS_PENDING);
7014 ksmbd_vfs_posix_lock_wait(flock);
7016 if (work->state != KSMBD_WORK_ACTIVE) {
7017 list_del(&smb_lock->llist);
7018 spin_lock(&work->conn->llist_lock);
7019 list_del(&smb_lock->clist);
7020 spin_unlock(&work->conn->llist_lock);
7021 locks_free_lock(flock);
7023 if (work->state == KSMBD_WORK_CANCELLED) {
7024 spin_lock(&fp->f_lock);
7025 list_del(&work->fp_entry);
7026 spin_unlock(&fp->f_lock);
7030 smb2_send_interim_resp(work,
7032 work->send_no_response = 1;
7035 init_smb2_rsp_hdr(work);
7036 smb2_set_err_rsp(work);
7038 STATUS_RANGE_NOT_LOCKED;
7043 list_del(&smb_lock->llist);
7044 spin_lock(&work->conn->llist_lock);
7045 list_del(&smb_lock->clist);
7046 spin_unlock(&work->conn->llist_lock);
7048 spin_lock(&fp->f_lock);
7049 list_del(&work->fp_entry);
7050 spin_unlock(&fp->f_lock);
7053 spin_lock(&work->conn->llist_lock);
7054 list_add_tail(&smb_lock->clist,
7055 &work->conn->lock_list);
7056 list_add_tail(&smb_lock->flist,
7058 spin_unlock(&work->conn->llist_lock);
7059 list_add(&smb_lock->llist, &rollback_list);
7060 ksmbd_debug(SMB, "successful in taking lock\n");
7067 if (atomic_read(&fp->f_ci->op_count) > 1)
7068 smb_break_all_oplock(work, fp);
7070 rsp->StructureSize = cpu_to_le16(4);
7071 ksmbd_debug(SMB, "successful in taking lock\n");
7072 rsp->hdr.Status = STATUS_SUCCESS;
7074 inc_rfc1001_len(work->response_buf, 4);
7075 ksmbd_fd_put(work, fp);
7079 list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
7080 locks_free_lock(smb_lock->fl);
7081 list_del(&smb_lock->llist);
7085 list_for_each_entry_safe(smb_lock, tmp, &rollback_list, llist) {
7086 struct file_lock *rlock = NULL;
7088 rlock = smb_flock_init(filp);
7089 rlock->fl_type = F_UNLCK;
7090 rlock->fl_start = smb_lock->start;
7091 rlock->fl_end = smb_lock->end;
7093 rc = vfs_lock_file(filp, 0, rlock, NULL);
7095 pr_err("rollback unlock fail : %d\n", rc);
7097 list_del(&smb_lock->llist);
7098 spin_lock(&work->conn->llist_lock);
7099 if (!list_empty(&smb_lock->flist))
7100 list_del(&smb_lock->flist);
7101 list_del(&smb_lock->clist);
7102 spin_unlock(&work->conn->llist_lock);
7104 locks_free_lock(smb_lock->fl);
7105 locks_free_lock(rlock);
7109 ksmbd_debug(SMB, "failed in taking lock(flags : %x), err : %d\n", flags, err);
7111 if (!rsp->hdr.Status) {
7113 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7114 else if (err == -ENOMEM)
7115 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
7116 else if (err == -ENOENT)
7117 rsp->hdr.Status = STATUS_FILE_CLOSED;
7119 rsp->hdr.Status = STATUS_LOCK_NOT_GRANTED;
7122 smb2_set_err_rsp(work);
7123 ksmbd_fd_put(work, fp);
7127 static int fsctl_copychunk(struct ksmbd_work *work,
7128 struct copychunk_ioctl_req *ci_req,
7129 unsigned int cnt_code,
7130 unsigned int input_count,
7131 unsigned long long volatile_id,
7132 unsigned long long persistent_id,
7133 struct smb2_ioctl_rsp *rsp)
7135 struct copychunk_ioctl_rsp *ci_rsp;
7136 struct ksmbd_file *src_fp = NULL, *dst_fp = NULL;
7137 struct srv_copychunk *chunks;
7138 unsigned int i, chunk_count, chunk_count_written = 0;
7139 unsigned int chunk_size_written = 0;
7140 loff_t total_size_written = 0;
7143 ci_rsp = (struct copychunk_ioctl_rsp *)&rsp->Buffer[0];
7145 rsp->VolatileFileId = volatile_id;
7146 rsp->PersistentFileId = persistent_id;
7147 ci_rsp->ChunksWritten =
7148 cpu_to_le32(ksmbd_server_side_copy_max_chunk_count());
7149 ci_rsp->ChunkBytesWritten =
7150 cpu_to_le32(ksmbd_server_side_copy_max_chunk_size());
7151 ci_rsp->TotalBytesWritten =
7152 cpu_to_le32(ksmbd_server_side_copy_max_total_size());
7154 chunks = (struct srv_copychunk *)&ci_req->Chunks[0];
7155 chunk_count = le32_to_cpu(ci_req->ChunkCount);
7156 if (chunk_count == 0)
7158 total_size_written = 0;
7160 /* verify the SRV_COPYCHUNK_COPY packet */
7161 if (chunk_count > ksmbd_server_side_copy_max_chunk_count() ||
7162 input_count < offsetof(struct copychunk_ioctl_req, Chunks) +
7163 chunk_count * sizeof(struct srv_copychunk)) {
7164 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7168 for (i = 0; i < chunk_count; i++) {
7169 if (le32_to_cpu(chunks[i].Length) == 0 ||
7170 le32_to_cpu(chunks[i].Length) > ksmbd_server_side_copy_max_chunk_size())
7172 total_size_written += le32_to_cpu(chunks[i].Length);
7175 if (i < chunk_count ||
7176 total_size_written > ksmbd_server_side_copy_max_total_size()) {
7177 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7181 src_fp = ksmbd_lookup_foreign_fd(work,
7182 le64_to_cpu(ci_req->ResumeKey[0]));
7183 dst_fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
7186 src_fp->persistent_id != le64_to_cpu(ci_req->ResumeKey[1])) {
7187 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
7192 rsp->hdr.Status = STATUS_FILE_CLOSED;
7197 * FILE_READ_DATA should only be included in
7198 * the FSCTL_COPYCHUNK case
7200 if (cnt_code == FSCTL_COPYCHUNK &&
7201 !(dst_fp->daccess & (FILE_READ_DATA_LE | FILE_GENERIC_READ_LE))) {
7202 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7206 ret = ksmbd_vfs_copy_file_ranges(work, src_fp, dst_fp,
7207 chunks, chunk_count,
7208 &chunk_count_written,
7209 &chunk_size_written,
7210 &total_size_written);
7213 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7215 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
7216 else if (ret == -EBADF)
7217 rsp->hdr.Status = STATUS_INVALID_HANDLE;
7218 else if (ret == -EFBIG || ret == -ENOSPC)
7219 rsp->hdr.Status = STATUS_DISK_FULL;
7220 else if (ret == -EINVAL)
7221 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7222 else if (ret == -EISDIR)
7223 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
7224 else if (ret == -E2BIG)
7225 rsp->hdr.Status = STATUS_INVALID_VIEW_SIZE;
7227 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
7230 ci_rsp->ChunksWritten = cpu_to_le32(chunk_count_written);
7231 ci_rsp->ChunkBytesWritten = cpu_to_le32(chunk_size_written);
7232 ci_rsp->TotalBytesWritten = cpu_to_le32(total_size_written);
7234 ksmbd_fd_put(work, src_fp);
7235 ksmbd_fd_put(work, dst_fp);
7239 static __be32 idev_ipv4_address(struct in_device *idev)
7243 struct in_ifaddr *ifa;
7246 in_dev_for_each_ifa_rcu(ifa, idev) {
7247 if (ifa->ifa_flags & IFA_F_SECONDARY)
7250 addr = ifa->ifa_address;
7257 static int fsctl_query_iface_info_ioctl(struct ksmbd_conn *conn,
7258 struct smb2_ioctl_rsp *rsp,
7259 unsigned int out_buf_len)
7261 struct network_interface_info_ioctl_rsp *nii_rsp = NULL;
7263 struct net_device *netdev;
7264 struct sockaddr_storage_rsp *sockaddr_storage;
7266 unsigned long long speed;
7269 for_each_netdev(&init_net, netdev) {
7270 bool ipv4_set = false;
7272 if (netdev->type == ARPHRD_LOOPBACK)
7275 flags = dev_get_flags(netdev);
7276 if (!(flags & IFF_RUNNING))
7280 nbytes + sizeof(struct network_interface_info_ioctl_rsp)) {
7285 nii_rsp = (struct network_interface_info_ioctl_rsp *)
7286 &rsp->Buffer[nbytes];
7287 nii_rsp->IfIndex = cpu_to_le32(netdev->ifindex);
7289 nii_rsp->Capability = 0;
7290 if (netdev->real_num_tx_queues > 1)
7291 nii_rsp->Capability |= cpu_to_le32(RSS_CAPABLE);
7292 if (ksmbd_rdma_capable_netdev(netdev))
7293 nii_rsp->Capability |= cpu_to_le32(RDMA_CAPABLE);
7295 nii_rsp->Next = cpu_to_le32(152);
7296 nii_rsp->Reserved = 0;
7298 if (netdev->ethtool_ops->get_link_ksettings) {
7299 struct ethtool_link_ksettings cmd;
7301 netdev->ethtool_ops->get_link_ksettings(netdev, &cmd);
7302 speed = cmd.base.speed;
7304 ksmbd_debug(SMB, "%s %s\n", netdev->name,
7305 "speed is unknown, defaulting to 1Gb/sec");
7310 nii_rsp->LinkSpeed = cpu_to_le64(speed);
7312 sockaddr_storage = (struct sockaddr_storage_rsp *)
7313 nii_rsp->SockAddr_Storage;
7314 memset(sockaddr_storage, 0, 128);
7317 struct in_device *idev;
7319 sockaddr_storage->Family = cpu_to_le16(INTERNETWORK);
7320 sockaddr_storage->addr4.Port = 0;
7322 idev = __in_dev_get_rtnl(netdev);
7325 sockaddr_storage->addr4.IPv4address =
7326 idev_ipv4_address(idev);
7327 nbytes += sizeof(struct network_interface_info_ioctl_rsp);
7331 struct inet6_dev *idev6;
7332 struct inet6_ifaddr *ifa;
7333 __u8 *ipv6_addr = sockaddr_storage->addr6.IPv6address;
7335 sockaddr_storage->Family = cpu_to_le16(INTERNETWORKV6);
7336 sockaddr_storage->addr6.Port = 0;
7337 sockaddr_storage->addr6.FlowInfo = 0;
7339 idev6 = __in6_dev_get(netdev);
7343 list_for_each_entry(ifa, &idev6->addr_list, if_list) {
7344 if (ifa->flags & (IFA_F_TENTATIVE |
7347 memcpy(ipv6_addr, ifa->addr.s6_addr, 16);
7350 sockaddr_storage->addr6.ScopeId = 0;
7351 nbytes += sizeof(struct network_interface_info_ioctl_rsp);
7356 /* zero if this is last one */
7360 rsp->PersistentFileId = SMB2_NO_FID;
7361 rsp->VolatileFileId = SMB2_NO_FID;
7365 static int fsctl_validate_negotiate_info(struct ksmbd_conn *conn,
7366 struct validate_negotiate_info_req *neg_req,
7367 struct validate_negotiate_info_rsp *neg_rsp,
7368 unsigned int in_buf_len)
7373 if (in_buf_len < offsetof(struct validate_negotiate_info_req, Dialects) +
7374 le16_to_cpu(neg_req->DialectCount) * sizeof(__le16))
7377 dialect = ksmbd_lookup_dialect_by_id(neg_req->Dialects,
7378 neg_req->DialectCount);
7379 if (dialect == BAD_PROT_ID || dialect != conn->dialect) {
7384 if (strncmp(neg_req->Guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE)) {
7389 if (le16_to_cpu(neg_req->SecurityMode) != conn->cli_sec_mode) {
7394 if (le32_to_cpu(neg_req->Capabilities) != conn->cli_cap) {
7399 neg_rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
7400 memset(neg_rsp->Guid, 0, SMB2_CLIENT_GUID_SIZE);
7401 neg_rsp->SecurityMode = cpu_to_le16(conn->srv_sec_mode);
7402 neg_rsp->Dialect = cpu_to_le16(conn->dialect);
7407 static int fsctl_query_allocated_ranges(struct ksmbd_work *work, u64 id,
7408 struct file_allocated_range_buffer *qar_req,
7409 struct file_allocated_range_buffer *qar_rsp,
7410 unsigned int in_count, unsigned int *out_count)
7412 struct ksmbd_file *fp;
7413 loff_t start, length;
7420 fp = ksmbd_lookup_fd_fast(work, id);
7424 start = le64_to_cpu(qar_req->file_offset);
7425 length = le64_to_cpu(qar_req->length);
7427 ret = ksmbd_vfs_fqar_lseek(fp, start, length,
7428 qar_rsp, in_count, out_count);
7429 if (ret && ret != -E2BIG)
7432 ksmbd_fd_put(work, fp);
7436 static int fsctl_pipe_transceive(struct ksmbd_work *work, u64 id,
7437 unsigned int out_buf_len,
7438 struct smb2_ioctl_req *req,
7439 struct smb2_ioctl_rsp *rsp)
7441 struct ksmbd_rpc_command *rpc_resp;
7442 char *data_buf = (char *)&req->Buffer[0];
7445 rpc_resp = ksmbd_rpc_ioctl(work->sess, id, data_buf,
7446 le32_to_cpu(req->InputCount));
7448 if (rpc_resp->flags == KSMBD_RPC_SOME_NOT_MAPPED) {
7450 * set STATUS_SOME_NOT_MAPPED response
7451 * for unknown domain sid.
7453 rsp->hdr.Status = STATUS_SOME_NOT_MAPPED;
7454 } else if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
7455 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7457 } else if (rpc_resp->flags != KSMBD_RPC_OK) {
7458 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7462 nbytes = rpc_resp->payload_sz;
7463 if (rpc_resp->payload_sz > out_buf_len) {
7464 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
7465 nbytes = out_buf_len;
7468 if (!rpc_resp->payload_sz) {
7470 STATUS_UNEXPECTED_IO_ERROR;
7474 memcpy((char *)rsp->Buffer, rpc_resp->payload, nbytes);
7481 static inline int fsctl_set_sparse(struct ksmbd_work *work, u64 id,
7482 struct file_sparse *sparse)
7484 struct ksmbd_file *fp;
7485 struct user_namespace *user_ns;
7489 fp = ksmbd_lookup_fd_fast(work, id);
7492 user_ns = file_mnt_user_ns(fp->filp);
7494 old_fattr = fp->f_ci->m_fattr;
7495 if (sparse->SetSparse)
7496 fp->f_ci->m_fattr |= FILE_ATTRIBUTE_SPARSE_FILE_LE;
7498 fp->f_ci->m_fattr &= ~FILE_ATTRIBUTE_SPARSE_FILE_LE;
7500 if (fp->f_ci->m_fattr != old_fattr &&
7501 test_share_config_flag(work->tcon->share_conf,
7502 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS)) {
7503 struct xattr_dos_attrib da;
7505 ret = ksmbd_vfs_get_dos_attrib_xattr(user_ns,
7506 fp->filp->f_path.dentry, &da);
7510 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
7511 ret = ksmbd_vfs_set_dos_attrib_xattr(user_ns,
7512 fp->filp->f_path.dentry, &da);
7514 fp->f_ci->m_fattr = old_fattr;
7518 ksmbd_fd_put(work, fp);
7522 static int fsctl_request_resume_key(struct ksmbd_work *work,
7523 struct smb2_ioctl_req *req,
7524 struct resume_key_ioctl_rsp *key_rsp)
7526 struct ksmbd_file *fp;
7528 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
7532 memset(key_rsp, 0, sizeof(*key_rsp));
7533 key_rsp->ResumeKey[0] = req->VolatileFileId;
7534 key_rsp->ResumeKey[1] = req->PersistentFileId;
7535 ksmbd_fd_put(work, fp);
7541 * smb2_ioctl() - handler for smb2 ioctl command
7542 * @work: smb work containing ioctl command buffer
7544 * Return: 0 on success, otherwise error
7546 int smb2_ioctl(struct ksmbd_work *work)
7548 struct smb2_ioctl_req *req;
7549 struct smb2_ioctl_rsp *rsp;
7550 unsigned int cnt_code, nbytes = 0, out_buf_len, in_buf_len;
7551 u64 id = KSMBD_NO_FID;
7552 struct ksmbd_conn *conn = work->conn;
7555 if (work->next_smb2_rcv_hdr_off) {
7556 req = ksmbd_req_buf_next(work);
7557 rsp = ksmbd_resp_buf_next(work);
7558 if (!has_file_id(req->VolatileFileId)) {
7559 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
7560 work->compound_fid);
7561 id = work->compound_fid;
7564 req = smb2_get_msg(work->request_buf);
7565 rsp = smb2_get_msg(work->response_buf);
7568 if (!has_file_id(id))
7569 id = req->VolatileFileId;
7571 if (req->Flags != cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL)) {
7572 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7576 cnt_code = le32_to_cpu(req->CtlCode);
7577 ret = smb2_calc_max_out_buf_len(work, 48,
7578 le32_to_cpu(req->MaxOutputResponse));
7580 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7583 out_buf_len = (unsigned int)ret;
7584 in_buf_len = le32_to_cpu(req->InputCount);
7587 case FSCTL_DFS_GET_REFERRALS:
7588 case FSCTL_DFS_GET_REFERRALS_EX:
7589 /* Not support DFS yet */
7590 rsp->hdr.Status = STATUS_FS_DRIVER_REQUIRED;
7592 case FSCTL_CREATE_OR_GET_OBJECT_ID:
7594 struct file_object_buf_type1_ioctl_rsp *obj_buf;
7596 nbytes = sizeof(struct file_object_buf_type1_ioctl_rsp);
7597 obj_buf = (struct file_object_buf_type1_ioctl_rsp *)
7601 * TODO: This is dummy implementation to pass smbtorture
7602 * Need to check correct response later
7604 memset(obj_buf->ObjectId, 0x0, 16);
7605 memset(obj_buf->BirthVolumeId, 0x0, 16);
7606 memset(obj_buf->BirthObjectId, 0x0, 16);
7607 memset(obj_buf->DomainId, 0x0, 16);
7611 case FSCTL_PIPE_TRANSCEIVE:
7612 out_buf_len = min_t(u32, KSMBD_IPC_MAX_PAYLOAD, out_buf_len);
7613 nbytes = fsctl_pipe_transceive(work, id, out_buf_len, req, rsp);
7615 case FSCTL_VALIDATE_NEGOTIATE_INFO:
7616 if (conn->dialect < SMB30_PROT_ID) {
7621 if (in_buf_len < sizeof(struct validate_negotiate_info_req))
7624 if (out_buf_len < sizeof(struct validate_negotiate_info_rsp))
7627 ret = fsctl_validate_negotiate_info(conn,
7628 (struct validate_negotiate_info_req *)&req->Buffer[0],
7629 (struct validate_negotiate_info_rsp *)&rsp->Buffer[0],
7634 nbytes = sizeof(struct validate_negotiate_info_rsp);
7635 rsp->PersistentFileId = SMB2_NO_FID;
7636 rsp->VolatileFileId = SMB2_NO_FID;
7638 case FSCTL_QUERY_NETWORK_INTERFACE_INFO:
7639 ret = fsctl_query_iface_info_ioctl(conn, rsp, out_buf_len);
7644 case FSCTL_REQUEST_RESUME_KEY:
7645 if (out_buf_len < sizeof(struct resume_key_ioctl_rsp)) {
7650 ret = fsctl_request_resume_key(work, req,
7651 (struct resume_key_ioctl_rsp *)&rsp->Buffer[0]);
7654 rsp->PersistentFileId = req->PersistentFileId;
7655 rsp->VolatileFileId = req->VolatileFileId;
7656 nbytes = sizeof(struct resume_key_ioctl_rsp);
7658 case FSCTL_COPYCHUNK:
7659 case FSCTL_COPYCHUNK_WRITE:
7660 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7662 "User does not have write permission\n");
7667 if (in_buf_len < sizeof(struct copychunk_ioctl_req)) {
7672 if (out_buf_len < sizeof(struct copychunk_ioctl_rsp)) {
7677 nbytes = sizeof(struct copychunk_ioctl_rsp);
7678 rsp->VolatileFileId = req->VolatileFileId;
7679 rsp->PersistentFileId = req->PersistentFileId;
7680 fsctl_copychunk(work,
7681 (struct copychunk_ioctl_req *)&req->Buffer[0],
7682 le32_to_cpu(req->CtlCode),
7683 le32_to_cpu(req->InputCount),
7684 req->VolatileFileId,
7685 req->PersistentFileId,
7688 case FSCTL_SET_SPARSE:
7689 if (in_buf_len < sizeof(struct file_sparse)) {
7694 ret = fsctl_set_sparse(work, id,
7695 (struct file_sparse *)&req->Buffer[0]);
7699 case FSCTL_SET_ZERO_DATA:
7701 struct file_zero_data_information *zero_data;
7702 struct ksmbd_file *fp;
7703 loff_t off, len, bfz;
7705 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7707 "User does not have write permission\n");
7712 if (in_buf_len < sizeof(struct file_zero_data_information)) {
7718 (struct file_zero_data_information *)&req->Buffer[0];
7720 off = le64_to_cpu(zero_data->FileOffset);
7721 bfz = le64_to_cpu(zero_data->BeyondFinalZero);
7729 fp = ksmbd_lookup_fd_fast(work, id);
7735 ret = ksmbd_vfs_zero_data(work, fp, off, len);
7736 ksmbd_fd_put(work, fp);
7742 case FSCTL_QUERY_ALLOCATED_RANGES:
7743 if (in_buf_len < sizeof(struct file_allocated_range_buffer)) {
7748 ret = fsctl_query_allocated_ranges(work, id,
7749 (struct file_allocated_range_buffer *)&req->Buffer[0],
7750 (struct file_allocated_range_buffer *)&rsp->Buffer[0],
7752 sizeof(struct file_allocated_range_buffer), &nbytes);
7753 if (ret == -E2BIG) {
7754 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
7755 } else if (ret < 0) {
7760 nbytes *= sizeof(struct file_allocated_range_buffer);
7762 case FSCTL_GET_REPARSE_POINT:
7764 struct reparse_data_buffer *reparse_ptr;
7765 struct ksmbd_file *fp;
7767 reparse_ptr = (struct reparse_data_buffer *)&rsp->Buffer[0];
7768 fp = ksmbd_lookup_fd_fast(work, id);
7770 pr_err("not found fp!!\n");
7775 reparse_ptr->ReparseTag =
7776 smb2_get_reparse_tag_special_file(file_inode(fp->filp)->i_mode);
7777 reparse_ptr->ReparseDataLength = 0;
7778 ksmbd_fd_put(work, fp);
7779 nbytes = sizeof(struct reparse_data_buffer);
7782 case FSCTL_DUPLICATE_EXTENTS_TO_FILE:
7784 struct ksmbd_file *fp_in, *fp_out = NULL;
7785 struct duplicate_extents_to_file *dup_ext;
7786 loff_t src_off, dst_off, length, cloned;
7788 if (in_buf_len < sizeof(struct duplicate_extents_to_file)) {
7793 dup_ext = (struct duplicate_extents_to_file *)&req->Buffer[0];
7795 fp_in = ksmbd_lookup_fd_slow(work, dup_ext->VolatileFileHandle,
7796 dup_ext->PersistentFileHandle);
7798 pr_err("not found file handle in duplicate extent to file\n");
7803 fp_out = ksmbd_lookup_fd_fast(work, id);
7805 pr_err("not found fp\n");
7810 src_off = le64_to_cpu(dup_ext->SourceFileOffset);
7811 dst_off = le64_to_cpu(dup_ext->TargetFileOffset);
7812 length = le64_to_cpu(dup_ext->ByteCount);
7814 * XXX: It is not clear if FSCTL_DUPLICATE_EXTENTS_TO_FILE
7815 * should fall back to vfs_copy_file_range(). This could be
7816 * beneficial when re-exporting nfs/smb mount, but note that
7817 * this can result in partial copy that returns an error status.
7818 * If/when FSCTL_DUPLICATE_EXTENTS_TO_FILE_EX is implemented,
7819 * fall back to vfs_copy_file_range(), should be avoided when
7820 * the flag DUPLICATE_EXTENTS_DATA_EX_SOURCE_ATOMIC is set.
7822 cloned = vfs_clone_file_range(fp_in->filp, src_off,
7823 fp_out->filp, dst_off, length, 0);
7824 if (cloned == -EXDEV || cloned == -EOPNOTSUPP) {
7827 } else if (cloned != length) {
7828 cloned = vfs_copy_file_range(fp_in->filp, src_off,
7829 fp_out->filp, dst_off,
7831 if (cloned != length) {
7840 ksmbd_fd_put(work, fp_in);
7841 ksmbd_fd_put(work, fp_out);
7847 ksmbd_debug(SMB, "not implemented yet ioctl command 0x%x\n",
7853 rsp->CtlCode = cpu_to_le32(cnt_code);
7854 rsp->InputCount = cpu_to_le32(0);
7855 rsp->InputOffset = cpu_to_le32(112);
7856 rsp->OutputOffset = cpu_to_le32(112);
7857 rsp->OutputCount = cpu_to_le32(nbytes);
7858 rsp->StructureSize = cpu_to_le16(49);
7859 rsp->Reserved = cpu_to_le16(0);
7860 rsp->Flags = cpu_to_le32(0);
7861 rsp->Reserved2 = cpu_to_le32(0);
7862 inc_rfc1001_len(work->response_buf, 48 + nbytes);
7868 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7869 else if (ret == -ENOENT)
7870 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
7871 else if (ret == -EOPNOTSUPP)
7872 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7873 else if (ret == -ENOSPC)
7874 rsp->hdr.Status = STATUS_BUFFER_TOO_SMALL;
7875 else if (ret < 0 || rsp->hdr.Status == 0)
7876 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7877 smb2_set_err_rsp(work);
7882 * smb20_oplock_break_ack() - handler for smb2.0 oplock break command
7883 * @work: smb work containing oplock break command buffer
7887 static void smb20_oplock_break_ack(struct ksmbd_work *work)
7889 struct smb2_oplock_break *req = smb2_get_msg(work->request_buf);
7890 struct smb2_oplock_break *rsp = smb2_get_msg(work->response_buf);
7891 struct ksmbd_file *fp;
7892 struct oplock_info *opinfo = NULL;
7895 u64 volatile_id, persistent_id;
7896 char req_oplevel = 0, rsp_oplevel = 0;
7897 unsigned int oplock_change_type;
7899 volatile_id = req->VolatileFid;
7900 persistent_id = req->PersistentFid;
7901 req_oplevel = req->OplockLevel;
7902 ksmbd_debug(OPLOCK, "v_id %llu, p_id %llu request oplock level %d\n",
7903 volatile_id, persistent_id, req_oplevel);
7905 fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
7907 rsp->hdr.Status = STATUS_FILE_CLOSED;
7908 smb2_set_err_rsp(work);
7912 opinfo = opinfo_get(fp);
7914 pr_err("unexpected null oplock_info\n");
7915 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
7916 smb2_set_err_rsp(work);
7917 ksmbd_fd_put(work, fp);
7921 if (opinfo->level == SMB2_OPLOCK_LEVEL_NONE) {
7922 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
7926 if (opinfo->op_state == OPLOCK_STATE_NONE) {
7927 ksmbd_debug(SMB, "unexpected oplock state 0x%x\n", opinfo->op_state);
7928 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
7932 if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
7933 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
7934 (req_oplevel != SMB2_OPLOCK_LEVEL_II &&
7935 req_oplevel != SMB2_OPLOCK_LEVEL_NONE)) {
7936 err = STATUS_INVALID_OPLOCK_PROTOCOL;
7937 oplock_change_type = OPLOCK_WRITE_TO_NONE;
7938 } else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
7939 req_oplevel != SMB2_OPLOCK_LEVEL_NONE) {
7940 err = STATUS_INVALID_OPLOCK_PROTOCOL;
7941 oplock_change_type = OPLOCK_READ_TO_NONE;
7942 } else if (req_oplevel == SMB2_OPLOCK_LEVEL_II ||
7943 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
7944 err = STATUS_INVALID_DEVICE_STATE;
7945 if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
7946 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
7947 req_oplevel == SMB2_OPLOCK_LEVEL_II) {
7948 oplock_change_type = OPLOCK_WRITE_TO_READ;
7949 } else if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
7950 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
7951 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
7952 oplock_change_type = OPLOCK_WRITE_TO_NONE;
7953 } else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
7954 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
7955 oplock_change_type = OPLOCK_READ_TO_NONE;
7957 oplock_change_type = 0;
7960 oplock_change_type = 0;
7963 switch (oplock_change_type) {
7964 case OPLOCK_WRITE_TO_READ:
7965 ret = opinfo_write_to_read(opinfo);
7966 rsp_oplevel = SMB2_OPLOCK_LEVEL_II;
7968 case OPLOCK_WRITE_TO_NONE:
7969 ret = opinfo_write_to_none(opinfo);
7970 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
7972 case OPLOCK_READ_TO_NONE:
7973 ret = opinfo_read_to_none(opinfo);
7974 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
7977 pr_err("unknown oplock change 0x%x -> 0x%x\n",
7978 opinfo->level, rsp_oplevel);
7982 rsp->hdr.Status = err;
7987 ksmbd_fd_put(work, fp);
7988 opinfo->op_state = OPLOCK_STATE_NONE;
7989 wake_up_interruptible_all(&opinfo->oplock_q);
7991 rsp->StructureSize = cpu_to_le16(24);
7992 rsp->OplockLevel = rsp_oplevel;
7995 rsp->VolatileFid = volatile_id;
7996 rsp->PersistentFid = persistent_id;
7997 inc_rfc1001_len(work->response_buf, 24);
8001 opinfo->op_state = OPLOCK_STATE_NONE;
8002 wake_up_interruptible_all(&opinfo->oplock_q);
8005 ksmbd_fd_put(work, fp);
8006 smb2_set_err_rsp(work);
8009 static int check_lease_state(struct lease *lease, __le32 req_state)
8011 if ((lease->new_state ==
8012 (SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE)) &&
8013 !(req_state & SMB2_LEASE_WRITE_CACHING_LE)) {
8014 lease->new_state = req_state;
8018 if (lease->new_state == req_state)
8025 * smb21_lease_break_ack() - handler for smb2.1 lease break command
8026 * @work: smb work containing lease break command buffer
8030 static void smb21_lease_break_ack(struct ksmbd_work *work)
8032 struct ksmbd_conn *conn = work->conn;
8033 struct smb2_lease_ack *req = smb2_get_msg(work->request_buf);
8034 struct smb2_lease_ack *rsp = smb2_get_msg(work->response_buf);
8035 struct oplock_info *opinfo;
8038 unsigned int lease_change_type;
8040 struct lease *lease;
8042 ksmbd_debug(OPLOCK, "smb21 lease break, lease state(0x%x)\n",
8043 le32_to_cpu(req->LeaseState));
8044 opinfo = lookup_lease_in_table(conn, req->LeaseKey);
8046 ksmbd_debug(OPLOCK, "file not opened\n");
8047 smb2_set_err_rsp(work);
8048 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8051 lease = opinfo->o_lease;
8053 if (opinfo->op_state == OPLOCK_STATE_NONE) {
8054 pr_err("unexpected lease break state 0x%x\n",
8056 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8060 if (check_lease_state(lease, req->LeaseState)) {
8061 rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
8063 "req lease state: 0x%x, expected state: 0x%x\n",
8064 req->LeaseState, lease->new_state);
8068 if (!atomic_read(&opinfo->breaking_cnt)) {
8069 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8073 /* check for bad lease state */
8074 if (req->LeaseState &
8075 (~(SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE))) {
8076 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8077 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8078 lease_change_type = OPLOCK_WRITE_TO_NONE;
8080 lease_change_type = OPLOCK_READ_TO_NONE;
8081 ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8082 le32_to_cpu(lease->state),
8083 le32_to_cpu(req->LeaseState));
8084 } else if (lease->state == SMB2_LEASE_READ_CACHING_LE &&
8085 req->LeaseState != SMB2_LEASE_NONE_LE) {
8086 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8087 lease_change_type = OPLOCK_READ_TO_NONE;
8088 ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8089 le32_to_cpu(lease->state),
8090 le32_to_cpu(req->LeaseState));
8092 /* valid lease state changes */
8093 err = STATUS_INVALID_DEVICE_STATE;
8094 if (req->LeaseState == SMB2_LEASE_NONE_LE) {
8095 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8096 lease_change_type = OPLOCK_WRITE_TO_NONE;
8098 lease_change_type = OPLOCK_READ_TO_NONE;
8099 } else if (req->LeaseState & SMB2_LEASE_READ_CACHING_LE) {
8100 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8101 lease_change_type = OPLOCK_WRITE_TO_READ;
8103 lease_change_type = OPLOCK_READ_HANDLE_TO_READ;
8105 lease_change_type = 0;
8109 switch (lease_change_type) {
8110 case OPLOCK_WRITE_TO_READ:
8111 ret = opinfo_write_to_read(opinfo);
8113 case OPLOCK_READ_HANDLE_TO_READ:
8114 ret = opinfo_read_handle_to_read(opinfo);
8116 case OPLOCK_WRITE_TO_NONE:
8117 ret = opinfo_write_to_none(opinfo);
8119 case OPLOCK_READ_TO_NONE:
8120 ret = opinfo_read_to_none(opinfo);
8123 ksmbd_debug(OPLOCK, "unknown lease change 0x%x -> 0x%x\n",
8124 le32_to_cpu(lease->state),
8125 le32_to_cpu(req->LeaseState));
8128 lease_state = lease->state;
8129 opinfo->op_state = OPLOCK_STATE_NONE;
8130 wake_up_interruptible_all(&opinfo->oplock_q);
8131 atomic_dec(&opinfo->breaking_cnt);
8132 wake_up_interruptible_all(&opinfo->oplock_brk);
8136 rsp->hdr.Status = err;
8140 rsp->StructureSize = cpu_to_le16(36);
8143 memcpy(rsp->LeaseKey, req->LeaseKey, 16);
8144 rsp->LeaseState = lease_state;
8145 rsp->LeaseDuration = 0;
8146 inc_rfc1001_len(work->response_buf, 36);
8150 opinfo->op_state = OPLOCK_STATE_NONE;
8151 wake_up_interruptible_all(&opinfo->oplock_q);
8152 atomic_dec(&opinfo->breaking_cnt);
8153 wake_up_interruptible_all(&opinfo->oplock_brk);
8156 smb2_set_err_rsp(work);
8160 * smb2_oplock_break() - dispatcher for smb2.0 and 2.1 oplock/lease break
8161 * @work: smb work containing oplock/lease break command buffer
8165 int smb2_oplock_break(struct ksmbd_work *work)
8167 struct smb2_oplock_break *req = smb2_get_msg(work->request_buf);
8168 struct smb2_oplock_break *rsp = smb2_get_msg(work->response_buf);
8170 switch (le16_to_cpu(req->StructureSize)) {
8171 case OP_BREAK_STRUCT_SIZE_20:
8172 smb20_oplock_break_ack(work);
8174 case OP_BREAK_STRUCT_SIZE_21:
8175 smb21_lease_break_ack(work);
8178 ksmbd_debug(OPLOCK, "invalid break cmd %d\n",
8179 le16_to_cpu(req->StructureSize));
8180 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8181 smb2_set_err_rsp(work);
8188 * smb2_notify() - handler for smb2 notify request
8189 * @work: smb work containing notify command buffer
8193 int smb2_notify(struct ksmbd_work *work)
8195 struct smb2_change_notify_req *req;
8196 struct smb2_change_notify_rsp *rsp;
8198 WORK_BUFFERS(work, req, rsp);
8200 if (work->next_smb2_rcv_hdr_off && req->hdr.NextCommand) {
8201 rsp->hdr.Status = STATUS_INTERNAL_ERROR;
8202 smb2_set_err_rsp(work);
8206 smb2_set_err_rsp(work);
8207 rsp->hdr.Status = STATUS_NOT_IMPLEMENTED;
8212 * smb2_is_sign_req() - handler for checking packet signing status
8213 * @work: smb work containing notify command buffer
8214 * @command: SMB2 command id
8216 * Return: true if packed is signed, false otherwise
8218 bool smb2_is_sign_req(struct ksmbd_work *work, unsigned int command)
8220 struct smb2_hdr *rcv_hdr2 = smb2_get_msg(work->request_buf);
8222 if ((rcv_hdr2->Flags & SMB2_FLAGS_SIGNED) &&
8223 command != SMB2_NEGOTIATE_HE &&
8224 command != SMB2_SESSION_SETUP_HE &&
8225 command != SMB2_OPLOCK_BREAK_HE)
8232 * smb2_check_sign_req() - handler for req packet sign processing
8233 * @work: smb work containing notify command buffer
8235 * Return: 1 on success, 0 otherwise
8237 int smb2_check_sign_req(struct ksmbd_work *work)
8239 struct smb2_hdr *hdr;
8240 char signature_req[SMB2_SIGNATURE_SIZE];
8241 char signature[SMB2_HMACSHA256_SIZE];
8245 hdr = smb2_get_msg(work->request_buf);
8246 if (work->next_smb2_rcv_hdr_off)
8247 hdr = ksmbd_req_buf_next(work);
8249 if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8250 len = get_rfc1002_len(work->request_buf);
8251 else if (hdr->NextCommand)
8252 len = le32_to_cpu(hdr->NextCommand);
8254 len = get_rfc1002_len(work->request_buf) -
8255 work->next_smb2_rcv_hdr_off;
8257 memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8258 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8260 iov[0].iov_base = (char *)&hdr->ProtocolId;
8261 iov[0].iov_len = len;
8263 if (ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, 1,
8267 if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8268 pr_err("bad smb2 signature\n");
8276 * smb2_set_sign_rsp() - handler for rsp packet sign processing
8277 * @work: smb work containing notify command buffer
8280 void smb2_set_sign_rsp(struct ksmbd_work *work)
8282 struct smb2_hdr *hdr;
8283 struct smb2_hdr *req_hdr;
8284 char signature[SMB2_HMACSHA256_SIZE];
8289 hdr = smb2_get_msg(work->response_buf);
8290 if (work->next_smb2_rsp_hdr_off)
8291 hdr = ksmbd_resp_buf_next(work);
8293 req_hdr = ksmbd_req_buf_next(work);
8295 if (!work->next_smb2_rsp_hdr_off) {
8296 len = get_rfc1002_len(work->response_buf);
8297 if (req_hdr->NextCommand)
8298 len = ALIGN(len, 8);
8300 len = get_rfc1002_len(work->response_buf) -
8301 work->next_smb2_rsp_hdr_off;
8302 len = ALIGN(len, 8);
8305 if (req_hdr->NextCommand)
8306 hdr->NextCommand = cpu_to_le32(len);
8308 hdr->Flags |= SMB2_FLAGS_SIGNED;
8309 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8311 iov[0].iov_base = (char *)&hdr->ProtocolId;
8312 iov[0].iov_len = len;
8314 if (work->aux_payload_sz) {
8315 iov[0].iov_len -= work->aux_payload_sz;
8317 iov[1].iov_base = work->aux_payload_buf;
8318 iov[1].iov_len = work->aux_payload_sz;
8322 if (!ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, n_vec,
8324 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
8328 * smb3_check_sign_req() - handler for req packet sign processing
8329 * @work: smb work containing notify command buffer
8331 * Return: 1 on success, 0 otherwise
8333 int smb3_check_sign_req(struct ksmbd_work *work)
8335 struct ksmbd_conn *conn = work->conn;
8337 struct smb2_hdr *hdr;
8338 struct channel *chann;
8339 char signature_req[SMB2_SIGNATURE_SIZE];
8340 char signature[SMB2_CMACAES_SIZE];
8344 hdr = smb2_get_msg(work->request_buf);
8345 if (work->next_smb2_rcv_hdr_off)
8346 hdr = ksmbd_req_buf_next(work);
8348 if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8349 len = get_rfc1002_len(work->request_buf);
8350 else if (hdr->NextCommand)
8351 len = le32_to_cpu(hdr->NextCommand);
8353 len = get_rfc1002_len(work->request_buf) -
8354 work->next_smb2_rcv_hdr_off;
8356 if (le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8357 signing_key = work->sess->smb3signingkey;
8359 chann = lookup_chann_list(work->sess, conn);
8362 signing_key = chann->smb3signingkey;
8366 pr_err("SMB3 signing key is not generated\n");
8370 memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8371 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8372 iov[0].iov_base = (char *)&hdr->ProtocolId;
8373 iov[0].iov_len = len;
8375 if (ksmbd_sign_smb3_pdu(conn, signing_key, iov, 1, signature))
8378 if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8379 pr_err("bad smb2 signature\n");
8387 * smb3_set_sign_rsp() - handler for rsp packet sign processing
8388 * @work: smb work containing notify command buffer
8391 void smb3_set_sign_rsp(struct ksmbd_work *work)
8393 struct ksmbd_conn *conn = work->conn;
8394 struct smb2_hdr *req_hdr, *hdr;
8395 struct channel *chann;
8396 char signature[SMB2_CMACAES_SIZE];
8402 hdr = smb2_get_msg(work->response_buf);
8403 if (work->next_smb2_rsp_hdr_off)
8404 hdr = ksmbd_resp_buf_next(work);
8406 req_hdr = ksmbd_req_buf_next(work);
8408 if (!work->next_smb2_rsp_hdr_off) {
8409 len = get_rfc1002_len(work->response_buf);
8410 if (req_hdr->NextCommand)
8411 len = ALIGN(len, 8);
8413 len = get_rfc1002_len(work->response_buf) -
8414 work->next_smb2_rsp_hdr_off;
8415 len = ALIGN(len, 8);
8418 if (conn->binding == false &&
8419 le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8420 signing_key = work->sess->smb3signingkey;
8422 chann = lookup_chann_list(work->sess, work->conn);
8425 signing_key = chann->smb3signingkey;
8431 if (req_hdr->NextCommand)
8432 hdr->NextCommand = cpu_to_le32(len);
8434 hdr->Flags |= SMB2_FLAGS_SIGNED;
8435 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8436 iov[0].iov_base = (char *)&hdr->ProtocolId;
8437 iov[0].iov_len = len;
8438 if (work->aux_payload_sz) {
8439 iov[0].iov_len -= work->aux_payload_sz;
8440 iov[1].iov_base = work->aux_payload_buf;
8441 iov[1].iov_len = work->aux_payload_sz;
8445 if (!ksmbd_sign_smb3_pdu(conn, signing_key, iov, n_vec, signature))
8446 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
8450 * smb3_preauth_hash_rsp() - handler for computing preauth hash on response
8451 * @work: smb work containing response buffer
8454 void smb3_preauth_hash_rsp(struct ksmbd_work *work)
8456 struct ksmbd_conn *conn = work->conn;
8457 struct ksmbd_session *sess = work->sess;
8458 struct smb2_hdr *req, *rsp;
8460 if (conn->dialect != SMB311_PROT_ID)
8463 WORK_BUFFERS(work, req, rsp);
8465 if (le16_to_cpu(req->Command) == SMB2_NEGOTIATE_HE &&
8467 ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
8468 conn->preauth_info->Preauth_HashValue);
8470 if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE && sess) {
8473 if (conn->binding) {
8474 struct preauth_session *preauth_sess;
8476 preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
8479 hash_value = preauth_sess->Preauth_HashValue;
8481 hash_value = sess->Preauth_HashValue;
8485 ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
8490 static void fill_transform_hdr(void *tr_buf, char *old_buf, __le16 cipher_type)
8492 struct smb2_transform_hdr *tr_hdr = tr_buf + 4;
8493 struct smb2_hdr *hdr = smb2_get_msg(old_buf);
8494 unsigned int orig_len = get_rfc1002_len(old_buf);
8496 /* tr_buf must be cleared by the caller */
8497 tr_hdr->ProtocolId = SMB2_TRANSFORM_PROTO_NUM;
8498 tr_hdr->OriginalMessageSize = cpu_to_le32(orig_len);
8499 tr_hdr->Flags = cpu_to_le16(TRANSFORM_FLAG_ENCRYPTED);
8500 if (cipher_type == SMB2_ENCRYPTION_AES128_GCM ||
8501 cipher_type == SMB2_ENCRYPTION_AES256_GCM)
8502 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_GCM_NONCE);
8504 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_CCM_NONCE);
8505 memcpy(&tr_hdr->SessionId, &hdr->SessionId, 8);
8506 inc_rfc1001_len(tr_buf, sizeof(struct smb2_transform_hdr));
8507 inc_rfc1001_len(tr_buf, orig_len);
8510 int smb3_encrypt_resp(struct ksmbd_work *work)
8512 char *buf = work->response_buf;
8515 int buf_size = 0, rq_nvec = 2 + (work->aux_payload_sz ? 1 : 0);
8517 if (ARRAY_SIZE(iov) < rq_nvec)
8520 work->tr_buf = kzalloc(sizeof(struct smb2_transform_hdr) + 4, GFP_KERNEL);
8524 /* fill transform header */
8525 fill_transform_hdr(work->tr_buf, buf, work->conn->cipher_type);
8527 iov[0].iov_base = work->tr_buf;
8528 iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
8529 buf_size += iov[0].iov_len - 4;
8531 iov[1].iov_base = buf + 4;
8532 iov[1].iov_len = get_rfc1002_len(buf);
8533 if (work->aux_payload_sz) {
8534 iov[1].iov_len = work->resp_hdr_sz - 4;
8536 iov[2].iov_base = work->aux_payload_buf;
8537 iov[2].iov_len = work->aux_payload_sz;
8538 buf_size += iov[2].iov_len;
8540 buf_size += iov[1].iov_len;
8541 work->resp_hdr_sz = iov[1].iov_len;
8543 rc = ksmbd_crypt_message(work->conn, iov, rq_nvec, 1);
8547 memmove(buf, iov[1].iov_base, iov[1].iov_len);
8548 *(__be32 *)work->tr_buf = cpu_to_be32(buf_size);
8553 bool smb3_is_transform_hdr(void *buf)
8555 struct smb2_transform_hdr *trhdr = smb2_get_msg(buf);
8557 return trhdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM;
8560 int smb3_decrypt_req(struct ksmbd_work *work)
8562 struct ksmbd_conn *conn = work->conn;
8563 struct ksmbd_session *sess;
8564 char *buf = work->request_buf;
8565 unsigned int pdu_length = get_rfc1002_len(buf);
8567 int buf_data_size = pdu_length - sizeof(struct smb2_transform_hdr);
8568 struct smb2_transform_hdr *tr_hdr = smb2_get_msg(buf);
8571 if (buf_data_size < sizeof(struct smb2_hdr)) {
8572 pr_err("Transform message is too small (%u)\n",
8574 return -ECONNABORTED;
8577 if (buf_data_size < le32_to_cpu(tr_hdr->OriginalMessageSize)) {
8578 pr_err("Transform message is broken\n");
8579 return -ECONNABORTED;
8582 sess = ksmbd_session_lookup_all(conn, le64_to_cpu(tr_hdr->SessionId));
8584 pr_err("invalid session id(%llx) in transform header\n",
8585 le64_to_cpu(tr_hdr->SessionId));
8586 return -ECONNABORTED;
8589 iov[0].iov_base = buf;
8590 iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
8591 iov[1].iov_base = buf + sizeof(struct smb2_transform_hdr) + 4;
8592 iov[1].iov_len = buf_data_size;
8593 rc = ksmbd_crypt_message(conn, iov, 2, 0);
8597 memmove(buf + 4, iov[1].iov_base, buf_data_size);
8598 *(__be32 *)buf = cpu_to_be32(buf_data_size);
8603 bool smb3_11_final_sess_setup_resp(struct ksmbd_work *work)
8605 struct ksmbd_conn *conn = work->conn;
8606 struct smb2_hdr *rsp = smb2_get_msg(work->response_buf);
8608 if (conn->dialect < SMB30_PROT_ID)
8611 if (work->next_smb2_rcv_hdr_off)
8612 rsp = ksmbd_resp_buf_next(work);
8614 if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE &&
8615 rsp->Status == STATUS_SUCCESS)