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>
15 #include <linux/filelock.h>
24 #include "connection.h"
25 #include "transport_ipc.h"
26 #include "transport_rdma.h"
28 #include "vfs_cache.h"
32 #include "smb_common.h"
33 #include "smbstatus.h"
34 #include "ksmbd_work.h"
35 #include "mgmt/user_config.h"
36 #include "mgmt/share_config.h"
37 #include "mgmt/tree_connect.h"
38 #include "mgmt/user_session.h"
39 #include "mgmt/ksmbd_ida.h"
42 static void __wbuf(struct ksmbd_work *work, void **req, void **rsp)
44 if (work->next_smb2_rcv_hdr_off) {
45 *req = ksmbd_req_buf_next(work);
46 *rsp = ksmbd_resp_buf_next(work);
48 *req = smb2_get_msg(work->request_buf);
49 *rsp = smb2_get_msg(work->response_buf);
53 #define WORK_BUFFERS(w, rq, rs) __wbuf((w), (void **)&(rq), (void **)&(rs))
56 * check_session_id() - check for valid session id in smb header
57 * @conn: connection instance
58 * @id: session id from smb header
60 * Return: 1 if valid session id, otherwise 0
62 static inline bool check_session_id(struct ksmbd_conn *conn, u64 id)
64 struct ksmbd_session *sess;
66 if (id == 0 || id == -1)
69 sess = ksmbd_session_lookup_all(conn, id);
72 pr_err("Invalid user session id: %llu\n", id);
76 struct channel *lookup_chann_list(struct ksmbd_session *sess, struct ksmbd_conn *conn)
78 return xa_load(&sess->ksmbd_chann_list, (long)conn);
82 * smb2_get_ksmbd_tcon() - get tree connection information using a tree id.
85 * Return: 0 if there is a tree connection matched or these are
86 * skipable commands, otherwise error
88 int smb2_get_ksmbd_tcon(struct ksmbd_work *work)
90 struct smb2_hdr *req_hdr = smb2_get_msg(work->request_buf);
91 unsigned int cmd = le16_to_cpu(req_hdr->Command);
95 if (cmd == SMB2_TREE_CONNECT_HE ||
96 cmd == SMB2_CANCEL_HE ||
97 cmd == SMB2_LOGOFF_HE) {
98 ksmbd_debug(SMB, "skip to check tree connect request\n");
102 if (xa_empty(&work->sess->tree_conns)) {
103 ksmbd_debug(SMB, "NO tree connected\n");
107 tree_id = le32_to_cpu(req_hdr->Id.SyncId.TreeId);
108 work->tcon = ksmbd_tree_conn_lookup(work->sess, tree_id);
110 pr_err("Invalid tid %d\n", tree_id);
118 * smb2_set_err_rsp() - set error response code on smb response
119 * @work: smb work containing response buffer
121 void smb2_set_err_rsp(struct ksmbd_work *work)
123 struct smb2_err_rsp *err_rsp;
125 if (work->next_smb2_rcv_hdr_off)
126 err_rsp = ksmbd_resp_buf_next(work);
128 err_rsp = smb2_get_msg(work->response_buf);
130 if (err_rsp->hdr.Status != STATUS_STOPPED_ON_SYMLINK) {
131 err_rsp->StructureSize = SMB2_ERROR_STRUCTURE_SIZE2_LE;
132 err_rsp->ErrorContextCount = 0;
133 err_rsp->Reserved = 0;
134 err_rsp->ByteCount = 0;
135 err_rsp->ErrorData[0] = 0;
136 inc_rfc1001_len(work->response_buf, SMB2_ERROR_STRUCTURE_SIZE2);
141 * is_smb2_neg_cmd() - is it smb2 negotiation command
142 * @work: smb work containing smb header
144 * Return: true if smb2 negotiation command, otherwise false
146 bool is_smb2_neg_cmd(struct ksmbd_work *work)
148 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
150 /* is it SMB2 header ? */
151 if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
154 /* make sure it is request not response message */
155 if (hdr->Flags & SMB2_FLAGS_SERVER_TO_REDIR)
158 if (hdr->Command != SMB2_NEGOTIATE)
165 * is_smb2_rsp() - is it smb2 response
166 * @work: smb work containing smb response buffer
168 * Return: true if smb2 response, otherwise false
170 bool is_smb2_rsp(struct ksmbd_work *work)
172 struct smb2_hdr *hdr = smb2_get_msg(work->response_buf);
174 /* is it SMB2 header ? */
175 if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
178 /* make sure it is response not request message */
179 if (!(hdr->Flags & SMB2_FLAGS_SERVER_TO_REDIR))
186 * get_smb2_cmd_val() - get smb command code from smb header
187 * @work: smb work containing smb request buffer
189 * Return: smb2 request command value
191 u16 get_smb2_cmd_val(struct ksmbd_work *work)
193 struct smb2_hdr *rcv_hdr;
195 if (work->next_smb2_rcv_hdr_off)
196 rcv_hdr = ksmbd_req_buf_next(work);
198 rcv_hdr = smb2_get_msg(work->request_buf);
199 return le16_to_cpu(rcv_hdr->Command);
203 * set_smb2_rsp_status() - set error response code on smb2 header
204 * @work: smb work containing response buffer
205 * @err: error response code
207 void set_smb2_rsp_status(struct ksmbd_work *work, __le32 err)
209 struct smb2_hdr *rsp_hdr;
211 if (work->next_smb2_rcv_hdr_off)
212 rsp_hdr = ksmbd_resp_buf_next(work);
214 rsp_hdr = smb2_get_msg(work->response_buf);
215 rsp_hdr->Status = err;
216 smb2_set_err_rsp(work);
220 * init_smb2_neg_rsp() - initialize smb2 response for negotiate command
221 * @work: smb work containing smb request buffer
223 * smb2 negotiate response is sent in reply of smb1 negotiate command for
224 * dialect auto-negotiation.
226 int init_smb2_neg_rsp(struct ksmbd_work *work)
228 struct smb2_hdr *rsp_hdr;
229 struct smb2_negotiate_rsp *rsp;
230 struct ksmbd_conn *conn = work->conn;
232 *(__be32 *)work->response_buf =
233 cpu_to_be32(conn->vals->header_size);
235 rsp_hdr = smb2_get_msg(work->response_buf);
236 memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
237 rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
238 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
239 rsp_hdr->CreditRequest = cpu_to_le16(2);
240 rsp_hdr->Command = SMB2_NEGOTIATE;
241 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
242 rsp_hdr->NextCommand = 0;
243 rsp_hdr->MessageId = 0;
244 rsp_hdr->Id.SyncId.ProcessId = 0;
245 rsp_hdr->Id.SyncId.TreeId = 0;
246 rsp_hdr->SessionId = 0;
247 memset(rsp_hdr->Signature, 0, 16);
249 rsp = smb2_get_msg(work->response_buf);
251 WARN_ON(ksmbd_conn_good(conn));
253 rsp->StructureSize = cpu_to_le16(65);
254 ksmbd_debug(SMB, "conn->dialect 0x%x\n", conn->dialect);
255 rsp->DialectRevision = cpu_to_le16(conn->dialect);
256 /* Not setting conn guid rsp->ServerGUID, as it
257 * not used by client for identifying connection
259 rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
260 /* Default Max Message Size till SMB2.0, 64K*/
261 rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
262 rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
263 rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);
265 rsp->SystemTime = cpu_to_le64(ksmbd_systime());
266 rsp->ServerStartTime = 0;
268 rsp->SecurityBufferOffset = cpu_to_le16(128);
269 rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
270 ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) +
271 le16_to_cpu(rsp->SecurityBufferOffset));
272 inc_rfc1001_len(work->response_buf,
273 sizeof(struct smb2_negotiate_rsp) -
274 sizeof(struct smb2_hdr) + AUTH_GSS_LENGTH);
275 rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
276 if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY)
277 rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
278 conn->use_spnego = true;
280 ksmbd_conn_set_need_negotiate(conn);
285 * smb2_set_rsp_credits() - set number of credits in response buffer
286 * @work: smb work containing smb response buffer
288 int smb2_set_rsp_credits(struct ksmbd_work *work)
290 struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
291 struct smb2_hdr *hdr = ksmbd_resp_buf_next(work);
292 struct ksmbd_conn *conn = work->conn;
293 unsigned short credits_requested, aux_max;
294 unsigned short credit_charge, credits_granted = 0;
296 if (work->send_no_response)
299 hdr->CreditCharge = req_hdr->CreditCharge;
301 if (conn->total_credits > conn->vals->max_credits) {
302 hdr->CreditRequest = 0;
303 pr_err("Total credits overflow: %d\n", conn->total_credits);
307 credit_charge = max_t(unsigned short,
308 le16_to_cpu(req_hdr->CreditCharge), 1);
309 if (credit_charge > conn->total_credits) {
310 ksmbd_debug(SMB, "Insufficient credits granted, given: %u, granted: %u\n",
311 credit_charge, conn->total_credits);
315 conn->total_credits -= credit_charge;
316 conn->outstanding_credits -= credit_charge;
317 credits_requested = max_t(unsigned short,
318 le16_to_cpu(req_hdr->CreditRequest), 1);
320 /* according to smb2.credits smbtorture, Windows server
321 * 2016 or later grant up to 8192 credits at once.
323 * TODO: Need to adjuct CreditRequest value according to
326 if (hdr->Command == SMB2_NEGOTIATE)
329 aux_max = conn->vals->max_credits - conn->total_credits;
330 credits_granted = min_t(unsigned short, credits_requested, aux_max);
332 conn->total_credits += credits_granted;
333 work->credits_granted += credits_granted;
335 if (!req_hdr->NextCommand) {
336 /* Update CreditRequest in last request */
337 hdr->CreditRequest = cpu_to_le16(work->credits_granted);
340 "credits: requested[%d] granted[%d] total_granted[%d]\n",
341 credits_requested, credits_granted,
342 conn->total_credits);
347 * init_chained_smb2_rsp() - initialize smb2 chained response
348 * @work: smb work containing smb response buffer
350 static void init_chained_smb2_rsp(struct ksmbd_work *work)
352 struct smb2_hdr *req = ksmbd_req_buf_next(work);
353 struct smb2_hdr *rsp = ksmbd_resp_buf_next(work);
354 struct smb2_hdr *rsp_hdr;
355 struct smb2_hdr *rcv_hdr;
356 int next_hdr_offset = 0;
359 /* Len of this response = updated RFC len - offset of previous cmd
360 * in the compound rsp
363 /* Storing the current local FID which may be needed by subsequent
364 * command in the compound request
366 if (req->Command == SMB2_CREATE && rsp->Status == STATUS_SUCCESS) {
367 work->compound_fid = ((struct smb2_create_rsp *)rsp)->VolatileFileId;
368 work->compound_pfid = ((struct smb2_create_rsp *)rsp)->PersistentFileId;
369 work->compound_sid = le64_to_cpu(rsp->SessionId);
372 len = get_rfc1002_len(work->response_buf) - work->next_smb2_rsp_hdr_off;
373 next_hdr_offset = le32_to_cpu(req->NextCommand);
375 new_len = ALIGN(len, 8);
376 inc_rfc1001_len(work->response_buf,
377 sizeof(struct smb2_hdr) + new_len - len);
378 rsp->NextCommand = cpu_to_le32(new_len);
380 work->next_smb2_rcv_hdr_off += next_hdr_offset;
381 work->next_smb2_rsp_hdr_off += new_len;
383 "Compound req new_len = %d rcv off = %d rsp off = %d\n",
384 new_len, work->next_smb2_rcv_hdr_off,
385 work->next_smb2_rsp_hdr_off);
387 rsp_hdr = ksmbd_resp_buf_next(work);
388 rcv_hdr = ksmbd_req_buf_next(work);
390 if (!(rcv_hdr->Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
391 ksmbd_debug(SMB, "related flag should be set\n");
392 work->compound_fid = KSMBD_NO_FID;
393 work->compound_pfid = KSMBD_NO_FID;
395 memset((char *)rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
396 rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
397 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
398 rsp_hdr->Command = rcv_hdr->Command;
401 * Message is response. We don't grant oplock yet.
403 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR |
404 SMB2_FLAGS_RELATED_OPERATIONS);
405 rsp_hdr->NextCommand = 0;
406 rsp_hdr->MessageId = rcv_hdr->MessageId;
407 rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
408 rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
409 rsp_hdr->SessionId = rcv_hdr->SessionId;
410 memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);
414 * is_chained_smb2_message() - check for chained command
415 * @work: smb work containing smb request buffer
417 * Return: true if chained request, otherwise false
419 bool is_chained_smb2_message(struct ksmbd_work *work)
421 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
422 unsigned int len, next_cmd;
424 if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
427 hdr = ksmbd_req_buf_next(work);
428 next_cmd = le32_to_cpu(hdr->NextCommand);
430 if ((u64)work->next_smb2_rcv_hdr_off + next_cmd +
431 __SMB2_HEADER_STRUCTURE_SIZE >
432 get_rfc1002_len(work->request_buf)) {
433 pr_err("next command(%u) offset exceeds smb msg size\n",
438 if ((u64)get_rfc1002_len(work->response_buf) + MAX_CIFS_SMALL_BUFFER_SIZE >
440 pr_err("next response offset exceeds response buffer size\n");
444 ksmbd_debug(SMB, "got SMB2 chained command\n");
445 init_chained_smb2_rsp(work);
447 } else if (work->next_smb2_rcv_hdr_off) {
449 * This is last request in chained command,
450 * align response to 8 byte
452 len = ALIGN(get_rfc1002_len(work->response_buf), 8);
453 len = len - get_rfc1002_len(work->response_buf);
455 ksmbd_debug(SMB, "padding len %u\n", len);
456 inc_rfc1001_len(work->response_buf, len);
457 if (work->aux_payload_sz)
458 work->aux_payload_sz += len;
465 * init_smb2_rsp_hdr() - initialize smb2 response
466 * @work: smb work containing smb request buffer
470 int init_smb2_rsp_hdr(struct ksmbd_work *work)
472 struct smb2_hdr *rsp_hdr = smb2_get_msg(work->response_buf);
473 struct smb2_hdr *rcv_hdr = smb2_get_msg(work->request_buf);
474 struct ksmbd_conn *conn = work->conn;
476 memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
477 *(__be32 *)work->response_buf =
478 cpu_to_be32(conn->vals->header_size);
479 rsp_hdr->ProtocolId = rcv_hdr->ProtocolId;
480 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
481 rsp_hdr->Command = rcv_hdr->Command;
484 * Message is response. We don't grant oplock yet.
486 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
487 rsp_hdr->NextCommand = 0;
488 rsp_hdr->MessageId = rcv_hdr->MessageId;
489 rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
490 rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
491 rsp_hdr->SessionId = rcv_hdr->SessionId;
492 memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);
498 * smb2_allocate_rsp_buf() - allocate smb2 response buffer
499 * @work: smb work containing smb request buffer
501 * Return: 0 on success, otherwise -ENOMEM
503 int smb2_allocate_rsp_buf(struct ksmbd_work *work)
505 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
506 size_t small_sz = MAX_CIFS_SMALL_BUFFER_SIZE;
507 size_t large_sz = small_sz + work->conn->vals->max_trans_size;
508 size_t sz = small_sz;
509 int cmd = le16_to_cpu(hdr->Command);
511 if (cmd == SMB2_IOCTL_HE || cmd == SMB2_QUERY_DIRECTORY_HE)
514 if (cmd == SMB2_QUERY_INFO_HE) {
515 struct smb2_query_info_req *req;
517 req = smb2_get_msg(work->request_buf);
518 if ((req->InfoType == SMB2_O_INFO_FILE &&
519 (req->FileInfoClass == FILE_FULL_EA_INFORMATION ||
520 req->FileInfoClass == FILE_ALL_INFORMATION)) ||
521 req->InfoType == SMB2_O_INFO_SECURITY)
525 /* allocate large response buf for chained commands */
526 if (le32_to_cpu(hdr->NextCommand) > 0)
529 work->response_buf = kvmalloc(sz, GFP_KERNEL | __GFP_ZERO);
530 if (!work->response_buf)
533 work->response_sz = sz;
538 * smb2_check_user_session() - check for valid session for a user
539 * @work: smb work containing smb request buffer
541 * Return: 0 on success, otherwise error
543 int smb2_check_user_session(struct ksmbd_work *work)
545 struct smb2_hdr *req_hdr = smb2_get_msg(work->request_buf);
546 struct ksmbd_conn *conn = work->conn;
547 unsigned int cmd = conn->ops->get_cmd_val(work);
548 unsigned long long sess_id;
552 * SMB2_ECHO, SMB2_NEGOTIATE, SMB2_SESSION_SETUP command do not
553 * require a session id, so no need to validate user session's for
556 if (cmd == SMB2_ECHO_HE || cmd == SMB2_NEGOTIATE_HE ||
557 cmd == SMB2_SESSION_SETUP_HE)
560 if (!ksmbd_conn_good(conn))
563 sess_id = le64_to_cpu(req_hdr->SessionId);
564 /* Check for validity of user session */
565 work->sess = ksmbd_session_lookup_all(conn, sess_id);
568 ksmbd_debug(SMB, "Invalid user session, Uid %llu\n", sess_id);
572 static void destroy_previous_session(struct ksmbd_conn *conn,
573 struct ksmbd_user *user, u64 id)
575 struct ksmbd_session *prev_sess = ksmbd_session_lookup_slowpath(id);
576 struct ksmbd_user *prev_user;
577 struct channel *chann;
583 prev_user = prev_sess->user;
586 strcmp(user->name, prev_user->name) ||
587 user->passkey_sz != prev_user->passkey_sz ||
588 memcmp(user->passkey, prev_user->passkey, user->passkey_sz))
591 prev_sess->state = SMB2_SESSION_EXPIRED;
592 xa_for_each(&prev_sess->ksmbd_chann_list, index, chann)
593 ksmbd_conn_set_exiting(chann->conn);
597 * smb2_get_name() - get filename string from on the wire smb format
598 * @src: source buffer
599 * @maxlen: maxlen of source string
600 * @local_nls: nls_table pointer
602 * Return: matching converted filename on success, otherwise error ptr
605 smb2_get_name(const char *src, const int maxlen, struct nls_table *local_nls)
609 name = smb_strndup_from_utf16(src, maxlen, 1, local_nls);
611 pr_err("failed to get name %ld\n", PTR_ERR(name));
615 ksmbd_conv_path_to_unix(name);
616 ksmbd_strip_last_slash(name);
620 int setup_async_work(struct ksmbd_work *work, void (*fn)(void **), void **arg)
622 struct smb2_hdr *rsp_hdr;
623 struct ksmbd_conn *conn = work->conn;
626 rsp_hdr = smb2_get_msg(work->response_buf);
627 rsp_hdr->Flags |= SMB2_FLAGS_ASYNC_COMMAND;
629 id = ksmbd_acquire_async_msg_id(&conn->async_ida);
631 pr_err("Failed to alloc async message id\n");
634 work->asynchronous = true;
636 rsp_hdr->Id.AsyncId = cpu_to_le64(id);
639 "Send interim Response to inform async request id : %d\n",
642 work->cancel_fn = fn;
643 work->cancel_argv = arg;
645 if (list_empty(&work->async_request_entry)) {
646 spin_lock(&conn->request_lock);
647 list_add_tail(&work->async_request_entry, &conn->async_requests);
648 spin_unlock(&conn->request_lock);
654 void release_async_work(struct ksmbd_work *work)
656 struct ksmbd_conn *conn = work->conn;
658 spin_lock(&conn->request_lock);
659 list_del_init(&work->async_request_entry);
660 spin_unlock(&conn->request_lock);
662 work->asynchronous = 0;
663 work->cancel_fn = NULL;
664 kfree(work->cancel_argv);
665 work->cancel_argv = NULL;
666 if (work->async_id) {
667 ksmbd_release_id(&conn->async_ida, work->async_id);
672 void smb2_send_interim_resp(struct ksmbd_work *work, __le32 status)
674 struct smb2_hdr *rsp_hdr;
676 rsp_hdr = smb2_get_msg(work->response_buf);
677 smb2_set_err_rsp(work);
678 rsp_hdr->Status = status;
681 ksmbd_conn_write(work);
686 static __le32 smb2_get_reparse_tag_special_file(umode_t mode)
688 if (S_ISDIR(mode) || S_ISREG(mode))
692 return IO_REPARSE_TAG_LX_SYMLINK_LE;
693 else if (S_ISFIFO(mode))
694 return IO_REPARSE_TAG_LX_FIFO_LE;
695 else if (S_ISSOCK(mode))
696 return IO_REPARSE_TAG_AF_UNIX_LE;
697 else if (S_ISCHR(mode))
698 return IO_REPARSE_TAG_LX_CHR_LE;
699 else if (S_ISBLK(mode))
700 return IO_REPARSE_TAG_LX_BLK_LE;
706 * smb2_get_dos_mode() - get file mode in dos format from unix mode
707 * @stat: kstat containing file mode
708 * @attribute: attribute flags
710 * Return: converted dos mode
712 static int smb2_get_dos_mode(struct kstat *stat, int attribute)
716 if (S_ISDIR(stat->mode)) {
717 attr = FILE_ATTRIBUTE_DIRECTORY |
718 (attribute & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM));
720 attr = (attribute & 0x00005137) | FILE_ATTRIBUTE_ARCHIVE;
721 attr &= ~(FILE_ATTRIBUTE_DIRECTORY);
722 if (S_ISREG(stat->mode) && (server_conf.share_fake_fscaps &
723 FILE_SUPPORTS_SPARSE_FILES))
724 attr |= FILE_ATTRIBUTE_SPARSE_FILE;
726 if (smb2_get_reparse_tag_special_file(stat->mode))
727 attr |= FILE_ATTRIBUTE_REPARSE_POINT;
733 static void build_preauth_ctxt(struct smb2_preauth_neg_context *pneg_ctxt,
736 pneg_ctxt->ContextType = SMB2_PREAUTH_INTEGRITY_CAPABILITIES;
737 pneg_ctxt->DataLength = cpu_to_le16(38);
738 pneg_ctxt->HashAlgorithmCount = cpu_to_le16(1);
739 pneg_ctxt->Reserved = cpu_to_le32(0);
740 pneg_ctxt->SaltLength = cpu_to_le16(SMB311_SALT_SIZE);
741 get_random_bytes(pneg_ctxt->Salt, SMB311_SALT_SIZE);
742 pneg_ctxt->HashAlgorithms = hash_id;
745 static void build_encrypt_ctxt(struct smb2_encryption_neg_context *pneg_ctxt,
748 pneg_ctxt->ContextType = SMB2_ENCRYPTION_CAPABILITIES;
749 pneg_ctxt->DataLength = cpu_to_le16(4);
750 pneg_ctxt->Reserved = cpu_to_le32(0);
751 pneg_ctxt->CipherCount = cpu_to_le16(1);
752 pneg_ctxt->Ciphers[0] = cipher_type;
755 static void build_sign_cap_ctxt(struct smb2_signing_capabilities *pneg_ctxt,
758 pneg_ctxt->ContextType = SMB2_SIGNING_CAPABILITIES;
759 pneg_ctxt->DataLength =
760 cpu_to_le16((sizeof(struct smb2_signing_capabilities) + 2)
761 - sizeof(struct smb2_neg_context));
762 pneg_ctxt->Reserved = cpu_to_le32(0);
763 pneg_ctxt->SigningAlgorithmCount = cpu_to_le16(1);
764 pneg_ctxt->SigningAlgorithms[0] = sign_algo;
767 static void build_posix_ctxt(struct smb2_posix_neg_context *pneg_ctxt)
769 pneg_ctxt->ContextType = SMB2_POSIX_EXTENSIONS_AVAILABLE;
770 pneg_ctxt->DataLength = cpu_to_le16(POSIX_CTXT_DATA_LEN);
771 /* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */
772 pneg_ctxt->Name[0] = 0x93;
773 pneg_ctxt->Name[1] = 0xAD;
774 pneg_ctxt->Name[2] = 0x25;
775 pneg_ctxt->Name[3] = 0x50;
776 pneg_ctxt->Name[4] = 0x9C;
777 pneg_ctxt->Name[5] = 0xB4;
778 pneg_ctxt->Name[6] = 0x11;
779 pneg_ctxt->Name[7] = 0xE7;
780 pneg_ctxt->Name[8] = 0xB4;
781 pneg_ctxt->Name[9] = 0x23;
782 pneg_ctxt->Name[10] = 0x83;
783 pneg_ctxt->Name[11] = 0xDE;
784 pneg_ctxt->Name[12] = 0x96;
785 pneg_ctxt->Name[13] = 0x8B;
786 pneg_ctxt->Name[14] = 0xCD;
787 pneg_ctxt->Name[15] = 0x7C;
790 static void assemble_neg_contexts(struct ksmbd_conn *conn,
791 struct smb2_negotiate_rsp *rsp,
794 char * const pneg_ctxt = (char *)rsp +
795 le32_to_cpu(rsp->NegotiateContextOffset);
796 int neg_ctxt_cnt = 1;
800 "assemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
801 build_preauth_ctxt((struct smb2_preauth_neg_context *)pneg_ctxt,
802 conn->preauth_info->Preauth_HashId);
803 inc_rfc1001_len(smb2_buf_len, AUTH_GSS_PADDING);
804 ctxt_size = sizeof(struct smb2_preauth_neg_context);
806 if (conn->cipher_type) {
807 /* Round to 8 byte boundary */
808 ctxt_size = round_up(ctxt_size, 8);
810 "assemble SMB2_ENCRYPTION_CAPABILITIES context\n");
811 build_encrypt_ctxt((struct smb2_encryption_neg_context *)
812 (pneg_ctxt + ctxt_size),
815 ctxt_size += sizeof(struct smb2_encryption_neg_context) + 2;
818 /* compression context not yet supported */
819 WARN_ON(conn->compress_algorithm != SMB3_COMPRESS_NONE);
821 if (conn->posix_ext_supported) {
822 ctxt_size = round_up(ctxt_size, 8);
824 "assemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
825 build_posix_ctxt((struct smb2_posix_neg_context *)
826 (pneg_ctxt + ctxt_size));
828 ctxt_size += sizeof(struct smb2_posix_neg_context);
831 if (conn->signing_negotiated) {
832 ctxt_size = round_up(ctxt_size, 8);
834 "assemble SMB2_SIGNING_CAPABILITIES context\n");
835 build_sign_cap_ctxt((struct smb2_signing_capabilities *)
836 (pneg_ctxt + ctxt_size),
837 conn->signing_algorithm);
839 ctxt_size += sizeof(struct smb2_signing_capabilities) + 2;
842 rsp->NegotiateContextCount = cpu_to_le16(neg_ctxt_cnt);
843 inc_rfc1001_len(smb2_buf_len, ctxt_size);
846 static __le32 decode_preauth_ctxt(struct ksmbd_conn *conn,
847 struct smb2_preauth_neg_context *pneg_ctxt,
851 * sizeof(smb2_preauth_neg_context) assumes SMB311_SALT_SIZE Salt,
852 * which may not be present. Only check for used HashAlgorithms[1].
854 if (len_of_ctxts < MIN_PREAUTH_CTXT_DATA_LEN)
855 return STATUS_INVALID_PARAMETER;
857 if (pneg_ctxt->HashAlgorithms != SMB2_PREAUTH_INTEGRITY_SHA512)
858 return STATUS_NO_PREAUTH_INTEGRITY_HASH_OVERLAP;
860 conn->preauth_info->Preauth_HashId = SMB2_PREAUTH_INTEGRITY_SHA512;
861 return STATUS_SUCCESS;
864 static void decode_encrypt_ctxt(struct ksmbd_conn *conn,
865 struct smb2_encryption_neg_context *pneg_ctxt,
868 int cph_cnt = le16_to_cpu(pneg_ctxt->CipherCount);
869 int i, cphs_size = cph_cnt * sizeof(__le16);
871 conn->cipher_type = 0;
873 if (sizeof(struct smb2_encryption_neg_context) + cphs_size >
875 pr_err("Invalid cipher count(%d)\n", cph_cnt);
879 if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION_OFF)
882 for (i = 0; i < cph_cnt; i++) {
883 if (pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_GCM ||
884 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_CCM ||
885 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_CCM ||
886 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_GCM) {
887 ksmbd_debug(SMB, "Cipher ID = 0x%x\n",
888 pneg_ctxt->Ciphers[i]);
889 conn->cipher_type = pneg_ctxt->Ciphers[i];
896 * smb3_encryption_negotiated() - checks if server and client agreed on enabling encryption
897 * @conn: smb connection
899 * Return: true if connection should be encrypted, else false
901 bool smb3_encryption_negotiated(struct ksmbd_conn *conn)
903 if (!conn->ops->generate_encryptionkey)
907 * SMB 3.0 and 3.0.2 dialects use the SMB2_GLOBAL_CAP_ENCRYPTION flag.
908 * SMB 3.1.1 uses the cipher_type field.
910 return (conn->vals->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION) ||
914 static void decode_compress_ctxt(struct ksmbd_conn *conn,
915 struct smb2_compression_capabilities_context *pneg_ctxt)
917 conn->compress_algorithm = SMB3_COMPRESS_NONE;
920 static void decode_sign_cap_ctxt(struct ksmbd_conn *conn,
921 struct smb2_signing_capabilities *pneg_ctxt,
924 int sign_algo_cnt = le16_to_cpu(pneg_ctxt->SigningAlgorithmCount);
925 int i, sign_alos_size = sign_algo_cnt * sizeof(__le16);
927 conn->signing_negotiated = false;
929 if (sizeof(struct smb2_signing_capabilities) + sign_alos_size >
931 pr_err("Invalid signing algorithm count(%d)\n", sign_algo_cnt);
935 for (i = 0; i < sign_algo_cnt; i++) {
936 if (pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_HMAC_SHA256_LE ||
937 pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_AES_CMAC_LE) {
938 ksmbd_debug(SMB, "Signing Algorithm ID = 0x%x\n",
939 pneg_ctxt->SigningAlgorithms[i]);
940 conn->signing_negotiated = true;
941 conn->signing_algorithm =
942 pneg_ctxt->SigningAlgorithms[i];
948 static __le32 deassemble_neg_contexts(struct ksmbd_conn *conn,
949 struct smb2_negotiate_req *req,
952 /* +4 is to account for the RFC1001 len field */
953 struct smb2_neg_context *pctx = (struct smb2_neg_context *)req;
954 int i = 0, len_of_ctxts;
955 int offset = le32_to_cpu(req->NegotiateContextOffset);
956 int neg_ctxt_cnt = le16_to_cpu(req->NegotiateContextCount);
957 __le32 status = STATUS_INVALID_PARAMETER;
959 ksmbd_debug(SMB, "decoding %d negotiate contexts\n", neg_ctxt_cnt);
960 if (len_of_smb <= offset) {
961 ksmbd_debug(SMB, "Invalid response: negotiate context offset\n");
965 len_of_ctxts = len_of_smb - offset;
967 while (i++ < neg_ctxt_cnt) {
970 /* check that offset is not beyond end of SMB */
971 if (len_of_ctxts == 0)
974 if (len_of_ctxts < sizeof(struct smb2_neg_context))
977 pctx = (struct smb2_neg_context *)((char *)pctx + offset);
978 clen = le16_to_cpu(pctx->DataLength);
979 if (clen + sizeof(struct smb2_neg_context) > len_of_ctxts)
982 if (pctx->ContextType == SMB2_PREAUTH_INTEGRITY_CAPABILITIES) {
984 "deassemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
985 if (conn->preauth_info->Preauth_HashId)
988 status = decode_preauth_ctxt(conn,
989 (struct smb2_preauth_neg_context *)pctx,
991 if (status != STATUS_SUCCESS)
993 } else if (pctx->ContextType == SMB2_ENCRYPTION_CAPABILITIES) {
995 "deassemble SMB2_ENCRYPTION_CAPABILITIES context\n");
996 if (conn->cipher_type)
999 decode_encrypt_ctxt(conn,
1000 (struct smb2_encryption_neg_context *)pctx,
1002 } else if (pctx->ContextType == SMB2_COMPRESSION_CAPABILITIES) {
1004 "deassemble SMB2_COMPRESSION_CAPABILITIES context\n");
1005 if (conn->compress_algorithm)
1008 decode_compress_ctxt(conn,
1009 (struct smb2_compression_capabilities_context *)pctx);
1010 } else if (pctx->ContextType == SMB2_NETNAME_NEGOTIATE_CONTEXT_ID) {
1012 "deassemble SMB2_NETNAME_NEGOTIATE_CONTEXT_ID context\n");
1013 } else if (pctx->ContextType == SMB2_POSIX_EXTENSIONS_AVAILABLE) {
1015 "deassemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
1016 conn->posix_ext_supported = true;
1017 } else if (pctx->ContextType == SMB2_SIGNING_CAPABILITIES) {
1019 "deassemble SMB2_SIGNING_CAPABILITIES context\n");
1020 decode_sign_cap_ctxt(conn,
1021 (struct smb2_signing_capabilities *)pctx,
1025 /* offsets must be 8 byte aligned */
1026 clen = (clen + 7) & ~0x7;
1027 offset = clen + sizeof(struct smb2_neg_context);
1028 len_of_ctxts -= clen + sizeof(struct smb2_neg_context);
1034 * smb2_handle_negotiate() - handler for smb2 negotiate command
1035 * @work: smb work containing smb request buffer
1039 int smb2_handle_negotiate(struct ksmbd_work *work)
1041 struct ksmbd_conn *conn = work->conn;
1042 struct smb2_negotiate_req *req = smb2_get_msg(work->request_buf);
1043 struct smb2_negotiate_rsp *rsp = smb2_get_msg(work->response_buf);
1045 unsigned int smb2_buf_len, smb2_neg_size;
1048 ksmbd_debug(SMB, "Received negotiate request\n");
1049 conn->need_neg = false;
1050 if (ksmbd_conn_good(conn)) {
1051 pr_err("conn->tcp_status is already in CifsGood State\n");
1052 work->send_no_response = 1;
1056 if (req->DialectCount == 0) {
1057 pr_err("malformed packet\n");
1058 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1063 smb2_buf_len = get_rfc1002_len(work->request_buf);
1064 smb2_neg_size = offsetof(struct smb2_negotiate_req, Dialects);
1065 if (smb2_neg_size > smb2_buf_len) {
1066 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1071 if (conn->dialect == SMB311_PROT_ID) {
1072 unsigned int nego_ctxt_off = le32_to_cpu(req->NegotiateContextOffset);
1074 if (smb2_buf_len < nego_ctxt_off) {
1075 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1080 if (smb2_neg_size > nego_ctxt_off) {
1081 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1086 if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
1088 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1093 if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
1095 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1101 conn->cli_cap = le32_to_cpu(req->Capabilities);
1102 switch (conn->dialect) {
1103 case SMB311_PROT_ID:
1104 conn->preauth_info =
1105 kzalloc(sizeof(struct preauth_integrity_info),
1107 if (!conn->preauth_info) {
1109 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1113 status = deassemble_neg_contexts(conn, req,
1114 get_rfc1002_len(work->request_buf));
1115 if (status != STATUS_SUCCESS) {
1116 pr_err("deassemble_neg_contexts error(0x%x)\n",
1118 rsp->hdr.Status = status;
1120 kfree(conn->preauth_info);
1121 conn->preauth_info = NULL;
1125 rc = init_smb3_11_server(conn);
1127 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1128 kfree(conn->preauth_info);
1129 conn->preauth_info = NULL;
1133 ksmbd_gen_preauth_integrity_hash(conn,
1135 conn->preauth_info->Preauth_HashValue);
1136 rsp->NegotiateContextOffset =
1137 cpu_to_le32(OFFSET_OF_NEG_CONTEXT);
1138 assemble_neg_contexts(conn, rsp, work->response_buf);
1140 case SMB302_PROT_ID:
1141 init_smb3_02_server(conn);
1144 init_smb3_0_server(conn);
1147 init_smb2_1_server(conn);
1152 ksmbd_debug(SMB, "Server dialect :0x%x not supported\n",
1154 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
1158 rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
1161 conn->connection_type = conn->dialect;
1163 rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
1164 rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
1165 rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);
1167 memcpy(conn->ClientGUID, req->ClientGUID,
1168 SMB2_CLIENT_GUID_SIZE);
1169 conn->cli_sec_mode = le16_to_cpu(req->SecurityMode);
1171 rsp->StructureSize = cpu_to_le16(65);
1172 rsp->DialectRevision = cpu_to_le16(conn->dialect);
1173 /* Not setting conn guid rsp->ServerGUID, as it
1174 * not used by client for identifying server
1176 memset(rsp->ServerGUID, 0, SMB2_CLIENT_GUID_SIZE);
1178 rsp->SystemTime = cpu_to_le64(ksmbd_systime());
1179 rsp->ServerStartTime = 0;
1180 ksmbd_debug(SMB, "negotiate context offset %d, count %d\n",
1181 le32_to_cpu(rsp->NegotiateContextOffset),
1182 le16_to_cpu(rsp->NegotiateContextCount));
1184 rsp->SecurityBufferOffset = cpu_to_le16(128);
1185 rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
1186 ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) +
1187 le16_to_cpu(rsp->SecurityBufferOffset));
1188 inc_rfc1001_len(work->response_buf, sizeof(struct smb2_negotiate_rsp) -
1189 sizeof(struct smb2_hdr) + AUTH_GSS_LENGTH);
1190 rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
1191 conn->use_spnego = true;
1193 if ((server_conf.signing == KSMBD_CONFIG_OPT_AUTO ||
1194 server_conf.signing == KSMBD_CONFIG_OPT_DISABLED) &&
1195 req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED_LE)
1197 else if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY) {
1198 server_conf.enforced_signing = true;
1199 rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
1203 conn->srv_sec_mode = le16_to_cpu(rsp->SecurityMode);
1204 ksmbd_conn_set_need_negotiate(conn);
1208 smb2_set_err_rsp(work);
1213 static int alloc_preauth_hash(struct ksmbd_session *sess,
1214 struct ksmbd_conn *conn)
1216 if (sess->Preauth_HashValue)
1219 sess->Preauth_HashValue = kmemdup(conn->preauth_info->Preauth_HashValue,
1220 PREAUTH_HASHVALUE_SIZE, GFP_KERNEL);
1221 if (!sess->Preauth_HashValue)
1227 static int generate_preauth_hash(struct ksmbd_work *work)
1229 struct ksmbd_conn *conn = work->conn;
1230 struct ksmbd_session *sess = work->sess;
1233 if (conn->dialect != SMB311_PROT_ID)
1236 if (conn->binding) {
1237 struct preauth_session *preauth_sess;
1239 preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
1240 if (!preauth_sess) {
1241 preauth_sess = ksmbd_preauth_session_alloc(conn, sess->id);
1246 preauth_hash = preauth_sess->Preauth_HashValue;
1248 if (!sess->Preauth_HashValue)
1249 if (alloc_preauth_hash(sess, conn))
1251 preauth_hash = sess->Preauth_HashValue;
1254 ksmbd_gen_preauth_integrity_hash(conn, work->request_buf, preauth_hash);
1258 static int decode_negotiation_token(struct ksmbd_conn *conn,
1259 struct negotiate_message *negblob,
1262 if (!conn->use_spnego)
1265 if (ksmbd_decode_negTokenInit((char *)negblob, sz, conn)) {
1266 if (ksmbd_decode_negTokenTarg((char *)negblob, sz, conn)) {
1267 conn->auth_mechs |= KSMBD_AUTH_NTLMSSP;
1268 conn->preferred_auth_mech = KSMBD_AUTH_NTLMSSP;
1269 conn->use_spnego = false;
1275 static int ntlm_negotiate(struct ksmbd_work *work,
1276 struct negotiate_message *negblob,
1279 struct smb2_sess_setup_rsp *rsp = smb2_get_msg(work->response_buf);
1280 struct challenge_message *chgblob;
1281 unsigned char *spnego_blob = NULL;
1282 u16 spnego_blob_len;
1286 ksmbd_debug(SMB, "negotiate phase\n");
1287 rc = ksmbd_decode_ntlmssp_neg_blob(negblob, negblob_len, work->conn);
1291 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1293 (struct challenge_message *)((char *)&rsp->hdr.ProtocolId + sz);
1294 memset(chgblob, 0, sizeof(struct challenge_message));
1296 if (!work->conn->use_spnego) {
1297 sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
1301 rsp->SecurityBufferLength = cpu_to_le16(sz);
1305 sz = sizeof(struct challenge_message);
1306 sz += (strlen(ksmbd_netbios_name()) * 2 + 1 + 4) * 6;
1308 neg_blob = kzalloc(sz, GFP_KERNEL);
1312 chgblob = (struct challenge_message *)neg_blob;
1313 sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
1319 rc = build_spnego_ntlmssp_neg_blob(&spnego_blob, &spnego_blob_len,
1326 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1327 memcpy((char *)&rsp->hdr.ProtocolId + sz, spnego_blob, spnego_blob_len);
1328 rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
1336 static struct authenticate_message *user_authblob(struct ksmbd_conn *conn,
1337 struct smb2_sess_setup_req *req)
1341 if (conn->use_spnego && conn->mechToken)
1342 return (struct authenticate_message *)conn->mechToken;
1344 sz = le16_to_cpu(req->SecurityBufferOffset);
1345 return (struct authenticate_message *)((char *)&req->hdr.ProtocolId
1349 static struct ksmbd_user *session_user(struct ksmbd_conn *conn,
1350 struct smb2_sess_setup_req *req)
1352 struct authenticate_message *authblob;
1353 struct ksmbd_user *user;
1355 unsigned int name_off, name_len, secbuf_len;
1357 secbuf_len = le16_to_cpu(req->SecurityBufferLength);
1358 if (secbuf_len < sizeof(struct authenticate_message)) {
1359 ksmbd_debug(SMB, "blob len %d too small\n", secbuf_len);
1362 authblob = user_authblob(conn, req);
1363 name_off = le32_to_cpu(authblob->UserName.BufferOffset);
1364 name_len = le16_to_cpu(authblob->UserName.Length);
1366 if (secbuf_len < (u64)name_off + name_len)
1369 name = smb_strndup_from_utf16((const char *)authblob + name_off,
1374 pr_err("cannot allocate memory\n");
1378 ksmbd_debug(SMB, "session setup request for user %s\n", name);
1379 user = ksmbd_login_user(name);
1384 static int ntlm_authenticate(struct ksmbd_work *work)
1386 struct smb2_sess_setup_req *req = smb2_get_msg(work->request_buf);
1387 struct smb2_sess_setup_rsp *rsp = smb2_get_msg(work->response_buf);
1388 struct ksmbd_conn *conn = work->conn;
1389 struct ksmbd_session *sess = work->sess;
1390 struct channel *chann = NULL;
1391 struct ksmbd_user *user;
1395 ksmbd_debug(SMB, "authenticate phase\n");
1396 if (conn->use_spnego) {
1397 unsigned char *spnego_blob;
1398 u16 spnego_blob_len;
1400 rc = build_spnego_ntlmssp_auth_blob(&spnego_blob,
1406 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1407 memcpy((char *)&rsp->hdr.ProtocolId + sz, spnego_blob, spnego_blob_len);
1408 rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
1410 inc_rfc1001_len(work->response_buf, spnego_blob_len - 1);
1413 user = session_user(conn, req);
1415 ksmbd_debug(SMB, "Unknown user name or an error\n");
1419 /* Check for previous session */
1420 prev_id = le64_to_cpu(req->PreviousSessionId);
1421 if (prev_id && prev_id != sess->id)
1422 destroy_previous_session(conn, user, prev_id);
1424 if (sess->state == SMB2_SESSION_VALID) {
1426 * Reuse session if anonymous try to connect
1427 * on reauthetication.
1429 if (conn->binding == false && ksmbd_anonymous_user(user)) {
1430 ksmbd_free_user(user);
1434 if (!ksmbd_compare_user(sess->user, user)) {
1435 ksmbd_free_user(user);
1438 ksmbd_free_user(user);
1443 if (conn->binding == false && user_guest(sess->user)) {
1444 rsp->SessionFlags = SMB2_SESSION_FLAG_IS_GUEST_LE;
1446 struct authenticate_message *authblob;
1448 authblob = user_authblob(conn, req);
1449 sz = le16_to_cpu(req->SecurityBufferLength);
1450 rc = ksmbd_decode_ntlmssp_auth_blob(authblob, sz, conn, sess);
1452 set_user_flag(sess->user, KSMBD_USER_FLAG_BAD_PASSWORD);
1453 ksmbd_debug(SMB, "authentication failed\n");
1459 * If session state is SMB2_SESSION_VALID, We can assume
1460 * that it is reauthentication. And the user/password
1461 * has been verified, so return it here.
1463 if (sess->state == SMB2_SESSION_VALID) {
1465 goto binding_session;
1469 if ((rsp->SessionFlags != SMB2_SESSION_FLAG_IS_GUEST_LE &&
1470 (conn->sign || server_conf.enforced_signing)) ||
1471 (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
1474 if (smb3_encryption_negotiated(conn) &&
1475 !(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1476 rc = conn->ops->generate_encryptionkey(conn, sess);
1479 "SMB3 encryption key generation failed\n");
1483 if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION)
1484 rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
1486 * signing is disable if encryption is enable
1493 if (conn->dialect >= SMB30_PROT_ID) {
1494 chann = lookup_chann_list(sess, conn);
1496 chann = kmalloc(sizeof(struct channel), GFP_KERNEL);
1501 xa_store(&sess->ksmbd_chann_list, (long)conn, chann, GFP_KERNEL);
1505 if (conn->ops->generate_signingkey) {
1506 rc = conn->ops->generate_signingkey(sess, conn);
1508 ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
1513 if (!ksmbd_conn_lookup_dialect(conn)) {
1514 pr_err("fail to verify the dialect\n");
1520 #ifdef CONFIG_SMB_SERVER_KERBEROS5
1521 static int krb5_authenticate(struct ksmbd_work *work)
1523 struct smb2_sess_setup_req *req = smb2_get_msg(work->request_buf);
1524 struct smb2_sess_setup_rsp *rsp = smb2_get_msg(work->response_buf);
1525 struct ksmbd_conn *conn = work->conn;
1526 struct ksmbd_session *sess = work->sess;
1527 char *in_blob, *out_blob;
1528 struct channel *chann = NULL;
1530 int in_len, out_len;
1533 in_blob = (char *)&req->hdr.ProtocolId +
1534 le16_to_cpu(req->SecurityBufferOffset);
1535 in_len = le16_to_cpu(req->SecurityBufferLength);
1536 out_blob = (char *)&rsp->hdr.ProtocolId +
1537 le16_to_cpu(rsp->SecurityBufferOffset);
1538 out_len = work->response_sz -
1539 (le16_to_cpu(rsp->SecurityBufferOffset) + 4);
1541 /* Check previous session */
1542 prev_sess_id = le64_to_cpu(req->PreviousSessionId);
1543 if (prev_sess_id && prev_sess_id != sess->id)
1544 destroy_previous_session(conn, sess->user, prev_sess_id);
1546 if (sess->state == SMB2_SESSION_VALID)
1547 ksmbd_free_user(sess->user);
1549 retval = ksmbd_krb5_authenticate(sess, in_blob, in_len,
1550 out_blob, &out_len);
1552 ksmbd_debug(SMB, "krb5 authentication failed\n");
1555 rsp->SecurityBufferLength = cpu_to_le16(out_len);
1556 inc_rfc1001_len(work->response_buf, out_len - 1);
1558 if ((conn->sign || server_conf.enforced_signing) ||
1559 (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
1562 if (smb3_encryption_negotiated(conn)) {
1563 retval = conn->ops->generate_encryptionkey(conn, sess);
1566 "SMB3 encryption key generation failed\n");
1570 if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION)
1571 rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
1575 if (conn->dialect >= SMB30_PROT_ID) {
1576 chann = lookup_chann_list(sess, conn);
1578 chann = kmalloc(sizeof(struct channel), GFP_KERNEL);
1583 xa_store(&sess->ksmbd_chann_list, (long)conn, chann, GFP_KERNEL);
1587 if (conn->ops->generate_signingkey) {
1588 retval = conn->ops->generate_signingkey(sess, conn);
1590 ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
1595 if (!ksmbd_conn_lookup_dialect(conn)) {
1596 pr_err("fail to verify the dialect\n");
1602 static int krb5_authenticate(struct ksmbd_work *work)
1608 int smb2_sess_setup(struct ksmbd_work *work)
1610 struct ksmbd_conn *conn = work->conn;
1611 struct smb2_sess_setup_req *req = smb2_get_msg(work->request_buf);
1612 struct smb2_sess_setup_rsp *rsp = smb2_get_msg(work->response_buf);
1613 struct ksmbd_session *sess;
1614 struct negotiate_message *negblob;
1615 unsigned int negblob_len, negblob_off;
1618 ksmbd_debug(SMB, "Received request for session setup\n");
1620 rsp->StructureSize = cpu_to_le16(9);
1621 rsp->SessionFlags = 0;
1622 rsp->SecurityBufferOffset = cpu_to_le16(72);
1623 rsp->SecurityBufferLength = 0;
1624 inc_rfc1001_len(work->response_buf, 9);
1626 ksmbd_conn_lock(conn);
1627 if (!req->hdr.SessionId) {
1628 sess = ksmbd_smb2_session_create();
1633 rsp->hdr.SessionId = cpu_to_le64(sess->id);
1634 rc = ksmbd_session_register(conn, sess);
1637 } else if (conn->dialect >= SMB30_PROT_ID &&
1638 (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
1639 req->Flags & SMB2_SESSION_REQ_FLAG_BINDING) {
1640 u64 sess_id = le64_to_cpu(req->hdr.SessionId);
1642 sess = ksmbd_session_lookup_slowpath(sess_id);
1648 if (conn->dialect != sess->dialect) {
1653 if (!(req->hdr.Flags & SMB2_FLAGS_SIGNED)) {
1658 if (strncmp(conn->ClientGUID, sess->ClientGUID,
1659 SMB2_CLIENT_GUID_SIZE)) {
1664 if (sess->state == SMB2_SESSION_IN_PROGRESS) {
1669 if (sess->state == SMB2_SESSION_EXPIRED) {
1674 if (ksmbd_conn_need_reconnect(conn)) {
1680 if (ksmbd_session_lookup(conn, sess_id)) {
1685 if (user_guest(sess->user)) {
1690 conn->binding = true;
1691 } else if ((conn->dialect < SMB30_PROT_ID ||
1692 server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
1693 (req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1698 sess = ksmbd_session_lookup(conn,
1699 le64_to_cpu(req->hdr.SessionId));
1705 if (sess->state == SMB2_SESSION_EXPIRED) {
1710 if (ksmbd_conn_need_reconnect(conn)) {
1718 negblob_off = le16_to_cpu(req->SecurityBufferOffset);
1719 negblob_len = le16_to_cpu(req->SecurityBufferLength);
1720 if (negblob_off < offsetof(struct smb2_sess_setup_req, Buffer) ||
1721 negblob_len < offsetof(struct negotiate_message, NegotiateFlags)) {
1726 negblob = (struct negotiate_message *)((char *)&req->hdr.ProtocolId +
1729 if (decode_negotiation_token(conn, negblob, negblob_len) == 0) {
1730 if (conn->mechToken)
1731 negblob = (struct negotiate_message *)conn->mechToken;
1734 if (server_conf.auth_mechs & conn->auth_mechs) {
1735 rc = generate_preauth_hash(work);
1739 if (conn->preferred_auth_mech &
1740 (KSMBD_AUTH_KRB5 | KSMBD_AUTH_MSKRB5)) {
1741 rc = krb5_authenticate(work);
1747 if (!ksmbd_conn_need_reconnect(conn)) {
1748 ksmbd_conn_set_good(conn);
1749 sess->state = SMB2_SESSION_VALID;
1751 kfree(sess->Preauth_HashValue);
1752 sess->Preauth_HashValue = NULL;
1753 } else if (conn->preferred_auth_mech == KSMBD_AUTH_NTLMSSP) {
1754 if (negblob->MessageType == NtLmNegotiate) {
1755 rc = ntlm_negotiate(work, negblob, negblob_len);
1759 STATUS_MORE_PROCESSING_REQUIRED;
1761 * Note: here total size -1 is done as an
1762 * adjustment for 0 size blob
1764 inc_rfc1001_len(work->response_buf,
1765 le16_to_cpu(rsp->SecurityBufferLength) - 1);
1767 } else if (negblob->MessageType == NtLmAuthenticate) {
1768 rc = ntlm_authenticate(work);
1772 if (!ksmbd_conn_need_reconnect(conn)) {
1773 ksmbd_conn_set_good(conn);
1774 sess->state = SMB2_SESSION_VALID;
1776 if (conn->binding) {
1777 struct preauth_session *preauth_sess;
1780 ksmbd_preauth_session_lookup(conn, sess->id);
1782 list_del(&preauth_sess->preauth_entry);
1783 kfree(preauth_sess);
1786 kfree(sess->Preauth_HashValue);
1787 sess->Preauth_HashValue = NULL;
1789 pr_info_ratelimited("Unknown NTLMSSP message type : 0x%x\n",
1790 le32_to_cpu(negblob->MessageType));
1794 /* TODO: need one more negotiation */
1795 pr_err("Not support the preferred authentication\n");
1799 pr_err("Not support authentication\n");
1805 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1806 else if (rc == -ENOENT)
1807 rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
1808 else if (rc == -EACCES)
1809 rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
1810 else if (rc == -EFAULT)
1811 rsp->hdr.Status = STATUS_NETWORK_SESSION_EXPIRED;
1812 else if (rc == -ENOMEM)
1813 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
1814 else if (rc == -EOPNOTSUPP)
1815 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
1817 rsp->hdr.Status = STATUS_LOGON_FAILURE;
1819 if (conn->use_spnego && conn->mechToken) {
1820 kfree(conn->mechToken);
1821 conn->mechToken = NULL;
1826 * SecurityBufferOffset should be set to zero
1827 * in session setup error response.
1829 rsp->SecurityBufferOffset = 0;
1832 bool try_delay = false;
1835 * To avoid dictionary attacks (repeated session setups rapidly sent) to
1836 * connect to server, ksmbd make a delay of a 5 seconds on session setup
1837 * failure to make it harder to send enough random connection requests
1838 * to break into a server.
1840 if (sess->user && sess->user->flags & KSMBD_USER_FLAG_DELAY_SESSION)
1843 sess->last_active = jiffies;
1844 sess->state = SMB2_SESSION_EXPIRED;
1846 ksmbd_conn_set_need_reconnect(conn);
1848 ksmbd_conn_set_need_negotiate(conn);
1853 ksmbd_conn_unlock(conn);
1858 * smb2_tree_connect() - handler for smb2 tree connect command
1859 * @work: smb work containing smb request buffer
1861 * Return: 0 on success, otherwise error
1863 int smb2_tree_connect(struct ksmbd_work *work)
1865 struct ksmbd_conn *conn = work->conn;
1866 struct smb2_tree_connect_req *req = smb2_get_msg(work->request_buf);
1867 struct smb2_tree_connect_rsp *rsp = smb2_get_msg(work->response_buf);
1868 struct ksmbd_session *sess = work->sess;
1869 char *treename = NULL, *name = NULL;
1870 struct ksmbd_tree_conn_status status;
1871 struct ksmbd_share_config *share;
1874 treename = smb_strndup_from_utf16(req->Buffer,
1875 le16_to_cpu(req->PathLength), true,
1877 if (IS_ERR(treename)) {
1878 pr_err("treename is NULL\n");
1879 status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
1883 name = ksmbd_extract_sharename(conn->um, treename);
1885 status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
1889 ksmbd_debug(SMB, "tree connect request for tree %s treename %s\n",
1892 status = ksmbd_tree_conn_connect(conn, sess, name);
1893 if (status.ret == KSMBD_TREE_CONN_STATUS_OK)
1894 rsp->hdr.Id.SyncId.TreeId = cpu_to_le32(status.tree_conn->id);
1898 share = status.tree_conn->share_conf;
1899 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
1900 ksmbd_debug(SMB, "IPC share path request\n");
1901 rsp->ShareType = SMB2_SHARE_TYPE_PIPE;
1902 rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
1903 FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE |
1904 FILE_DELETE_LE | FILE_READ_CONTROL_LE |
1905 FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
1906 FILE_SYNCHRONIZE_LE;
1908 rsp->ShareType = SMB2_SHARE_TYPE_DISK;
1909 rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
1910 FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE;
1911 if (test_tree_conn_flag(status.tree_conn,
1912 KSMBD_TREE_CONN_FLAG_WRITABLE)) {
1913 rsp->MaximalAccess |= FILE_WRITE_DATA_LE |
1914 FILE_APPEND_DATA_LE | FILE_WRITE_EA_LE |
1915 FILE_DELETE_LE | FILE_WRITE_ATTRIBUTES_LE |
1916 FILE_DELETE_CHILD_LE | FILE_READ_CONTROL_LE |
1917 FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
1918 FILE_SYNCHRONIZE_LE;
1922 status.tree_conn->maximal_access = le32_to_cpu(rsp->MaximalAccess);
1923 if (conn->posix_ext_supported)
1924 status.tree_conn->posix_extensions = true;
1926 rsp->StructureSize = cpu_to_le16(16);
1927 inc_rfc1001_len(work->response_buf, 16);
1929 rsp->Capabilities = 0;
1931 /* default manual caching */
1932 rsp->ShareFlags = SMB2_SHAREFLAG_MANUAL_CACHING;
1934 if (!IS_ERR(treename))
1939 switch (status.ret) {
1940 case KSMBD_TREE_CONN_STATUS_OK:
1941 rsp->hdr.Status = STATUS_SUCCESS;
1946 case KSMBD_TREE_CONN_STATUS_NO_SHARE:
1947 rsp->hdr.Status = STATUS_BAD_NETWORK_NAME;
1950 case KSMBD_TREE_CONN_STATUS_NOMEM:
1951 rsp->hdr.Status = STATUS_NO_MEMORY;
1953 case KSMBD_TREE_CONN_STATUS_ERROR:
1954 case KSMBD_TREE_CONN_STATUS_TOO_MANY_CONNS:
1955 case KSMBD_TREE_CONN_STATUS_TOO_MANY_SESSIONS:
1956 rsp->hdr.Status = STATUS_ACCESS_DENIED;
1959 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1962 rsp->hdr.Status = STATUS_ACCESS_DENIED;
1965 if (status.ret != KSMBD_TREE_CONN_STATUS_OK)
1966 smb2_set_err_rsp(work);
1972 * smb2_create_open_flags() - convert smb open flags to unix open flags
1973 * @file_present: is file already present
1974 * @access: file access flags
1975 * @disposition: file disposition flags
1976 * @may_flags: set with MAY_ flags
1978 * Return: file open flags
1980 static int smb2_create_open_flags(bool file_present, __le32 access,
1984 int oflags = O_NONBLOCK | O_LARGEFILE;
1986 if (access & FILE_READ_DESIRED_ACCESS_LE &&
1987 access & FILE_WRITE_DESIRE_ACCESS_LE) {
1989 *may_flags = MAY_OPEN | MAY_READ | MAY_WRITE;
1990 } else if (access & FILE_WRITE_DESIRE_ACCESS_LE) {
1992 *may_flags = MAY_OPEN | MAY_WRITE;
1995 *may_flags = MAY_OPEN | MAY_READ;
1998 if (access == FILE_READ_ATTRIBUTES_LE)
2002 switch (disposition & FILE_CREATE_MASK_LE) {
2004 case FILE_CREATE_LE:
2006 case FILE_SUPERSEDE_LE:
2007 case FILE_OVERWRITE_LE:
2008 case FILE_OVERWRITE_IF_LE:
2015 switch (disposition & FILE_CREATE_MASK_LE) {
2016 case FILE_SUPERSEDE_LE:
2017 case FILE_CREATE_LE:
2018 case FILE_OPEN_IF_LE:
2019 case FILE_OVERWRITE_IF_LE:
2023 case FILE_OVERWRITE_LE:
2035 * smb2_tree_disconnect() - handler for smb tree connect request
2036 * @work: smb work containing request buffer
2040 int smb2_tree_disconnect(struct ksmbd_work *work)
2042 struct smb2_tree_disconnect_rsp *rsp = smb2_get_msg(work->response_buf);
2043 struct ksmbd_session *sess = work->sess;
2044 struct ksmbd_tree_connect *tcon = work->tcon;
2046 rsp->StructureSize = cpu_to_le16(4);
2047 inc_rfc1001_len(work->response_buf, 4);
2049 ksmbd_debug(SMB, "request\n");
2051 if (!tcon || test_and_set_bit(TREE_CONN_EXPIRE, &tcon->status)) {
2052 struct smb2_tree_disconnect_req *req =
2053 smb2_get_msg(work->request_buf);
2055 ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
2057 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2058 smb2_set_err_rsp(work);
2062 ksmbd_close_tree_conn_fds(work);
2063 ksmbd_tree_conn_disconnect(sess, tcon);
2069 * smb2_session_logoff() - handler for session log off request
2070 * @work: smb work containing request buffer
2074 int smb2_session_logoff(struct ksmbd_work *work)
2076 struct ksmbd_conn *conn = work->conn;
2077 struct smb2_logoff_rsp *rsp = smb2_get_msg(work->response_buf);
2078 struct ksmbd_session *sess;
2079 struct smb2_logoff_req *req = smb2_get_msg(work->request_buf);
2080 u64 sess_id = le64_to_cpu(req->hdr.SessionId);
2082 rsp->StructureSize = cpu_to_le16(4);
2083 inc_rfc1001_len(work->response_buf, 4);
2085 ksmbd_debug(SMB, "request\n");
2087 ksmbd_all_conn_set_status(sess_id, KSMBD_SESS_NEED_RECONNECT);
2088 ksmbd_close_session_fds(work);
2089 ksmbd_conn_wait_idle(conn, sess_id);
2092 * Re-lookup session to validate if session is deleted
2093 * while waiting request complete
2095 sess = ksmbd_session_lookup_all(conn, sess_id);
2096 if (ksmbd_tree_conn_session_logoff(sess)) {
2097 ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
2098 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2099 smb2_set_err_rsp(work);
2103 ksmbd_destroy_file_table(&sess->file_table);
2104 sess->state = SMB2_SESSION_EXPIRED;
2106 ksmbd_free_user(sess->user);
2108 ksmbd_all_conn_set_status(sess_id, KSMBD_SESS_NEED_NEGOTIATE);
2113 * create_smb2_pipe() - create IPC pipe
2114 * @work: smb work containing request buffer
2116 * Return: 0 on success, otherwise error
2118 static noinline int create_smb2_pipe(struct ksmbd_work *work)
2120 struct smb2_create_rsp *rsp = smb2_get_msg(work->response_buf);
2121 struct smb2_create_req *req = smb2_get_msg(work->request_buf);
2126 name = smb_strndup_from_utf16(req->Buffer, le16_to_cpu(req->NameLength),
2127 1, work->conn->local_nls);
2129 rsp->hdr.Status = STATUS_NO_MEMORY;
2130 err = PTR_ERR(name);
2134 id = ksmbd_session_rpc_open(work->sess, name);
2136 pr_err("Unable to open RPC pipe: %d\n", id);
2141 rsp->hdr.Status = STATUS_SUCCESS;
2142 rsp->StructureSize = cpu_to_le16(89);
2143 rsp->OplockLevel = SMB2_OPLOCK_LEVEL_NONE;
2145 rsp->CreateAction = cpu_to_le32(FILE_OPENED);
2147 rsp->CreationTime = cpu_to_le64(0);
2148 rsp->LastAccessTime = cpu_to_le64(0);
2149 rsp->ChangeTime = cpu_to_le64(0);
2150 rsp->AllocationSize = cpu_to_le64(0);
2151 rsp->EndofFile = cpu_to_le64(0);
2152 rsp->FileAttributes = FILE_ATTRIBUTE_NORMAL_LE;
2154 rsp->VolatileFileId = id;
2155 rsp->PersistentFileId = 0;
2156 rsp->CreateContextsOffset = 0;
2157 rsp->CreateContextsLength = 0;
2159 inc_rfc1001_len(work->response_buf, 88); /* StructureSize - 1*/
2166 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2170 rsp->hdr.Status = STATUS_NO_MEMORY;
2177 smb2_set_err_rsp(work);
2182 * smb2_set_ea() - handler for setting extended attributes using set
2184 * @eabuf: set info command buffer
2185 * @buf_len: set info command buffer length
2186 * @path: dentry path for get ea
2188 * Return: 0 on success, otherwise error
2190 static int smb2_set_ea(struct smb2_ea_info *eabuf, unsigned int buf_len,
2191 const struct path *path)
2193 struct mnt_idmap *idmap = mnt_idmap(path->mnt);
2194 char *attr_name = NULL, *value;
2196 unsigned int next = 0;
2198 if (buf_len < sizeof(struct smb2_ea_info) + eabuf->EaNameLength +
2199 le16_to_cpu(eabuf->EaValueLength))
2202 attr_name = kmalloc(XATTR_NAME_MAX + 1, GFP_KERNEL);
2207 if (!eabuf->EaNameLength)
2211 "name : <%s>, name_len : %u, value_len : %u, next : %u\n",
2212 eabuf->name, eabuf->EaNameLength,
2213 le16_to_cpu(eabuf->EaValueLength),
2214 le32_to_cpu(eabuf->NextEntryOffset));
2216 if (eabuf->EaNameLength >
2217 (XATTR_NAME_MAX - XATTR_USER_PREFIX_LEN)) {
2222 memcpy(attr_name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN);
2223 memcpy(&attr_name[XATTR_USER_PREFIX_LEN], eabuf->name,
2224 eabuf->EaNameLength);
2225 attr_name[XATTR_USER_PREFIX_LEN + eabuf->EaNameLength] = '\0';
2226 value = (char *)&eabuf->name + eabuf->EaNameLength + 1;
2228 if (!eabuf->EaValueLength) {
2229 rc = ksmbd_vfs_casexattr_len(idmap,
2232 XATTR_USER_PREFIX_LEN +
2233 eabuf->EaNameLength);
2235 /* delete the EA only when it exits */
2237 rc = ksmbd_vfs_remove_xattr(idmap,
2243 "remove xattr failed(%d)\n",
2249 /* if the EA doesn't exist, just do nothing. */
2252 rc = ksmbd_vfs_setxattr(idmap,
2253 path->dentry, attr_name, value,
2254 le16_to_cpu(eabuf->EaValueLength), 0);
2257 "ksmbd_vfs_setxattr is failed(%d)\n",
2264 next = le32_to_cpu(eabuf->NextEntryOffset);
2265 if (next == 0 || buf_len < next)
2268 eabuf = (struct smb2_ea_info *)((char *)eabuf + next);
2269 if (next < (u32)eabuf->EaNameLength + le16_to_cpu(eabuf->EaValueLength))
2272 } while (next != 0);
2278 static noinline int smb2_set_stream_name_xattr(const struct path *path,
2279 struct ksmbd_file *fp,
2280 char *stream_name, int s_type)
2282 struct mnt_idmap *idmap = mnt_idmap(path->mnt);
2283 size_t xattr_stream_size;
2284 char *xattr_stream_name;
2287 rc = ksmbd_vfs_xattr_stream_name(stream_name,
2294 fp->stream.name = xattr_stream_name;
2295 fp->stream.size = xattr_stream_size;
2297 /* Check if there is stream prefix in xattr space */
2298 rc = ksmbd_vfs_casexattr_len(idmap,
2305 if (fp->cdoption == FILE_OPEN_LE) {
2306 ksmbd_debug(SMB, "XATTR stream name lookup failed: %d\n", rc);
2310 rc = ksmbd_vfs_setxattr(idmap, path->dentry,
2311 xattr_stream_name, NULL, 0, 0);
2313 pr_err("Failed to store XATTR stream name :%d\n", rc);
2317 static int smb2_remove_smb_xattrs(const struct path *path)
2319 struct mnt_idmap *idmap = mnt_idmap(path->mnt);
2320 char *name, *xattr_list = NULL;
2321 ssize_t xattr_list_len;
2324 xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
2325 if (xattr_list_len < 0) {
2327 } else if (!xattr_list_len) {
2328 ksmbd_debug(SMB, "empty xattr in the file\n");
2332 for (name = xattr_list; name - xattr_list < xattr_list_len;
2333 name += strlen(name) + 1) {
2334 ksmbd_debug(SMB, "%s, len %zd\n", name, strlen(name));
2336 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN) &&
2337 !strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
2338 STREAM_PREFIX_LEN)) {
2339 err = ksmbd_vfs_remove_xattr(idmap, path->dentry,
2342 ksmbd_debug(SMB, "remove xattr failed : %s\n",
2351 static int smb2_create_truncate(const struct path *path)
2353 int rc = vfs_truncate(path, 0);
2356 pr_err("vfs_truncate failed, rc %d\n", rc);
2360 rc = smb2_remove_smb_xattrs(path);
2361 if (rc == -EOPNOTSUPP)
2365 "ksmbd_truncate_stream_name_xattr failed, rc %d\n",
2370 static void smb2_new_xattrs(struct ksmbd_tree_connect *tcon, const struct path *path,
2371 struct ksmbd_file *fp)
2373 struct xattr_dos_attrib da = {0};
2376 if (!test_share_config_flag(tcon->share_conf,
2377 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2381 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
2382 da.itime = da.create_time = fp->create_time;
2383 da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
2384 XATTR_DOSINFO_ITIME;
2386 rc = ksmbd_vfs_set_dos_attrib_xattr(mnt_idmap(path->mnt),
2389 ksmbd_debug(SMB, "failed to store file attribute into xattr\n");
2392 static void smb2_update_xattrs(struct ksmbd_tree_connect *tcon,
2393 const struct path *path, struct ksmbd_file *fp)
2395 struct xattr_dos_attrib da;
2398 fp->f_ci->m_fattr &= ~(FILE_ATTRIBUTE_HIDDEN_LE | FILE_ATTRIBUTE_SYSTEM_LE);
2400 /* get FileAttributes from XATTR_NAME_DOS_ATTRIBUTE */
2401 if (!test_share_config_flag(tcon->share_conf,
2402 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2405 rc = ksmbd_vfs_get_dos_attrib_xattr(mnt_idmap(path->mnt),
2408 fp->f_ci->m_fattr = cpu_to_le32(da.attr);
2409 fp->create_time = da.create_time;
2410 fp->itime = da.itime;
2414 static int smb2_creat(struct ksmbd_work *work, struct path *path, char *name,
2415 int open_flags, umode_t posix_mode, bool is_dir)
2417 struct ksmbd_tree_connect *tcon = work->tcon;
2418 struct ksmbd_share_config *share = tcon->share_conf;
2422 if (!(open_flags & O_CREAT))
2425 ksmbd_debug(SMB, "file does not exist, so creating\n");
2426 if (is_dir == true) {
2427 ksmbd_debug(SMB, "creating directory\n");
2429 mode = share_config_directory_mode(share, posix_mode);
2430 rc = ksmbd_vfs_mkdir(work, name, mode);
2434 ksmbd_debug(SMB, "creating regular file\n");
2436 mode = share_config_create_mode(share, posix_mode);
2437 rc = ksmbd_vfs_create(work, name, mode);
2442 rc = ksmbd_vfs_kern_path_locked(work, name, 0, path, 0);
2444 pr_err("cannot get linux path (%s), err = %d\n",
2451 static int smb2_create_sd_buffer(struct ksmbd_work *work,
2452 struct smb2_create_req *req,
2453 const struct path *path)
2455 struct create_context *context;
2456 struct create_sd_buf_req *sd_buf;
2458 if (!req->CreateContextsOffset)
2461 /* Parse SD BUFFER create contexts */
2462 context = smb2_find_context_vals(req, SMB2_CREATE_SD_BUFFER, 4);
2465 else if (IS_ERR(context))
2466 return PTR_ERR(context);
2469 "Set ACLs using SMB2_CREATE_SD_BUFFER context\n");
2470 sd_buf = (struct create_sd_buf_req *)context;
2471 if (le16_to_cpu(context->DataOffset) +
2472 le32_to_cpu(context->DataLength) <
2473 sizeof(struct create_sd_buf_req))
2475 return set_info_sec(work->conn, work->tcon, path, &sd_buf->ntsd,
2476 le32_to_cpu(sd_buf->ccontext.DataLength), true);
2479 static void ksmbd_acls_fattr(struct smb_fattr *fattr,
2480 struct mnt_idmap *idmap,
2481 struct inode *inode)
2483 vfsuid_t vfsuid = i_uid_into_vfsuid(idmap, inode);
2484 vfsgid_t vfsgid = i_gid_into_vfsgid(idmap, inode);
2486 fattr->cf_uid = vfsuid_into_kuid(vfsuid);
2487 fattr->cf_gid = vfsgid_into_kgid(vfsgid);
2488 fattr->cf_mode = inode->i_mode;
2489 fattr->cf_acls = NULL;
2490 fattr->cf_dacls = NULL;
2492 if (IS_ENABLED(CONFIG_FS_POSIX_ACL)) {
2493 fattr->cf_acls = get_inode_acl(inode, ACL_TYPE_ACCESS);
2494 if (S_ISDIR(inode->i_mode))
2495 fattr->cf_dacls = get_inode_acl(inode, ACL_TYPE_DEFAULT);
2500 * smb2_open() - handler for smb file open request
2501 * @work: smb work containing request buffer
2503 * Return: 0 on success, otherwise error
2505 int smb2_open(struct ksmbd_work *work)
2507 struct ksmbd_conn *conn = work->conn;
2508 struct ksmbd_session *sess = work->sess;
2509 struct ksmbd_tree_connect *tcon = work->tcon;
2510 struct smb2_create_req *req;
2511 struct smb2_create_rsp *rsp;
2513 struct ksmbd_share_config *share = tcon->share_conf;
2514 struct ksmbd_file *fp = NULL;
2515 struct file *filp = NULL;
2516 struct mnt_idmap *idmap = NULL;
2518 struct create_context *context;
2519 struct lease_ctx_info *lc = NULL;
2520 struct create_ea_buf_req *ea_buf = NULL;
2521 struct oplock_info *opinfo;
2522 __le32 *next_ptr = NULL;
2523 int req_op_level = 0, open_flags = 0, may_flags = 0, file_info = 0;
2525 int contxt_cnt = 0, query_disk_id = 0;
2526 int maximal_access_ctxt = 0, posix_ctxt = 0;
2530 char *stream_name = NULL;
2531 bool file_present = false, created = false, already_permitted = false;
2532 int share_ret, need_truncate = 0;
2534 umode_t posix_mode = 0;
2535 __le32 daccess, maximal_access = 0;
2537 WORK_BUFFERS(work, req, rsp);
2539 if (req->hdr.NextCommand && !work->next_smb2_rcv_hdr_off &&
2540 (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
2541 ksmbd_debug(SMB, "invalid flag in chained command\n");
2542 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2543 smb2_set_err_rsp(work);
2547 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
2548 ksmbd_debug(SMB, "IPC pipe create request\n");
2549 return create_smb2_pipe(work);
2552 if (req->NameLength) {
2553 if ((req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
2554 *(char *)req->Buffer == '\\') {
2555 pr_err("not allow directory name included leading slash\n");
2560 name = smb2_get_name(req->Buffer,
2561 le16_to_cpu(req->NameLength),
2562 work->conn->local_nls);
2571 ksmbd_debug(SMB, "converted name = %s\n", name);
2572 if (strchr(name, ':')) {
2573 if (!test_share_config_flag(work->tcon->share_conf,
2574 KSMBD_SHARE_FLAG_STREAMS)) {
2578 rc = parse_stream_name(name, &stream_name, &s_type);
2583 rc = ksmbd_validate_filename(name);
2587 if (ksmbd_share_veto_filename(share, name)) {
2589 ksmbd_debug(SMB, "Reject open(), vetoed file: %s\n",
2594 name = kstrdup("", GFP_KERNEL);
2601 req_op_level = req->RequestedOplockLevel;
2602 if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE)
2603 lc = parse_lease_state(req);
2605 if (le32_to_cpu(req->ImpersonationLevel) > le32_to_cpu(IL_DELEGATE)) {
2606 pr_err("Invalid impersonationlevel : 0x%x\n",
2607 le32_to_cpu(req->ImpersonationLevel));
2609 rsp->hdr.Status = STATUS_BAD_IMPERSONATION_LEVEL;
2613 if (req->CreateOptions && !(req->CreateOptions & CREATE_OPTIONS_MASK_LE)) {
2614 pr_err("Invalid create options : 0x%x\n",
2615 le32_to_cpu(req->CreateOptions));
2619 if (req->CreateOptions & FILE_SEQUENTIAL_ONLY_LE &&
2620 req->CreateOptions & FILE_RANDOM_ACCESS_LE)
2621 req->CreateOptions = ~(FILE_SEQUENTIAL_ONLY_LE);
2623 if (req->CreateOptions &
2624 (FILE_OPEN_BY_FILE_ID_LE | CREATE_TREE_CONNECTION |
2625 FILE_RESERVE_OPFILTER_LE)) {
2630 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
2631 if (req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE) {
2634 } else if (req->CreateOptions & FILE_NO_COMPRESSION_LE) {
2635 req->CreateOptions = ~(FILE_NO_COMPRESSION_LE);
2640 if (le32_to_cpu(req->CreateDisposition) >
2641 le32_to_cpu(FILE_OVERWRITE_IF_LE)) {
2642 pr_err("Invalid create disposition : 0x%x\n",
2643 le32_to_cpu(req->CreateDisposition));
2648 if (!(req->DesiredAccess & DESIRED_ACCESS_MASK)) {
2649 pr_err("Invalid desired access : 0x%x\n",
2650 le32_to_cpu(req->DesiredAccess));
2655 if (req->FileAttributes && !(req->FileAttributes & FILE_ATTRIBUTE_MASK_LE)) {
2656 pr_err("Invalid file attribute : 0x%x\n",
2657 le32_to_cpu(req->FileAttributes));
2662 if (req->CreateContextsOffset) {
2663 /* Parse non-durable handle create contexts */
2664 context = smb2_find_context_vals(req, SMB2_CREATE_EA_BUFFER, 4);
2665 if (IS_ERR(context)) {
2666 rc = PTR_ERR(context);
2668 } else if (context) {
2669 ea_buf = (struct create_ea_buf_req *)context;
2670 if (le16_to_cpu(context->DataOffset) +
2671 le32_to_cpu(context->DataLength) <
2672 sizeof(struct create_ea_buf_req)) {
2676 if (req->CreateOptions & FILE_NO_EA_KNOWLEDGE_LE) {
2677 rsp->hdr.Status = STATUS_ACCESS_DENIED;
2683 context = smb2_find_context_vals(req,
2684 SMB2_CREATE_QUERY_MAXIMAL_ACCESS_REQUEST, 4);
2685 if (IS_ERR(context)) {
2686 rc = PTR_ERR(context);
2688 } else if (context) {
2690 "get query maximal access context\n");
2691 maximal_access_ctxt = 1;
2694 context = smb2_find_context_vals(req,
2695 SMB2_CREATE_TIMEWARP_REQUEST, 4);
2696 if (IS_ERR(context)) {
2697 rc = PTR_ERR(context);
2699 } else if (context) {
2700 ksmbd_debug(SMB, "get timewarp context\n");
2705 if (tcon->posix_extensions) {
2706 context = smb2_find_context_vals(req,
2707 SMB2_CREATE_TAG_POSIX, 16);
2708 if (IS_ERR(context)) {
2709 rc = PTR_ERR(context);
2711 } else if (context) {
2712 struct create_posix *posix =
2713 (struct create_posix *)context;
2714 if (le16_to_cpu(context->DataOffset) +
2715 le32_to_cpu(context->DataLength) <
2716 sizeof(struct create_posix) - 4) {
2720 ksmbd_debug(SMB, "get posix context\n");
2722 posix_mode = le32_to_cpu(posix->Mode);
2728 if (ksmbd_override_fsids(work)) {
2733 rc = ksmbd_vfs_kern_path_locked(work, name, LOOKUP_NO_SYMLINKS, &path, 1);
2735 file_present = true;
2737 if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE) {
2739 * If file exists with under flags, return access
2742 if (req->CreateDisposition == FILE_OVERWRITE_IF_LE ||
2743 req->CreateDisposition == FILE_OPEN_IF_LE) {
2748 if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
2750 "User does not have write permission\n");
2754 } else if (d_is_symlink(path.dentry)) {
2759 file_present = true;
2760 idmap = mnt_idmap(path.mnt);
2764 ksmbd_debug(SMB, "can not get linux path for %s, rc = %d\n",
2770 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
2771 if (s_type == DATA_STREAM) {
2773 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2776 if (file_present && S_ISDIR(d_inode(path.dentry)->i_mode) &&
2777 s_type == DATA_STREAM) {
2779 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
2783 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE &&
2784 req->FileAttributes & FILE_ATTRIBUTE_NORMAL_LE) {
2785 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2793 if (file_present && req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE &&
2794 S_ISDIR(d_inode(path.dentry)->i_mode) &&
2795 !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2796 ksmbd_debug(SMB, "open() argument is a directory: %s, %x\n",
2797 name, req->CreateOptions);
2798 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
2803 if (file_present && (req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
2804 !(req->CreateDisposition == FILE_CREATE_LE) &&
2805 !S_ISDIR(d_inode(path.dentry)->i_mode)) {
2806 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2811 if (!stream_name && file_present &&
2812 req->CreateDisposition == FILE_CREATE_LE) {
2817 daccess = smb_map_generic_desired_access(req->DesiredAccess);
2819 if (file_present && !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2820 rc = smb_check_perm_dacl(conn, &path, &daccess,
2826 if (daccess & FILE_MAXIMAL_ACCESS_LE) {
2827 if (!file_present) {
2828 daccess = cpu_to_le32(GENERIC_ALL_FLAGS);
2830 rc = ksmbd_vfs_query_maximal_access(idmap,
2835 already_permitted = true;
2837 maximal_access = daccess;
2840 open_flags = smb2_create_open_flags(file_present, daccess,
2841 req->CreateDisposition,
2844 if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
2845 if (open_flags & O_CREAT) {
2847 "User does not have write permission\n");
2853 /*create file if not present */
2854 if (!file_present) {
2855 rc = smb2_creat(work, &path, name, open_flags, posix_mode,
2856 req->CreateOptions & FILE_DIRECTORY_FILE_LE);
2858 if (rc == -ENOENT) {
2860 rsp->hdr.Status = STATUS_OBJECT_PATH_NOT_FOUND;
2866 idmap = mnt_idmap(path.mnt);
2868 if (le32_to_cpu(ea_buf->ccontext.DataLength) <
2869 sizeof(struct smb2_ea_info)) {
2874 rc = smb2_set_ea(&ea_buf->ea,
2875 le32_to_cpu(ea_buf->ccontext.DataLength),
2877 if (rc == -EOPNOTSUPP)
2882 } else if (!already_permitted) {
2883 /* FILE_READ_ATTRIBUTE is allowed without inode_permission,
2884 * because execute(search) permission on a parent directory,
2885 * is already granted.
2887 if (daccess & ~(FILE_READ_ATTRIBUTES_LE | FILE_READ_CONTROL_LE)) {
2888 rc = inode_permission(idmap,
2889 d_inode(path.dentry),
2894 if ((daccess & FILE_DELETE_LE) ||
2895 (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2896 rc = inode_permission(idmap,
2897 d_inode(path.dentry->d_parent),
2898 MAY_EXEC | MAY_WRITE);
2905 rc = ksmbd_query_inode_status(d_inode(path.dentry->d_parent));
2906 if (rc == KSMBD_INODE_STATUS_PENDING_DELETE) {
2912 filp = dentry_open(&path, open_flags, current_cred());
2915 pr_err("dentry open for dir failed, rc %d\n", rc);
2920 if (!(open_flags & O_TRUNC))
2921 file_info = FILE_OPENED;
2923 file_info = FILE_OVERWRITTEN;
2925 if ((req->CreateDisposition & FILE_CREATE_MASK_LE) ==
2927 file_info = FILE_SUPERSEDED;
2928 } else if (open_flags & O_CREAT) {
2929 file_info = FILE_CREATED;
2932 ksmbd_vfs_set_fadvise(filp, req->CreateOptions);
2934 /* Obtain Volatile-ID */
2935 fp = ksmbd_open_fd(work, filp);
2943 /* Get Persistent-ID */
2944 ksmbd_open_durable_fd(fp);
2945 if (!has_file_id(fp->persistent_id)) {
2950 fp->cdoption = req->CreateDisposition;
2951 fp->daccess = daccess;
2952 fp->saccess = req->ShareAccess;
2953 fp->coption = req->CreateOptions;
2955 /* Set default windows and posix acls if creating new file */
2958 struct inode *inode = d_inode(path.dentry);
2960 posix_acl_rc = ksmbd_vfs_inherit_posix_acl(idmap,
2962 d_inode(path.dentry->d_parent));
2964 ksmbd_debug(SMB, "inherit posix acl failed : %d\n", posix_acl_rc);
2966 if (test_share_config_flag(work->tcon->share_conf,
2967 KSMBD_SHARE_FLAG_ACL_XATTR)) {
2968 rc = smb_inherit_dacl(conn, &path, sess->user->uid,
2973 rc = smb2_create_sd_buffer(work, req, &path);
2976 ksmbd_vfs_set_init_posix_acl(idmap,
2979 if (test_share_config_flag(work->tcon->share_conf,
2980 KSMBD_SHARE_FLAG_ACL_XATTR)) {
2981 struct smb_fattr fattr;
2982 struct smb_ntsd *pntsd;
2983 int pntsd_size, ace_num = 0;
2985 ksmbd_acls_fattr(&fattr, idmap, inode);
2987 ace_num = fattr.cf_acls->a_count;
2989 ace_num += fattr.cf_dacls->a_count;
2991 pntsd = kmalloc(sizeof(struct smb_ntsd) +
2992 sizeof(struct smb_sid) * 3 +
2993 sizeof(struct smb_acl) +
2994 sizeof(struct smb_ace) * ace_num * 2,
2997 posix_acl_release(fattr.cf_acls);
2998 posix_acl_release(fattr.cf_dacls);
3002 rc = build_sec_desc(idmap,
3007 &pntsd_size, &fattr);
3008 posix_acl_release(fattr.cf_acls);
3009 posix_acl_release(fattr.cf_dacls);
3015 rc = ksmbd_vfs_set_sd_xattr(conn,
3022 pr_err("failed to store ntacl in xattr : %d\n",
3031 rc = smb2_set_stream_name_xattr(&path,
3037 file_info = FILE_CREATED;
3040 fp->attrib_only = !(req->DesiredAccess & ~(FILE_READ_ATTRIBUTES_LE |
3041 FILE_WRITE_ATTRIBUTES_LE | FILE_SYNCHRONIZE_LE));
3042 if (!S_ISDIR(file_inode(filp)->i_mode) && open_flags & O_TRUNC &&
3043 !fp->attrib_only && !stream_name) {
3044 smb_break_all_oplock(work, fp);
3048 /* fp should be searchable through ksmbd_inode.m_fp_list
3049 * after daccess, saccess, attrib_only, and stream are
3052 write_lock(&fp->f_ci->m_lock);
3053 list_add(&fp->node, &fp->f_ci->m_fp_list);
3054 write_unlock(&fp->f_ci->m_lock);
3056 /* Check delete pending among previous fp before oplock break */
3057 if (ksmbd_inode_pending_delete(fp)) {
3062 share_ret = ksmbd_smb_check_shared_mode(fp->filp, fp);
3063 if (!test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_OPLOCKS) ||
3064 (req_op_level == SMB2_OPLOCK_LEVEL_LEASE &&
3065 !(conn->vals->capabilities & SMB2_GLOBAL_CAP_LEASING))) {
3066 if (share_ret < 0 && !S_ISDIR(file_inode(fp->filp)->i_mode)) {
3071 if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE) {
3072 req_op_level = smb2_map_lease_to_oplock(lc->req_state);
3074 "lease req for(%s) req oplock state 0x%x, lease state 0x%x\n",
3075 name, req_op_level, lc->req_state);
3076 rc = find_same_lease_key(sess, fp->f_ci, lc);
3079 } else if (open_flags == O_RDONLY &&
3080 (req_op_level == SMB2_OPLOCK_LEVEL_BATCH ||
3081 req_op_level == SMB2_OPLOCK_LEVEL_EXCLUSIVE))
3082 req_op_level = SMB2_OPLOCK_LEVEL_II;
3084 rc = smb_grant_oplock(work, req_op_level,
3085 fp->persistent_id, fp,
3086 le32_to_cpu(req->hdr.Id.SyncId.TreeId),
3092 if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)
3093 ksmbd_fd_set_delete_on_close(fp, file_info);
3095 if (need_truncate) {
3096 rc = smb2_create_truncate(&path);
3101 if (req->CreateContextsOffset) {
3102 struct create_alloc_size_req *az_req;
3104 az_req = (struct create_alloc_size_req *)smb2_find_context_vals(req,
3105 SMB2_CREATE_ALLOCATION_SIZE, 4);
3106 if (IS_ERR(az_req)) {
3107 rc = PTR_ERR(az_req);
3109 } else if (az_req) {
3113 if (le16_to_cpu(az_req->ccontext.DataOffset) +
3114 le32_to_cpu(az_req->ccontext.DataLength) <
3115 sizeof(struct create_alloc_size_req)) {
3119 alloc_size = le64_to_cpu(az_req->AllocationSize);
3121 "request smb2 create allocate size : %llu\n",
3123 smb_break_all_levII_oplock(work, fp, 1);
3124 err = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
3128 "vfs_fallocate is failed : %d\n",
3132 context = smb2_find_context_vals(req, SMB2_CREATE_QUERY_ON_DISK_ID, 4);
3133 if (IS_ERR(context)) {
3134 rc = PTR_ERR(context);
3136 } else if (context) {
3137 ksmbd_debug(SMB, "get query on disk id context\n");
3142 rc = ksmbd_vfs_getattr(&path, &stat);
3146 if (stat.result_mask & STATX_BTIME)
3147 fp->create_time = ksmbd_UnixTimeToNT(stat.btime);
3149 fp->create_time = ksmbd_UnixTimeToNT(stat.ctime);
3150 if (req->FileAttributes || fp->f_ci->m_fattr == 0)
3152 cpu_to_le32(smb2_get_dos_mode(&stat, le32_to_cpu(req->FileAttributes)));
3155 smb2_update_xattrs(tcon, &path, fp);
3157 smb2_new_xattrs(tcon, &path, fp);
3159 memcpy(fp->client_guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE);
3161 rsp->StructureSize = cpu_to_le16(89);
3163 opinfo = rcu_dereference(fp->f_opinfo);
3164 rsp->OplockLevel = opinfo != NULL ? opinfo->level : 0;
3167 rsp->CreateAction = cpu_to_le32(file_info);
3168 rsp->CreationTime = cpu_to_le64(fp->create_time);
3169 time = ksmbd_UnixTimeToNT(stat.atime);
3170 rsp->LastAccessTime = cpu_to_le64(time);
3171 time = ksmbd_UnixTimeToNT(stat.mtime);
3172 rsp->LastWriteTime = cpu_to_le64(time);
3173 time = ksmbd_UnixTimeToNT(stat.ctime);
3174 rsp->ChangeTime = cpu_to_le64(time);
3175 rsp->AllocationSize = S_ISDIR(stat.mode) ? 0 :
3176 cpu_to_le64(stat.blocks << 9);
3177 rsp->EndofFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
3178 rsp->FileAttributes = fp->f_ci->m_fattr;
3182 rsp->PersistentFileId = fp->persistent_id;
3183 rsp->VolatileFileId = fp->volatile_id;
3185 rsp->CreateContextsOffset = 0;
3186 rsp->CreateContextsLength = 0;
3187 inc_rfc1001_len(work->response_buf, 88); /* StructureSize - 1*/
3189 /* If lease is request send lease context response */
3190 if (opinfo && opinfo->is_lease) {
3191 struct create_context *lease_ccontext;
3193 ksmbd_debug(SMB, "lease granted on(%s) lease state 0x%x\n",
3194 name, opinfo->o_lease->state);
3195 rsp->OplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
3197 lease_ccontext = (struct create_context *)rsp->Buffer;
3199 create_lease_buf(rsp->Buffer, opinfo->o_lease);
3200 le32_add_cpu(&rsp->CreateContextsLength,
3201 conn->vals->create_lease_size);
3202 inc_rfc1001_len(work->response_buf,
3203 conn->vals->create_lease_size);
3204 next_ptr = &lease_ccontext->Next;
3205 next_off = conn->vals->create_lease_size;
3208 if (maximal_access_ctxt) {
3209 struct create_context *mxac_ccontext;
3211 if (maximal_access == 0)
3212 ksmbd_vfs_query_maximal_access(idmap,
3215 mxac_ccontext = (struct create_context *)(rsp->Buffer +
3216 le32_to_cpu(rsp->CreateContextsLength));
3218 create_mxac_rsp_buf(rsp->Buffer +
3219 le32_to_cpu(rsp->CreateContextsLength),
3220 le32_to_cpu(maximal_access));
3221 le32_add_cpu(&rsp->CreateContextsLength,
3222 conn->vals->create_mxac_size);
3223 inc_rfc1001_len(work->response_buf,
3224 conn->vals->create_mxac_size);
3226 *next_ptr = cpu_to_le32(next_off);
3227 next_ptr = &mxac_ccontext->Next;
3228 next_off = conn->vals->create_mxac_size;
3231 if (query_disk_id) {
3232 struct create_context *disk_id_ccontext;
3234 disk_id_ccontext = (struct create_context *)(rsp->Buffer +
3235 le32_to_cpu(rsp->CreateContextsLength));
3237 create_disk_id_rsp_buf(rsp->Buffer +
3238 le32_to_cpu(rsp->CreateContextsLength),
3239 stat.ino, tcon->id);
3240 le32_add_cpu(&rsp->CreateContextsLength,
3241 conn->vals->create_disk_id_size);
3242 inc_rfc1001_len(work->response_buf,
3243 conn->vals->create_disk_id_size);
3245 *next_ptr = cpu_to_le32(next_off);
3246 next_ptr = &disk_id_ccontext->Next;
3247 next_off = conn->vals->create_disk_id_size;
3252 create_posix_rsp_buf(rsp->Buffer +
3253 le32_to_cpu(rsp->CreateContextsLength),
3255 le32_add_cpu(&rsp->CreateContextsLength,
3256 conn->vals->create_posix_size);
3257 inc_rfc1001_len(work->response_buf,
3258 conn->vals->create_posix_size);
3260 *next_ptr = cpu_to_le32(next_off);
3263 if (contxt_cnt > 0) {
3264 rsp->CreateContextsOffset =
3265 cpu_to_le32(offsetof(struct smb2_create_rsp, Buffer));
3269 if (file_present || created) {
3270 inode_unlock(d_inode(path.dentry->d_parent));
3273 ksmbd_revert_fsids(work);
3278 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
3279 else if (rc == -EOPNOTSUPP)
3280 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
3281 else if (rc == -EACCES || rc == -ESTALE || rc == -EXDEV)
3282 rsp->hdr.Status = STATUS_ACCESS_DENIED;
3283 else if (rc == -ENOENT)
3284 rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
3285 else if (rc == -EPERM)
3286 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
3287 else if (rc == -EBUSY)
3288 rsp->hdr.Status = STATUS_DELETE_PENDING;
3289 else if (rc == -EBADF)
3290 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
3291 else if (rc == -ENOEXEC)
3292 rsp->hdr.Status = STATUS_DUPLICATE_OBJECTID;
3293 else if (rc == -ENXIO)
3294 rsp->hdr.Status = STATUS_NO_SUCH_DEVICE;
3295 else if (rc == -EEXIST)
3296 rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
3297 else if (rc == -EMFILE)
3298 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
3299 if (!rsp->hdr.Status)
3300 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
3303 ksmbd_fd_put(work, fp);
3304 smb2_set_err_rsp(work);
3305 ksmbd_debug(SMB, "Error response: %x\n", rsp->hdr.Status);
3314 static int readdir_info_level_struct_sz(int info_level)
3316 switch (info_level) {
3317 case FILE_FULL_DIRECTORY_INFORMATION:
3318 return sizeof(struct file_full_directory_info);
3319 case FILE_BOTH_DIRECTORY_INFORMATION:
3320 return sizeof(struct file_both_directory_info);
3321 case FILE_DIRECTORY_INFORMATION:
3322 return sizeof(struct file_directory_info);
3323 case FILE_NAMES_INFORMATION:
3324 return sizeof(struct file_names_info);
3325 case FILEID_FULL_DIRECTORY_INFORMATION:
3326 return sizeof(struct file_id_full_dir_info);
3327 case FILEID_BOTH_DIRECTORY_INFORMATION:
3328 return sizeof(struct file_id_both_directory_info);
3329 case SMB_FIND_FILE_POSIX_INFO:
3330 return sizeof(struct smb2_posix_info);
3336 static int dentry_name(struct ksmbd_dir_info *d_info, int info_level)
3338 switch (info_level) {
3339 case FILE_FULL_DIRECTORY_INFORMATION:
3341 struct file_full_directory_info *ffdinfo;
3343 ffdinfo = (struct file_full_directory_info *)d_info->rptr;
3344 d_info->rptr += le32_to_cpu(ffdinfo->NextEntryOffset);
3345 d_info->name = ffdinfo->FileName;
3346 d_info->name_len = le32_to_cpu(ffdinfo->FileNameLength);
3349 case FILE_BOTH_DIRECTORY_INFORMATION:
3351 struct file_both_directory_info *fbdinfo;
3353 fbdinfo = (struct file_both_directory_info *)d_info->rptr;
3354 d_info->rptr += le32_to_cpu(fbdinfo->NextEntryOffset);
3355 d_info->name = fbdinfo->FileName;
3356 d_info->name_len = le32_to_cpu(fbdinfo->FileNameLength);
3359 case FILE_DIRECTORY_INFORMATION:
3361 struct file_directory_info *fdinfo;
3363 fdinfo = (struct file_directory_info *)d_info->rptr;
3364 d_info->rptr += le32_to_cpu(fdinfo->NextEntryOffset);
3365 d_info->name = fdinfo->FileName;
3366 d_info->name_len = le32_to_cpu(fdinfo->FileNameLength);
3369 case FILE_NAMES_INFORMATION:
3371 struct file_names_info *fninfo;
3373 fninfo = (struct file_names_info *)d_info->rptr;
3374 d_info->rptr += le32_to_cpu(fninfo->NextEntryOffset);
3375 d_info->name = fninfo->FileName;
3376 d_info->name_len = le32_to_cpu(fninfo->FileNameLength);
3379 case FILEID_FULL_DIRECTORY_INFORMATION:
3381 struct file_id_full_dir_info *dinfo;
3383 dinfo = (struct file_id_full_dir_info *)d_info->rptr;
3384 d_info->rptr += le32_to_cpu(dinfo->NextEntryOffset);
3385 d_info->name = dinfo->FileName;
3386 d_info->name_len = le32_to_cpu(dinfo->FileNameLength);
3389 case FILEID_BOTH_DIRECTORY_INFORMATION:
3391 struct file_id_both_directory_info *fibdinfo;
3393 fibdinfo = (struct file_id_both_directory_info *)d_info->rptr;
3394 d_info->rptr += le32_to_cpu(fibdinfo->NextEntryOffset);
3395 d_info->name = fibdinfo->FileName;
3396 d_info->name_len = le32_to_cpu(fibdinfo->FileNameLength);
3399 case SMB_FIND_FILE_POSIX_INFO:
3401 struct smb2_posix_info *posix_info;
3403 posix_info = (struct smb2_posix_info *)d_info->rptr;
3404 d_info->rptr += le32_to_cpu(posix_info->NextEntryOffset);
3405 d_info->name = posix_info->name;
3406 d_info->name_len = le32_to_cpu(posix_info->name_len);
3415 * smb2_populate_readdir_entry() - encode directory entry in smb2 response
3417 * @conn: connection instance
3418 * @info_level: smb information level
3419 * @d_info: structure included variables for query dir
3420 * @ksmbd_kstat: ksmbd wrapper of dirent stat information
3422 * if directory has many entries, find first can't read it fully.
3423 * find next might be called multiple times to read remaining dir entries
3425 * Return: 0 on success, otherwise error
3427 static int smb2_populate_readdir_entry(struct ksmbd_conn *conn, int info_level,
3428 struct ksmbd_dir_info *d_info,
3429 struct ksmbd_kstat *ksmbd_kstat)
3431 int next_entry_offset = 0;
3435 int struct_sz, rc = 0;
3437 conv_name = ksmbd_convert_dir_info_name(d_info,
3443 /* Somehow the name has only terminating NULL bytes */
3446 goto free_conv_name;
3449 struct_sz = readdir_info_level_struct_sz(info_level) + conv_len;
3450 next_entry_offset = ALIGN(struct_sz, KSMBD_DIR_INFO_ALIGNMENT);
3451 d_info->last_entry_off_align = next_entry_offset - struct_sz;
3453 if (next_entry_offset > d_info->out_buf_len) {
3454 d_info->out_buf_len = 0;
3456 goto free_conv_name;
3459 kstat = d_info->wptr;
3460 if (info_level != FILE_NAMES_INFORMATION)
3461 kstat = ksmbd_vfs_init_kstat(&d_info->wptr, ksmbd_kstat);
3463 switch (info_level) {
3464 case FILE_FULL_DIRECTORY_INFORMATION:
3466 struct file_full_directory_info *ffdinfo;
3468 ffdinfo = (struct file_full_directory_info *)kstat;
3469 ffdinfo->FileNameLength = cpu_to_le32(conv_len);
3471 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3472 if (ffdinfo->EaSize)
3473 ffdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3474 if (d_info->hide_dot_file && d_info->name[0] == '.')
3475 ffdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3476 memcpy(ffdinfo->FileName, conv_name, conv_len);
3477 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3480 case FILE_BOTH_DIRECTORY_INFORMATION:
3482 struct file_both_directory_info *fbdinfo;
3484 fbdinfo = (struct file_both_directory_info *)kstat;
3485 fbdinfo->FileNameLength = cpu_to_le32(conv_len);
3487 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3488 if (fbdinfo->EaSize)
3489 fbdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3490 fbdinfo->ShortNameLength = 0;
3491 fbdinfo->Reserved = 0;
3492 if (d_info->hide_dot_file && d_info->name[0] == '.')
3493 fbdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3494 memcpy(fbdinfo->FileName, conv_name, conv_len);
3495 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3498 case FILE_DIRECTORY_INFORMATION:
3500 struct file_directory_info *fdinfo;
3502 fdinfo = (struct file_directory_info *)kstat;
3503 fdinfo->FileNameLength = cpu_to_le32(conv_len);
3504 if (d_info->hide_dot_file && d_info->name[0] == '.')
3505 fdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3506 memcpy(fdinfo->FileName, conv_name, conv_len);
3507 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3510 case FILE_NAMES_INFORMATION:
3512 struct file_names_info *fninfo;
3514 fninfo = (struct file_names_info *)kstat;
3515 fninfo->FileNameLength = cpu_to_le32(conv_len);
3516 memcpy(fninfo->FileName, conv_name, conv_len);
3517 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3520 case FILEID_FULL_DIRECTORY_INFORMATION:
3522 struct file_id_full_dir_info *dinfo;
3524 dinfo = (struct file_id_full_dir_info *)kstat;
3525 dinfo->FileNameLength = cpu_to_le32(conv_len);
3527 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3529 dinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3530 dinfo->Reserved = 0;
3531 dinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
3532 if (d_info->hide_dot_file && d_info->name[0] == '.')
3533 dinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3534 memcpy(dinfo->FileName, conv_name, conv_len);
3535 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3538 case FILEID_BOTH_DIRECTORY_INFORMATION:
3540 struct file_id_both_directory_info *fibdinfo;
3542 fibdinfo = (struct file_id_both_directory_info *)kstat;
3543 fibdinfo->FileNameLength = cpu_to_le32(conv_len);
3545 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3546 if (fibdinfo->EaSize)
3547 fibdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3548 fibdinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
3549 fibdinfo->ShortNameLength = 0;
3550 fibdinfo->Reserved = 0;
3551 fibdinfo->Reserved2 = cpu_to_le16(0);
3552 if (d_info->hide_dot_file && d_info->name[0] == '.')
3553 fibdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3554 memcpy(fibdinfo->FileName, conv_name, conv_len);
3555 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3558 case SMB_FIND_FILE_POSIX_INFO:
3560 struct smb2_posix_info *posix_info;
3563 posix_info = (struct smb2_posix_info *)kstat;
3564 posix_info->Ignored = 0;
3565 posix_info->CreationTime = cpu_to_le64(ksmbd_kstat->create_time);
3566 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->ctime);
3567 posix_info->ChangeTime = cpu_to_le64(time);
3568 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->atime);
3569 posix_info->LastAccessTime = cpu_to_le64(time);
3570 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->mtime);
3571 posix_info->LastWriteTime = cpu_to_le64(time);
3572 posix_info->EndOfFile = cpu_to_le64(ksmbd_kstat->kstat->size);
3573 posix_info->AllocationSize = cpu_to_le64(ksmbd_kstat->kstat->blocks << 9);
3574 posix_info->DeviceId = cpu_to_le32(ksmbd_kstat->kstat->rdev);
3575 posix_info->HardLinks = cpu_to_le32(ksmbd_kstat->kstat->nlink);
3576 posix_info->Mode = cpu_to_le32(ksmbd_kstat->kstat->mode & 0777);
3577 posix_info->Inode = cpu_to_le64(ksmbd_kstat->kstat->ino);
3578 posix_info->DosAttributes =
3579 S_ISDIR(ksmbd_kstat->kstat->mode) ?
3580 FILE_ATTRIBUTE_DIRECTORY_LE : FILE_ATTRIBUTE_ARCHIVE_LE;
3581 if (d_info->hide_dot_file && d_info->name[0] == '.')
3582 posix_info->DosAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3584 * SidBuffer(32) contain two sids(Domain sid(16), UNIX group sid(16)).
3585 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) +
3586 * sub_auth(4 * 1(num_subauth)) + RID(4).
3588 id_to_sid(from_kuid_munged(&init_user_ns, ksmbd_kstat->kstat->uid),
3589 SIDUNIX_USER, (struct smb_sid *)&posix_info->SidBuffer[0]);
3590 id_to_sid(from_kgid_munged(&init_user_ns, ksmbd_kstat->kstat->gid),
3591 SIDUNIX_GROUP, (struct smb_sid *)&posix_info->SidBuffer[16]);
3592 memcpy(posix_info->name, conv_name, conv_len);
3593 posix_info->name_len = cpu_to_le32(conv_len);
3594 posix_info->NextEntryOffset = cpu_to_le32(next_entry_offset);
3598 } /* switch (info_level) */
3600 d_info->last_entry_offset = d_info->data_count;
3601 d_info->data_count += next_entry_offset;
3602 d_info->out_buf_len -= next_entry_offset;
3603 d_info->wptr += next_entry_offset;
3606 "info_level : %d, buf_len :%d, next_offset : %d, data_count : %d\n",
3607 info_level, d_info->out_buf_len,
3608 next_entry_offset, d_info->data_count);
3615 struct smb2_query_dir_private {
3616 struct ksmbd_work *work;
3617 char *search_pattern;
3618 struct ksmbd_file *dir_fp;
3620 struct ksmbd_dir_info *d_info;
3624 static void lock_dir(struct ksmbd_file *dir_fp)
3626 struct dentry *dir = dir_fp->filp->f_path.dentry;
3628 inode_lock_nested(d_inode(dir), I_MUTEX_PARENT);
3631 static void unlock_dir(struct ksmbd_file *dir_fp)
3633 struct dentry *dir = dir_fp->filp->f_path.dentry;
3635 inode_unlock(d_inode(dir));
3638 static int process_query_dir_entries(struct smb2_query_dir_private *priv)
3640 struct mnt_idmap *idmap = file_mnt_idmap(priv->dir_fp->filp);
3642 struct ksmbd_kstat ksmbd_kstat;
3646 for (i = 0; i < priv->d_info->num_entry; i++) {
3647 struct dentry *dent;
3649 if (dentry_name(priv->d_info, priv->info_level))
3652 lock_dir(priv->dir_fp);
3653 dent = lookup_one(idmap, priv->d_info->name,
3654 priv->dir_fp->filp->f_path.dentry,
3655 priv->d_info->name_len);
3656 unlock_dir(priv->dir_fp);
3659 ksmbd_debug(SMB, "Cannot lookup `%s' [%ld]\n",
3664 if (unlikely(d_is_negative(dent))) {
3666 ksmbd_debug(SMB, "Negative dentry `%s'\n",
3667 priv->d_info->name);
3671 ksmbd_kstat.kstat = &kstat;
3672 if (priv->info_level != FILE_NAMES_INFORMATION)
3673 ksmbd_vfs_fill_dentry_attrs(priv->work,
3678 rc = smb2_populate_readdir_entry(priv->work->conn,
3689 static int reserve_populate_dentry(struct ksmbd_dir_info *d_info,
3694 int next_entry_offset;
3696 struct_sz = readdir_info_level_struct_sz(info_level);
3697 if (struct_sz == -EOPNOTSUPP)
3700 conv_len = (d_info->name_len + 1) * 2;
3701 next_entry_offset = ALIGN(struct_sz + conv_len,
3702 KSMBD_DIR_INFO_ALIGNMENT);
3704 if (next_entry_offset > d_info->out_buf_len) {
3705 d_info->out_buf_len = 0;
3709 switch (info_level) {
3710 case FILE_FULL_DIRECTORY_INFORMATION:
3712 struct file_full_directory_info *ffdinfo;
3714 ffdinfo = (struct file_full_directory_info *)d_info->wptr;
3715 memcpy(ffdinfo->FileName, d_info->name, d_info->name_len);
3716 ffdinfo->FileName[d_info->name_len] = 0x00;
3717 ffdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3718 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3721 case FILE_BOTH_DIRECTORY_INFORMATION:
3723 struct file_both_directory_info *fbdinfo;
3725 fbdinfo = (struct file_both_directory_info *)d_info->wptr;
3726 memcpy(fbdinfo->FileName, d_info->name, d_info->name_len);
3727 fbdinfo->FileName[d_info->name_len] = 0x00;
3728 fbdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3729 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3732 case FILE_DIRECTORY_INFORMATION:
3734 struct file_directory_info *fdinfo;
3736 fdinfo = (struct file_directory_info *)d_info->wptr;
3737 memcpy(fdinfo->FileName, d_info->name, d_info->name_len);
3738 fdinfo->FileName[d_info->name_len] = 0x00;
3739 fdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3740 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3743 case FILE_NAMES_INFORMATION:
3745 struct file_names_info *fninfo;
3747 fninfo = (struct file_names_info *)d_info->wptr;
3748 memcpy(fninfo->FileName, d_info->name, d_info->name_len);
3749 fninfo->FileName[d_info->name_len] = 0x00;
3750 fninfo->FileNameLength = cpu_to_le32(d_info->name_len);
3751 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3754 case FILEID_FULL_DIRECTORY_INFORMATION:
3756 struct file_id_full_dir_info *dinfo;
3758 dinfo = (struct file_id_full_dir_info *)d_info->wptr;
3759 memcpy(dinfo->FileName, d_info->name, d_info->name_len);
3760 dinfo->FileName[d_info->name_len] = 0x00;
3761 dinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3762 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3765 case FILEID_BOTH_DIRECTORY_INFORMATION:
3767 struct file_id_both_directory_info *fibdinfo;
3769 fibdinfo = (struct file_id_both_directory_info *)d_info->wptr;
3770 memcpy(fibdinfo->FileName, d_info->name, d_info->name_len);
3771 fibdinfo->FileName[d_info->name_len] = 0x00;
3772 fibdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3773 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3776 case SMB_FIND_FILE_POSIX_INFO:
3778 struct smb2_posix_info *posix_info;
3780 posix_info = (struct smb2_posix_info *)d_info->wptr;
3781 memcpy(posix_info->name, d_info->name, d_info->name_len);
3782 posix_info->name[d_info->name_len] = 0x00;
3783 posix_info->name_len = cpu_to_le32(d_info->name_len);
3784 posix_info->NextEntryOffset =
3785 cpu_to_le32(next_entry_offset);
3788 } /* switch (info_level) */
3790 d_info->num_entry++;
3791 d_info->out_buf_len -= next_entry_offset;
3792 d_info->wptr += next_entry_offset;
3796 static bool __query_dir(struct dir_context *ctx, const char *name, int namlen,
3797 loff_t offset, u64 ino, unsigned int d_type)
3799 struct ksmbd_readdir_data *buf;
3800 struct smb2_query_dir_private *priv;
3801 struct ksmbd_dir_info *d_info;
3804 buf = container_of(ctx, struct ksmbd_readdir_data, ctx);
3805 priv = buf->private;
3806 d_info = priv->d_info;
3808 /* dot and dotdot entries are already reserved */
3809 if (!strcmp(".", name) || !strcmp("..", name))
3811 if (ksmbd_share_veto_filename(priv->work->tcon->share_conf, name))
3813 if (!match_pattern(name, namlen, priv->search_pattern))
3816 d_info->name = name;
3817 d_info->name_len = namlen;
3818 rc = reserve_populate_dentry(d_info, priv->info_level);
3821 if (d_info->flags & SMB2_RETURN_SINGLE_ENTRY)
3822 d_info->out_buf_len = 0;
3826 static int verify_info_level(int info_level)
3828 switch (info_level) {
3829 case FILE_FULL_DIRECTORY_INFORMATION:
3830 case FILE_BOTH_DIRECTORY_INFORMATION:
3831 case FILE_DIRECTORY_INFORMATION:
3832 case FILE_NAMES_INFORMATION:
3833 case FILEID_FULL_DIRECTORY_INFORMATION:
3834 case FILEID_BOTH_DIRECTORY_INFORMATION:
3835 case SMB_FIND_FILE_POSIX_INFO:
3844 static int smb2_resp_buf_len(struct ksmbd_work *work, unsigned short hdr2_len)
3848 free_len = (int)(work->response_sz -
3849 (get_rfc1002_len(work->response_buf) + 4)) - hdr2_len;
3853 static int smb2_calc_max_out_buf_len(struct ksmbd_work *work,
3854 unsigned short hdr2_len,
3855 unsigned int out_buf_len)
3859 if (out_buf_len > work->conn->vals->max_trans_size)
3862 free_len = smb2_resp_buf_len(work, hdr2_len);
3866 return min_t(int, out_buf_len, free_len);
3869 int smb2_query_dir(struct ksmbd_work *work)
3871 struct ksmbd_conn *conn = work->conn;
3872 struct smb2_query_directory_req *req;
3873 struct smb2_query_directory_rsp *rsp;
3874 struct ksmbd_share_config *share = work->tcon->share_conf;
3875 struct ksmbd_file *dir_fp = NULL;
3876 struct ksmbd_dir_info d_info;
3878 char *srch_ptr = NULL;
3879 unsigned char srch_flag;
3881 struct smb2_query_dir_private query_dir_private = {NULL, };
3883 WORK_BUFFERS(work, req, rsp);
3885 if (ksmbd_override_fsids(work)) {
3886 rsp->hdr.Status = STATUS_NO_MEMORY;
3887 smb2_set_err_rsp(work);
3891 rc = verify_info_level(req->FileInformationClass);
3897 dir_fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
3903 if (!(dir_fp->daccess & FILE_LIST_DIRECTORY_LE) ||
3904 inode_permission(file_mnt_idmap(dir_fp->filp),
3905 file_inode(dir_fp->filp),
3906 MAY_READ | MAY_EXEC)) {
3907 pr_err("no right to enumerate directory (%pD)\n", dir_fp->filp);
3912 if (!S_ISDIR(file_inode(dir_fp->filp)->i_mode)) {
3913 pr_err("can't do query dir for a file\n");
3918 srch_flag = req->Flags;
3919 srch_ptr = smb_strndup_from_utf16(req->Buffer,
3920 le16_to_cpu(req->FileNameLength), 1,
3922 if (IS_ERR(srch_ptr)) {
3923 ksmbd_debug(SMB, "Search Pattern not found\n");
3927 ksmbd_debug(SMB, "Search pattern is %s\n", srch_ptr);
3930 if (srch_flag & SMB2_REOPEN || srch_flag & SMB2_RESTART_SCANS) {
3931 ksmbd_debug(SMB, "Restart directory scan\n");
3932 generic_file_llseek(dir_fp->filp, 0, SEEK_SET);
3935 memset(&d_info, 0, sizeof(struct ksmbd_dir_info));
3936 d_info.wptr = (char *)rsp->Buffer;
3937 d_info.rptr = (char *)rsp->Buffer;
3938 d_info.out_buf_len =
3939 smb2_calc_max_out_buf_len(work, 8,
3940 le32_to_cpu(req->OutputBufferLength));
3941 if (d_info.out_buf_len < 0) {
3945 d_info.flags = srch_flag;
3948 * reserve dot and dotdot entries in head of buffer
3951 rc = ksmbd_populate_dot_dotdot_entries(work, req->FileInformationClass,
3952 dir_fp, &d_info, srch_ptr,
3953 smb2_populate_readdir_entry);
3959 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_HIDE_DOT_FILES))
3960 d_info.hide_dot_file = true;
3962 buffer_sz = d_info.out_buf_len;
3963 d_info.rptr = d_info.wptr;
3964 query_dir_private.work = work;
3965 query_dir_private.search_pattern = srch_ptr;
3966 query_dir_private.dir_fp = dir_fp;
3967 query_dir_private.d_info = &d_info;
3968 query_dir_private.info_level = req->FileInformationClass;
3969 dir_fp->readdir_data.private = &query_dir_private;
3970 set_ctx_actor(&dir_fp->readdir_data.ctx, __query_dir);
3972 rc = iterate_dir(dir_fp->filp, &dir_fp->readdir_data.ctx);
3974 * req->OutputBufferLength is too small to contain even one entry.
3975 * In this case, it immediately returns OutputBufferLength 0 to client.
3977 if (!d_info.out_buf_len && !d_info.num_entry)
3979 if (rc > 0 || rc == -ENOSPC)
3984 d_info.wptr = d_info.rptr;
3985 d_info.out_buf_len = buffer_sz;
3986 rc = process_query_dir_entries(&query_dir_private);
3990 if (!d_info.data_count && d_info.out_buf_len >= 0) {
3991 if (srch_flag & SMB2_RETURN_SINGLE_ENTRY && !is_asterisk(srch_ptr)) {
3992 rsp->hdr.Status = STATUS_NO_SUCH_FILE;
3994 dir_fp->dot_dotdot[0] = dir_fp->dot_dotdot[1] = 0;
3995 rsp->hdr.Status = STATUS_NO_MORE_FILES;
3997 rsp->StructureSize = cpu_to_le16(9);
3998 rsp->OutputBufferOffset = cpu_to_le16(0);
3999 rsp->OutputBufferLength = cpu_to_le32(0);
4001 inc_rfc1001_len(work->response_buf, 9);
4004 ((struct file_directory_info *)
4005 ((char *)rsp->Buffer + d_info.last_entry_offset))
4006 ->NextEntryOffset = 0;
4007 if (d_info.data_count >= d_info.last_entry_off_align)
4008 d_info.data_count -= d_info.last_entry_off_align;
4010 rsp->StructureSize = cpu_to_le16(9);
4011 rsp->OutputBufferOffset = cpu_to_le16(72);
4012 rsp->OutputBufferLength = cpu_to_le32(d_info.data_count);
4013 inc_rfc1001_len(work->response_buf, 8 + d_info.data_count);
4017 ksmbd_fd_put(work, dir_fp);
4018 ksmbd_revert_fsids(work);
4022 pr_err("error while processing smb2 query dir rc = %d\n", rc);
4027 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
4028 else if (rc == -EACCES)
4029 rsp->hdr.Status = STATUS_ACCESS_DENIED;
4030 else if (rc == -ENOENT)
4031 rsp->hdr.Status = STATUS_NO_SUCH_FILE;
4032 else if (rc == -EBADF)
4033 rsp->hdr.Status = STATUS_FILE_CLOSED;
4034 else if (rc == -ENOMEM)
4035 rsp->hdr.Status = STATUS_NO_MEMORY;
4036 else if (rc == -EFAULT)
4037 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
4038 else if (rc == -EIO)
4039 rsp->hdr.Status = STATUS_FILE_CORRUPT_ERROR;
4040 if (!rsp->hdr.Status)
4041 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
4043 smb2_set_err_rsp(work);
4044 ksmbd_fd_put(work, dir_fp);
4045 ksmbd_revert_fsids(work);
4050 * buffer_check_err() - helper function to check buffer errors
4051 * @reqOutputBufferLength: max buffer length expected in command response
4052 * @rsp: query info response buffer contains output buffer length
4053 * @rsp_org: base response buffer pointer in case of chained response
4054 * @infoclass_size: query info class response buffer size
4056 * Return: 0 on success, otherwise error
4058 static int buffer_check_err(int reqOutputBufferLength,
4059 struct smb2_query_info_rsp *rsp,
4060 void *rsp_org, int infoclass_size)
4062 if (reqOutputBufferLength < le32_to_cpu(rsp->OutputBufferLength)) {
4063 if (reqOutputBufferLength < infoclass_size) {
4064 pr_err("Invalid Buffer Size Requested\n");
4065 rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
4066 *(__be32 *)rsp_org = cpu_to_be32(sizeof(struct smb2_hdr));
4070 ksmbd_debug(SMB, "Buffer Overflow\n");
4071 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
4072 *(__be32 *)rsp_org = cpu_to_be32(sizeof(struct smb2_hdr) +
4073 reqOutputBufferLength);
4074 rsp->OutputBufferLength = cpu_to_le32(reqOutputBufferLength);
4079 static void get_standard_info_pipe(struct smb2_query_info_rsp *rsp,
4082 struct smb2_file_standard_info *sinfo;
4084 sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
4086 sinfo->AllocationSize = cpu_to_le64(4096);
4087 sinfo->EndOfFile = cpu_to_le64(0);
4088 sinfo->NumberOfLinks = cpu_to_le32(1);
4089 sinfo->DeletePending = 1;
4090 sinfo->Directory = 0;
4091 rsp->OutputBufferLength =
4092 cpu_to_le32(sizeof(struct smb2_file_standard_info));
4093 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_standard_info));
4096 static void get_internal_info_pipe(struct smb2_query_info_rsp *rsp, u64 num,
4099 struct smb2_file_internal_info *file_info;
4101 file_info = (struct smb2_file_internal_info *)rsp->Buffer;
4103 /* any unique number */
4104 file_info->IndexNumber = cpu_to_le64(num | (1ULL << 63));
4105 rsp->OutputBufferLength =
4106 cpu_to_le32(sizeof(struct smb2_file_internal_info));
4107 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_internal_info));
4110 static int smb2_get_info_file_pipe(struct ksmbd_session *sess,
4111 struct smb2_query_info_req *req,
4112 struct smb2_query_info_rsp *rsp,
4119 * Windows can sometime send query file info request on
4120 * pipe without opening it, checking error condition here
4122 id = req->VolatileFileId;
4123 if (!ksmbd_session_rpc_method(sess, id))
4126 ksmbd_debug(SMB, "FileInfoClass %u, FileId 0x%llx\n",
4127 req->FileInfoClass, req->VolatileFileId);
4129 switch (req->FileInfoClass) {
4130 case FILE_STANDARD_INFORMATION:
4131 get_standard_info_pipe(rsp, rsp_org);
4132 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4134 FILE_STANDARD_INFORMATION_SIZE);
4136 case FILE_INTERNAL_INFORMATION:
4137 get_internal_info_pipe(rsp, id, rsp_org);
4138 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4140 FILE_INTERNAL_INFORMATION_SIZE);
4143 ksmbd_debug(SMB, "smb2_info_file_pipe for %u not supported\n",
4144 req->FileInfoClass);
4151 * smb2_get_ea() - handler for smb2 get extended attribute command
4152 * @work: smb work containing query info command buffer
4153 * @fp: ksmbd_file pointer
4154 * @req: get extended attribute request
4155 * @rsp: response buffer pointer
4156 * @rsp_org: base response buffer pointer in case of chained response
4158 * Return: 0 on success, otherwise error
4160 static int smb2_get_ea(struct ksmbd_work *work, struct ksmbd_file *fp,
4161 struct smb2_query_info_req *req,
4162 struct smb2_query_info_rsp *rsp, void *rsp_org)
4164 struct smb2_ea_info *eainfo, *prev_eainfo;
4165 char *name, *ptr, *xattr_list = NULL, *buf;
4166 int rc, name_len, value_len, xattr_list_len, idx;
4167 ssize_t buf_free_len, alignment_bytes, next_offset, rsp_data_cnt = 0;
4168 struct smb2_ea_info_req *ea_req = NULL;
4169 const struct path *path;
4170 struct mnt_idmap *idmap = file_mnt_idmap(fp->filp);
4172 if (!(fp->daccess & FILE_READ_EA_LE)) {
4173 pr_err("Not permitted to read ext attr : 0x%x\n",
4178 path = &fp->filp->f_path;
4179 /* single EA entry is requested with given user.* name */
4180 if (req->InputBufferLength) {
4181 if (le32_to_cpu(req->InputBufferLength) <
4182 sizeof(struct smb2_ea_info_req))
4185 ea_req = (struct smb2_ea_info_req *)req->Buffer;
4187 /* need to send all EAs, if no specific EA is requested*/
4188 if (le32_to_cpu(req->Flags) & SL_RETURN_SINGLE_ENTRY)
4190 "All EAs are requested but need to send single EA entry in rsp flags 0x%x\n",
4191 le32_to_cpu(req->Flags));
4195 smb2_calc_max_out_buf_len(work, 8,
4196 le32_to_cpu(req->OutputBufferLength));
4197 if (buf_free_len < 0)
4200 rc = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
4202 rsp->hdr.Status = STATUS_INVALID_HANDLE;
4204 } else if (!rc) { /* there is no EA in the file */
4205 ksmbd_debug(SMB, "no ea data in the file\n");
4208 xattr_list_len = rc;
4210 ptr = (char *)rsp->Buffer;
4211 eainfo = (struct smb2_ea_info *)ptr;
4212 prev_eainfo = eainfo;
4215 while (idx < xattr_list_len) {
4216 name = xattr_list + idx;
4217 name_len = strlen(name);
4219 ksmbd_debug(SMB, "%s, len %d\n", name, name_len);
4220 idx += name_len + 1;
4223 * CIFS does not support EA other than user.* namespace,
4224 * still keep the framework generic, to list other attrs
4227 if (strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4230 if (!strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
4234 if (req->InputBufferLength &&
4235 strncmp(&name[XATTR_USER_PREFIX_LEN], ea_req->name,
4236 ea_req->EaNameLength))
4239 if (!strncmp(&name[XATTR_USER_PREFIX_LEN],
4240 DOS_ATTRIBUTE_PREFIX, DOS_ATTRIBUTE_PREFIX_LEN))
4243 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4244 name_len -= XATTR_USER_PREFIX_LEN;
4246 ptr = (char *)(&eainfo->name + name_len + 1);
4247 buf_free_len -= (offsetof(struct smb2_ea_info, name) +
4249 /* bailout if xattr can't fit in buf_free_len */
4250 value_len = ksmbd_vfs_getxattr(idmap, path->dentry,
4252 if (value_len <= 0) {
4254 rsp->hdr.Status = STATUS_INVALID_HANDLE;
4258 buf_free_len -= value_len;
4259 if (buf_free_len < 0) {
4264 memcpy(ptr, buf, value_len);
4269 eainfo->EaNameLength = name_len;
4271 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4272 memcpy(eainfo->name, &name[XATTR_USER_PREFIX_LEN],
4275 memcpy(eainfo->name, name, name_len);
4277 eainfo->name[name_len] = '\0';
4278 eainfo->EaValueLength = cpu_to_le16(value_len);
4279 next_offset = offsetof(struct smb2_ea_info, name) +
4280 name_len + 1 + value_len;
4282 /* align next xattr entry at 4 byte bundary */
4283 alignment_bytes = ((next_offset + 3) & ~3) - next_offset;
4284 if (alignment_bytes) {
4285 memset(ptr, '\0', alignment_bytes);
4286 ptr += alignment_bytes;
4287 next_offset += alignment_bytes;
4288 buf_free_len -= alignment_bytes;
4290 eainfo->NextEntryOffset = cpu_to_le32(next_offset);
4291 prev_eainfo = eainfo;
4292 eainfo = (struct smb2_ea_info *)ptr;
4293 rsp_data_cnt += next_offset;
4295 if (req->InputBufferLength) {
4296 ksmbd_debug(SMB, "single entry requested\n");
4301 /* no more ea entries */
4302 prev_eainfo->NextEntryOffset = 0;
4305 if (rsp_data_cnt == 0)
4306 rsp->hdr.Status = STATUS_NO_EAS_ON_FILE;
4307 rsp->OutputBufferLength = cpu_to_le32(rsp_data_cnt);
4308 inc_rfc1001_len(rsp_org, rsp_data_cnt);
4314 static void get_file_access_info(struct smb2_query_info_rsp *rsp,
4315 struct ksmbd_file *fp, void *rsp_org)
4317 struct smb2_file_access_info *file_info;
4319 file_info = (struct smb2_file_access_info *)rsp->Buffer;
4320 file_info->AccessFlags = fp->daccess;
4321 rsp->OutputBufferLength =
4322 cpu_to_le32(sizeof(struct smb2_file_access_info));
4323 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_access_info));
4326 static int get_file_basic_info(struct smb2_query_info_rsp *rsp,
4327 struct ksmbd_file *fp, void *rsp_org)
4329 struct smb2_file_basic_info *basic_info;
4333 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4334 pr_err("no right to read the attributes : 0x%x\n",
4339 basic_info = (struct smb2_file_basic_info *)rsp->Buffer;
4340 generic_fillattr(file_mnt_idmap(fp->filp), file_inode(fp->filp),
4342 basic_info->CreationTime = cpu_to_le64(fp->create_time);
4343 time = ksmbd_UnixTimeToNT(stat.atime);
4344 basic_info->LastAccessTime = cpu_to_le64(time);
4345 time = ksmbd_UnixTimeToNT(stat.mtime);
4346 basic_info->LastWriteTime = cpu_to_le64(time);
4347 time = ksmbd_UnixTimeToNT(stat.ctime);
4348 basic_info->ChangeTime = cpu_to_le64(time);
4349 basic_info->Attributes = fp->f_ci->m_fattr;
4350 basic_info->Pad1 = 0;
4351 rsp->OutputBufferLength =
4352 cpu_to_le32(sizeof(struct smb2_file_basic_info));
4353 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_basic_info));
4357 static unsigned long long get_allocation_size(struct inode *inode,
4360 unsigned long long alloc_size = 0;
4362 if (!S_ISDIR(stat->mode)) {
4363 if ((inode->i_blocks << 9) <= stat->size)
4364 alloc_size = stat->size;
4366 alloc_size = inode->i_blocks << 9;
4372 static void get_file_standard_info(struct smb2_query_info_rsp *rsp,
4373 struct ksmbd_file *fp, void *rsp_org)
4375 struct smb2_file_standard_info *sinfo;
4376 unsigned int delete_pending;
4377 struct inode *inode;
4380 inode = file_inode(fp->filp);
4381 generic_fillattr(file_mnt_idmap(fp->filp), inode, &stat);
4383 sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
4384 delete_pending = ksmbd_inode_pending_delete(fp);
4386 sinfo->AllocationSize = cpu_to_le64(get_allocation_size(inode, &stat));
4387 sinfo->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4388 sinfo->NumberOfLinks = cpu_to_le32(get_nlink(&stat) - delete_pending);
4389 sinfo->DeletePending = delete_pending;
4390 sinfo->Directory = S_ISDIR(stat.mode) ? 1 : 0;
4391 rsp->OutputBufferLength =
4392 cpu_to_le32(sizeof(struct smb2_file_standard_info));
4393 inc_rfc1001_len(rsp_org,
4394 sizeof(struct smb2_file_standard_info));
4397 static void get_file_alignment_info(struct smb2_query_info_rsp *rsp,
4400 struct smb2_file_alignment_info *file_info;
4402 file_info = (struct smb2_file_alignment_info *)rsp->Buffer;
4403 file_info->AlignmentRequirement = 0;
4404 rsp->OutputBufferLength =
4405 cpu_to_le32(sizeof(struct smb2_file_alignment_info));
4406 inc_rfc1001_len(rsp_org,
4407 sizeof(struct smb2_file_alignment_info));
4410 static int get_file_all_info(struct ksmbd_work *work,
4411 struct smb2_query_info_rsp *rsp,
4412 struct ksmbd_file *fp,
4415 struct ksmbd_conn *conn = work->conn;
4416 struct smb2_file_all_info *file_info;
4417 unsigned int delete_pending;
4418 struct inode *inode;
4424 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4425 ksmbd_debug(SMB, "no right to read the attributes : 0x%x\n",
4430 filename = convert_to_nt_pathname(work->tcon->share_conf, &fp->filp->f_path);
4431 if (IS_ERR(filename))
4432 return PTR_ERR(filename);
4434 inode = file_inode(fp->filp);
4435 generic_fillattr(file_mnt_idmap(fp->filp), inode, &stat);
4437 ksmbd_debug(SMB, "filename = %s\n", filename);
4438 delete_pending = ksmbd_inode_pending_delete(fp);
4439 file_info = (struct smb2_file_all_info *)rsp->Buffer;
4441 file_info->CreationTime = cpu_to_le64(fp->create_time);
4442 time = ksmbd_UnixTimeToNT(stat.atime);
4443 file_info->LastAccessTime = cpu_to_le64(time);
4444 time = ksmbd_UnixTimeToNT(stat.mtime);
4445 file_info->LastWriteTime = cpu_to_le64(time);
4446 time = ksmbd_UnixTimeToNT(stat.ctime);
4447 file_info->ChangeTime = cpu_to_le64(time);
4448 file_info->Attributes = fp->f_ci->m_fattr;
4449 file_info->Pad1 = 0;
4450 file_info->AllocationSize =
4451 cpu_to_le64(get_allocation_size(inode, &stat));
4452 file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4453 file_info->NumberOfLinks =
4454 cpu_to_le32(get_nlink(&stat) - delete_pending);
4455 file_info->DeletePending = delete_pending;
4456 file_info->Directory = S_ISDIR(stat.mode) ? 1 : 0;
4457 file_info->Pad2 = 0;
4458 file_info->IndexNumber = cpu_to_le64(stat.ino);
4459 file_info->EASize = 0;
4460 file_info->AccessFlags = fp->daccess;
4461 file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
4462 file_info->Mode = fp->coption;
4463 file_info->AlignmentRequirement = 0;
4464 conv_len = smbConvertToUTF16((__le16 *)file_info->FileName, filename,
4465 PATH_MAX, conn->local_nls, 0);
4467 file_info->FileNameLength = cpu_to_le32(conv_len);
4468 rsp->OutputBufferLength =
4469 cpu_to_le32(sizeof(struct smb2_file_all_info) + conv_len - 1);
4471 inc_rfc1001_len(rsp_org, le32_to_cpu(rsp->OutputBufferLength));
4475 static void get_file_alternate_info(struct ksmbd_work *work,
4476 struct smb2_query_info_rsp *rsp,
4477 struct ksmbd_file *fp,
4480 struct ksmbd_conn *conn = work->conn;
4481 struct smb2_file_alt_name_info *file_info;
4482 struct dentry *dentry = fp->filp->f_path.dentry;
4485 spin_lock(&dentry->d_lock);
4486 file_info = (struct smb2_file_alt_name_info *)rsp->Buffer;
4487 conv_len = ksmbd_extract_shortname(conn,
4488 dentry->d_name.name,
4489 file_info->FileName);
4490 spin_unlock(&dentry->d_lock);
4491 file_info->FileNameLength = cpu_to_le32(conv_len);
4492 rsp->OutputBufferLength =
4493 cpu_to_le32(sizeof(struct smb2_file_alt_name_info) + conv_len);
4494 inc_rfc1001_len(rsp_org, le32_to_cpu(rsp->OutputBufferLength));
4497 static void get_file_stream_info(struct ksmbd_work *work,
4498 struct smb2_query_info_rsp *rsp,
4499 struct ksmbd_file *fp,
4502 struct ksmbd_conn *conn = work->conn;
4503 struct smb2_file_stream_info *file_info;
4504 char *stream_name, *xattr_list = NULL, *stream_buf;
4506 const struct path *path = &fp->filp->f_path;
4507 ssize_t xattr_list_len;
4508 int nbytes = 0, streamlen, stream_name_len, next, idx = 0;
4510 struct smb2_query_info_req *req = ksmbd_req_buf_next(work);
4512 generic_fillattr(file_mnt_idmap(fp->filp), file_inode(fp->filp),
4514 file_info = (struct smb2_file_stream_info *)rsp->Buffer;
4517 smb2_calc_max_out_buf_len(work, 8,
4518 le32_to_cpu(req->OutputBufferLength));
4519 if (buf_free_len < 0)
4522 xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
4523 if (xattr_list_len < 0) {
4525 } else if (!xattr_list_len) {
4526 ksmbd_debug(SMB, "empty xattr in the file\n");
4530 while (idx < xattr_list_len) {
4531 stream_name = xattr_list + idx;
4532 streamlen = strlen(stream_name);
4533 idx += streamlen + 1;
4535 ksmbd_debug(SMB, "%s, len %d\n", stream_name, streamlen);
4537 if (strncmp(&stream_name[XATTR_USER_PREFIX_LEN],
4538 STREAM_PREFIX, STREAM_PREFIX_LEN))
4541 stream_name_len = streamlen - (XATTR_USER_PREFIX_LEN +
4543 streamlen = stream_name_len;
4547 stream_buf = kmalloc(streamlen + 1, GFP_KERNEL);
4551 streamlen = snprintf(stream_buf, streamlen + 1,
4552 ":%s", &stream_name[XATTR_NAME_STREAM_LEN]);
4554 next = sizeof(struct smb2_file_stream_info) + streamlen * 2;
4555 if (next > buf_free_len) {
4560 file_info = (struct smb2_file_stream_info *)&rsp->Buffer[nbytes];
4561 streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
4562 stream_buf, streamlen,
4563 conn->local_nls, 0);
4566 file_info->StreamNameLength = cpu_to_le32(streamlen);
4567 file_info->StreamSize = cpu_to_le64(stream_name_len);
4568 file_info->StreamAllocationSize = cpu_to_le64(stream_name_len);
4571 buf_free_len -= next;
4572 file_info->NextEntryOffset = cpu_to_le32(next);
4576 if (!S_ISDIR(stat.mode) &&
4577 buf_free_len >= sizeof(struct smb2_file_stream_info) + 7 * 2) {
4578 file_info = (struct smb2_file_stream_info *)
4579 &rsp->Buffer[nbytes];
4580 streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
4581 "::$DATA", 7, conn->local_nls, 0);
4583 file_info->StreamNameLength = cpu_to_le32(streamlen);
4584 file_info->StreamSize = cpu_to_le64(stat.size);
4585 file_info->StreamAllocationSize = cpu_to_le64(stat.blocks << 9);
4586 nbytes += sizeof(struct smb2_file_stream_info) + streamlen;
4589 /* last entry offset should be 0 */
4590 file_info->NextEntryOffset = 0;
4593 rsp->OutputBufferLength = cpu_to_le32(nbytes);
4594 inc_rfc1001_len(rsp_org, nbytes);
4597 static void get_file_internal_info(struct smb2_query_info_rsp *rsp,
4598 struct ksmbd_file *fp, void *rsp_org)
4600 struct smb2_file_internal_info *file_info;
4603 generic_fillattr(file_mnt_idmap(fp->filp), file_inode(fp->filp),
4605 file_info = (struct smb2_file_internal_info *)rsp->Buffer;
4606 file_info->IndexNumber = cpu_to_le64(stat.ino);
4607 rsp->OutputBufferLength =
4608 cpu_to_le32(sizeof(struct smb2_file_internal_info));
4609 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_internal_info));
4612 static int get_file_network_open_info(struct smb2_query_info_rsp *rsp,
4613 struct ksmbd_file *fp, void *rsp_org)
4615 struct smb2_file_ntwrk_info *file_info;
4616 struct inode *inode;
4620 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4621 pr_err("no right to read the attributes : 0x%x\n",
4626 file_info = (struct smb2_file_ntwrk_info *)rsp->Buffer;
4628 inode = file_inode(fp->filp);
4629 generic_fillattr(file_mnt_idmap(fp->filp), inode, &stat);
4631 file_info->CreationTime = cpu_to_le64(fp->create_time);
4632 time = ksmbd_UnixTimeToNT(stat.atime);
4633 file_info->LastAccessTime = cpu_to_le64(time);
4634 time = ksmbd_UnixTimeToNT(stat.mtime);
4635 file_info->LastWriteTime = cpu_to_le64(time);
4636 time = ksmbd_UnixTimeToNT(stat.ctime);
4637 file_info->ChangeTime = cpu_to_le64(time);
4638 file_info->Attributes = fp->f_ci->m_fattr;
4639 file_info->AllocationSize =
4640 cpu_to_le64(get_allocation_size(inode, &stat));
4641 file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4642 file_info->Reserved = cpu_to_le32(0);
4643 rsp->OutputBufferLength =
4644 cpu_to_le32(sizeof(struct smb2_file_ntwrk_info));
4645 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_ntwrk_info));
4649 static void get_file_ea_info(struct smb2_query_info_rsp *rsp, void *rsp_org)
4651 struct smb2_file_ea_info *file_info;
4653 file_info = (struct smb2_file_ea_info *)rsp->Buffer;
4654 file_info->EASize = 0;
4655 rsp->OutputBufferLength =
4656 cpu_to_le32(sizeof(struct smb2_file_ea_info));
4657 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_ea_info));
4660 static void get_file_position_info(struct smb2_query_info_rsp *rsp,
4661 struct ksmbd_file *fp, void *rsp_org)
4663 struct smb2_file_pos_info *file_info;
4665 file_info = (struct smb2_file_pos_info *)rsp->Buffer;
4666 file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
4667 rsp->OutputBufferLength =
4668 cpu_to_le32(sizeof(struct smb2_file_pos_info));
4669 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_pos_info));
4672 static void get_file_mode_info(struct smb2_query_info_rsp *rsp,
4673 struct ksmbd_file *fp, void *rsp_org)
4675 struct smb2_file_mode_info *file_info;
4677 file_info = (struct smb2_file_mode_info *)rsp->Buffer;
4678 file_info->Mode = fp->coption & FILE_MODE_INFO_MASK;
4679 rsp->OutputBufferLength =
4680 cpu_to_le32(sizeof(struct smb2_file_mode_info));
4681 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_mode_info));
4684 static void get_file_compression_info(struct smb2_query_info_rsp *rsp,
4685 struct ksmbd_file *fp, void *rsp_org)
4687 struct smb2_file_comp_info *file_info;
4690 generic_fillattr(file_mnt_idmap(fp->filp), file_inode(fp->filp),
4693 file_info = (struct smb2_file_comp_info *)rsp->Buffer;
4694 file_info->CompressedFileSize = cpu_to_le64(stat.blocks << 9);
4695 file_info->CompressionFormat = COMPRESSION_FORMAT_NONE;
4696 file_info->CompressionUnitShift = 0;
4697 file_info->ChunkShift = 0;
4698 file_info->ClusterShift = 0;
4699 memset(&file_info->Reserved[0], 0, 3);
4701 rsp->OutputBufferLength =
4702 cpu_to_le32(sizeof(struct smb2_file_comp_info));
4703 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_comp_info));
4706 static int get_file_attribute_tag_info(struct smb2_query_info_rsp *rsp,
4707 struct ksmbd_file *fp, void *rsp_org)
4709 struct smb2_file_attr_tag_info *file_info;
4711 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4712 pr_err("no right to read the attributes : 0x%x\n",
4717 file_info = (struct smb2_file_attr_tag_info *)rsp->Buffer;
4718 file_info->FileAttributes = fp->f_ci->m_fattr;
4719 file_info->ReparseTag = 0;
4720 rsp->OutputBufferLength =
4721 cpu_to_le32(sizeof(struct smb2_file_attr_tag_info));
4722 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_attr_tag_info));
4726 static int find_file_posix_info(struct smb2_query_info_rsp *rsp,
4727 struct ksmbd_file *fp, void *rsp_org)
4729 struct smb311_posix_qinfo *file_info;
4730 struct inode *inode = file_inode(fp->filp);
4731 struct mnt_idmap *idmap = file_mnt_idmap(fp->filp);
4732 vfsuid_t vfsuid = i_uid_into_vfsuid(idmap, inode);
4733 vfsgid_t vfsgid = i_gid_into_vfsgid(idmap, inode);
4735 int out_buf_len = sizeof(struct smb311_posix_qinfo) + 32;
4737 file_info = (struct smb311_posix_qinfo *)rsp->Buffer;
4738 file_info->CreationTime = cpu_to_le64(fp->create_time);
4739 time = ksmbd_UnixTimeToNT(inode->i_atime);
4740 file_info->LastAccessTime = cpu_to_le64(time);
4741 time = ksmbd_UnixTimeToNT(inode->i_mtime);
4742 file_info->LastWriteTime = cpu_to_le64(time);
4743 time = ksmbd_UnixTimeToNT(inode->i_ctime);
4744 file_info->ChangeTime = cpu_to_le64(time);
4745 file_info->DosAttributes = fp->f_ci->m_fattr;
4746 file_info->Inode = cpu_to_le64(inode->i_ino);
4747 file_info->EndOfFile = cpu_to_le64(inode->i_size);
4748 file_info->AllocationSize = cpu_to_le64(inode->i_blocks << 9);
4749 file_info->HardLinks = cpu_to_le32(inode->i_nlink);
4750 file_info->Mode = cpu_to_le32(inode->i_mode & 0777);
4751 file_info->DeviceId = cpu_to_le32(inode->i_rdev);
4754 * Sids(32) contain two sids(Domain sid(16), UNIX group sid(16)).
4755 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) +
4756 * sub_auth(4 * 1(num_subauth)) + RID(4).
4758 id_to_sid(from_kuid_munged(&init_user_ns, vfsuid_into_kuid(vfsuid)),
4759 SIDUNIX_USER, (struct smb_sid *)&file_info->Sids[0]);
4760 id_to_sid(from_kgid_munged(&init_user_ns, vfsgid_into_kgid(vfsgid)),
4761 SIDUNIX_GROUP, (struct smb_sid *)&file_info->Sids[16]);
4763 rsp->OutputBufferLength = cpu_to_le32(out_buf_len);
4764 inc_rfc1001_len(rsp_org, out_buf_len);
4768 static int smb2_get_info_file(struct ksmbd_work *work,
4769 struct smb2_query_info_req *req,
4770 struct smb2_query_info_rsp *rsp)
4772 struct ksmbd_file *fp;
4773 int fileinfoclass = 0;
4775 int file_infoclass_size;
4776 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
4778 if (test_share_config_flag(work->tcon->share_conf,
4779 KSMBD_SHARE_FLAG_PIPE)) {
4780 /* smb2 info file called for pipe */
4781 return smb2_get_info_file_pipe(work->sess, req, rsp,
4782 work->response_buf);
4785 if (work->next_smb2_rcv_hdr_off) {
4786 if (!has_file_id(req->VolatileFileId)) {
4787 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
4788 work->compound_fid);
4789 id = work->compound_fid;
4790 pid = work->compound_pfid;
4794 if (!has_file_id(id)) {
4795 id = req->VolatileFileId;
4796 pid = req->PersistentFileId;
4799 fp = ksmbd_lookup_fd_slow(work, id, pid);
4803 fileinfoclass = req->FileInfoClass;
4805 switch (fileinfoclass) {
4806 case FILE_ACCESS_INFORMATION:
4807 get_file_access_info(rsp, fp, work->response_buf);
4808 file_infoclass_size = FILE_ACCESS_INFORMATION_SIZE;
4811 case FILE_BASIC_INFORMATION:
4812 rc = get_file_basic_info(rsp, fp, work->response_buf);
4813 file_infoclass_size = FILE_BASIC_INFORMATION_SIZE;
4816 case FILE_STANDARD_INFORMATION:
4817 get_file_standard_info(rsp, fp, work->response_buf);
4818 file_infoclass_size = FILE_STANDARD_INFORMATION_SIZE;
4821 case FILE_ALIGNMENT_INFORMATION:
4822 get_file_alignment_info(rsp, work->response_buf);
4823 file_infoclass_size = FILE_ALIGNMENT_INFORMATION_SIZE;
4826 case FILE_ALL_INFORMATION:
4827 rc = get_file_all_info(work, rsp, fp, work->response_buf);
4828 file_infoclass_size = FILE_ALL_INFORMATION_SIZE;
4831 case FILE_ALTERNATE_NAME_INFORMATION:
4832 get_file_alternate_info(work, rsp, fp, work->response_buf);
4833 file_infoclass_size = FILE_ALTERNATE_NAME_INFORMATION_SIZE;
4836 case FILE_STREAM_INFORMATION:
4837 get_file_stream_info(work, rsp, fp, work->response_buf);
4838 file_infoclass_size = FILE_STREAM_INFORMATION_SIZE;
4841 case FILE_INTERNAL_INFORMATION:
4842 get_file_internal_info(rsp, fp, work->response_buf);
4843 file_infoclass_size = FILE_INTERNAL_INFORMATION_SIZE;
4846 case FILE_NETWORK_OPEN_INFORMATION:
4847 rc = get_file_network_open_info(rsp, fp, work->response_buf);
4848 file_infoclass_size = FILE_NETWORK_OPEN_INFORMATION_SIZE;
4851 case FILE_EA_INFORMATION:
4852 get_file_ea_info(rsp, work->response_buf);
4853 file_infoclass_size = FILE_EA_INFORMATION_SIZE;
4856 case FILE_FULL_EA_INFORMATION:
4857 rc = smb2_get_ea(work, fp, req, rsp, work->response_buf);
4858 file_infoclass_size = FILE_FULL_EA_INFORMATION_SIZE;
4861 case FILE_POSITION_INFORMATION:
4862 get_file_position_info(rsp, fp, work->response_buf);
4863 file_infoclass_size = FILE_POSITION_INFORMATION_SIZE;
4866 case FILE_MODE_INFORMATION:
4867 get_file_mode_info(rsp, fp, work->response_buf);
4868 file_infoclass_size = FILE_MODE_INFORMATION_SIZE;
4871 case FILE_COMPRESSION_INFORMATION:
4872 get_file_compression_info(rsp, fp, work->response_buf);
4873 file_infoclass_size = FILE_COMPRESSION_INFORMATION_SIZE;
4876 case FILE_ATTRIBUTE_TAG_INFORMATION:
4877 rc = get_file_attribute_tag_info(rsp, fp, work->response_buf);
4878 file_infoclass_size = FILE_ATTRIBUTE_TAG_INFORMATION_SIZE;
4880 case SMB_FIND_FILE_POSIX_INFO:
4881 if (!work->tcon->posix_extensions) {
4882 pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
4885 file_infoclass_size = find_file_posix_info(rsp, fp,
4886 work->response_buf);
4890 ksmbd_debug(SMB, "fileinfoclass %d not supported yet\n",
4895 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4896 rsp, work->response_buf,
4897 file_infoclass_size);
4898 ksmbd_fd_put(work, fp);
4902 static int smb2_get_info_filesystem(struct ksmbd_work *work,
4903 struct smb2_query_info_req *req,
4904 struct smb2_query_info_rsp *rsp)
4906 struct ksmbd_session *sess = work->sess;
4907 struct ksmbd_conn *conn = work->conn;
4908 struct ksmbd_share_config *share = work->tcon->share_conf;
4909 int fsinfoclass = 0;
4910 struct kstatfs stfs;
4913 int fs_infoclass_size = 0;
4918 rc = kern_path(share->path, LOOKUP_NO_SYMLINKS, &path);
4920 pr_err("cannot create vfs path\n");
4924 rc = vfs_statfs(&path, &stfs);
4926 pr_err("cannot do stat of path %s\n", share->path);
4931 fsinfoclass = req->FileInfoClass;
4933 switch (fsinfoclass) {
4934 case FS_DEVICE_INFORMATION:
4936 struct filesystem_device_info *info;
4938 info = (struct filesystem_device_info *)rsp->Buffer;
4940 info->DeviceType = cpu_to_le32(stfs.f_type);
4941 info->DeviceCharacteristics = cpu_to_le32(0x00000020);
4942 rsp->OutputBufferLength = cpu_to_le32(8);
4943 inc_rfc1001_len(work->response_buf, 8);
4944 fs_infoclass_size = FS_DEVICE_INFORMATION_SIZE;
4947 case FS_ATTRIBUTE_INFORMATION:
4949 struct filesystem_attribute_info *info;
4952 info = (struct filesystem_attribute_info *)rsp->Buffer;
4953 info->Attributes = cpu_to_le32(FILE_SUPPORTS_OBJECT_IDS |
4954 FILE_PERSISTENT_ACLS |
4955 FILE_UNICODE_ON_DISK |
4956 FILE_CASE_PRESERVED_NAMES |
4957 FILE_CASE_SENSITIVE_SEARCH |
4958 FILE_SUPPORTS_BLOCK_REFCOUNTING);
4960 info->Attributes |= cpu_to_le32(server_conf.share_fake_fscaps);
4962 if (test_share_config_flag(work->tcon->share_conf,
4963 KSMBD_SHARE_FLAG_STREAMS))
4964 info->Attributes |= cpu_to_le32(FILE_NAMED_STREAMS);
4966 info->MaxPathNameComponentLength = cpu_to_le32(stfs.f_namelen);
4967 len = smbConvertToUTF16((__le16 *)info->FileSystemName,
4968 "NTFS", PATH_MAX, conn->local_nls, 0);
4970 info->FileSystemNameLen = cpu_to_le32(len);
4971 sz = sizeof(struct filesystem_attribute_info) - 2 + len;
4972 rsp->OutputBufferLength = cpu_to_le32(sz);
4973 inc_rfc1001_len(work->response_buf, sz);
4974 fs_infoclass_size = FS_ATTRIBUTE_INFORMATION_SIZE;
4977 case FS_VOLUME_INFORMATION:
4979 struct filesystem_vol_info *info;
4981 unsigned int serial_crc = 0;
4983 info = (struct filesystem_vol_info *)(rsp->Buffer);
4984 info->VolumeCreationTime = 0;
4985 serial_crc = crc32_le(serial_crc, share->name,
4986 strlen(share->name));
4987 serial_crc = crc32_le(serial_crc, share->path,
4988 strlen(share->path));
4989 serial_crc = crc32_le(serial_crc, ksmbd_netbios_name(),
4990 strlen(ksmbd_netbios_name()));
4991 /* Taking dummy value of serial number*/
4992 info->SerialNumber = cpu_to_le32(serial_crc);
4993 len = smbConvertToUTF16((__le16 *)info->VolumeLabel,
4994 share->name, PATH_MAX,
4995 conn->local_nls, 0);
4997 info->VolumeLabelSize = cpu_to_le32(len);
4999 sz = sizeof(struct filesystem_vol_info) - 2 + len;
5000 rsp->OutputBufferLength = cpu_to_le32(sz);
5001 inc_rfc1001_len(work->response_buf, sz);
5002 fs_infoclass_size = FS_VOLUME_INFORMATION_SIZE;
5005 case FS_SIZE_INFORMATION:
5007 struct filesystem_info *info;
5009 info = (struct filesystem_info *)(rsp->Buffer);
5010 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
5011 info->FreeAllocationUnits = cpu_to_le64(stfs.f_bfree);
5012 info->SectorsPerAllocationUnit = cpu_to_le32(1);
5013 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
5014 rsp->OutputBufferLength = cpu_to_le32(24);
5015 inc_rfc1001_len(work->response_buf, 24);
5016 fs_infoclass_size = FS_SIZE_INFORMATION_SIZE;
5019 case FS_FULL_SIZE_INFORMATION:
5021 struct smb2_fs_full_size_info *info;
5023 info = (struct smb2_fs_full_size_info *)(rsp->Buffer);
5024 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
5025 info->CallerAvailableAllocationUnits =
5026 cpu_to_le64(stfs.f_bavail);
5027 info->ActualAvailableAllocationUnits =
5028 cpu_to_le64(stfs.f_bfree);
5029 info->SectorsPerAllocationUnit = cpu_to_le32(1);
5030 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
5031 rsp->OutputBufferLength = cpu_to_le32(32);
5032 inc_rfc1001_len(work->response_buf, 32);
5033 fs_infoclass_size = FS_FULL_SIZE_INFORMATION_SIZE;
5036 case FS_OBJECT_ID_INFORMATION:
5038 struct object_id_info *info;
5040 info = (struct object_id_info *)(rsp->Buffer);
5042 if (!user_guest(sess->user))
5043 memcpy(info->objid, user_passkey(sess->user), 16);
5045 memset(info->objid, 0, 16);
5047 info->extended_info.magic = cpu_to_le32(EXTENDED_INFO_MAGIC);
5048 info->extended_info.version = cpu_to_le32(1);
5049 info->extended_info.release = cpu_to_le32(1);
5050 info->extended_info.rel_date = 0;
5051 memcpy(info->extended_info.version_string, "1.1.0", strlen("1.1.0"));
5052 rsp->OutputBufferLength = cpu_to_le32(64);
5053 inc_rfc1001_len(work->response_buf, 64);
5054 fs_infoclass_size = FS_OBJECT_ID_INFORMATION_SIZE;
5057 case FS_SECTOR_SIZE_INFORMATION:
5059 struct smb3_fs_ss_info *info;
5060 unsigned int sector_size =
5061 min_t(unsigned int, path.mnt->mnt_sb->s_blocksize, 4096);
5063 info = (struct smb3_fs_ss_info *)(rsp->Buffer);
5065 info->LogicalBytesPerSector = cpu_to_le32(sector_size);
5066 info->PhysicalBytesPerSectorForAtomicity =
5067 cpu_to_le32(sector_size);
5068 info->PhysicalBytesPerSectorForPerf = cpu_to_le32(sector_size);
5069 info->FSEffPhysicalBytesPerSectorForAtomicity =
5070 cpu_to_le32(sector_size);
5071 info->Flags = cpu_to_le32(SSINFO_FLAGS_ALIGNED_DEVICE |
5072 SSINFO_FLAGS_PARTITION_ALIGNED_ON_DEVICE);
5073 info->ByteOffsetForSectorAlignment = 0;
5074 info->ByteOffsetForPartitionAlignment = 0;
5075 rsp->OutputBufferLength = cpu_to_le32(28);
5076 inc_rfc1001_len(work->response_buf, 28);
5077 fs_infoclass_size = FS_SECTOR_SIZE_INFORMATION_SIZE;
5080 case FS_CONTROL_INFORMATION:
5083 * TODO : The current implementation is based on
5084 * test result with win7(NTFS) server. It's need to
5085 * modify this to get valid Quota values
5088 struct smb2_fs_control_info *info;
5090 info = (struct smb2_fs_control_info *)(rsp->Buffer);
5091 info->FreeSpaceStartFiltering = 0;
5092 info->FreeSpaceThreshold = 0;
5093 info->FreeSpaceStopFiltering = 0;
5094 info->DefaultQuotaThreshold = cpu_to_le64(SMB2_NO_FID);
5095 info->DefaultQuotaLimit = cpu_to_le64(SMB2_NO_FID);
5097 rsp->OutputBufferLength = cpu_to_le32(48);
5098 inc_rfc1001_len(work->response_buf, 48);
5099 fs_infoclass_size = FS_CONTROL_INFORMATION_SIZE;
5102 case FS_POSIX_INFORMATION:
5104 struct filesystem_posix_info *info;
5106 if (!work->tcon->posix_extensions) {
5107 pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
5110 info = (struct filesystem_posix_info *)(rsp->Buffer);
5111 info->OptimalTransferSize = cpu_to_le32(stfs.f_bsize);
5112 info->BlockSize = cpu_to_le32(stfs.f_bsize);
5113 info->TotalBlocks = cpu_to_le64(stfs.f_blocks);
5114 info->BlocksAvail = cpu_to_le64(stfs.f_bfree);
5115 info->UserBlocksAvail = cpu_to_le64(stfs.f_bavail);
5116 info->TotalFileNodes = cpu_to_le64(stfs.f_files);
5117 info->FreeFileNodes = cpu_to_le64(stfs.f_ffree);
5118 rsp->OutputBufferLength = cpu_to_le32(56);
5119 inc_rfc1001_len(work->response_buf, 56);
5120 fs_infoclass_size = FS_POSIX_INFORMATION_SIZE;
5128 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
5129 rsp, work->response_buf,
5135 static int smb2_get_info_sec(struct ksmbd_work *work,
5136 struct smb2_query_info_req *req,
5137 struct smb2_query_info_rsp *rsp)
5139 struct ksmbd_file *fp;
5140 struct mnt_idmap *idmap;
5141 struct smb_ntsd *pntsd = (struct smb_ntsd *)rsp->Buffer, *ppntsd = NULL;
5142 struct smb_fattr fattr = {{0}};
5143 struct inode *inode;
5144 __u32 secdesclen = 0;
5145 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
5146 int addition_info = le32_to_cpu(req->AdditionalInformation);
5147 int rc = 0, ppntsd_size = 0;
5149 if (addition_info & ~(OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO |
5150 PROTECTED_DACL_SECINFO |
5151 UNPROTECTED_DACL_SECINFO)) {
5152 ksmbd_debug(SMB, "Unsupported addition info: 0x%x)\n",
5155 pntsd->revision = cpu_to_le16(1);
5156 pntsd->type = cpu_to_le16(SELF_RELATIVE | DACL_PROTECTED);
5157 pntsd->osidoffset = 0;
5158 pntsd->gsidoffset = 0;
5159 pntsd->sacloffset = 0;
5160 pntsd->dacloffset = 0;
5162 secdesclen = sizeof(struct smb_ntsd);
5163 rsp->OutputBufferLength = cpu_to_le32(secdesclen);
5164 inc_rfc1001_len(work->response_buf, secdesclen);
5169 if (work->next_smb2_rcv_hdr_off) {
5170 if (!has_file_id(req->VolatileFileId)) {
5171 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
5172 work->compound_fid);
5173 id = work->compound_fid;
5174 pid = work->compound_pfid;
5178 if (!has_file_id(id)) {
5179 id = req->VolatileFileId;
5180 pid = req->PersistentFileId;
5183 fp = ksmbd_lookup_fd_slow(work, id, pid);
5187 idmap = file_mnt_idmap(fp->filp);
5188 inode = file_inode(fp->filp);
5189 ksmbd_acls_fattr(&fattr, idmap, inode);
5191 if (test_share_config_flag(work->tcon->share_conf,
5192 KSMBD_SHARE_FLAG_ACL_XATTR))
5193 ppntsd_size = ksmbd_vfs_get_sd_xattr(work->conn, idmap,
5194 fp->filp->f_path.dentry,
5197 /* Check if sd buffer size exceeds response buffer size */
5198 if (smb2_resp_buf_len(work, 8) > ppntsd_size)
5199 rc = build_sec_desc(idmap, pntsd, ppntsd, ppntsd_size,
5200 addition_info, &secdesclen, &fattr);
5201 posix_acl_release(fattr.cf_acls);
5202 posix_acl_release(fattr.cf_dacls);
5204 ksmbd_fd_put(work, fp);
5208 rsp->OutputBufferLength = cpu_to_le32(secdesclen);
5209 inc_rfc1001_len(work->response_buf, secdesclen);
5214 * smb2_query_info() - handler for smb2 query info command
5215 * @work: smb work containing query info request buffer
5217 * Return: 0 on success, otherwise error
5219 int smb2_query_info(struct ksmbd_work *work)
5221 struct smb2_query_info_req *req;
5222 struct smb2_query_info_rsp *rsp;
5225 WORK_BUFFERS(work, req, rsp);
5227 ksmbd_debug(SMB, "GOT query info request\n");
5229 switch (req->InfoType) {
5230 case SMB2_O_INFO_FILE:
5231 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
5232 rc = smb2_get_info_file(work, req, rsp);
5234 case SMB2_O_INFO_FILESYSTEM:
5235 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILESYSTEM\n");
5236 rc = smb2_get_info_filesystem(work, req, rsp);
5238 case SMB2_O_INFO_SECURITY:
5239 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
5240 rc = smb2_get_info_sec(work, req, rsp);
5243 ksmbd_debug(SMB, "InfoType %d not supported yet\n",
5250 rsp->hdr.Status = STATUS_ACCESS_DENIED;
5251 else if (rc == -ENOENT)
5252 rsp->hdr.Status = STATUS_FILE_CLOSED;
5253 else if (rc == -EIO)
5254 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
5255 else if (rc == -EOPNOTSUPP || rsp->hdr.Status == 0)
5256 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
5257 smb2_set_err_rsp(work);
5259 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n",
5263 rsp->StructureSize = cpu_to_le16(9);
5264 rsp->OutputBufferOffset = cpu_to_le16(72);
5265 inc_rfc1001_len(work->response_buf, 8);
5270 * smb2_close_pipe() - handler for closing IPC pipe
5271 * @work: smb work containing close request buffer
5275 static noinline int smb2_close_pipe(struct ksmbd_work *work)
5278 struct smb2_close_req *req = smb2_get_msg(work->request_buf);
5279 struct smb2_close_rsp *rsp = smb2_get_msg(work->response_buf);
5281 id = req->VolatileFileId;
5282 ksmbd_session_rpc_close(work->sess, id);
5284 rsp->StructureSize = cpu_to_le16(60);
5287 rsp->CreationTime = 0;
5288 rsp->LastAccessTime = 0;
5289 rsp->LastWriteTime = 0;
5290 rsp->ChangeTime = 0;
5291 rsp->AllocationSize = 0;
5293 rsp->Attributes = 0;
5294 inc_rfc1001_len(work->response_buf, 60);
5299 * smb2_close() - handler for smb2 close file command
5300 * @work: smb work containing close request buffer
5304 int smb2_close(struct ksmbd_work *work)
5306 u64 volatile_id = KSMBD_NO_FID;
5308 struct smb2_close_req *req;
5309 struct smb2_close_rsp *rsp;
5310 struct ksmbd_conn *conn = work->conn;
5311 struct ksmbd_file *fp;
5312 struct inode *inode;
5316 WORK_BUFFERS(work, req, rsp);
5318 if (test_share_config_flag(work->tcon->share_conf,
5319 KSMBD_SHARE_FLAG_PIPE)) {
5320 ksmbd_debug(SMB, "IPC pipe close request\n");
5321 return smb2_close_pipe(work);
5324 sess_id = le64_to_cpu(req->hdr.SessionId);
5325 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5326 sess_id = work->compound_sid;
5328 work->compound_sid = 0;
5329 if (check_session_id(conn, sess_id)) {
5330 work->compound_sid = sess_id;
5332 rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
5333 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5334 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
5339 if (work->next_smb2_rcv_hdr_off &&
5340 !has_file_id(req->VolatileFileId)) {
5341 if (!has_file_id(work->compound_fid)) {
5342 /* file already closed, return FILE_CLOSED */
5343 ksmbd_debug(SMB, "file already closed\n");
5344 rsp->hdr.Status = STATUS_FILE_CLOSED;
5349 "Compound request set FID = %llu:%llu\n",
5351 work->compound_pfid);
5352 volatile_id = work->compound_fid;
5354 /* file closed, stored id is not valid anymore */
5355 work->compound_fid = KSMBD_NO_FID;
5356 work->compound_pfid = KSMBD_NO_FID;
5359 volatile_id = req->VolatileFileId;
5361 ksmbd_debug(SMB, "volatile_id = %llu\n", volatile_id);
5363 rsp->StructureSize = cpu_to_le16(60);
5366 if (req->Flags == SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB) {
5367 fp = ksmbd_lookup_fd_fast(work, volatile_id);
5373 inode = file_inode(fp->filp);
5374 rsp->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB;
5375 rsp->AllocationSize = S_ISDIR(inode->i_mode) ? 0 :
5376 cpu_to_le64(inode->i_blocks << 9);
5377 rsp->EndOfFile = cpu_to_le64(inode->i_size);
5378 rsp->Attributes = fp->f_ci->m_fattr;
5379 rsp->CreationTime = cpu_to_le64(fp->create_time);
5380 time = ksmbd_UnixTimeToNT(inode->i_atime);
5381 rsp->LastAccessTime = cpu_to_le64(time);
5382 time = ksmbd_UnixTimeToNT(inode->i_mtime);
5383 rsp->LastWriteTime = cpu_to_le64(time);
5384 time = ksmbd_UnixTimeToNT(inode->i_ctime);
5385 rsp->ChangeTime = cpu_to_le64(time);
5386 ksmbd_fd_put(work, fp);
5389 rsp->AllocationSize = 0;
5391 rsp->Attributes = 0;
5392 rsp->CreationTime = 0;
5393 rsp->LastAccessTime = 0;
5394 rsp->LastWriteTime = 0;
5395 rsp->ChangeTime = 0;
5398 err = ksmbd_close_fd(work, volatile_id);
5401 if (rsp->hdr.Status == 0)
5402 rsp->hdr.Status = STATUS_FILE_CLOSED;
5403 smb2_set_err_rsp(work);
5405 inc_rfc1001_len(work->response_buf, 60);
5412 * smb2_echo() - handler for smb2 echo(ping) command
5413 * @work: smb work containing echo request buffer
5417 int smb2_echo(struct ksmbd_work *work)
5419 struct smb2_echo_rsp *rsp = smb2_get_msg(work->response_buf);
5421 rsp->StructureSize = cpu_to_le16(4);
5423 inc_rfc1001_len(work->response_buf, 4);
5427 static int smb2_rename(struct ksmbd_work *work,
5428 struct ksmbd_file *fp,
5429 struct smb2_file_rename_info *file_info,
5430 struct nls_table *local_nls)
5432 struct ksmbd_share_config *share = fp->tcon->share_conf;
5433 char *new_name = NULL;
5436 ksmbd_debug(SMB, "setting FILE_RENAME_INFO\n");
5437 new_name = smb2_get_name(file_info->FileName,
5438 le32_to_cpu(file_info->FileNameLength),
5440 if (IS_ERR(new_name))
5441 return PTR_ERR(new_name);
5443 if (strchr(new_name, ':')) {
5445 char *xattr_stream_name, *stream_name = NULL;
5446 size_t xattr_stream_size;
5449 rc = parse_stream_name(new_name, &stream_name, &s_type);
5453 len = strlen(new_name);
5454 if (len > 0 && new_name[len - 1] != '/') {
5455 pr_err("not allow base filename in rename\n");
5460 rc = ksmbd_vfs_xattr_stream_name(stream_name,
5467 rc = ksmbd_vfs_setxattr(file_mnt_idmap(fp->filp),
5468 fp->filp->f_path.dentry,
5472 pr_err("failed to store stream name in xattr: %d\n",
5481 ksmbd_debug(SMB, "new name %s\n", new_name);
5482 if (ksmbd_share_veto_filename(share, new_name)) {
5484 ksmbd_debug(SMB, "Can't rename vetoed file: %s\n", new_name);
5488 if (!file_info->ReplaceIfExists)
5489 flags = RENAME_NOREPLACE;
5491 rc = ksmbd_vfs_rename(work, &fp->filp->f_path, new_name, flags);
5497 static int smb2_create_link(struct ksmbd_work *work,
5498 struct ksmbd_share_config *share,
5499 struct smb2_file_link_info *file_info,
5500 unsigned int buf_len, struct file *filp,
5501 struct nls_table *local_nls)
5503 char *link_name = NULL, *target_name = NULL, *pathname = NULL;
5505 bool file_present = false;
5508 if (buf_len < (u64)sizeof(struct smb2_file_link_info) +
5509 le32_to_cpu(file_info->FileNameLength))
5512 ksmbd_debug(SMB, "setting FILE_LINK_INFORMATION\n");
5513 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
5517 link_name = smb2_get_name(file_info->FileName,
5518 le32_to_cpu(file_info->FileNameLength),
5520 if (IS_ERR(link_name) || S_ISDIR(file_inode(filp)->i_mode)) {
5525 ksmbd_debug(SMB, "link name is %s\n", link_name);
5526 target_name = file_path(filp, pathname, PATH_MAX);
5527 if (IS_ERR(target_name)) {
5532 ksmbd_debug(SMB, "target name is %s\n", target_name);
5533 rc = ksmbd_vfs_kern_path_locked(work, link_name, LOOKUP_NO_SYMLINKS,
5539 file_present = true;
5541 if (file_info->ReplaceIfExists) {
5543 rc = ksmbd_vfs_remove_file(work, &path);
5546 ksmbd_debug(SMB, "cannot delete %s\n",
5554 ksmbd_debug(SMB, "link already exists\n");
5559 rc = ksmbd_vfs_link(work, target_name, link_name);
5564 inode_unlock(d_inode(path.dentry->d_parent));
5567 if (!IS_ERR(link_name))
5573 static int set_file_basic_info(struct ksmbd_file *fp,
5574 struct smb2_file_basic_info *file_info,
5575 struct ksmbd_share_config *share)
5579 struct inode *inode;
5580 struct mnt_idmap *idmap;
5583 if (!(fp->daccess & FILE_WRITE_ATTRIBUTES_LE))
5588 inode = file_inode(filp);
5589 idmap = file_mnt_idmap(filp);
5591 if (file_info->CreationTime)
5592 fp->create_time = le64_to_cpu(file_info->CreationTime);
5594 if (file_info->LastAccessTime) {
5595 attrs.ia_atime = ksmbd_NTtimeToUnix(file_info->LastAccessTime);
5596 attrs.ia_valid |= (ATTR_ATIME | ATTR_ATIME_SET);
5599 attrs.ia_valid |= ATTR_CTIME;
5600 if (file_info->ChangeTime)
5601 attrs.ia_ctime = ksmbd_NTtimeToUnix(file_info->ChangeTime);
5603 attrs.ia_ctime = inode->i_ctime;
5605 if (file_info->LastWriteTime) {
5606 attrs.ia_mtime = ksmbd_NTtimeToUnix(file_info->LastWriteTime);
5607 attrs.ia_valid |= (ATTR_MTIME | ATTR_MTIME_SET);
5610 if (file_info->Attributes) {
5611 if (!S_ISDIR(inode->i_mode) &&
5612 file_info->Attributes & FILE_ATTRIBUTE_DIRECTORY_LE) {
5613 pr_err("can't change a file to a directory\n");
5617 if (!(S_ISDIR(inode->i_mode) && file_info->Attributes == FILE_ATTRIBUTE_NORMAL_LE))
5618 fp->f_ci->m_fattr = file_info->Attributes |
5619 (fp->f_ci->m_fattr & FILE_ATTRIBUTE_DIRECTORY_LE);
5622 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_STORE_DOS_ATTRS) &&
5623 (file_info->CreationTime || file_info->Attributes)) {
5624 struct xattr_dos_attrib da = {0};
5627 da.itime = fp->itime;
5628 da.create_time = fp->create_time;
5629 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
5630 da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
5631 XATTR_DOSINFO_ITIME;
5633 rc = ksmbd_vfs_set_dos_attrib_xattr(idmap,
5634 filp->f_path.dentry, &da);
5637 "failed to restore file attribute in EA\n");
5641 if (attrs.ia_valid) {
5642 struct dentry *dentry = filp->f_path.dentry;
5643 struct inode *inode = d_inode(dentry);
5645 if (IS_IMMUTABLE(inode) || IS_APPEND(inode))
5649 inode->i_ctime = attrs.ia_ctime;
5650 attrs.ia_valid &= ~ATTR_CTIME;
5651 rc = notify_change(idmap, dentry, &attrs, NULL);
5652 inode_unlock(inode);
5657 static int set_file_allocation_info(struct ksmbd_work *work,
5658 struct ksmbd_file *fp,
5659 struct smb2_file_alloc_info *file_alloc_info)
5662 * TODO : It's working fine only when store dos attributes
5663 * is not yes. need to implement a logic which works
5664 * properly with any smb.conf option
5668 struct inode *inode;
5671 if (!(fp->daccess & FILE_WRITE_DATA_LE))
5674 alloc_blks = (le64_to_cpu(file_alloc_info->AllocationSize) + 511) >> 9;
5675 inode = file_inode(fp->filp);
5677 if (alloc_blks > inode->i_blocks) {
5678 smb_break_all_levII_oplock(work, fp, 1);
5679 rc = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
5681 if (rc && rc != -EOPNOTSUPP) {
5682 pr_err("vfs_fallocate is failed : %d\n", rc);
5685 } else if (alloc_blks < inode->i_blocks) {
5689 * Allocation size could be smaller than original one
5690 * which means allocated blocks in file should be
5691 * deallocated. use truncate to cut out it, but inode
5692 * size is also updated with truncate offset.
5693 * inode size is retained by backup inode size.
5695 size = i_size_read(inode);
5696 rc = ksmbd_vfs_truncate(work, fp, alloc_blks * 512);
5698 pr_err("truncate failed!, err %d\n", rc);
5701 if (size < alloc_blks * 512)
5702 i_size_write(inode, size);
5707 static int set_end_of_file_info(struct ksmbd_work *work, struct ksmbd_file *fp,
5708 struct smb2_file_eof_info *file_eof_info)
5711 struct inode *inode;
5714 if (!(fp->daccess & FILE_WRITE_DATA_LE))
5717 newsize = le64_to_cpu(file_eof_info->EndOfFile);
5718 inode = file_inode(fp->filp);
5721 * If FILE_END_OF_FILE_INFORMATION of set_info_file is called
5722 * on FAT32 shared device, truncate execution time is too long
5723 * and network error could cause from windows client. because
5724 * truncate of some filesystem like FAT32 fill zero data in
5727 if (inode->i_sb->s_magic != MSDOS_SUPER_MAGIC) {
5728 ksmbd_debug(SMB, "truncated to newsize %lld\n", newsize);
5729 rc = ksmbd_vfs_truncate(work, fp, newsize);
5731 ksmbd_debug(SMB, "truncate failed!, err %d\n", rc);
5740 static int set_rename_info(struct ksmbd_work *work, struct ksmbd_file *fp,
5741 struct smb2_file_rename_info *rename_info,
5742 unsigned int buf_len)
5744 if (!(fp->daccess & FILE_DELETE_LE)) {
5745 pr_err("no right to delete : 0x%x\n", fp->daccess);
5749 if (buf_len < (u64)sizeof(struct smb2_file_rename_info) +
5750 le32_to_cpu(rename_info->FileNameLength))
5753 if (!le32_to_cpu(rename_info->FileNameLength))
5756 return smb2_rename(work, fp, rename_info, work->conn->local_nls);
5759 static int set_file_disposition_info(struct ksmbd_file *fp,
5760 struct smb2_file_disposition_info *file_info)
5762 struct inode *inode;
5764 if (!(fp->daccess & FILE_DELETE_LE)) {
5765 pr_err("no right to delete : 0x%x\n", fp->daccess);
5769 inode = file_inode(fp->filp);
5770 if (file_info->DeletePending) {
5771 if (S_ISDIR(inode->i_mode) &&
5772 ksmbd_vfs_empty_dir(fp) == -ENOTEMPTY)
5774 ksmbd_set_inode_pending_delete(fp);
5776 ksmbd_clear_inode_pending_delete(fp);
5781 static int set_file_position_info(struct ksmbd_file *fp,
5782 struct smb2_file_pos_info *file_info)
5784 loff_t current_byte_offset;
5785 unsigned long sector_size;
5786 struct inode *inode;
5788 inode = file_inode(fp->filp);
5789 current_byte_offset = le64_to_cpu(file_info->CurrentByteOffset);
5790 sector_size = inode->i_sb->s_blocksize;
5792 if (current_byte_offset < 0 ||
5793 (fp->coption == FILE_NO_INTERMEDIATE_BUFFERING_LE &&
5794 current_byte_offset & (sector_size - 1))) {
5795 pr_err("CurrentByteOffset is not valid : %llu\n",
5796 current_byte_offset);
5800 fp->filp->f_pos = current_byte_offset;
5804 static int set_file_mode_info(struct ksmbd_file *fp,
5805 struct smb2_file_mode_info *file_info)
5809 mode = file_info->Mode;
5811 if ((mode & ~FILE_MODE_INFO_MASK)) {
5812 pr_err("Mode is not valid : 0x%x\n", le32_to_cpu(mode));
5817 * TODO : need to implement consideration for
5818 * FILE_SYNCHRONOUS_IO_ALERT and FILE_SYNCHRONOUS_IO_NONALERT
5820 ksmbd_vfs_set_fadvise(fp->filp, mode);
5826 * smb2_set_info_file() - handler for smb2 set info command
5827 * @work: smb work containing set info command buffer
5828 * @fp: ksmbd_file pointer
5829 * @req: request buffer pointer
5830 * @share: ksmbd_share_config pointer
5832 * Return: 0 on success, otherwise error
5833 * TODO: need to implement an error handling for STATUS_INFO_LENGTH_MISMATCH
5835 static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp,
5836 struct smb2_set_info_req *req,
5837 struct ksmbd_share_config *share)
5839 unsigned int buf_len = le32_to_cpu(req->BufferLength);
5841 switch (req->FileInfoClass) {
5842 case FILE_BASIC_INFORMATION:
5844 if (buf_len < sizeof(struct smb2_file_basic_info))
5847 return set_file_basic_info(fp, (struct smb2_file_basic_info *)req->Buffer, share);
5849 case FILE_ALLOCATION_INFORMATION:
5851 if (buf_len < sizeof(struct smb2_file_alloc_info))
5854 return set_file_allocation_info(work, fp,
5855 (struct smb2_file_alloc_info *)req->Buffer);
5857 case FILE_END_OF_FILE_INFORMATION:
5859 if (buf_len < sizeof(struct smb2_file_eof_info))
5862 return set_end_of_file_info(work, fp,
5863 (struct smb2_file_eof_info *)req->Buffer);
5865 case FILE_RENAME_INFORMATION:
5867 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
5869 "User does not have write permission\n");
5873 if (buf_len < sizeof(struct smb2_file_rename_info))
5876 return set_rename_info(work, fp,
5877 (struct smb2_file_rename_info *)req->Buffer,
5880 case FILE_LINK_INFORMATION:
5882 if (buf_len < sizeof(struct smb2_file_link_info))
5885 return smb2_create_link(work, work->tcon->share_conf,
5886 (struct smb2_file_link_info *)req->Buffer,
5888 work->conn->local_nls);
5890 case FILE_DISPOSITION_INFORMATION:
5892 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
5894 "User does not have write permission\n");
5898 if (buf_len < sizeof(struct smb2_file_disposition_info))
5901 return set_file_disposition_info(fp,
5902 (struct smb2_file_disposition_info *)req->Buffer);
5904 case FILE_FULL_EA_INFORMATION:
5906 if (!(fp->daccess & FILE_WRITE_EA_LE)) {
5907 pr_err("Not permitted to write ext attr: 0x%x\n",
5912 if (buf_len < sizeof(struct smb2_ea_info))
5915 return smb2_set_ea((struct smb2_ea_info *)req->Buffer,
5916 buf_len, &fp->filp->f_path);
5918 case FILE_POSITION_INFORMATION:
5920 if (buf_len < sizeof(struct smb2_file_pos_info))
5923 return set_file_position_info(fp, (struct smb2_file_pos_info *)req->Buffer);
5925 case FILE_MODE_INFORMATION:
5927 if (buf_len < sizeof(struct smb2_file_mode_info))
5930 return set_file_mode_info(fp, (struct smb2_file_mode_info *)req->Buffer);
5934 pr_err("Unimplemented Fileinfoclass :%d\n", req->FileInfoClass);
5938 static int smb2_set_info_sec(struct ksmbd_file *fp, int addition_info,
5939 char *buffer, int buf_len)
5941 struct smb_ntsd *pntsd = (struct smb_ntsd *)buffer;
5943 fp->saccess |= FILE_SHARE_DELETE_LE;
5945 return set_info_sec(fp->conn, fp->tcon, &fp->filp->f_path, pntsd,
5950 * smb2_set_info() - handler for smb2 set info command handler
5951 * @work: smb work containing set info request buffer
5953 * Return: 0 on success, otherwise error
5955 int smb2_set_info(struct ksmbd_work *work)
5957 struct smb2_set_info_req *req;
5958 struct smb2_set_info_rsp *rsp;
5959 struct ksmbd_file *fp;
5961 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
5963 ksmbd_debug(SMB, "Received set info request\n");
5965 if (work->next_smb2_rcv_hdr_off) {
5966 req = ksmbd_req_buf_next(work);
5967 rsp = ksmbd_resp_buf_next(work);
5968 if (!has_file_id(req->VolatileFileId)) {
5969 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
5970 work->compound_fid);
5971 id = work->compound_fid;
5972 pid = work->compound_pfid;
5975 req = smb2_get_msg(work->request_buf);
5976 rsp = smb2_get_msg(work->response_buf);
5979 if (!has_file_id(id)) {
5980 id = req->VolatileFileId;
5981 pid = req->PersistentFileId;
5984 fp = ksmbd_lookup_fd_slow(work, id, pid);
5986 ksmbd_debug(SMB, "Invalid id for close: %u\n", id);
5991 switch (req->InfoType) {
5992 case SMB2_O_INFO_FILE:
5993 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
5994 rc = smb2_set_info_file(work, fp, req, work->tcon->share_conf);
5996 case SMB2_O_INFO_SECURITY:
5997 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
5998 if (ksmbd_override_fsids(work)) {
6002 rc = smb2_set_info_sec(fp,
6003 le32_to_cpu(req->AdditionalInformation),
6005 le32_to_cpu(req->BufferLength));
6006 ksmbd_revert_fsids(work);
6015 rsp->StructureSize = cpu_to_le16(2);
6016 inc_rfc1001_len(work->response_buf, 2);
6017 ksmbd_fd_put(work, fp);
6021 if (rc == -EACCES || rc == -EPERM || rc == -EXDEV)
6022 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6023 else if (rc == -EINVAL)
6024 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6025 else if (rc == -ESHARE)
6026 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6027 else if (rc == -ENOENT)
6028 rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
6029 else if (rc == -EBUSY || rc == -ENOTEMPTY)
6030 rsp->hdr.Status = STATUS_DIRECTORY_NOT_EMPTY;
6031 else if (rc == -EAGAIN)
6032 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6033 else if (rc == -EBADF || rc == -ESTALE)
6034 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6035 else if (rc == -EEXIST)
6036 rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
6037 else if (rsp->hdr.Status == 0 || rc == -EOPNOTSUPP)
6038 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
6039 smb2_set_err_rsp(work);
6040 ksmbd_fd_put(work, fp);
6041 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n", rc);
6046 * smb2_read_pipe() - handler for smb2 read from IPC pipe
6047 * @work: smb work containing read IPC pipe command buffer
6049 * Return: 0 on success, otherwise error
6051 static noinline int smb2_read_pipe(struct ksmbd_work *work)
6053 int nbytes = 0, err;
6055 struct ksmbd_rpc_command *rpc_resp;
6056 struct smb2_read_req *req = smb2_get_msg(work->request_buf);
6057 struct smb2_read_rsp *rsp = smb2_get_msg(work->response_buf);
6059 id = req->VolatileFileId;
6061 inc_rfc1001_len(work->response_buf, 16);
6062 rpc_resp = ksmbd_rpc_read(work->sess, id);
6064 if (rpc_resp->flags != KSMBD_RPC_OK) {
6069 work->aux_payload_buf =
6070 kvmalloc(rpc_resp->payload_sz, GFP_KERNEL | __GFP_ZERO);
6071 if (!work->aux_payload_buf) {
6076 memcpy(work->aux_payload_buf, rpc_resp->payload,
6077 rpc_resp->payload_sz);
6079 nbytes = rpc_resp->payload_sz;
6080 work->resp_hdr_sz = get_rfc1002_len(work->response_buf) + 4;
6081 work->aux_payload_sz = nbytes;
6085 rsp->StructureSize = cpu_to_le16(17);
6086 rsp->DataOffset = 80;
6088 rsp->DataLength = cpu_to_le32(nbytes);
6089 rsp->DataRemaining = 0;
6091 inc_rfc1001_len(work->response_buf, nbytes);
6095 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
6096 smb2_set_err_rsp(work);
6101 static int smb2_set_remote_key_for_rdma(struct ksmbd_work *work,
6102 struct smb2_buffer_desc_v1 *desc,
6104 __le16 ChannelInfoLength)
6106 unsigned int i, ch_count;
6108 if (work->conn->dialect == SMB30_PROT_ID &&
6109 Channel != SMB2_CHANNEL_RDMA_V1)
6112 ch_count = le16_to_cpu(ChannelInfoLength) / sizeof(*desc);
6113 if (ksmbd_debug_types & KSMBD_DEBUG_RDMA) {
6114 for (i = 0; i < ch_count; i++) {
6115 pr_info("RDMA r/w request %#x: token %#x, length %#x\n",
6117 le32_to_cpu(desc[i].token),
6118 le32_to_cpu(desc[i].length));
6124 work->need_invalidate_rkey =
6125 (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE);
6126 if (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE)
6127 work->remote_key = le32_to_cpu(desc->token);
6131 static ssize_t smb2_read_rdma_channel(struct ksmbd_work *work,
6132 struct smb2_read_req *req, void *data_buf,
6137 err = ksmbd_conn_rdma_write(work->conn, data_buf, length,
6138 (struct smb2_buffer_desc_v1 *)
6139 ((char *)req + le16_to_cpu(req->ReadChannelInfoOffset)),
6140 le16_to_cpu(req->ReadChannelInfoLength));
6148 * smb2_read() - handler for smb2 read from file
6149 * @work: smb work containing read command buffer
6151 * Return: 0 on success, otherwise error
6153 int smb2_read(struct ksmbd_work *work)
6155 struct ksmbd_conn *conn = work->conn;
6156 struct smb2_read_req *req;
6157 struct smb2_read_rsp *rsp;
6158 struct ksmbd_file *fp = NULL;
6160 size_t length, mincount;
6161 ssize_t nbytes = 0, remain_bytes = 0;
6163 bool is_rdma_channel = false;
6164 unsigned int max_read_size = conn->vals->max_read_size;
6166 WORK_BUFFERS(work, req, rsp);
6168 if (test_share_config_flag(work->tcon->share_conf,
6169 KSMBD_SHARE_FLAG_PIPE)) {
6170 ksmbd_debug(SMB, "IPC pipe read request\n");
6171 return smb2_read_pipe(work);
6174 if (req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE ||
6175 req->Channel == SMB2_CHANNEL_RDMA_V1) {
6176 is_rdma_channel = true;
6177 max_read_size = get_smbd_max_read_write_size();
6180 if (is_rdma_channel == true) {
6181 unsigned int ch_offset = le16_to_cpu(req->ReadChannelInfoOffset);
6183 if (ch_offset < offsetof(struct smb2_read_req, Buffer)) {
6187 err = smb2_set_remote_key_for_rdma(work,
6188 (struct smb2_buffer_desc_v1 *)
6189 ((char *)req + ch_offset),
6191 req->ReadChannelInfoLength);
6196 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
6202 if (!(fp->daccess & (FILE_READ_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
6203 pr_err("Not permitted to read : 0x%x\n", fp->daccess);
6208 offset = le64_to_cpu(req->Offset);
6209 length = le32_to_cpu(req->Length);
6210 mincount = le32_to_cpu(req->MinimumCount);
6212 if (length > max_read_size) {
6213 ksmbd_debug(SMB, "limiting read size to max size(%u)\n",
6219 ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
6220 fp->filp, offset, length);
6222 work->aux_payload_buf = kvmalloc(length, GFP_KERNEL | __GFP_ZERO);
6223 if (!work->aux_payload_buf) {
6228 nbytes = ksmbd_vfs_read(work, fp, length, &offset);
6234 if ((nbytes == 0 && length != 0) || nbytes < mincount) {
6235 kvfree(work->aux_payload_buf);
6236 work->aux_payload_buf = NULL;
6237 rsp->hdr.Status = STATUS_END_OF_FILE;
6238 smb2_set_err_rsp(work);
6239 ksmbd_fd_put(work, fp);
6243 ksmbd_debug(SMB, "nbytes %zu, offset %lld mincount %zu\n",
6244 nbytes, offset, mincount);
6246 if (is_rdma_channel == true) {
6247 /* write data to the client using rdma channel */
6248 remain_bytes = smb2_read_rdma_channel(work, req,
6249 work->aux_payload_buf,
6251 kvfree(work->aux_payload_buf);
6252 work->aux_payload_buf = NULL;
6255 if (remain_bytes < 0) {
6256 err = (int)remain_bytes;
6261 rsp->StructureSize = cpu_to_le16(17);
6262 rsp->DataOffset = 80;
6264 rsp->DataLength = cpu_to_le32(nbytes);
6265 rsp->DataRemaining = cpu_to_le32(remain_bytes);
6267 inc_rfc1001_len(work->response_buf, 16);
6268 work->resp_hdr_sz = get_rfc1002_len(work->response_buf) + 4;
6269 work->aux_payload_sz = nbytes;
6270 inc_rfc1001_len(work->response_buf, nbytes);
6271 ksmbd_fd_put(work, fp);
6277 rsp->hdr.Status = STATUS_INVALID_DEVICE_REQUEST;
6278 else if (err == -EAGAIN)
6279 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6280 else if (err == -ENOENT)
6281 rsp->hdr.Status = STATUS_FILE_CLOSED;
6282 else if (err == -EACCES)
6283 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6284 else if (err == -ESHARE)
6285 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6286 else if (err == -EINVAL)
6287 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6289 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6291 smb2_set_err_rsp(work);
6293 ksmbd_fd_put(work, fp);
6298 * smb2_write_pipe() - handler for smb2 write on IPC pipe
6299 * @work: smb work containing write IPC pipe command buffer
6301 * Return: 0 on success, otherwise error
6303 static noinline int smb2_write_pipe(struct ksmbd_work *work)
6305 struct smb2_write_req *req = smb2_get_msg(work->request_buf);
6306 struct smb2_write_rsp *rsp = smb2_get_msg(work->response_buf);
6307 struct ksmbd_rpc_command *rpc_resp;
6309 int err = 0, ret = 0;
6313 length = le32_to_cpu(req->Length);
6314 id = req->VolatileFileId;
6316 if ((u64)le16_to_cpu(req->DataOffset) + length >
6317 get_rfc1002_len(work->request_buf)) {
6318 pr_err("invalid write data offset %u, smb_len %u\n",
6319 le16_to_cpu(req->DataOffset),
6320 get_rfc1002_len(work->request_buf));
6325 data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
6326 le16_to_cpu(req->DataOffset));
6328 rpc_resp = ksmbd_rpc_write(work->sess, id, data_buf, length);
6330 if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
6331 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
6333 smb2_set_err_rsp(work);
6336 if (rpc_resp->flags != KSMBD_RPC_OK) {
6337 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6338 smb2_set_err_rsp(work);
6345 rsp->StructureSize = cpu_to_le16(17);
6346 rsp->DataOffset = 0;
6348 rsp->DataLength = cpu_to_le32(length);
6349 rsp->DataRemaining = 0;
6351 inc_rfc1001_len(work->response_buf, 16);
6355 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6356 smb2_set_err_rsp(work);
6362 static ssize_t smb2_write_rdma_channel(struct ksmbd_work *work,
6363 struct smb2_write_req *req,
6364 struct ksmbd_file *fp,
6365 loff_t offset, size_t length, bool sync)
6371 data_buf = kvmalloc(length, GFP_KERNEL | __GFP_ZERO);
6375 ret = ksmbd_conn_rdma_read(work->conn, data_buf, length,
6376 (struct smb2_buffer_desc_v1 *)
6377 ((char *)req + le16_to_cpu(req->WriteChannelInfoOffset)),
6378 le16_to_cpu(req->WriteChannelInfoLength));
6384 ret = ksmbd_vfs_write(work, fp, data_buf, length, &offset, sync, &nbytes);
6393 * smb2_write() - handler for smb2 write from file
6394 * @work: smb work containing write command buffer
6396 * Return: 0 on success, otherwise error
6398 int smb2_write(struct ksmbd_work *work)
6400 struct smb2_write_req *req;
6401 struct smb2_write_rsp *rsp;
6402 struct ksmbd_file *fp = NULL;
6407 bool writethrough = false, is_rdma_channel = false;
6409 unsigned int max_write_size = work->conn->vals->max_write_size;
6411 WORK_BUFFERS(work, req, rsp);
6413 if (test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_PIPE)) {
6414 ksmbd_debug(SMB, "IPC pipe write request\n");
6415 return smb2_write_pipe(work);
6418 offset = le64_to_cpu(req->Offset);
6419 length = le32_to_cpu(req->Length);
6421 if (req->Channel == SMB2_CHANNEL_RDMA_V1 ||
6422 req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE) {
6423 is_rdma_channel = true;
6424 max_write_size = get_smbd_max_read_write_size();
6425 length = le32_to_cpu(req->RemainingBytes);
6428 if (is_rdma_channel == true) {
6429 unsigned int ch_offset = le16_to_cpu(req->WriteChannelInfoOffset);
6431 if (req->Length != 0 || req->DataOffset != 0 ||
6432 ch_offset < offsetof(struct smb2_write_req, Buffer)) {
6436 err = smb2_set_remote_key_for_rdma(work,
6437 (struct smb2_buffer_desc_v1 *)
6438 ((char *)req + ch_offset),
6440 req->WriteChannelInfoLength);
6445 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
6446 ksmbd_debug(SMB, "User does not have write permission\n");
6451 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
6457 if (!(fp->daccess & (FILE_WRITE_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
6458 pr_err("Not permitted to write : 0x%x\n", fp->daccess);
6463 if (length > max_write_size) {
6464 ksmbd_debug(SMB, "limiting write size to max size(%u)\n",
6470 ksmbd_debug(SMB, "flags %u\n", le32_to_cpu(req->Flags));
6471 if (le32_to_cpu(req->Flags) & SMB2_WRITEFLAG_WRITE_THROUGH)
6472 writethrough = true;
6474 if (is_rdma_channel == false) {
6475 if (le16_to_cpu(req->DataOffset) <
6476 offsetof(struct smb2_write_req, Buffer)) {
6481 data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
6482 le16_to_cpu(req->DataOffset));
6484 ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
6485 fp->filp, offset, length);
6486 err = ksmbd_vfs_write(work, fp, data_buf, length, &offset,
6487 writethrough, &nbytes);
6491 /* read data from the client using rdma channel, and
6494 nbytes = smb2_write_rdma_channel(work, req, fp, offset, length,
6502 rsp->StructureSize = cpu_to_le16(17);
6503 rsp->DataOffset = 0;
6505 rsp->DataLength = cpu_to_le32(nbytes);
6506 rsp->DataRemaining = 0;
6508 inc_rfc1001_len(work->response_buf, 16);
6509 ksmbd_fd_put(work, fp);
6514 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6515 else if (err == -ENOSPC || err == -EFBIG)
6516 rsp->hdr.Status = STATUS_DISK_FULL;
6517 else if (err == -ENOENT)
6518 rsp->hdr.Status = STATUS_FILE_CLOSED;
6519 else if (err == -EACCES)
6520 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6521 else if (err == -ESHARE)
6522 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6523 else if (err == -EINVAL)
6524 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6526 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6528 smb2_set_err_rsp(work);
6529 ksmbd_fd_put(work, fp);
6534 * smb2_flush() - handler for smb2 flush file - fsync
6535 * @work: smb work containing flush command buffer
6537 * Return: 0 on success, otherwise error
6539 int smb2_flush(struct ksmbd_work *work)
6541 struct smb2_flush_req *req;
6542 struct smb2_flush_rsp *rsp;
6545 WORK_BUFFERS(work, req, rsp);
6547 ksmbd_debug(SMB, "SMB2_FLUSH called for fid %llu\n", req->VolatileFileId);
6549 err = ksmbd_vfs_fsync(work, req->VolatileFileId, req->PersistentFileId);
6553 rsp->StructureSize = cpu_to_le16(4);
6555 inc_rfc1001_len(work->response_buf, 4);
6560 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6561 smb2_set_err_rsp(work);
6568 * smb2_cancel() - handler for smb2 cancel command
6569 * @work: smb work containing cancel command buffer
6571 * Return: 0 on success, otherwise error
6573 int smb2_cancel(struct ksmbd_work *work)
6575 struct ksmbd_conn *conn = work->conn;
6576 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
6577 struct smb2_hdr *chdr;
6578 struct ksmbd_work *iter;
6579 struct list_head *command_list;
6581 ksmbd_debug(SMB, "smb2 cancel called on mid %llu, async flags 0x%x\n",
6582 hdr->MessageId, hdr->Flags);
6584 if (hdr->Flags & SMB2_FLAGS_ASYNC_COMMAND) {
6585 command_list = &conn->async_requests;
6587 spin_lock(&conn->request_lock);
6588 list_for_each_entry(iter, command_list,
6589 async_request_entry) {
6590 chdr = smb2_get_msg(iter->request_buf);
6592 if (iter->async_id !=
6593 le64_to_cpu(hdr->Id.AsyncId))
6597 "smb2 with AsyncId %llu cancelled command = 0x%x\n",
6598 le64_to_cpu(hdr->Id.AsyncId),
6599 le16_to_cpu(chdr->Command));
6600 iter->state = KSMBD_WORK_CANCELLED;
6601 if (iter->cancel_fn)
6602 iter->cancel_fn(iter->cancel_argv);
6605 spin_unlock(&conn->request_lock);
6607 command_list = &conn->requests;
6609 spin_lock(&conn->request_lock);
6610 list_for_each_entry(iter, command_list, request_entry) {
6611 chdr = smb2_get_msg(iter->request_buf);
6613 if (chdr->MessageId != hdr->MessageId ||
6618 "smb2 with mid %llu cancelled command = 0x%x\n",
6619 le64_to_cpu(hdr->MessageId),
6620 le16_to_cpu(chdr->Command));
6621 iter->state = KSMBD_WORK_CANCELLED;
6624 spin_unlock(&conn->request_lock);
6627 /* For SMB2_CANCEL command itself send no response*/
6628 work->send_no_response = 1;
6632 struct file_lock *smb_flock_init(struct file *f)
6634 struct file_lock *fl;
6636 fl = locks_alloc_lock();
6640 locks_init_lock(fl);
6643 fl->fl_pid = current->tgid;
6645 fl->fl_flags = FL_POSIX;
6647 fl->fl_lmops = NULL;
6653 static int smb2_set_flock_flags(struct file_lock *flock, int flags)
6657 /* Checking for wrong flag combination during lock request*/
6659 case SMB2_LOCKFLAG_SHARED:
6660 ksmbd_debug(SMB, "received shared request\n");
6662 flock->fl_type = F_RDLCK;
6663 flock->fl_flags |= FL_SLEEP;
6665 case SMB2_LOCKFLAG_EXCLUSIVE:
6666 ksmbd_debug(SMB, "received exclusive request\n");
6668 flock->fl_type = F_WRLCK;
6669 flock->fl_flags |= FL_SLEEP;
6671 case SMB2_LOCKFLAG_SHARED | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
6673 "received shared & fail immediately request\n");
6675 flock->fl_type = F_RDLCK;
6677 case SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
6679 "received exclusive & fail immediately request\n");
6681 flock->fl_type = F_WRLCK;
6683 case SMB2_LOCKFLAG_UNLOCK:
6684 ksmbd_debug(SMB, "received unlock request\n");
6685 flock->fl_type = F_UNLCK;
6693 static struct ksmbd_lock *smb2_lock_init(struct file_lock *flock,
6694 unsigned int cmd, int flags,
6695 struct list_head *lock_list)
6697 struct ksmbd_lock *lock;
6699 lock = kzalloc(sizeof(struct ksmbd_lock), GFP_KERNEL);
6705 lock->start = flock->fl_start;
6706 lock->end = flock->fl_end;
6707 lock->flags = flags;
6708 if (lock->start == lock->end)
6710 INIT_LIST_HEAD(&lock->clist);
6711 INIT_LIST_HEAD(&lock->flist);
6712 INIT_LIST_HEAD(&lock->llist);
6713 list_add_tail(&lock->llist, lock_list);
6718 static void smb2_remove_blocked_lock(void **argv)
6720 struct file_lock *flock = (struct file_lock *)argv[0];
6722 ksmbd_vfs_posix_lock_unblock(flock);
6723 wake_up(&flock->fl_wait);
6726 static inline bool lock_defer_pending(struct file_lock *fl)
6728 /* check pending lock waiters */
6729 return waitqueue_active(&fl->fl_wait);
6733 * smb2_lock() - handler for smb2 file lock command
6734 * @work: smb work containing lock command buffer
6736 * Return: 0 on success, otherwise error
6738 int smb2_lock(struct ksmbd_work *work)
6740 struct smb2_lock_req *req = smb2_get_msg(work->request_buf);
6741 struct smb2_lock_rsp *rsp = smb2_get_msg(work->response_buf);
6742 struct smb2_lock_element *lock_ele;
6743 struct ksmbd_file *fp = NULL;
6744 struct file_lock *flock = NULL;
6745 struct file *filp = NULL;
6749 int err = -EIO, i, rc = 0;
6750 u64 lock_start, lock_length;
6751 struct ksmbd_lock *smb_lock = NULL, *cmp_lock, *tmp, *tmp2;
6752 struct ksmbd_conn *conn;
6754 LIST_HEAD(lock_list);
6755 LIST_HEAD(rollback_list);
6758 ksmbd_debug(SMB, "Received lock request\n");
6759 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
6761 ksmbd_debug(SMB, "Invalid file id for lock : %llu\n", req->VolatileFileId);
6767 lock_count = le16_to_cpu(req->LockCount);
6768 lock_ele = req->locks;
6770 ksmbd_debug(SMB, "lock count is %d\n", lock_count);
6776 for (i = 0; i < lock_count; i++) {
6777 flags = le32_to_cpu(lock_ele[i].Flags);
6779 flock = smb_flock_init(filp);
6783 cmd = smb2_set_flock_flags(flock, flags);
6785 lock_start = le64_to_cpu(lock_ele[i].Offset);
6786 lock_length = le64_to_cpu(lock_ele[i].Length);
6787 if (lock_start > U64_MAX - lock_length) {
6788 pr_err("Invalid lock range requested\n");
6789 rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
6790 locks_free_lock(flock);
6794 if (lock_start > OFFSET_MAX)
6795 flock->fl_start = OFFSET_MAX;
6797 flock->fl_start = lock_start;
6799 lock_length = le64_to_cpu(lock_ele[i].Length);
6800 if (lock_length > OFFSET_MAX - flock->fl_start)
6801 lock_length = OFFSET_MAX - flock->fl_start;
6803 flock->fl_end = flock->fl_start + lock_length;
6805 if (flock->fl_end < flock->fl_start) {
6807 "the end offset(%llx) is smaller than the start offset(%llx)\n",
6808 flock->fl_end, flock->fl_start);
6809 rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
6810 locks_free_lock(flock);
6814 /* Check conflict locks in one request */
6815 list_for_each_entry(cmp_lock, &lock_list, llist) {
6816 if (cmp_lock->fl->fl_start <= flock->fl_start &&
6817 cmp_lock->fl->fl_end >= flock->fl_end) {
6818 if (cmp_lock->fl->fl_type != F_UNLCK &&
6819 flock->fl_type != F_UNLCK) {
6820 pr_err("conflict two locks in one request\n");
6822 locks_free_lock(flock);
6828 smb_lock = smb2_lock_init(flock, cmd, flags, &lock_list);
6831 locks_free_lock(flock);
6836 list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
6837 if (smb_lock->cmd < 0) {
6842 if (!(smb_lock->flags & SMB2_LOCKFLAG_MASK)) {
6847 if ((prior_lock & (SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_SHARED) &&
6848 smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) ||
6849 (prior_lock == SMB2_LOCKFLAG_UNLOCK &&
6850 !(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK))) {
6855 prior_lock = smb_lock->flags;
6857 if (!(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) &&
6858 !(smb_lock->flags & SMB2_LOCKFLAG_FAIL_IMMEDIATELY))
6862 /* check locks in connection list */
6863 down_read(&conn_list_lock);
6864 list_for_each_entry(conn, &conn_list, conns_list) {
6865 spin_lock(&conn->llist_lock);
6866 list_for_each_entry_safe(cmp_lock, tmp2, &conn->lock_list, clist) {
6867 if (file_inode(cmp_lock->fl->fl_file) !=
6868 file_inode(smb_lock->fl->fl_file))
6871 if (smb_lock->fl->fl_type == F_UNLCK) {
6872 if (cmp_lock->fl->fl_file == smb_lock->fl->fl_file &&
6873 cmp_lock->start == smb_lock->start &&
6874 cmp_lock->end == smb_lock->end &&
6875 !lock_defer_pending(cmp_lock->fl)) {
6877 list_del(&cmp_lock->flist);
6878 list_del(&cmp_lock->clist);
6879 spin_unlock(&conn->llist_lock);
6880 up_read(&conn_list_lock);
6882 locks_free_lock(cmp_lock->fl);
6889 if (cmp_lock->fl->fl_file == smb_lock->fl->fl_file) {
6890 if (smb_lock->flags & SMB2_LOCKFLAG_SHARED)
6893 if (cmp_lock->flags & SMB2_LOCKFLAG_SHARED)
6897 /* check zero byte lock range */
6898 if (cmp_lock->zero_len && !smb_lock->zero_len &&
6899 cmp_lock->start > smb_lock->start &&
6900 cmp_lock->start < smb_lock->end) {
6901 spin_unlock(&conn->llist_lock);
6902 up_read(&conn_list_lock);
6903 pr_err("previous lock conflict with zero byte lock range\n");
6907 if (smb_lock->zero_len && !cmp_lock->zero_len &&
6908 smb_lock->start > cmp_lock->start &&
6909 smb_lock->start < cmp_lock->end) {
6910 spin_unlock(&conn->llist_lock);
6911 up_read(&conn_list_lock);
6912 pr_err("current lock conflict with zero byte lock range\n");
6916 if (((cmp_lock->start <= smb_lock->start &&
6917 cmp_lock->end > smb_lock->start) ||
6918 (cmp_lock->start < smb_lock->end &&
6919 cmp_lock->end >= smb_lock->end)) &&
6920 !cmp_lock->zero_len && !smb_lock->zero_len) {
6921 spin_unlock(&conn->llist_lock);
6922 up_read(&conn_list_lock);
6923 pr_err("Not allow lock operation on exclusive lock range\n");
6927 spin_unlock(&conn->llist_lock);
6929 up_read(&conn_list_lock);
6931 if (smb_lock->fl->fl_type == F_UNLCK && nolock) {
6932 pr_err("Try to unlock nolocked range\n");
6933 rsp->hdr.Status = STATUS_RANGE_NOT_LOCKED;
6938 if (smb_lock->zero_len) {
6943 flock = smb_lock->fl;
6944 list_del(&smb_lock->llist);
6946 rc = vfs_lock_file(filp, smb_lock->cmd, flock, NULL);
6948 if (flags & SMB2_LOCKFLAG_UNLOCK) {
6950 ksmbd_debug(SMB, "File unlocked\n");
6951 } else if (rc == -ENOENT) {
6952 rsp->hdr.Status = STATUS_NOT_LOCKED;
6955 locks_free_lock(flock);
6958 if (rc == FILE_LOCK_DEFERRED) {
6962 "would have to wait for getting lock\n");
6963 spin_lock(&work->conn->llist_lock);
6964 list_add_tail(&smb_lock->clist,
6965 &work->conn->lock_list);
6966 spin_unlock(&work->conn->llist_lock);
6967 list_add(&smb_lock->llist, &rollback_list);
6969 argv = kmalloc(sizeof(void *), GFP_KERNEL);
6976 rc = setup_async_work(work,
6977 smb2_remove_blocked_lock,
6983 spin_lock(&fp->f_lock);
6984 list_add(&work->fp_entry, &fp->blocked_works);
6985 spin_unlock(&fp->f_lock);
6987 smb2_send_interim_resp(work, STATUS_PENDING);
6989 ksmbd_vfs_posix_lock_wait(flock);
6991 spin_lock(&fp->f_lock);
6992 list_del(&work->fp_entry);
6993 spin_unlock(&fp->f_lock);
6995 if (work->state != KSMBD_WORK_ACTIVE) {
6996 list_del(&smb_lock->llist);
6997 spin_lock(&work->conn->llist_lock);
6998 list_del(&smb_lock->clist);
6999 spin_unlock(&work->conn->llist_lock);
7000 locks_free_lock(flock);
7002 if (work->state == KSMBD_WORK_CANCELLED) {
7006 smb2_send_interim_resp(work,
7008 work->send_no_response = 1;
7012 init_smb2_rsp_hdr(work);
7013 smb2_set_err_rsp(work);
7015 STATUS_RANGE_NOT_LOCKED;
7020 list_del(&smb_lock->llist);
7021 spin_lock(&work->conn->llist_lock);
7022 list_del(&smb_lock->clist);
7023 spin_unlock(&work->conn->llist_lock);
7024 release_async_work(work);
7027 spin_lock(&work->conn->llist_lock);
7028 list_add_tail(&smb_lock->clist,
7029 &work->conn->lock_list);
7030 list_add_tail(&smb_lock->flist,
7032 spin_unlock(&work->conn->llist_lock);
7033 list_add(&smb_lock->llist, &rollback_list);
7034 ksmbd_debug(SMB, "successful in taking lock\n");
7041 if (atomic_read(&fp->f_ci->op_count) > 1)
7042 smb_break_all_oplock(work, fp);
7044 rsp->StructureSize = cpu_to_le16(4);
7045 ksmbd_debug(SMB, "successful in taking lock\n");
7046 rsp->hdr.Status = STATUS_SUCCESS;
7048 inc_rfc1001_len(work->response_buf, 4);
7049 ksmbd_fd_put(work, fp);
7053 list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
7054 locks_free_lock(smb_lock->fl);
7055 list_del(&smb_lock->llist);
7059 list_for_each_entry_safe(smb_lock, tmp, &rollback_list, llist) {
7060 struct file_lock *rlock = NULL;
7062 rlock = smb_flock_init(filp);
7063 rlock->fl_type = F_UNLCK;
7064 rlock->fl_start = smb_lock->start;
7065 rlock->fl_end = smb_lock->end;
7067 rc = vfs_lock_file(filp, F_SETLK, rlock, NULL);
7069 pr_err("rollback unlock fail : %d\n", rc);
7071 list_del(&smb_lock->llist);
7072 spin_lock(&work->conn->llist_lock);
7073 if (!list_empty(&smb_lock->flist))
7074 list_del(&smb_lock->flist);
7075 list_del(&smb_lock->clist);
7076 spin_unlock(&work->conn->llist_lock);
7078 locks_free_lock(smb_lock->fl);
7079 locks_free_lock(rlock);
7083 ksmbd_debug(SMB, "failed in taking lock(flags : %x), err : %d\n", flags, err);
7085 if (!rsp->hdr.Status) {
7087 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7088 else if (err == -ENOMEM)
7089 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
7090 else if (err == -ENOENT)
7091 rsp->hdr.Status = STATUS_FILE_CLOSED;
7093 rsp->hdr.Status = STATUS_LOCK_NOT_GRANTED;
7096 smb2_set_err_rsp(work);
7097 ksmbd_fd_put(work, fp);
7101 static int fsctl_copychunk(struct ksmbd_work *work,
7102 struct copychunk_ioctl_req *ci_req,
7103 unsigned int cnt_code,
7104 unsigned int input_count,
7105 unsigned long long volatile_id,
7106 unsigned long long persistent_id,
7107 struct smb2_ioctl_rsp *rsp)
7109 struct copychunk_ioctl_rsp *ci_rsp;
7110 struct ksmbd_file *src_fp = NULL, *dst_fp = NULL;
7111 struct srv_copychunk *chunks;
7112 unsigned int i, chunk_count, chunk_count_written = 0;
7113 unsigned int chunk_size_written = 0;
7114 loff_t total_size_written = 0;
7117 ci_rsp = (struct copychunk_ioctl_rsp *)&rsp->Buffer[0];
7119 rsp->VolatileFileId = volatile_id;
7120 rsp->PersistentFileId = persistent_id;
7121 ci_rsp->ChunksWritten =
7122 cpu_to_le32(ksmbd_server_side_copy_max_chunk_count());
7123 ci_rsp->ChunkBytesWritten =
7124 cpu_to_le32(ksmbd_server_side_copy_max_chunk_size());
7125 ci_rsp->TotalBytesWritten =
7126 cpu_to_le32(ksmbd_server_side_copy_max_total_size());
7128 chunks = (struct srv_copychunk *)&ci_req->Chunks[0];
7129 chunk_count = le32_to_cpu(ci_req->ChunkCount);
7130 if (chunk_count == 0)
7132 total_size_written = 0;
7134 /* verify the SRV_COPYCHUNK_COPY packet */
7135 if (chunk_count > ksmbd_server_side_copy_max_chunk_count() ||
7136 input_count < offsetof(struct copychunk_ioctl_req, Chunks) +
7137 chunk_count * sizeof(struct srv_copychunk)) {
7138 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7142 for (i = 0; i < chunk_count; i++) {
7143 if (le32_to_cpu(chunks[i].Length) == 0 ||
7144 le32_to_cpu(chunks[i].Length) > ksmbd_server_side_copy_max_chunk_size())
7146 total_size_written += le32_to_cpu(chunks[i].Length);
7149 if (i < chunk_count ||
7150 total_size_written > ksmbd_server_side_copy_max_total_size()) {
7151 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7155 src_fp = ksmbd_lookup_foreign_fd(work,
7156 le64_to_cpu(ci_req->ResumeKey[0]));
7157 dst_fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
7160 src_fp->persistent_id != le64_to_cpu(ci_req->ResumeKey[1])) {
7161 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
7166 rsp->hdr.Status = STATUS_FILE_CLOSED;
7171 * FILE_READ_DATA should only be included in
7172 * the FSCTL_COPYCHUNK case
7174 if (cnt_code == FSCTL_COPYCHUNK &&
7175 !(dst_fp->daccess & (FILE_READ_DATA_LE | FILE_GENERIC_READ_LE))) {
7176 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7180 ret = ksmbd_vfs_copy_file_ranges(work, src_fp, dst_fp,
7181 chunks, chunk_count,
7182 &chunk_count_written,
7183 &chunk_size_written,
7184 &total_size_written);
7187 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7189 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
7190 else if (ret == -EBADF)
7191 rsp->hdr.Status = STATUS_INVALID_HANDLE;
7192 else if (ret == -EFBIG || ret == -ENOSPC)
7193 rsp->hdr.Status = STATUS_DISK_FULL;
7194 else if (ret == -EINVAL)
7195 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7196 else if (ret == -EISDIR)
7197 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
7198 else if (ret == -E2BIG)
7199 rsp->hdr.Status = STATUS_INVALID_VIEW_SIZE;
7201 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
7204 ci_rsp->ChunksWritten = cpu_to_le32(chunk_count_written);
7205 ci_rsp->ChunkBytesWritten = cpu_to_le32(chunk_size_written);
7206 ci_rsp->TotalBytesWritten = cpu_to_le32(total_size_written);
7208 ksmbd_fd_put(work, src_fp);
7209 ksmbd_fd_put(work, dst_fp);
7213 static __be32 idev_ipv4_address(struct in_device *idev)
7217 struct in_ifaddr *ifa;
7220 in_dev_for_each_ifa_rcu(ifa, idev) {
7221 if (ifa->ifa_flags & IFA_F_SECONDARY)
7224 addr = ifa->ifa_address;
7231 static int fsctl_query_iface_info_ioctl(struct ksmbd_conn *conn,
7232 struct smb2_ioctl_rsp *rsp,
7233 unsigned int out_buf_len)
7235 struct network_interface_info_ioctl_rsp *nii_rsp = NULL;
7237 struct net_device *netdev;
7238 struct sockaddr_storage_rsp *sockaddr_storage;
7240 unsigned long long speed;
7243 for_each_netdev(&init_net, netdev) {
7244 bool ipv4_set = false;
7246 if (netdev->type == ARPHRD_LOOPBACK)
7249 flags = dev_get_flags(netdev);
7250 if (!(flags & IFF_RUNNING))
7254 nbytes + sizeof(struct network_interface_info_ioctl_rsp)) {
7259 nii_rsp = (struct network_interface_info_ioctl_rsp *)
7260 &rsp->Buffer[nbytes];
7261 nii_rsp->IfIndex = cpu_to_le32(netdev->ifindex);
7263 nii_rsp->Capability = 0;
7264 if (netdev->real_num_tx_queues > 1)
7265 nii_rsp->Capability |= cpu_to_le32(RSS_CAPABLE);
7266 if (ksmbd_rdma_capable_netdev(netdev))
7267 nii_rsp->Capability |= cpu_to_le32(RDMA_CAPABLE);
7269 nii_rsp->Next = cpu_to_le32(152);
7270 nii_rsp->Reserved = 0;
7272 if (netdev->ethtool_ops->get_link_ksettings) {
7273 struct ethtool_link_ksettings cmd;
7275 netdev->ethtool_ops->get_link_ksettings(netdev, &cmd);
7276 speed = cmd.base.speed;
7278 ksmbd_debug(SMB, "%s %s\n", netdev->name,
7279 "speed is unknown, defaulting to 1Gb/sec");
7284 nii_rsp->LinkSpeed = cpu_to_le64(speed);
7286 sockaddr_storage = (struct sockaddr_storage_rsp *)
7287 nii_rsp->SockAddr_Storage;
7288 memset(sockaddr_storage, 0, 128);
7291 struct in_device *idev;
7293 sockaddr_storage->Family = cpu_to_le16(INTERNETWORK);
7294 sockaddr_storage->addr4.Port = 0;
7296 idev = __in_dev_get_rtnl(netdev);
7299 sockaddr_storage->addr4.IPv4address =
7300 idev_ipv4_address(idev);
7301 nbytes += sizeof(struct network_interface_info_ioctl_rsp);
7305 struct inet6_dev *idev6;
7306 struct inet6_ifaddr *ifa;
7307 __u8 *ipv6_addr = sockaddr_storage->addr6.IPv6address;
7309 sockaddr_storage->Family = cpu_to_le16(INTERNETWORKV6);
7310 sockaddr_storage->addr6.Port = 0;
7311 sockaddr_storage->addr6.FlowInfo = 0;
7313 idev6 = __in6_dev_get(netdev);
7317 list_for_each_entry(ifa, &idev6->addr_list, if_list) {
7318 if (ifa->flags & (IFA_F_TENTATIVE |
7321 memcpy(ipv6_addr, ifa->addr.s6_addr, 16);
7324 sockaddr_storage->addr6.ScopeId = 0;
7325 nbytes += sizeof(struct network_interface_info_ioctl_rsp);
7330 /* zero if this is last one */
7334 rsp->PersistentFileId = SMB2_NO_FID;
7335 rsp->VolatileFileId = SMB2_NO_FID;
7339 static int fsctl_validate_negotiate_info(struct ksmbd_conn *conn,
7340 struct validate_negotiate_info_req *neg_req,
7341 struct validate_negotiate_info_rsp *neg_rsp,
7342 unsigned int in_buf_len)
7347 if (in_buf_len < offsetof(struct validate_negotiate_info_req, Dialects) +
7348 le16_to_cpu(neg_req->DialectCount) * sizeof(__le16))
7351 dialect = ksmbd_lookup_dialect_by_id(neg_req->Dialects,
7352 neg_req->DialectCount);
7353 if (dialect == BAD_PROT_ID || dialect != conn->dialect) {
7358 if (strncmp(neg_req->Guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE)) {
7363 if (le16_to_cpu(neg_req->SecurityMode) != conn->cli_sec_mode) {
7368 if (le32_to_cpu(neg_req->Capabilities) != conn->cli_cap) {
7373 neg_rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
7374 memset(neg_rsp->Guid, 0, SMB2_CLIENT_GUID_SIZE);
7375 neg_rsp->SecurityMode = cpu_to_le16(conn->srv_sec_mode);
7376 neg_rsp->Dialect = cpu_to_le16(conn->dialect);
7381 static int fsctl_query_allocated_ranges(struct ksmbd_work *work, u64 id,
7382 struct file_allocated_range_buffer *qar_req,
7383 struct file_allocated_range_buffer *qar_rsp,
7384 unsigned int in_count, unsigned int *out_count)
7386 struct ksmbd_file *fp;
7387 loff_t start, length;
7394 start = le64_to_cpu(qar_req->file_offset);
7395 length = le64_to_cpu(qar_req->length);
7397 if (start < 0 || length < 0)
7400 fp = ksmbd_lookup_fd_fast(work, id);
7404 ret = ksmbd_vfs_fqar_lseek(fp, start, length,
7405 qar_rsp, in_count, out_count);
7406 if (ret && ret != -E2BIG)
7409 ksmbd_fd_put(work, fp);
7413 static int fsctl_pipe_transceive(struct ksmbd_work *work, u64 id,
7414 unsigned int out_buf_len,
7415 struct smb2_ioctl_req *req,
7416 struct smb2_ioctl_rsp *rsp)
7418 struct ksmbd_rpc_command *rpc_resp;
7419 char *data_buf = (char *)&req->Buffer[0];
7422 rpc_resp = ksmbd_rpc_ioctl(work->sess, id, data_buf,
7423 le32_to_cpu(req->InputCount));
7425 if (rpc_resp->flags == KSMBD_RPC_SOME_NOT_MAPPED) {
7427 * set STATUS_SOME_NOT_MAPPED response
7428 * for unknown domain sid.
7430 rsp->hdr.Status = STATUS_SOME_NOT_MAPPED;
7431 } else if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
7432 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7434 } else if (rpc_resp->flags != KSMBD_RPC_OK) {
7435 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7439 nbytes = rpc_resp->payload_sz;
7440 if (rpc_resp->payload_sz > out_buf_len) {
7441 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
7442 nbytes = out_buf_len;
7445 if (!rpc_resp->payload_sz) {
7447 STATUS_UNEXPECTED_IO_ERROR;
7451 memcpy((char *)rsp->Buffer, rpc_resp->payload, nbytes);
7458 static inline int fsctl_set_sparse(struct ksmbd_work *work, u64 id,
7459 struct file_sparse *sparse)
7461 struct ksmbd_file *fp;
7462 struct mnt_idmap *idmap;
7466 fp = ksmbd_lookup_fd_fast(work, id);
7469 idmap = file_mnt_idmap(fp->filp);
7471 old_fattr = fp->f_ci->m_fattr;
7472 if (sparse->SetSparse)
7473 fp->f_ci->m_fattr |= FILE_ATTRIBUTE_SPARSE_FILE_LE;
7475 fp->f_ci->m_fattr &= ~FILE_ATTRIBUTE_SPARSE_FILE_LE;
7477 if (fp->f_ci->m_fattr != old_fattr &&
7478 test_share_config_flag(work->tcon->share_conf,
7479 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS)) {
7480 struct xattr_dos_attrib da;
7482 ret = ksmbd_vfs_get_dos_attrib_xattr(idmap,
7483 fp->filp->f_path.dentry, &da);
7487 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
7488 ret = ksmbd_vfs_set_dos_attrib_xattr(idmap,
7489 fp->filp->f_path.dentry, &da);
7491 fp->f_ci->m_fattr = old_fattr;
7495 ksmbd_fd_put(work, fp);
7499 static int fsctl_request_resume_key(struct ksmbd_work *work,
7500 struct smb2_ioctl_req *req,
7501 struct resume_key_ioctl_rsp *key_rsp)
7503 struct ksmbd_file *fp;
7505 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
7509 memset(key_rsp, 0, sizeof(*key_rsp));
7510 key_rsp->ResumeKey[0] = req->VolatileFileId;
7511 key_rsp->ResumeKey[1] = req->PersistentFileId;
7512 ksmbd_fd_put(work, fp);
7518 * smb2_ioctl() - handler for smb2 ioctl command
7519 * @work: smb work containing ioctl command buffer
7521 * Return: 0 on success, otherwise error
7523 int smb2_ioctl(struct ksmbd_work *work)
7525 struct smb2_ioctl_req *req;
7526 struct smb2_ioctl_rsp *rsp;
7527 unsigned int cnt_code, nbytes = 0, out_buf_len, in_buf_len;
7528 u64 id = KSMBD_NO_FID;
7529 struct ksmbd_conn *conn = work->conn;
7532 if (work->next_smb2_rcv_hdr_off) {
7533 req = ksmbd_req_buf_next(work);
7534 rsp = ksmbd_resp_buf_next(work);
7535 if (!has_file_id(req->VolatileFileId)) {
7536 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
7537 work->compound_fid);
7538 id = work->compound_fid;
7541 req = smb2_get_msg(work->request_buf);
7542 rsp = smb2_get_msg(work->response_buf);
7545 if (!has_file_id(id))
7546 id = req->VolatileFileId;
7548 if (req->Flags != cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL)) {
7549 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7553 cnt_code = le32_to_cpu(req->CtlCode);
7554 ret = smb2_calc_max_out_buf_len(work, 48,
7555 le32_to_cpu(req->MaxOutputResponse));
7557 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7560 out_buf_len = (unsigned int)ret;
7561 in_buf_len = le32_to_cpu(req->InputCount);
7564 case FSCTL_DFS_GET_REFERRALS:
7565 case FSCTL_DFS_GET_REFERRALS_EX:
7566 /* Not support DFS yet */
7567 rsp->hdr.Status = STATUS_FS_DRIVER_REQUIRED;
7569 case FSCTL_CREATE_OR_GET_OBJECT_ID:
7571 struct file_object_buf_type1_ioctl_rsp *obj_buf;
7573 nbytes = sizeof(struct file_object_buf_type1_ioctl_rsp);
7574 obj_buf = (struct file_object_buf_type1_ioctl_rsp *)
7578 * TODO: This is dummy implementation to pass smbtorture
7579 * Need to check correct response later
7581 memset(obj_buf->ObjectId, 0x0, 16);
7582 memset(obj_buf->BirthVolumeId, 0x0, 16);
7583 memset(obj_buf->BirthObjectId, 0x0, 16);
7584 memset(obj_buf->DomainId, 0x0, 16);
7588 case FSCTL_PIPE_TRANSCEIVE:
7589 out_buf_len = min_t(u32, KSMBD_IPC_MAX_PAYLOAD, out_buf_len);
7590 nbytes = fsctl_pipe_transceive(work, id, out_buf_len, req, rsp);
7592 case FSCTL_VALIDATE_NEGOTIATE_INFO:
7593 if (conn->dialect < SMB30_PROT_ID) {
7598 if (in_buf_len < offsetof(struct validate_negotiate_info_req,
7604 if (out_buf_len < sizeof(struct validate_negotiate_info_rsp)) {
7609 ret = fsctl_validate_negotiate_info(conn,
7610 (struct validate_negotiate_info_req *)&req->Buffer[0],
7611 (struct validate_negotiate_info_rsp *)&rsp->Buffer[0],
7616 nbytes = sizeof(struct validate_negotiate_info_rsp);
7617 rsp->PersistentFileId = SMB2_NO_FID;
7618 rsp->VolatileFileId = SMB2_NO_FID;
7620 case FSCTL_QUERY_NETWORK_INTERFACE_INFO:
7621 ret = fsctl_query_iface_info_ioctl(conn, rsp, out_buf_len);
7626 case FSCTL_REQUEST_RESUME_KEY:
7627 if (out_buf_len < sizeof(struct resume_key_ioctl_rsp)) {
7632 ret = fsctl_request_resume_key(work, req,
7633 (struct resume_key_ioctl_rsp *)&rsp->Buffer[0]);
7636 rsp->PersistentFileId = req->PersistentFileId;
7637 rsp->VolatileFileId = req->VolatileFileId;
7638 nbytes = sizeof(struct resume_key_ioctl_rsp);
7640 case FSCTL_COPYCHUNK:
7641 case FSCTL_COPYCHUNK_WRITE:
7642 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7644 "User does not have write permission\n");
7649 if (in_buf_len < sizeof(struct copychunk_ioctl_req)) {
7654 if (out_buf_len < sizeof(struct copychunk_ioctl_rsp)) {
7659 nbytes = sizeof(struct copychunk_ioctl_rsp);
7660 rsp->VolatileFileId = req->VolatileFileId;
7661 rsp->PersistentFileId = req->PersistentFileId;
7662 fsctl_copychunk(work,
7663 (struct copychunk_ioctl_req *)&req->Buffer[0],
7664 le32_to_cpu(req->CtlCode),
7665 le32_to_cpu(req->InputCount),
7666 req->VolatileFileId,
7667 req->PersistentFileId,
7670 case FSCTL_SET_SPARSE:
7671 if (in_buf_len < sizeof(struct file_sparse)) {
7676 ret = fsctl_set_sparse(work, id,
7677 (struct file_sparse *)&req->Buffer[0]);
7681 case FSCTL_SET_ZERO_DATA:
7683 struct file_zero_data_information *zero_data;
7684 struct ksmbd_file *fp;
7685 loff_t off, len, bfz;
7687 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7689 "User does not have write permission\n");
7694 if (in_buf_len < sizeof(struct file_zero_data_information)) {
7700 (struct file_zero_data_information *)&req->Buffer[0];
7702 off = le64_to_cpu(zero_data->FileOffset);
7703 bfz = le64_to_cpu(zero_data->BeyondFinalZero);
7704 if (off < 0 || bfz < 0 || off > bfz) {
7711 fp = ksmbd_lookup_fd_fast(work, id);
7717 ret = ksmbd_vfs_zero_data(work, fp, off, len);
7718 ksmbd_fd_put(work, fp);
7724 case FSCTL_QUERY_ALLOCATED_RANGES:
7725 if (in_buf_len < sizeof(struct file_allocated_range_buffer)) {
7730 ret = fsctl_query_allocated_ranges(work, id,
7731 (struct file_allocated_range_buffer *)&req->Buffer[0],
7732 (struct file_allocated_range_buffer *)&rsp->Buffer[0],
7734 sizeof(struct file_allocated_range_buffer), &nbytes);
7735 if (ret == -E2BIG) {
7736 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
7737 } else if (ret < 0) {
7742 nbytes *= sizeof(struct file_allocated_range_buffer);
7744 case FSCTL_GET_REPARSE_POINT:
7746 struct reparse_data_buffer *reparse_ptr;
7747 struct ksmbd_file *fp;
7749 reparse_ptr = (struct reparse_data_buffer *)&rsp->Buffer[0];
7750 fp = ksmbd_lookup_fd_fast(work, id);
7752 pr_err("not found fp!!\n");
7757 reparse_ptr->ReparseTag =
7758 smb2_get_reparse_tag_special_file(file_inode(fp->filp)->i_mode);
7759 reparse_ptr->ReparseDataLength = 0;
7760 ksmbd_fd_put(work, fp);
7761 nbytes = sizeof(struct reparse_data_buffer);
7764 case FSCTL_DUPLICATE_EXTENTS_TO_FILE:
7766 struct ksmbd_file *fp_in, *fp_out = NULL;
7767 struct duplicate_extents_to_file *dup_ext;
7768 loff_t src_off, dst_off, length, cloned;
7770 if (in_buf_len < sizeof(struct duplicate_extents_to_file)) {
7775 dup_ext = (struct duplicate_extents_to_file *)&req->Buffer[0];
7777 fp_in = ksmbd_lookup_fd_slow(work, dup_ext->VolatileFileHandle,
7778 dup_ext->PersistentFileHandle);
7780 pr_err("not found file handle in duplicate extent to file\n");
7785 fp_out = ksmbd_lookup_fd_fast(work, id);
7787 pr_err("not found fp\n");
7792 src_off = le64_to_cpu(dup_ext->SourceFileOffset);
7793 dst_off = le64_to_cpu(dup_ext->TargetFileOffset);
7794 length = le64_to_cpu(dup_ext->ByteCount);
7796 * XXX: It is not clear if FSCTL_DUPLICATE_EXTENTS_TO_FILE
7797 * should fall back to vfs_copy_file_range(). This could be
7798 * beneficial when re-exporting nfs/smb mount, but note that
7799 * this can result in partial copy that returns an error status.
7800 * If/when FSCTL_DUPLICATE_EXTENTS_TO_FILE_EX is implemented,
7801 * fall back to vfs_copy_file_range(), should be avoided when
7802 * the flag DUPLICATE_EXTENTS_DATA_EX_SOURCE_ATOMIC is set.
7804 cloned = vfs_clone_file_range(fp_in->filp, src_off,
7805 fp_out->filp, dst_off, length, 0);
7806 if (cloned == -EXDEV || cloned == -EOPNOTSUPP) {
7809 } else if (cloned != length) {
7810 cloned = vfs_copy_file_range(fp_in->filp, src_off,
7811 fp_out->filp, dst_off,
7813 if (cloned != length) {
7822 ksmbd_fd_put(work, fp_in);
7823 ksmbd_fd_put(work, fp_out);
7829 ksmbd_debug(SMB, "not implemented yet ioctl command 0x%x\n",
7835 rsp->CtlCode = cpu_to_le32(cnt_code);
7836 rsp->InputCount = cpu_to_le32(0);
7837 rsp->InputOffset = cpu_to_le32(112);
7838 rsp->OutputOffset = cpu_to_le32(112);
7839 rsp->OutputCount = cpu_to_le32(nbytes);
7840 rsp->StructureSize = cpu_to_le16(49);
7841 rsp->Reserved = cpu_to_le16(0);
7842 rsp->Flags = cpu_to_le32(0);
7843 rsp->Reserved2 = cpu_to_le32(0);
7844 inc_rfc1001_len(work->response_buf, 48 + nbytes);
7850 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7851 else if (ret == -ENOENT)
7852 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
7853 else if (ret == -EOPNOTSUPP)
7854 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7855 else if (ret == -ENOSPC)
7856 rsp->hdr.Status = STATUS_BUFFER_TOO_SMALL;
7857 else if (ret < 0 || rsp->hdr.Status == 0)
7858 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7859 smb2_set_err_rsp(work);
7864 * smb20_oplock_break_ack() - handler for smb2.0 oplock break command
7865 * @work: smb work containing oplock break command buffer
7869 static void smb20_oplock_break_ack(struct ksmbd_work *work)
7871 struct smb2_oplock_break *req = smb2_get_msg(work->request_buf);
7872 struct smb2_oplock_break *rsp = smb2_get_msg(work->response_buf);
7873 struct ksmbd_file *fp;
7874 struct oplock_info *opinfo = NULL;
7877 u64 volatile_id, persistent_id;
7878 char req_oplevel = 0, rsp_oplevel = 0;
7879 unsigned int oplock_change_type;
7881 volatile_id = req->VolatileFid;
7882 persistent_id = req->PersistentFid;
7883 req_oplevel = req->OplockLevel;
7884 ksmbd_debug(OPLOCK, "v_id %llu, p_id %llu request oplock level %d\n",
7885 volatile_id, persistent_id, req_oplevel);
7887 fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
7889 rsp->hdr.Status = STATUS_FILE_CLOSED;
7890 smb2_set_err_rsp(work);
7894 opinfo = opinfo_get(fp);
7896 pr_err("unexpected null oplock_info\n");
7897 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
7898 smb2_set_err_rsp(work);
7899 ksmbd_fd_put(work, fp);
7903 if (opinfo->level == SMB2_OPLOCK_LEVEL_NONE) {
7904 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
7908 if (opinfo->op_state == OPLOCK_STATE_NONE) {
7909 ksmbd_debug(SMB, "unexpected oplock state 0x%x\n", opinfo->op_state);
7910 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
7914 if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
7915 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
7916 (req_oplevel != SMB2_OPLOCK_LEVEL_II &&
7917 req_oplevel != SMB2_OPLOCK_LEVEL_NONE)) {
7918 err = STATUS_INVALID_OPLOCK_PROTOCOL;
7919 oplock_change_type = OPLOCK_WRITE_TO_NONE;
7920 } else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
7921 req_oplevel != SMB2_OPLOCK_LEVEL_NONE) {
7922 err = STATUS_INVALID_OPLOCK_PROTOCOL;
7923 oplock_change_type = OPLOCK_READ_TO_NONE;
7924 } else if (req_oplevel == SMB2_OPLOCK_LEVEL_II ||
7925 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
7926 err = STATUS_INVALID_DEVICE_STATE;
7927 if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
7928 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
7929 req_oplevel == SMB2_OPLOCK_LEVEL_II) {
7930 oplock_change_type = OPLOCK_WRITE_TO_READ;
7931 } else if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
7932 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
7933 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
7934 oplock_change_type = OPLOCK_WRITE_TO_NONE;
7935 } else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
7936 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
7937 oplock_change_type = OPLOCK_READ_TO_NONE;
7939 oplock_change_type = 0;
7942 oplock_change_type = 0;
7945 switch (oplock_change_type) {
7946 case OPLOCK_WRITE_TO_READ:
7947 ret = opinfo_write_to_read(opinfo);
7948 rsp_oplevel = SMB2_OPLOCK_LEVEL_II;
7950 case OPLOCK_WRITE_TO_NONE:
7951 ret = opinfo_write_to_none(opinfo);
7952 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
7954 case OPLOCK_READ_TO_NONE:
7955 ret = opinfo_read_to_none(opinfo);
7956 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
7959 pr_err("unknown oplock change 0x%x -> 0x%x\n",
7960 opinfo->level, rsp_oplevel);
7964 rsp->hdr.Status = err;
7969 ksmbd_fd_put(work, fp);
7970 opinfo->op_state = OPLOCK_STATE_NONE;
7971 wake_up_interruptible_all(&opinfo->oplock_q);
7973 rsp->StructureSize = cpu_to_le16(24);
7974 rsp->OplockLevel = rsp_oplevel;
7977 rsp->VolatileFid = volatile_id;
7978 rsp->PersistentFid = persistent_id;
7979 inc_rfc1001_len(work->response_buf, 24);
7983 opinfo->op_state = OPLOCK_STATE_NONE;
7984 wake_up_interruptible_all(&opinfo->oplock_q);
7987 ksmbd_fd_put(work, fp);
7988 smb2_set_err_rsp(work);
7991 static int check_lease_state(struct lease *lease, __le32 req_state)
7993 if ((lease->new_state ==
7994 (SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE)) &&
7995 !(req_state & SMB2_LEASE_WRITE_CACHING_LE)) {
7996 lease->new_state = req_state;
8000 if (lease->new_state == req_state)
8007 * smb21_lease_break_ack() - handler for smb2.1 lease break command
8008 * @work: smb work containing lease break command buffer
8012 static void smb21_lease_break_ack(struct ksmbd_work *work)
8014 struct ksmbd_conn *conn = work->conn;
8015 struct smb2_lease_ack *req = smb2_get_msg(work->request_buf);
8016 struct smb2_lease_ack *rsp = smb2_get_msg(work->response_buf);
8017 struct oplock_info *opinfo;
8020 unsigned int lease_change_type;
8022 struct lease *lease;
8024 ksmbd_debug(OPLOCK, "smb21 lease break, lease state(0x%x)\n",
8025 le32_to_cpu(req->LeaseState));
8026 opinfo = lookup_lease_in_table(conn, req->LeaseKey);
8028 ksmbd_debug(OPLOCK, "file not opened\n");
8029 smb2_set_err_rsp(work);
8030 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8033 lease = opinfo->o_lease;
8035 if (opinfo->op_state == OPLOCK_STATE_NONE) {
8036 pr_err("unexpected lease break state 0x%x\n",
8038 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8042 if (check_lease_state(lease, req->LeaseState)) {
8043 rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
8045 "req lease state: 0x%x, expected state: 0x%x\n",
8046 req->LeaseState, lease->new_state);
8050 if (!atomic_read(&opinfo->breaking_cnt)) {
8051 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8055 /* check for bad lease state */
8056 if (req->LeaseState &
8057 (~(SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE))) {
8058 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8059 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8060 lease_change_type = OPLOCK_WRITE_TO_NONE;
8062 lease_change_type = OPLOCK_READ_TO_NONE;
8063 ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8064 le32_to_cpu(lease->state),
8065 le32_to_cpu(req->LeaseState));
8066 } else if (lease->state == SMB2_LEASE_READ_CACHING_LE &&
8067 req->LeaseState != SMB2_LEASE_NONE_LE) {
8068 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8069 lease_change_type = OPLOCK_READ_TO_NONE;
8070 ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8071 le32_to_cpu(lease->state),
8072 le32_to_cpu(req->LeaseState));
8074 /* valid lease state changes */
8075 err = STATUS_INVALID_DEVICE_STATE;
8076 if (req->LeaseState == SMB2_LEASE_NONE_LE) {
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 } else if (req->LeaseState & SMB2_LEASE_READ_CACHING_LE) {
8082 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8083 lease_change_type = OPLOCK_WRITE_TO_READ;
8085 lease_change_type = OPLOCK_READ_HANDLE_TO_READ;
8087 lease_change_type = 0;
8091 switch (lease_change_type) {
8092 case OPLOCK_WRITE_TO_READ:
8093 ret = opinfo_write_to_read(opinfo);
8095 case OPLOCK_READ_HANDLE_TO_READ:
8096 ret = opinfo_read_handle_to_read(opinfo);
8098 case OPLOCK_WRITE_TO_NONE:
8099 ret = opinfo_write_to_none(opinfo);
8101 case OPLOCK_READ_TO_NONE:
8102 ret = opinfo_read_to_none(opinfo);
8105 ksmbd_debug(OPLOCK, "unknown lease change 0x%x -> 0x%x\n",
8106 le32_to_cpu(lease->state),
8107 le32_to_cpu(req->LeaseState));
8110 lease_state = lease->state;
8111 opinfo->op_state = OPLOCK_STATE_NONE;
8112 wake_up_interruptible_all(&opinfo->oplock_q);
8113 atomic_dec(&opinfo->breaking_cnt);
8114 wake_up_interruptible_all(&opinfo->oplock_brk);
8118 rsp->hdr.Status = err;
8122 rsp->StructureSize = cpu_to_le16(36);
8125 memcpy(rsp->LeaseKey, req->LeaseKey, 16);
8126 rsp->LeaseState = lease_state;
8127 rsp->LeaseDuration = 0;
8128 inc_rfc1001_len(work->response_buf, 36);
8132 opinfo->op_state = OPLOCK_STATE_NONE;
8133 wake_up_interruptible_all(&opinfo->oplock_q);
8134 atomic_dec(&opinfo->breaking_cnt);
8135 wake_up_interruptible_all(&opinfo->oplock_brk);
8138 smb2_set_err_rsp(work);
8142 * smb2_oplock_break() - dispatcher for smb2.0 and 2.1 oplock/lease break
8143 * @work: smb work containing oplock/lease break command buffer
8147 int smb2_oplock_break(struct ksmbd_work *work)
8149 struct smb2_oplock_break *req = smb2_get_msg(work->request_buf);
8150 struct smb2_oplock_break *rsp = smb2_get_msg(work->response_buf);
8152 switch (le16_to_cpu(req->StructureSize)) {
8153 case OP_BREAK_STRUCT_SIZE_20:
8154 smb20_oplock_break_ack(work);
8156 case OP_BREAK_STRUCT_SIZE_21:
8157 smb21_lease_break_ack(work);
8160 ksmbd_debug(OPLOCK, "invalid break cmd %d\n",
8161 le16_to_cpu(req->StructureSize));
8162 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8163 smb2_set_err_rsp(work);
8170 * smb2_notify() - handler for smb2 notify request
8171 * @work: smb work containing notify command buffer
8175 int smb2_notify(struct ksmbd_work *work)
8177 struct smb2_change_notify_req *req;
8178 struct smb2_change_notify_rsp *rsp;
8180 WORK_BUFFERS(work, req, rsp);
8182 if (work->next_smb2_rcv_hdr_off && req->hdr.NextCommand) {
8183 rsp->hdr.Status = STATUS_INTERNAL_ERROR;
8184 smb2_set_err_rsp(work);
8188 smb2_set_err_rsp(work);
8189 rsp->hdr.Status = STATUS_NOT_IMPLEMENTED;
8194 * smb2_is_sign_req() - handler for checking packet signing status
8195 * @work: smb work containing notify command buffer
8196 * @command: SMB2 command id
8198 * Return: true if packed is signed, false otherwise
8200 bool smb2_is_sign_req(struct ksmbd_work *work, unsigned int command)
8202 struct smb2_hdr *rcv_hdr2 = smb2_get_msg(work->request_buf);
8204 if ((rcv_hdr2->Flags & SMB2_FLAGS_SIGNED) &&
8205 command != SMB2_NEGOTIATE_HE &&
8206 command != SMB2_SESSION_SETUP_HE &&
8207 command != SMB2_OPLOCK_BREAK_HE)
8214 * smb2_check_sign_req() - handler for req packet sign processing
8215 * @work: smb work containing notify command buffer
8217 * Return: 1 on success, 0 otherwise
8219 int smb2_check_sign_req(struct ksmbd_work *work)
8221 struct smb2_hdr *hdr;
8222 char signature_req[SMB2_SIGNATURE_SIZE];
8223 char signature[SMB2_HMACSHA256_SIZE];
8227 hdr = smb2_get_msg(work->request_buf);
8228 if (work->next_smb2_rcv_hdr_off)
8229 hdr = ksmbd_req_buf_next(work);
8231 if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8232 len = get_rfc1002_len(work->request_buf);
8233 else if (hdr->NextCommand)
8234 len = le32_to_cpu(hdr->NextCommand);
8236 len = get_rfc1002_len(work->request_buf) -
8237 work->next_smb2_rcv_hdr_off;
8239 memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8240 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8242 iov[0].iov_base = (char *)&hdr->ProtocolId;
8243 iov[0].iov_len = len;
8245 if (ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, 1,
8249 if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8250 pr_err("bad smb2 signature\n");
8258 * smb2_set_sign_rsp() - handler for rsp packet sign processing
8259 * @work: smb work containing notify command buffer
8262 void smb2_set_sign_rsp(struct ksmbd_work *work)
8264 struct smb2_hdr *hdr;
8265 struct smb2_hdr *req_hdr;
8266 char signature[SMB2_HMACSHA256_SIZE];
8271 hdr = smb2_get_msg(work->response_buf);
8272 if (work->next_smb2_rsp_hdr_off)
8273 hdr = ksmbd_resp_buf_next(work);
8275 req_hdr = ksmbd_req_buf_next(work);
8277 if (!work->next_smb2_rsp_hdr_off) {
8278 len = get_rfc1002_len(work->response_buf);
8279 if (req_hdr->NextCommand)
8280 len = ALIGN(len, 8);
8282 len = get_rfc1002_len(work->response_buf) -
8283 work->next_smb2_rsp_hdr_off;
8284 len = ALIGN(len, 8);
8287 if (req_hdr->NextCommand)
8288 hdr->NextCommand = cpu_to_le32(len);
8290 hdr->Flags |= SMB2_FLAGS_SIGNED;
8291 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8293 iov[0].iov_base = (char *)&hdr->ProtocolId;
8294 iov[0].iov_len = len;
8296 if (work->aux_payload_sz) {
8297 iov[0].iov_len -= work->aux_payload_sz;
8299 iov[1].iov_base = work->aux_payload_buf;
8300 iov[1].iov_len = work->aux_payload_sz;
8304 if (!ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, n_vec,
8306 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
8310 * smb3_check_sign_req() - handler for req packet sign processing
8311 * @work: smb work containing notify command buffer
8313 * Return: 1 on success, 0 otherwise
8315 int smb3_check_sign_req(struct ksmbd_work *work)
8317 struct ksmbd_conn *conn = work->conn;
8319 struct smb2_hdr *hdr;
8320 struct channel *chann;
8321 char signature_req[SMB2_SIGNATURE_SIZE];
8322 char signature[SMB2_CMACAES_SIZE];
8326 hdr = smb2_get_msg(work->request_buf);
8327 if (work->next_smb2_rcv_hdr_off)
8328 hdr = ksmbd_req_buf_next(work);
8330 if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8331 len = get_rfc1002_len(work->request_buf);
8332 else if (hdr->NextCommand)
8333 len = le32_to_cpu(hdr->NextCommand);
8335 len = get_rfc1002_len(work->request_buf) -
8336 work->next_smb2_rcv_hdr_off;
8338 if (le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8339 signing_key = work->sess->smb3signingkey;
8341 chann = lookup_chann_list(work->sess, conn);
8345 signing_key = chann->smb3signingkey;
8349 pr_err("SMB3 signing key is not generated\n");
8353 memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8354 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8355 iov[0].iov_base = (char *)&hdr->ProtocolId;
8356 iov[0].iov_len = len;
8358 if (ksmbd_sign_smb3_pdu(conn, signing_key, iov, 1, signature))
8361 if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8362 pr_err("bad smb2 signature\n");
8370 * smb3_set_sign_rsp() - handler for rsp packet sign processing
8371 * @work: smb work containing notify command buffer
8374 void smb3_set_sign_rsp(struct ksmbd_work *work)
8376 struct ksmbd_conn *conn = work->conn;
8377 struct smb2_hdr *req_hdr, *hdr;
8378 struct channel *chann;
8379 char signature[SMB2_CMACAES_SIZE];
8385 hdr = smb2_get_msg(work->response_buf);
8386 if (work->next_smb2_rsp_hdr_off)
8387 hdr = ksmbd_resp_buf_next(work);
8389 req_hdr = ksmbd_req_buf_next(work);
8391 if (!work->next_smb2_rsp_hdr_off) {
8392 len = get_rfc1002_len(work->response_buf);
8393 if (req_hdr->NextCommand)
8394 len = ALIGN(len, 8);
8396 len = get_rfc1002_len(work->response_buf) -
8397 work->next_smb2_rsp_hdr_off;
8398 len = ALIGN(len, 8);
8401 if (conn->binding == false &&
8402 le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8403 signing_key = work->sess->smb3signingkey;
8405 chann = lookup_chann_list(work->sess, work->conn);
8409 signing_key = chann->smb3signingkey;
8415 if (req_hdr->NextCommand)
8416 hdr->NextCommand = cpu_to_le32(len);
8418 hdr->Flags |= SMB2_FLAGS_SIGNED;
8419 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8420 iov[0].iov_base = (char *)&hdr->ProtocolId;
8421 iov[0].iov_len = len;
8422 if (work->aux_payload_sz) {
8423 iov[0].iov_len -= work->aux_payload_sz;
8424 iov[1].iov_base = work->aux_payload_buf;
8425 iov[1].iov_len = work->aux_payload_sz;
8429 if (!ksmbd_sign_smb3_pdu(conn, signing_key, iov, n_vec, signature))
8430 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
8434 * smb3_preauth_hash_rsp() - handler for computing preauth hash on response
8435 * @work: smb work containing response buffer
8438 void smb3_preauth_hash_rsp(struct ksmbd_work *work)
8440 struct ksmbd_conn *conn = work->conn;
8441 struct ksmbd_session *sess = work->sess;
8442 struct smb2_hdr *req, *rsp;
8444 if (conn->dialect != SMB311_PROT_ID)
8447 WORK_BUFFERS(work, req, rsp);
8449 if (le16_to_cpu(req->Command) == SMB2_NEGOTIATE_HE &&
8451 ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
8452 conn->preauth_info->Preauth_HashValue);
8454 if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE && sess) {
8457 if (conn->binding) {
8458 struct preauth_session *preauth_sess;
8460 preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
8463 hash_value = preauth_sess->Preauth_HashValue;
8465 hash_value = sess->Preauth_HashValue;
8469 ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
8474 static void fill_transform_hdr(void *tr_buf, char *old_buf, __le16 cipher_type)
8476 struct smb2_transform_hdr *tr_hdr = tr_buf + 4;
8477 struct smb2_hdr *hdr = smb2_get_msg(old_buf);
8478 unsigned int orig_len = get_rfc1002_len(old_buf);
8480 /* tr_buf must be cleared by the caller */
8481 tr_hdr->ProtocolId = SMB2_TRANSFORM_PROTO_NUM;
8482 tr_hdr->OriginalMessageSize = cpu_to_le32(orig_len);
8483 tr_hdr->Flags = cpu_to_le16(TRANSFORM_FLAG_ENCRYPTED);
8484 if (cipher_type == SMB2_ENCRYPTION_AES128_GCM ||
8485 cipher_type == SMB2_ENCRYPTION_AES256_GCM)
8486 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_GCM_NONCE);
8488 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_CCM_NONCE);
8489 memcpy(&tr_hdr->SessionId, &hdr->SessionId, 8);
8490 inc_rfc1001_len(tr_buf, sizeof(struct smb2_transform_hdr));
8491 inc_rfc1001_len(tr_buf, orig_len);
8494 int smb3_encrypt_resp(struct ksmbd_work *work)
8496 char *buf = work->response_buf;
8499 int buf_size = 0, rq_nvec = 2 + (work->aux_payload_sz ? 1 : 0);
8501 if (ARRAY_SIZE(iov) < rq_nvec)
8504 work->tr_buf = kzalloc(sizeof(struct smb2_transform_hdr) + 4, GFP_KERNEL);
8508 /* fill transform header */
8509 fill_transform_hdr(work->tr_buf, buf, work->conn->cipher_type);
8511 iov[0].iov_base = work->tr_buf;
8512 iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
8513 buf_size += iov[0].iov_len - 4;
8515 iov[1].iov_base = buf + 4;
8516 iov[1].iov_len = get_rfc1002_len(buf);
8517 if (work->aux_payload_sz) {
8518 iov[1].iov_len = work->resp_hdr_sz - 4;
8520 iov[2].iov_base = work->aux_payload_buf;
8521 iov[2].iov_len = work->aux_payload_sz;
8522 buf_size += iov[2].iov_len;
8524 buf_size += iov[1].iov_len;
8525 work->resp_hdr_sz = iov[1].iov_len;
8527 rc = ksmbd_crypt_message(work, iov, rq_nvec, 1);
8531 memmove(buf, iov[1].iov_base, iov[1].iov_len);
8532 *(__be32 *)work->tr_buf = cpu_to_be32(buf_size);
8537 bool smb3_is_transform_hdr(void *buf)
8539 struct smb2_transform_hdr *trhdr = smb2_get_msg(buf);
8541 return trhdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM;
8544 int smb3_decrypt_req(struct ksmbd_work *work)
8546 struct ksmbd_session *sess;
8547 char *buf = work->request_buf;
8548 unsigned int pdu_length = get_rfc1002_len(buf);
8550 int buf_data_size = pdu_length - sizeof(struct smb2_transform_hdr);
8551 struct smb2_transform_hdr *tr_hdr = smb2_get_msg(buf);
8554 if (buf_data_size < sizeof(struct smb2_hdr)) {
8555 pr_err("Transform message is too small (%u)\n",
8557 return -ECONNABORTED;
8560 if (buf_data_size < le32_to_cpu(tr_hdr->OriginalMessageSize)) {
8561 pr_err("Transform message is broken\n");
8562 return -ECONNABORTED;
8565 sess = ksmbd_session_lookup_all(work->conn, le64_to_cpu(tr_hdr->SessionId));
8567 pr_err("invalid session id(%llx) in transform header\n",
8568 le64_to_cpu(tr_hdr->SessionId));
8569 return -ECONNABORTED;
8572 iov[0].iov_base = buf;
8573 iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
8574 iov[1].iov_base = buf + sizeof(struct smb2_transform_hdr) + 4;
8575 iov[1].iov_len = buf_data_size;
8576 rc = ksmbd_crypt_message(work, iov, 2, 0);
8580 memmove(buf + 4, iov[1].iov_base, buf_data_size);
8581 *(__be32 *)buf = cpu_to_be32(buf_data_size);
8586 bool smb3_11_final_sess_setup_resp(struct ksmbd_work *work)
8588 struct ksmbd_conn *conn = work->conn;
8589 struct ksmbd_session *sess = work->sess;
8590 struct smb2_hdr *rsp = smb2_get_msg(work->response_buf);
8592 if (conn->dialect < SMB30_PROT_ID)
8595 if (work->next_smb2_rcv_hdr_off)
8596 rsp = ksmbd_resp_buf_next(work);
8598 if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE &&
8599 sess->user && !user_guest(sess->user) &&
8600 rsp->Status == STATUS_SUCCESS)