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 = ksmbd_req_buf_next(work);
91 unsigned int cmd = le16_to_cpu(req_hdr->Command);
94 if (cmd == SMB2_TREE_CONNECT_HE ||
95 cmd == SMB2_CANCEL_HE ||
96 cmd == SMB2_LOGOFF_HE) {
97 ksmbd_debug(SMB, "skip to check tree connect request\n");
101 if (xa_empty(&work->sess->tree_conns)) {
102 ksmbd_debug(SMB, "NO tree connected\n");
106 tree_id = le32_to_cpu(req_hdr->Id.SyncId.TreeId);
109 * If request is not the first in Compound request,
110 * Just validate tree id in header with work->tcon->id.
112 if (work->next_smb2_rcv_hdr_off) {
114 pr_err("The first operation in the compound does not have tcon\n");
117 if (tree_id != UINT_MAX && work->tcon->id != tree_id) {
118 pr_err("tree id(%u) is different with id(%u) in first operation\n",
119 tree_id, work->tcon->id);
125 work->tcon = ksmbd_tree_conn_lookup(work->sess, tree_id);
127 pr_err("Invalid tid %d\n", tree_id);
135 * smb2_set_err_rsp() - set error response code on smb response
136 * @work: smb work containing response buffer
138 void smb2_set_err_rsp(struct ksmbd_work *work)
140 struct smb2_err_rsp *err_rsp;
142 if (work->next_smb2_rcv_hdr_off)
143 err_rsp = ksmbd_resp_buf_next(work);
145 err_rsp = smb2_get_msg(work->response_buf);
147 if (err_rsp->hdr.Status != STATUS_STOPPED_ON_SYMLINK) {
150 err_rsp->StructureSize = SMB2_ERROR_STRUCTURE_SIZE2_LE;
151 err_rsp->ErrorContextCount = 0;
152 err_rsp->Reserved = 0;
153 err_rsp->ByteCount = 0;
154 err_rsp->ErrorData[0] = 0;
155 err = ksmbd_iov_pin_rsp(work, (void *)err_rsp,
156 __SMB2_HEADER_STRUCTURE_SIZE +
157 SMB2_ERROR_STRUCTURE_SIZE2);
159 work->send_no_response = 1;
164 * is_smb2_neg_cmd() - is it smb2 negotiation command
165 * @work: smb work containing smb header
167 * Return: true if smb2 negotiation command, otherwise false
169 bool is_smb2_neg_cmd(struct ksmbd_work *work)
171 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
173 /* is it SMB2 header ? */
174 if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
177 /* make sure it is request not response message */
178 if (hdr->Flags & SMB2_FLAGS_SERVER_TO_REDIR)
181 if (hdr->Command != SMB2_NEGOTIATE)
188 * is_smb2_rsp() - is it smb2 response
189 * @work: smb work containing smb response buffer
191 * Return: true if smb2 response, otherwise false
193 bool is_smb2_rsp(struct ksmbd_work *work)
195 struct smb2_hdr *hdr = smb2_get_msg(work->response_buf);
197 /* is it SMB2 header ? */
198 if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
201 /* make sure it is response not request message */
202 if (!(hdr->Flags & SMB2_FLAGS_SERVER_TO_REDIR))
209 * get_smb2_cmd_val() - get smb command code from smb header
210 * @work: smb work containing smb request buffer
212 * Return: smb2 request command value
214 u16 get_smb2_cmd_val(struct ksmbd_work *work)
216 struct smb2_hdr *rcv_hdr;
218 if (work->next_smb2_rcv_hdr_off)
219 rcv_hdr = ksmbd_req_buf_next(work);
221 rcv_hdr = smb2_get_msg(work->request_buf);
222 return le16_to_cpu(rcv_hdr->Command);
226 * set_smb2_rsp_status() - set error response code on smb2 header
227 * @work: smb work containing response buffer
228 * @err: error response code
230 void set_smb2_rsp_status(struct ksmbd_work *work, __le32 err)
232 struct smb2_hdr *rsp_hdr;
234 if (work->next_smb2_rcv_hdr_off)
235 rsp_hdr = ksmbd_resp_buf_next(work);
237 rsp_hdr = smb2_get_msg(work->response_buf);
238 rsp_hdr->Status = err;
239 smb2_set_err_rsp(work);
243 * init_smb2_neg_rsp() - initialize smb2 response for negotiate command
244 * @work: smb work containing smb request buffer
246 * smb2 negotiate response is sent in reply of smb1 negotiate command for
247 * dialect auto-negotiation.
249 int init_smb2_neg_rsp(struct ksmbd_work *work)
251 struct smb2_hdr *rsp_hdr;
252 struct smb2_negotiate_rsp *rsp;
253 struct ksmbd_conn *conn = work->conn;
256 rsp_hdr = smb2_get_msg(work->response_buf);
257 memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
258 rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
259 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
260 rsp_hdr->CreditRequest = cpu_to_le16(2);
261 rsp_hdr->Command = SMB2_NEGOTIATE;
262 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
263 rsp_hdr->NextCommand = 0;
264 rsp_hdr->MessageId = 0;
265 rsp_hdr->Id.SyncId.ProcessId = 0;
266 rsp_hdr->Id.SyncId.TreeId = 0;
267 rsp_hdr->SessionId = 0;
268 memset(rsp_hdr->Signature, 0, 16);
270 rsp = smb2_get_msg(work->response_buf);
272 WARN_ON(ksmbd_conn_good(conn));
274 rsp->StructureSize = cpu_to_le16(65);
275 ksmbd_debug(SMB, "conn->dialect 0x%x\n", conn->dialect);
276 rsp->DialectRevision = cpu_to_le16(conn->dialect);
277 /* Not setting conn guid rsp->ServerGUID, as it
278 * not used by client for identifying connection
280 rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
281 /* Default Max Message Size till SMB2.0, 64K*/
282 rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
283 rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
284 rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);
286 rsp->SystemTime = cpu_to_le64(ksmbd_systime());
287 rsp->ServerStartTime = 0;
289 rsp->SecurityBufferOffset = cpu_to_le16(128);
290 rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
291 ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) +
292 le16_to_cpu(rsp->SecurityBufferOffset));
293 rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
294 if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY)
295 rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
296 err = ksmbd_iov_pin_rsp(work, rsp,
297 sizeof(struct smb2_negotiate_rsp) + AUTH_GSS_LENGTH);
300 conn->use_spnego = true;
302 ksmbd_conn_set_need_negotiate(conn);
307 * smb2_set_rsp_credits() - set number of credits in response buffer
308 * @work: smb work containing smb response buffer
310 int smb2_set_rsp_credits(struct ksmbd_work *work)
312 struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
313 struct smb2_hdr *hdr = ksmbd_resp_buf_next(work);
314 struct ksmbd_conn *conn = work->conn;
315 unsigned short credits_requested, aux_max;
316 unsigned short credit_charge, credits_granted = 0;
318 if (work->send_no_response)
321 hdr->CreditCharge = req_hdr->CreditCharge;
323 if (conn->total_credits > conn->vals->max_credits) {
324 hdr->CreditRequest = 0;
325 pr_err("Total credits overflow: %d\n", conn->total_credits);
329 credit_charge = max_t(unsigned short,
330 le16_to_cpu(req_hdr->CreditCharge), 1);
331 if (credit_charge > conn->total_credits) {
332 ksmbd_debug(SMB, "Insufficient credits granted, given: %u, granted: %u\n",
333 credit_charge, conn->total_credits);
337 conn->total_credits -= credit_charge;
338 conn->outstanding_credits -= credit_charge;
339 credits_requested = max_t(unsigned short,
340 le16_to_cpu(req_hdr->CreditRequest), 1);
342 /* according to smb2.credits smbtorture, Windows server
343 * 2016 or later grant up to 8192 credits at once.
345 * TODO: Need to adjuct CreditRequest value according to
348 if (hdr->Command == SMB2_NEGOTIATE)
351 aux_max = conn->vals->max_credits - conn->total_credits;
352 credits_granted = min_t(unsigned short, credits_requested, aux_max);
354 conn->total_credits += credits_granted;
355 work->credits_granted += credits_granted;
357 if (!req_hdr->NextCommand) {
358 /* Update CreditRequest in last request */
359 hdr->CreditRequest = cpu_to_le16(work->credits_granted);
362 "credits: requested[%d] granted[%d] total_granted[%d]\n",
363 credits_requested, credits_granted,
364 conn->total_credits);
369 * init_chained_smb2_rsp() - initialize smb2 chained response
370 * @work: smb work containing smb response buffer
372 static void init_chained_smb2_rsp(struct ksmbd_work *work)
374 struct smb2_hdr *req = ksmbd_req_buf_next(work);
375 struct smb2_hdr *rsp = ksmbd_resp_buf_next(work);
376 struct smb2_hdr *rsp_hdr;
377 struct smb2_hdr *rcv_hdr;
378 int next_hdr_offset = 0;
381 /* Len of this response = updated RFC len - offset of previous cmd
382 * in the compound rsp
385 /* Storing the current local FID which may be needed by subsequent
386 * command in the compound request
388 if (req->Command == SMB2_CREATE && rsp->Status == STATUS_SUCCESS) {
389 work->compound_fid = ((struct smb2_create_rsp *)rsp)->VolatileFileId;
390 work->compound_pfid = ((struct smb2_create_rsp *)rsp)->PersistentFileId;
391 work->compound_sid = le64_to_cpu(rsp->SessionId);
394 len = get_rfc1002_len(work->response_buf) - work->next_smb2_rsp_hdr_off;
395 next_hdr_offset = le32_to_cpu(req->NextCommand);
397 new_len = ALIGN(len, 8);
398 work->iov[work->iov_idx].iov_len += (new_len - len);
399 inc_rfc1001_len(work->response_buf, new_len - len);
400 rsp->NextCommand = cpu_to_le32(new_len);
402 work->next_smb2_rcv_hdr_off += next_hdr_offset;
403 work->curr_smb2_rsp_hdr_off = work->next_smb2_rsp_hdr_off;
404 work->next_smb2_rsp_hdr_off += new_len;
406 "Compound req new_len = %d rcv off = %d rsp off = %d\n",
407 new_len, work->next_smb2_rcv_hdr_off,
408 work->next_smb2_rsp_hdr_off);
410 rsp_hdr = ksmbd_resp_buf_next(work);
411 rcv_hdr = ksmbd_req_buf_next(work);
413 if (!(rcv_hdr->Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
414 ksmbd_debug(SMB, "related flag should be set\n");
415 work->compound_fid = KSMBD_NO_FID;
416 work->compound_pfid = KSMBD_NO_FID;
418 memset((char *)rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
419 rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
420 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
421 rsp_hdr->Command = rcv_hdr->Command;
424 * Message is response. We don't grant oplock yet.
426 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR |
427 SMB2_FLAGS_RELATED_OPERATIONS);
428 rsp_hdr->NextCommand = 0;
429 rsp_hdr->MessageId = rcv_hdr->MessageId;
430 rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
431 rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
432 rsp_hdr->SessionId = rcv_hdr->SessionId;
433 memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);
437 * is_chained_smb2_message() - check for chained command
438 * @work: smb work containing smb request buffer
440 * Return: true if chained request, otherwise false
442 bool is_chained_smb2_message(struct ksmbd_work *work)
444 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
445 unsigned int len, next_cmd;
447 if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
450 hdr = ksmbd_req_buf_next(work);
451 next_cmd = le32_to_cpu(hdr->NextCommand);
453 if ((u64)work->next_smb2_rcv_hdr_off + next_cmd +
454 __SMB2_HEADER_STRUCTURE_SIZE >
455 get_rfc1002_len(work->request_buf)) {
456 pr_err("next command(%u) offset exceeds smb msg size\n",
461 if ((u64)get_rfc1002_len(work->response_buf) + MAX_CIFS_SMALL_BUFFER_SIZE >
463 pr_err("next response offset exceeds response buffer size\n");
467 ksmbd_debug(SMB, "got SMB2 chained command\n");
468 init_chained_smb2_rsp(work);
470 } else if (work->next_smb2_rcv_hdr_off) {
472 * This is last request in chained command,
473 * align response to 8 byte
475 len = ALIGN(get_rfc1002_len(work->response_buf), 8);
476 len = len - get_rfc1002_len(work->response_buf);
478 ksmbd_debug(SMB, "padding len %u\n", len);
479 work->iov[work->iov_idx].iov_len += len;
480 inc_rfc1001_len(work->response_buf, len);
482 work->curr_smb2_rsp_hdr_off = work->next_smb2_rsp_hdr_off;
488 * init_smb2_rsp_hdr() - initialize smb2 response
489 * @work: smb work containing smb request buffer
493 int init_smb2_rsp_hdr(struct ksmbd_work *work)
495 struct smb2_hdr *rsp_hdr = smb2_get_msg(work->response_buf);
496 struct smb2_hdr *rcv_hdr = smb2_get_msg(work->request_buf);
498 memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
499 rsp_hdr->ProtocolId = rcv_hdr->ProtocolId;
500 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
501 rsp_hdr->Command = rcv_hdr->Command;
504 * Message is response. We don't grant oplock yet.
506 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
507 rsp_hdr->NextCommand = 0;
508 rsp_hdr->MessageId = rcv_hdr->MessageId;
509 rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
510 rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
511 rsp_hdr->SessionId = rcv_hdr->SessionId;
512 memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);
518 * smb2_allocate_rsp_buf() - allocate smb2 response buffer
519 * @work: smb work containing smb request buffer
521 * Return: 0 on success, otherwise -ENOMEM
523 int smb2_allocate_rsp_buf(struct ksmbd_work *work)
525 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
526 size_t small_sz = MAX_CIFS_SMALL_BUFFER_SIZE;
527 size_t large_sz = small_sz + work->conn->vals->max_trans_size;
528 size_t sz = small_sz;
529 int cmd = le16_to_cpu(hdr->Command);
531 if (cmd == SMB2_IOCTL_HE || cmd == SMB2_QUERY_DIRECTORY_HE)
534 if (cmd == SMB2_QUERY_INFO_HE) {
535 struct smb2_query_info_req *req;
537 req = smb2_get_msg(work->request_buf);
538 if ((req->InfoType == SMB2_O_INFO_FILE &&
539 (req->FileInfoClass == FILE_FULL_EA_INFORMATION ||
540 req->FileInfoClass == FILE_ALL_INFORMATION)) ||
541 req->InfoType == SMB2_O_INFO_SECURITY)
545 /* allocate large response buf for chained commands */
546 if (le32_to_cpu(hdr->NextCommand) > 0)
549 work->response_buf = kvzalloc(sz, GFP_KERNEL);
550 if (!work->response_buf)
553 work->response_sz = sz;
558 * smb2_check_user_session() - check for valid session for a user
559 * @work: smb work containing smb request buffer
561 * Return: 0 on success, otherwise error
563 int smb2_check_user_session(struct ksmbd_work *work)
565 struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
566 struct ksmbd_conn *conn = work->conn;
567 unsigned int cmd = le16_to_cpu(req_hdr->Command);
568 unsigned long long sess_id;
571 * SMB2_ECHO, SMB2_NEGOTIATE, SMB2_SESSION_SETUP command do not
572 * require a session id, so no need to validate user session's for
575 if (cmd == SMB2_ECHO_HE || cmd == SMB2_NEGOTIATE_HE ||
576 cmd == SMB2_SESSION_SETUP_HE)
579 if (!ksmbd_conn_good(conn))
582 sess_id = le64_to_cpu(req_hdr->SessionId);
585 * If request is not the first in Compound request,
586 * Just validate session id in header with work->sess->id.
588 if (work->next_smb2_rcv_hdr_off) {
590 pr_err("The first operation in the compound does not have sess\n");
593 if (sess_id != ULLONG_MAX && work->sess->id != sess_id) {
594 pr_err("session id(%llu) is different with the first operation(%lld)\n",
595 sess_id, work->sess->id);
601 /* Check for validity of user session */
602 work->sess = ksmbd_session_lookup_all(conn, sess_id);
605 ksmbd_debug(SMB, "Invalid user session, Uid %llu\n", sess_id);
609 static void destroy_previous_session(struct ksmbd_conn *conn,
610 struct ksmbd_user *user, u64 id)
612 struct ksmbd_session *prev_sess = ksmbd_session_lookup_slowpath(id);
613 struct ksmbd_user *prev_user;
614 struct channel *chann;
620 prev_user = prev_sess->user;
623 strcmp(user->name, prev_user->name) ||
624 user->passkey_sz != prev_user->passkey_sz ||
625 memcmp(user->passkey, prev_user->passkey, user->passkey_sz))
628 prev_sess->state = SMB2_SESSION_EXPIRED;
629 xa_for_each(&prev_sess->ksmbd_chann_list, index, chann)
630 ksmbd_conn_set_exiting(chann->conn);
634 * smb2_get_name() - get filename string from on the wire smb format
635 * @src: source buffer
636 * @maxlen: maxlen of source string
637 * @local_nls: nls_table pointer
639 * Return: matching converted filename on success, otherwise error ptr
642 smb2_get_name(const char *src, const int maxlen, struct nls_table *local_nls)
646 name = smb_strndup_from_utf16(src, maxlen, 1, local_nls);
648 pr_err("failed to get name %ld\n", PTR_ERR(name));
652 ksmbd_conv_path_to_unix(name);
653 ksmbd_strip_last_slash(name);
657 int setup_async_work(struct ksmbd_work *work, void (*fn)(void **), void **arg)
659 struct smb2_hdr *rsp_hdr;
660 struct ksmbd_conn *conn = work->conn;
663 rsp_hdr = ksmbd_resp_buf_next(work);
664 rsp_hdr->Flags |= SMB2_FLAGS_ASYNC_COMMAND;
666 id = ksmbd_acquire_async_msg_id(&conn->async_ida);
668 pr_err("Failed to alloc async message id\n");
671 work->asynchronous = true;
673 rsp_hdr->Id.AsyncId = cpu_to_le64(id);
676 "Send interim Response to inform async request id : %d\n",
679 work->cancel_fn = fn;
680 work->cancel_argv = arg;
682 if (list_empty(&work->async_request_entry)) {
683 spin_lock(&conn->request_lock);
684 list_add_tail(&work->async_request_entry, &conn->async_requests);
685 spin_unlock(&conn->request_lock);
691 void release_async_work(struct ksmbd_work *work)
693 struct ksmbd_conn *conn = work->conn;
695 spin_lock(&conn->request_lock);
696 list_del_init(&work->async_request_entry);
697 spin_unlock(&conn->request_lock);
699 work->asynchronous = 0;
700 work->cancel_fn = NULL;
701 kfree(work->cancel_argv);
702 work->cancel_argv = NULL;
703 if (work->async_id) {
704 ksmbd_release_id(&conn->async_ida, work->async_id);
709 void smb2_send_interim_resp(struct ksmbd_work *work, __le32 status)
711 struct smb2_hdr *rsp_hdr;
712 struct ksmbd_work *in_work = ksmbd_alloc_work_struct();
714 if (allocate_interim_rsp_buf(in_work)) {
715 pr_err("smb_allocate_rsp_buf failed!\n");
716 ksmbd_free_work_struct(in_work);
720 in_work->conn = work->conn;
721 memcpy(smb2_get_msg(in_work->response_buf), ksmbd_resp_buf_next(work),
722 __SMB2_HEADER_STRUCTURE_SIZE);
724 rsp_hdr = smb2_get_msg(in_work->response_buf);
725 smb2_set_err_rsp(in_work);
726 rsp_hdr->Status = status;
728 ksmbd_conn_write(in_work);
729 ksmbd_free_work_struct(in_work);
732 static __le32 smb2_get_reparse_tag_special_file(umode_t mode)
734 if (S_ISDIR(mode) || S_ISREG(mode))
738 return IO_REPARSE_TAG_LX_SYMLINK_LE;
739 else if (S_ISFIFO(mode))
740 return IO_REPARSE_TAG_LX_FIFO_LE;
741 else if (S_ISSOCK(mode))
742 return IO_REPARSE_TAG_AF_UNIX_LE;
743 else if (S_ISCHR(mode))
744 return IO_REPARSE_TAG_LX_CHR_LE;
745 else if (S_ISBLK(mode))
746 return IO_REPARSE_TAG_LX_BLK_LE;
752 * smb2_get_dos_mode() - get file mode in dos format from unix mode
753 * @stat: kstat containing file mode
754 * @attribute: attribute flags
756 * Return: converted dos mode
758 static int smb2_get_dos_mode(struct kstat *stat, int attribute)
762 if (S_ISDIR(stat->mode)) {
763 attr = FILE_ATTRIBUTE_DIRECTORY |
764 (attribute & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM));
766 attr = (attribute & 0x00005137) | FILE_ATTRIBUTE_ARCHIVE;
767 attr &= ~(FILE_ATTRIBUTE_DIRECTORY);
768 if (S_ISREG(stat->mode) && (server_conf.share_fake_fscaps &
769 FILE_SUPPORTS_SPARSE_FILES))
770 attr |= FILE_ATTRIBUTE_SPARSE_FILE;
772 if (smb2_get_reparse_tag_special_file(stat->mode))
773 attr |= FILE_ATTRIBUTE_REPARSE_POINT;
779 static void build_preauth_ctxt(struct smb2_preauth_neg_context *pneg_ctxt,
782 pneg_ctxt->ContextType = SMB2_PREAUTH_INTEGRITY_CAPABILITIES;
783 pneg_ctxt->DataLength = cpu_to_le16(38);
784 pneg_ctxt->HashAlgorithmCount = cpu_to_le16(1);
785 pneg_ctxt->Reserved = cpu_to_le32(0);
786 pneg_ctxt->SaltLength = cpu_to_le16(SMB311_SALT_SIZE);
787 get_random_bytes(pneg_ctxt->Salt, SMB311_SALT_SIZE);
788 pneg_ctxt->HashAlgorithms = hash_id;
791 static void build_encrypt_ctxt(struct smb2_encryption_neg_context *pneg_ctxt,
794 pneg_ctxt->ContextType = SMB2_ENCRYPTION_CAPABILITIES;
795 pneg_ctxt->DataLength = cpu_to_le16(4);
796 pneg_ctxt->Reserved = cpu_to_le32(0);
797 pneg_ctxt->CipherCount = cpu_to_le16(1);
798 pneg_ctxt->Ciphers[0] = cipher_type;
801 static void build_sign_cap_ctxt(struct smb2_signing_capabilities *pneg_ctxt,
804 pneg_ctxt->ContextType = SMB2_SIGNING_CAPABILITIES;
805 pneg_ctxt->DataLength =
806 cpu_to_le16((sizeof(struct smb2_signing_capabilities) + 2)
807 - sizeof(struct smb2_neg_context));
808 pneg_ctxt->Reserved = cpu_to_le32(0);
809 pneg_ctxt->SigningAlgorithmCount = cpu_to_le16(1);
810 pneg_ctxt->SigningAlgorithms[0] = sign_algo;
813 static void build_posix_ctxt(struct smb2_posix_neg_context *pneg_ctxt)
815 pneg_ctxt->ContextType = SMB2_POSIX_EXTENSIONS_AVAILABLE;
816 pneg_ctxt->DataLength = cpu_to_le16(POSIX_CTXT_DATA_LEN);
817 /* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */
818 pneg_ctxt->Name[0] = 0x93;
819 pneg_ctxt->Name[1] = 0xAD;
820 pneg_ctxt->Name[2] = 0x25;
821 pneg_ctxt->Name[3] = 0x50;
822 pneg_ctxt->Name[4] = 0x9C;
823 pneg_ctxt->Name[5] = 0xB4;
824 pneg_ctxt->Name[6] = 0x11;
825 pneg_ctxt->Name[7] = 0xE7;
826 pneg_ctxt->Name[8] = 0xB4;
827 pneg_ctxt->Name[9] = 0x23;
828 pneg_ctxt->Name[10] = 0x83;
829 pneg_ctxt->Name[11] = 0xDE;
830 pneg_ctxt->Name[12] = 0x96;
831 pneg_ctxt->Name[13] = 0x8B;
832 pneg_ctxt->Name[14] = 0xCD;
833 pneg_ctxt->Name[15] = 0x7C;
836 static unsigned int assemble_neg_contexts(struct ksmbd_conn *conn,
837 struct smb2_negotiate_rsp *rsp)
839 char * const pneg_ctxt = (char *)rsp +
840 le32_to_cpu(rsp->NegotiateContextOffset);
841 int neg_ctxt_cnt = 1;
845 "assemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
846 build_preauth_ctxt((struct smb2_preauth_neg_context *)pneg_ctxt,
847 conn->preauth_info->Preauth_HashId);
848 ctxt_size = sizeof(struct smb2_preauth_neg_context);
850 if (conn->cipher_type) {
851 /* Round to 8 byte boundary */
852 ctxt_size = round_up(ctxt_size, 8);
854 "assemble SMB2_ENCRYPTION_CAPABILITIES context\n");
855 build_encrypt_ctxt((struct smb2_encryption_neg_context *)
856 (pneg_ctxt + ctxt_size),
859 ctxt_size += sizeof(struct smb2_encryption_neg_context) + 2;
862 /* compression context not yet supported */
863 WARN_ON(conn->compress_algorithm != SMB3_COMPRESS_NONE);
865 if (conn->posix_ext_supported) {
866 ctxt_size = round_up(ctxt_size, 8);
868 "assemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
869 build_posix_ctxt((struct smb2_posix_neg_context *)
870 (pneg_ctxt + ctxt_size));
872 ctxt_size += sizeof(struct smb2_posix_neg_context);
875 if (conn->signing_negotiated) {
876 ctxt_size = round_up(ctxt_size, 8);
878 "assemble SMB2_SIGNING_CAPABILITIES context\n");
879 build_sign_cap_ctxt((struct smb2_signing_capabilities *)
880 (pneg_ctxt + ctxt_size),
881 conn->signing_algorithm);
883 ctxt_size += sizeof(struct smb2_signing_capabilities) + 2;
886 rsp->NegotiateContextCount = cpu_to_le16(neg_ctxt_cnt);
887 return ctxt_size + AUTH_GSS_PADDING;
890 static __le32 decode_preauth_ctxt(struct ksmbd_conn *conn,
891 struct smb2_preauth_neg_context *pneg_ctxt,
895 * sizeof(smb2_preauth_neg_context) assumes SMB311_SALT_SIZE Salt,
896 * which may not be present. Only check for used HashAlgorithms[1].
899 sizeof(struct smb2_neg_context) + MIN_PREAUTH_CTXT_DATA_LEN)
900 return STATUS_INVALID_PARAMETER;
902 if (pneg_ctxt->HashAlgorithms != SMB2_PREAUTH_INTEGRITY_SHA512)
903 return STATUS_NO_PREAUTH_INTEGRITY_HASH_OVERLAP;
905 conn->preauth_info->Preauth_HashId = SMB2_PREAUTH_INTEGRITY_SHA512;
906 return STATUS_SUCCESS;
909 static void decode_encrypt_ctxt(struct ksmbd_conn *conn,
910 struct smb2_encryption_neg_context *pneg_ctxt,
916 if (sizeof(struct smb2_encryption_neg_context) > ctxt_len) {
917 pr_err("Invalid SMB2_ENCRYPTION_CAPABILITIES context size\n");
921 conn->cipher_type = 0;
923 cph_cnt = le16_to_cpu(pneg_ctxt->CipherCount);
924 cphs_size = cph_cnt * sizeof(__le16);
926 if (sizeof(struct smb2_encryption_neg_context) + cphs_size >
928 pr_err("Invalid cipher count(%d)\n", cph_cnt);
932 if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION_OFF)
935 for (i = 0; i < cph_cnt; i++) {
936 if (pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_GCM ||
937 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_CCM ||
938 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_CCM ||
939 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_GCM) {
940 ksmbd_debug(SMB, "Cipher ID = 0x%x\n",
941 pneg_ctxt->Ciphers[i]);
942 conn->cipher_type = pneg_ctxt->Ciphers[i];
949 * smb3_encryption_negotiated() - checks if server and client agreed on enabling encryption
950 * @conn: smb connection
952 * Return: true if connection should be encrypted, else false
954 bool smb3_encryption_negotiated(struct ksmbd_conn *conn)
956 if (!conn->ops->generate_encryptionkey)
960 * SMB 3.0 and 3.0.2 dialects use the SMB2_GLOBAL_CAP_ENCRYPTION flag.
961 * SMB 3.1.1 uses the cipher_type field.
963 return (conn->vals->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION) ||
967 static void decode_compress_ctxt(struct ksmbd_conn *conn,
968 struct smb2_compression_capabilities_context *pneg_ctxt)
970 conn->compress_algorithm = SMB3_COMPRESS_NONE;
973 static void decode_sign_cap_ctxt(struct ksmbd_conn *conn,
974 struct smb2_signing_capabilities *pneg_ctxt,
978 int i, sign_alos_size;
980 if (sizeof(struct smb2_signing_capabilities) > ctxt_len) {
981 pr_err("Invalid SMB2_SIGNING_CAPABILITIES context length\n");
985 conn->signing_negotiated = false;
986 sign_algo_cnt = le16_to_cpu(pneg_ctxt->SigningAlgorithmCount);
987 sign_alos_size = sign_algo_cnt * sizeof(__le16);
989 if (sizeof(struct smb2_signing_capabilities) + sign_alos_size >
991 pr_err("Invalid signing algorithm count(%d)\n", sign_algo_cnt);
995 for (i = 0; i < sign_algo_cnt; i++) {
996 if (pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_HMAC_SHA256_LE ||
997 pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_AES_CMAC_LE) {
998 ksmbd_debug(SMB, "Signing Algorithm ID = 0x%x\n",
999 pneg_ctxt->SigningAlgorithms[i]);
1000 conn->signing_negotiated = true;
1001 conn->signing_algorithm =
1002 pneg_ctxt->SigningAlgorithms[i];
1008 static __le32 deassemble_neg_contexts(struct ksmbd_conn *conn,
1009 struct smb2_negotiate_req *req,
1010 unsigned int len_of_smb)
1012 /* +4 is to account for the RFC1001 len field */
1013 struct smb2_neg_context *pctx = (struct smb2_neg_context *)req;
1014 int i = 0, len_of_ctxts;
1015 unsigned int offset = le32_to_cpu(req->NegotiateContextOffset);
1016 unsigned int neg_ctxt_cnt = le16_to_cpu(req->NegotiateContextCount);
1017 __le32 status = STATUS_INVALID_PARAMETER;
1019 ksmbd_debug(SMB, "decoding %d negotiate contexts\n", neg_ctxt_cnt);
1020 if (len_of_smb <= offset) {
1021 ksmbd_debug(SMB, "Invalid response: negotiate context offset\n");
1025 len_of_ctxts = len_of_smb - offset;
1027 while (i++ < neg_ctxt_cnt) {
1030 if (len_of_ctxts < (int)sizeof(struct smb2_neg_context))
1033 pctx = (struct smb2_neg_context *)((char *)pctx + offset);
1034 clen = le16_to_cpu(pctx->DataLength);
1035 ctxt_len = clen + sizeof(struct smb2_neg_context);
1037 if (ctxt_len > len_of_ctxts)
1040 if (pctx->ContextType == SMB2_PREAUTH_INTEGRITY_CAPABILITIES) {
1042 "deassemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
1043 if (conn->preauth_info->Preauth_HashId)
1046 status = decode_preauth_ctxt(conn,
1047 (struct smb2_preauth_neg_context *)pctx,
1049 if (status != STATUS_SUCCESS)
1051 } else if (pctx->ContextType == SMB2_ENCRYPTION_CAPABILITIES) {
1053 "deassemble SMB2_ENCRYPTION_CAPABILITIES context\n");
1054 if (conn->cipher_type)
1057 decode_encrypt_ctxt(conn,
1058 (struct smb2_encryption_neg_context *)pctx,
1060 } else if (pctx->ContextType == SMB2_COMPRESSION_CAPABILITIES) {
1062 "deassemble SMB2_COMPRESSION_CAPABILITIES context\n");
1063 if (conn->compress_algorithm)
1066 decode_compress_ctxt(conn,
1067 (struct smb2_compression_capabilities_context *)pctx);
1068 } else if (pctx->ContextType == SMB2_NETNAME_NEGOTIATE_CONTEXT_ID) {
1070 "deassemble SMB2_NETNAME_NEGOTIATE_CONTEXT_ID context\n");
1071 } else if (pctx->ContextType == SMB2_POSIX_EXTENSIONS_AVAILABLE) {
1073 "deassemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
1074 conn->posix_ext_supported = true;
1075 } else if (pctx->ContextType == SMB2_SIGNING_CAPABILITIES) {
1077 "deassemble SMB2_SIGNING_CAPABILITIES context\n");
1079 decode_sign_cap_ctxt(conn,
1080 (struct smb2_signing_capabilities *)pctx,
1084 /* offsets must be 8 byte aligned */
1085 offset = (ctxt_len + 7) & ~0x7;
1086 len_of_ctxts -= offset;
1092 * smb2_handle_negotiate() - handler for smb2 negotiate command
1093 * @work: smb work containing smb request buffer
1097 int smb2_handle_negotiate(struct ksmbd_work *work)
1099 struct ksmbd_conn *conn = work->conn;
1100 struct smb2_negotiate_req *req = smb2_get_msg(work->request_buf);
1101 struct smb2_negotiate_rsp *rsp = smb2_get_msg(work->response_buf);
1103 unsigned int smb2_buf_len, smb2_neg_size, neg_ctxt_len = 0;
1106 ksmbd_debug(SMB, "Received negotiate request\n");
1107 conn->need_neg = false;
1108 if (ksmbd_conn_good(conn)) {
1109 pr_err("conn->tcp_status is already in CifsGood State\n");
1110 work->send_no_response = 1;
1114 smb2_buf_len = get_rfc1002_len(work->request_buf);
1115 smb2_neg_size = offsetof(struct smb2_negotiate_req, Dialects);
1116 if (smb2_neg_size > smb2_buf_len) {
1117 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1122 if (req->DialectCount == 0) {
1123 pr_err("malformed packet\n");
1124 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1129 if (conn->dialect == SMB311_PROT_ID) {
1130 unsigned int nego_ctxt_off = le32_to_cpu(req->NegotiateContextOffset);
1132 if (smb2_buf_len < nego_ctxt_off) {
1133 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1138 if (smb2_neg_size > nego_ctxt_off) {
1139 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1144 if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
1146 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1151 if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
1153 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1159 conn->cli_cap = le32_to_cpu(req->Capabilities);
1160 switch (conn->dialect) {
1161 case SMB311_PROT_ID:
1162 conn->preauth_info =
1163 kzalloc(sizeof(struct preauth_integrity_info),
1165 if (!conn->preauth_info) {
1167 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1171 status = deassemble_neg_contexts(conn, req,
1172 get_rfc1002_len(work->request_buf));
1173 if (status != STATUS_SUCCESS) {
1174 pr_err("deassemble_neg_contexts error(0x%x)\n",
1176 rsp->hdr.Status = status;
1178 kfree(conn->preauth_info);
1179 conn->preauth_info = NULL;
1183 rc = init_smb3_11_server(conn);
1185 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1186 kfree(conn->preauth_info);
1187 conn->preauth_info = NULL;
1191 ksmbd_gen_preauth_integrity_hash(conn,
1193 conn->preauth_info->Preauth_HashValue);
1194 rsp->NegotiateContextOffset =
1195 cpu_to_le32(OFFSET_OF_NEG_CONTEXT);
1196 neg_ctxt_len = assemble_neg_contexts(conn, rsp);
1198 case SMB302_PROT_ID:
1199 init_smb3_02_server(conn);
1202 init_smb3_0_server(conn);
1205 init_smb2_1_server(conn);
1210 ksmbd_debug(SMB, "Server dialect :0x%x not supported\n",
1212 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
1216 rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
1219 conn->connection_type = conn->dialect;
1221 rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
1222 rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
1223 rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);
1225 memcpy(conn->ClientGUID, req->ClientGUID,
1226 SMB2_CLIENT_GUID_SIZE);
1227 conn->cli_sec_mode = le16_to_cpu(req->SecurityMode);
1229 rsp->StructureSize = cpu_to_le16(65);
1230 rsp->DialectRevision = cpu_to_le16(conn->dialect);
1231 /* Not setting conn guid rsp->ServerGUID, as it
1232 * not used by client for identifying server
1234 memset(rsp->ServerGUID, 0, SMB2_CLIENT_GUID_SIZE);
1236 rsp->SystemTime = cpu_to_le64(ksmbd_systime());
1237 rsp->ServerStartTime = 0;
1238 ksmbd_debug(SMB, "negotiate context offset %d, count %d\n",
1239 le32_to_cpu(rsp->NegotiateContextOffset),
1240 le16_to_cpu(rsp->NegotiateContextCount));
1242 rsp->SecurityBufferOffset = cpu_to_le16(128);
1243 rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
1244 ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) +
1245 le16_to_cpu(rsp->SecurityBufferOffset));
1247 rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
1248 conn->use_spnego = true;
1250 if ((server_conf.signing == KSMBD_CONFIG_OPT_AUTO ||
1251 server_conf.signing == KSMBD_CONFIG_OPT_DISABLED) &&
1252 req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED_LE)
1254 else if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY) {
1255 server_conf.enforced_signing = true;
1256 rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
1260 conn->srv_sec_mode = le16_to_cpu(rsp->SecurityMode);
1261 ksmbd_conn_set_need_negotiate(conn);
1265 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
1268 rc = ksmbd_iov_pin_rsp(work, rsp,
1269 sizeof(struct smb2_negotiate_rsp) +
1270 AUTH_GSS_LENGTH + neg_ctxt_len);
1272 smb2_set_err_rsp(work);
1276 static int alloc_preauth_hash(struct ksmbd_session *sess,
1277 struct ksmbd_conn *conn)
1279 if (sess->Preauth_HashValue)
1282 sess->Preauth_HashValue = kmemdup(conn->preauth_info->Preauth_HashValue,
1283 PREAUTH_HASHVALUE_SIZE, GFP_KERNEL);
1284 if (!sess->Preauth_HashValue)
1290 static int generate_preauth_hash(struct ksmbd_work *work)
1292 struct ksmbd_conn *conn = work->conn;
1293 struct ksmbd_session *sess = work->sess;
1296 if (conn->dialect != SMB311_PROT_ID)
1299 if (conn->binding) {
1300 struct preauth_session *preauth_sess;
1302 preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
1303 if (!preauth_sess) {
1304 preauth_sess = ksmbd_preauth_session_alloc(conn, sess->id);
1309 preauth_hash = preauth_sess->Preauth_HashValue;
1311 if (!sess->Preauth_HashValue)
1312 if (alloc_preauth_hash(sess, conn))
1314 preauth_hash = sess->Preauth_HashValue;
1317 ksmbd_gen_preauth_integrity_hash(conn, work->request_buf, preauth_hash);
1321 static int decode_negotiation_token(struct ksmbd_conn *conn,
1322 struct negotiate_message *negblob,
1325 if (!conn->use_spnego)
1328 if (ksmbd_decode_negTokenInit((char *)negblob, sz, conn)) {
1329 if (ksmbd_decode_negTokenTarg((char *)negblob, sz, conn)) {
1330 conn->auth_mechs |= KSMBD_AUTH_NTLMSSP;
1331 conn->preferred_auth_mech = KSMBD_AUTH_NTLMSSP;
1332 conn->use_spnego = false;
1338 static int ntlm_negotiate(struct ksmbd_work *work,
1339 struct negotiate_message *negblob,
1340 size_t negblob_len, struct smb2_sess_setup_rsp *rsp)
1342 struct challenge_message *chgblob;
1343 unsigned char *spnego_blob = NULL;
1344 u16 spnego_blob_len;
1348 ksmbd_debug(SMB, "negotiate phase\n");
1349 rc = ksmbd_decode_ntlmssp_neg_blob(negblob, negblob_len, work->conn);
1353 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1355 (struct challenge_message *)((char *)&rsp->hdr.ProtocolId + sz);
1356 memset(chgblob, 0, sizeof(struct challenge_message));
1358 if (!work->conn->use_spnego) {
1359 sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
1363 rsp->SecurityBufferLength = cpu_to_le16(sz);
1367 sz = sizeof(struct challenge_message);
1368 sz += (strlen(ksmbd_netbios_name()) * 2 + 1 + 4) * 6;
1370 neg_blob = kzalloc(sz, GFP_KERNEL);
1374 chgblob = (struct challenge_message *)neg_blob;
1375 sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
1381 rc = build_spnego_ntlmssp_neg_blob(&spnego_blob, &spnego_blob_len,
1388 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1389 memcpy((char *)&rsp->hdr.ProtocolId + sz, spnego_blob, spnego_blob_len);
1390 rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
1398 static struct authenticate_message *user_authblob(struct ksmbd_conn *conn,
1399 struct smb2_sess_setup_req *req)
1403 if (conn->use_spnego && conn->mechToken)
1404 return (struct authenticate_message *)conn->mechToken;
1406 sz = le16_to_cpu(req->SecurityBufferOffset);
1407 return (struct authenticate_message *)((char *)&req->hdr.ProtocolId
1411 static struct ksmbd_user *session_user(struct ksmbd_conn *conn,
1412 struct smb2_sess_setup_req *req)
1414 struct authenticate_message *authblob;
1415 struct ksmbd_user *user;
1417 unsigned int name_off, name_len, secbuf_len;
1419 secbuf_len = le16_to_cpu(req->SecurityBufferLength);
1420 if (secbuf_len < sizeof(struct authenticate_message)) {
1421 ksmbd_debug(SMB, "blob len %d too small\n", secbuf_len);
1424 authblob = user_authblob(conn, req);
1425 name_off = le32_to_cpu(authblob->UserName.BufferOffset);
1426 name_len = le16_to_cpu(authblob->UserName.Length);
1428 if (secbuf_len < (u64)name_off + name_len)
1431 name = smb_strndup_from_utf16((const char *)authblob + name_off,
1436 pr_err("cannot allocate memory\n");
1440 ksmbd_debug(SMB, "session setup request for user %s\n", name);
1441 user = ksmbd_login_user(name);
1446 static int ntlm_authenticate(struct ksmbd_work *work,
1447 struct smb2_sess_setup_req *req,
1448 struct smb2_sess_setup_rsp *rsp)
1450 struct ksmbd_conn *conn = work->conn;
1451 struct ksmbd_session *sess = work->sess;
1452 struct channel *chann = NULL;
1453 struct ksmbd_user *user;
1457 ksmbd_debug(SMB, "authenticate phase\n");
1458 if (conn->use_spnego) {
1459 unsigned char *spnego_blob;
1460 u16 spnego_blob_len;
1462 rc = build_spnego_ntlmssp_auth_blob(&spnego_blob,
1468 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1469 memcpy((char *)&rsp->hdr.ProtocolId + sz, spnego_blob, spnego_blob_len);
1470 rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
1474 user = session_user(conn, req);
1476 ksmbd_debug(SMB, "Unknown user name or an error\n");
1480 /* Check for previous session */
1481 prev_id = le64_to_cpu(req->PreviousSessionId);
1482 if (prev_id && prev_id != sess->id)
1483 destroy_previous_session(conn, user, prev_id);
1485 if (sess->state == SMB2_SESSION_VALID) {
1487 * Reuse session if anonymous try to connect
1488 * on reauthetication.
1490 if (conn->binding == false && ksmbd_anonymous_user(user)) {
1491 ksmbd_free_user(user);
1495 if (!ksmbd_compare_user(sess->user, user)) {
1496 ksmbd_free_user(user);
1499 ksmbd_free_user(user);
1504 if (conn->binding == false && user_guest(sess->user)) {
1505 rsp->SessionFlags = SMB2_SESSION_FLAG_IS_GUEST_LE;
1507 struct authenticate_message *authblob;
1509 authblob = user_authblob(conn, req);
1510 sz = le16_to_cpu(req->SecurityBufferLength);
1511 rc = ksmbd_decode_ntlmssp_auth_blob(authblob, sz, conn, sess);
1513 set_user_flag(sess->user, KSMBD_USER_FLAG_BAD_PASSWORD);
1514 ksmbd_debug(SMB, "authentication failed\n");
1520 * If session state is SMB2_SESSION_VALID, We can assume
1521 * that it is reauthentication. And the user/password
1522 * has been verified, so return it here.
1524 if (sess->state == SMB2_SESSION_VALID) {
1526 goto binding_session;
1530 if ((rsp->SessionFlags != SMB2_SESSION_FLAG_IS_GUEST_LE &&
1531 (conn->sign || server_conf.enforced_signing)) ||
1532 (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
1535 if (smb3_encryption_negotiated(conn) &&
1536 !(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1537 rc = conn->ops->generate_encryptionkey(conn, sess);
1540 "SMB3 encryption key generation failed\n");
1544 if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION)
1545 rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
1547 * signing is disable if encryption is enable
1554 if (conn->dialect >= SMB30_PROT_ID) {
1555 chann = lookup_chann_list(sess, conn);
1557 chann = kmalloc(sizeof(struct channel), GFP_KERNEL);
1562 xa_store(&sess->ksmbd_chann_list, (long)conn, chann, GFP_KERNEL);
1566 if (conn->ops->generate_signingkey) {
1567 rc = conn->ops->generate_signingkey(sess, conn);
1569 ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
1574 if (!ksmbd_conn_lookup_dialect(conn)) {
1575 pr_err("fail to verify the dialect\n");
1581 #ifdef CONFIG_SMB_SERVER_KERBEROS5
1582 static int krb5_authenticate(struct ksmbd_work *work,
1583 struct smb2_sess_setup_req *req,
1584 struct smb2_sess_setup_rsp *rsp)
1586 struct ksmbd_conn *conn = work->conn;
1587 struct ksmbd_session *sess = work->sess;
1588 char *in_blob, *out_blob;
1589 struct channel *chann = NULL;
1591 int in_len, out_len;
1594 in_blob = (char *)&req->hdr.ProtocolId +
1595 le16_to_cpu(req->SecurityBufferOffset);
1596 in_len = le16_to_cpu(req->SecurityBufferLength);
1597 out_blob = (char *)&rsp->hdr.ProtocolId +
1598 le16_to_cpu(rsp->SecurityBufferOffset);
1599 out_len = work->response_sz -
1600 (le16_to_cpu(rsp->SecurityBufferOffset) + 4);
1602 /* Check previous session */
1603 prev_sess_id = le64_to_cpu(req->PreviousSessionId);
1604 if (prev_sess_id && prev_sess_id != sess->id)
1605 destroy_previous_session(conn, sess->user, prev_sess_id);
1607 if (sess->state == SMB2_SESSION_VALID)
1608 ksmbd_free_user(sess->user);
1610 retval = ksmbd_krb5_authenticate(sess, in_blob, in_len,
1611 out_blob, &out_len);
1613 ksmbd_debug(SMB, "krb5 authentication failed\n");
1616 rsp->SecurityBufferLength = cpu_to_le16(out_len);
1618 if ((conn->sign || server_conf.enforced_signing) ||
1619 (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
1622 if (smb3_encryption_negotiated(conn)) {
1623 retval = conn->ops->generate_encryptionkey(conn, sess);
1626 "SMB3 encryption key generation failed\n");
1630 if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION)
1631 rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
1635 if (conn->dialect >= SMB30_PROT_ID) {
1636 chann = lookup_chann_list(sess, conn);
1638 chann = kmalloc(sizeof(struct channel), GFP_KERNEL);
1643 xa_store(&sess->ksmbd_chann_list, (long)conn, chann, GFP_KERNEL);
1647 if (conn->ops->generate_signingkey) {
1648 retval = conn->ops->generate_signingkey(sess, conn);
1650 ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
1655 if (!ksmbd_conn_lookup_dialect(conn)) {
1656 pr_err("fail to verify the dialect\n");
1662 static int krb5_authenticate(struct ksmbd_work *work,
1663 struct smb2_sess_setup_req *req,
1664 struct smb2_sess_setup_rsp *rsp)
1670 int smb2_sess_setup(struct ksmbd_work *work)
1672 struct ksmbd_conn *conn = work->conn;
1673 struct smb2_sess_setup_req *req;
1674 struct smb2_sess_setup_rsp *rsp;
1675 struct ksmbd_session *sess;
1676 struct negotiate_message *negblob;
1677 unsigned int negblob_len, negblob_off;
1680 ksmbd_debug(SMB, "Received request for session setup\n");
1682 WORK_BUFFERS(work, req, rsp);
1684 rsp->StructureSize = cpu_to_le16(9);
1685 rsp->SessionFlags = 0;
1686 rsp->SecurityBufferOffset = cpu_to_le16(72);
1687 rsp->SecurityBufferLength = 0;
1689 ksmbd_conn_lock(conn);
1690 if (!req->hdr.SessionId) {
1691 sess = ksmbd_smb2_session_create();
1696 rsp->hdr.SessionId = cpu_to_le64(sess->id);
1697 rc = ksmbd_session_register(conn, sess);
1700 } else if (conn->dialect >= SMB30_PROT_ID &&
1701 (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
1702 req->Flags & SMB2_SESSION_REQ_FLAG_BINDING) {
1703 u64 sess_id = le64_to_cpu(req->hdr.SessionId);
1705 sess = ksmbd_session_lookup_slowpath(sess_id);
1711 if (conn->dialect != sess->dialect) {
1716 if (!(req->hdr.Flags & SMB2_FLAGS_SIGNED)) {
1721 if (strncmp(conn->ClientGUID, sess->ClientGUID,
1722 SMB2_CLIENT_GUID_SIZE)) {
1727 if (sess->state == SMB2_SESSION_IN_PROGRESS) {
1732 if (sess->state == SMB2_SESSION_EXPIRED) {
1737 if (ksmbd_conn_need_reconnect(conn)) {
1743 if (ksmbd_session_lookup(conn, sess_id)) {
1748 if (user_guest(sess->user)) {
1753 conn->binding = true;
1754 } else if ((conn->dialect < SMB30_PROT_ID ||
1755 server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
1756 (req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1761 sess = ksmbd_session_lookup(conn,
1762 le64_to_cpu(req->hdr.SessionId));
1768 if (sess->state == SMB2_SESSION_EXPIRED) {
1773 if (ksmbd_conn_need_reconnect(conn)) {
1781 negblob_off = le16_to_cpu(req->SecurityBufferOffset);
1782 negblob_len = le16_to_cpu(req->SecurityBufferLength);
1783 if (negblob_off < offsetof(struct smb2_sess_setup_req, Buffer) ||
1784 negblob_len < offsetof(struct negotiate_message, NegotiateFlags)) {
1789 negblob = (struct negotiate_message *)((char *)&req->hdr.ProtocolId +
1792 if (decode_negotiation_token(conn, negblob, negblob_len) == 0) {
1793 if (conn->mechToken)
1794 negblob = (struct negotiate_message *)conn->mechToken;
1797 if (server_conf.auth_mechs & conn->auth_mechs) {
1798 rc = generate_preauth_hash(work);
1802 if (conn->preferred_auth_mech &
1803 (KSMBD_AUTH_KRB5 | KSMBD_AUTH_MSKRB5)) {
1804 rc = krb5_authenticate(work, req, rsp);
1810 if (!ksmbd_conn_need_reconnect(conn)) {
1811 ksmbd_conn_set_good(conn);
1812 sess->state = SMB2_SESSION_VALID;
1814 kfree(sess->Preauth_HashValue);
1815 sess->Preauth_HashValue = NULL;
1816 } else if (conn->preferred_auth_mech == KSMBD_AUTH_NTLMSSP) {
1817 if (negblob->MessageType == NtLmNegotiate) {
1818 rc = ntlm_negotiate(work, negblob, negblob_len, rsp);
1822 STATUS_MORE_PROCESSING_REQUIRED;
1823 } else if (negblob->MessageType == NtLmAuthenticate) {
1824 rc = ntlm_authenticate(work, req, rsp);
1828 if (!ksmbd_conn_need_reconnect(conn)) {
1829 ksmbd_conn_set_good(conn);
1830 sess->state = SMB2_SESSION_VALID;
1832 if (conn->binding) {
1833 struct preauth_session *preauth_sess;
1836 ksmbd_preauth_session_lookup(conn, sess->id);
1838 list_del(&preauth_sess->preauth_entry);
1839 kfree(preauth_sess);
1842 kfree(sess->Preauth_HashValue);
1843 sess->Preauth_HashValue = NULL;
1845 pr_info_ratelimited("Unknown NTLMSSP message type : 0x%x\n",
1846 le32_to_cpu(negblob->MessageType));
1850 /* TODO: need one more negotiation */
1851 pr_err("Not support the preferred authentication\n");
1855 pr_err("Not support authentication\n");
1861 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1862 else if (rc == -ENOENT)
1863 rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
1864 else if (rc == -EACCES)
1865 rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
1866 else if (rc == -EFAULT)
1867 rsp->hdr.Status = STATUS_NETWORK_SESSION_EXPIRED;
1868 else if (rc == -ENOMEM)
1869 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
1870 else if (rc == -EOPNOTSUPP)
1871 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
1873 rsp->hdr.Status = STATUS_LOGON_FAILURE;
1875 if (conn->use_spnego && conn->mechToken) {
1876 kfree(conn->mechToken);
1877 conn->mechToken = NULL;
1882 * SecurityBufferOffset should be set to zero
1883 * in session setup error response.
1885 rsp->SecurityBufferOffset = 0;
1888 bool try_delay = false;
1891 * To avoid dictionary attacks (repeated session setups rapidly sent) to
1892 * connect to server, ksmbd make a delay of a 5 seconds on session setup
1893 * failure to make it harder to send enough random connection requests
1894 * to break into a server.
1896 if (sess->user && sess->user->flags & KSMBD_USER_FLAG_DELAY_SESSION)
1899 sess->last_active = jiffies;
1900 sess->state = SMB2_SESSION_EXPIRED;
1902 ksmbd_conn_set_need_reconnect(conn);
1904 ksmbd_conn_set_need_negotiate(conn);
1907 smb2_set_err_rsp(work);
1909 unsigned int iov_len;
1911 if (rsp->SecurityBufferLength)
1912 iov_len = offsetof(struct smb2_sess_setup_rsp, Buffer) +
1913 le16_to_cpu(rsp->SecurityBufferLength);
1915 iov_len = sizeof(struct smb2_sess_setup_rsp);
1916 rc = ksmbd_iov_pin_rsp(work, rsp, iov_len);
1918 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
1921 ksmbd_conn_unlock(conn);
1926 * smb2_tree_connect() - handler for smb2 tree connect command
1927 * @work: smb work containing smb request buffer
1929 * Return: 0 on success, otherwise error
1931 int smb2_tree_connect(struct ksmbd_work *work)
1933 struct ksmbd_conn *conn = work->conn;
1934 struct smb2_tree_connect_req *req;
1935 struct smb2_tree_connect_rsp *rsp;
1936 struct ksmbd_session *sess = work->sess;
1937 char *treename = NULL, *name = NULL;
1938 struct ksmbd_tree_conn_status status;
1939 struct ksmbd_share_config *share;
1942 WORK_BUFFERS(work, req, rsp);
1944 treename = smb_strndup_from_utf16(req->Buffer,
1945 le16_to_cpu(req->PathLength), true,
1947 if (IS_ERR(treename)) {
1948 pr_err("treename is NULL\n");
1949 status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
1953 name = ksmbd_extract_sharename(conn->um, treename);
1955 status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
1959 ksmbd_debug(SMB, "tree connect request for tree %s treename %s\n",
1962 status = ksmbd_tree_conn_connect(conn, sess, name);
1963 if (status.ret == KSMBD_TREE_CONN_STATUS_OK)
1964 rsp->hdr.Id.SyncId.TreeId = cpu_to_le32(status.tree_conn->id);
1968 share = status.tree_conn->share_conf;
1969 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
1970 ksmbd_debug(SMB, "IPC share path request\n");
1971 rsp->ShareType = SMB2_SHARE_TYPE_PIPE;
1972 rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
1973 FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE |
1974 FILE_DELETE_LE | FILE_READ_CONTROL_LE |
1975 FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
1976 FILE_SYNCHRONIZE_LE;
1978 rsp->ShareType = SMB2_SHARE_TYPE_DISK;
1979 rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
1980 FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE;
1981 if (test_tree_conn_flag(status.tree_conn,
1982 KSMBD_TREE_CONN_FLAG_WRITABLE)) {
1983 rsp->MaximalAccess |= FILE_WRITE_DATA_LE |
1984 FILE_APPEND_DATA_LE | FILE_WRITE_EA_LE |
1985 FILE_DELETE_LE | FILE_WRITE_ATTRIBUTES_LE |
1986 FILE_DELETE_CHILD_LE | FILE_READ_CONTROL_LE |
1987 FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
1988 FILE_SYNCHRONIZE_LE;
1992 status.tree_conn->maximal_access = le32_to_cpu(rsp->MaximalAccess);
1993 if (conn->posix_ext_supported)
1994 status.tree_conn->posix_extensions = true;
1996 rsp->StructureSize = cpu_to_le16(16);
1998 rsp->Capabilities = 0;
2000 /* default manual caching */
2001 rsp->ShareFlags = SMB2_SHAREFLAG_MANUAL_CACHING;
2003 rc = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_tree_connect_rsp));
2005 status.ret = KSMBD_TREE_CONN_STATUS_NOMEM;
2007 if (!IS_ERR(treename))
2012 switch (status.ret) {
2013 case KSMBD_TREE_CONN_STATUS_OK:
2014 rsp->hdr.Status = STATUS_SUCCESS;
2019 case KSMBD_TREE_CONN_STATUS_NO_SHARE:
2020 rsp->hdr.Status = STATUS_BAD_NETWORK_NAME;
2023 case KSMBD_TREE_CONN_STATUS_NOMEM:
2024 rsp->hdr.Status = STATUS_NO_MEMORY;
2026 case KSMBD_TREE_CONN_STATUS_ERROR:
2027 case KSMBD_TREE_CONN_STATUS_TOO_MANY_CONNS:
2028 case KSMBD_TREE_CONN_STATUS_TOO_MANY_SESSIONS:
2029 rsp->hdr.Status = STATUS_ACCESS_DENIED;
2032 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2035 rsp->hdr.Status = STATUS_ACCESS_DENIED;
2038 if (status.ret != KSMBD_TREE_CONN_STATUS_OK)
2039 smb2_set_err_rsp(work);
2045 * smb2_create_open_flags() - convert smb open flags to unix open flags
2046 * @file_present: is file already present
2047 * @access: file access flags
2048 * @disposition: file disposition flags
2049 * @may_flags: set with MAY_ flags
2051 * Return: file open flags
2053 static int smb2_create_open_flags(bool file_present, __le32 access,
2057 int oflags = O_NONBLOCK | O_LARGEFILE;
2059 if (access & FILE_READ_DESIRED_ACCESS_LE &&
2060 access & FILE_WRITE_DESIRE_ACCESS_LE) {
2062 *may_flags = MAY_OPEN | MAY_READ | MAY_WRITE;
2063 } else if (access & FILE_WRITE_DESIRE_ACCESS_LE) {
2065 *may_flags = MAY_OPEN | MAY_WRITE;
2068 *may_flags = MAY_OPEN | MAY_READ;
2071 if (access == FILE_READ_ATTRIBUTES_LE)
2075 switch (disposition & FILE_CREATE_MASK_LE) {
2077 case FILE_CREATE_LE:
2079 case FILE_SUPERSEDE_LE:
2080 case FILE_OVERWRITE_LE:
2081 case FILE_OVERWRITE_IF_LE:
2088 switch (disposition & FILE_CREATE_MASK_LE) {
2089 case FILE_SUPERSEDE_LE:
2090 case FILE_CREATE_LE:
2091 case FILE_OPEN_IF_LE:
2092 case FILE_OVERWRITE_IF_LE:
2096 case FILE_OVERWRITE_LE:
2108 * smb2_tree_disconnect() - handler for smb tree connect request
2109 * @work: smb work containing request buffer
2113 int smb2_tree_disconnect(struct ksmbd_work *work)
2115 struct smb2_tree_disconnect_rsp *rsp;
2116 struct smb2_tree_disconnect_req *req;
2117 struct ksmbd_session *sess = work->sess;
2118 struct ksmbd_tree_connect *tcon = work->tcon;
2121 WORK_BUFFERS(work, req, rsp);
2123 ksmbd_debug(SMB, "request\n");
2125 rsp->StructureSize = cpu_to_le16(4);
2126 err = ksmbd_iov_pin_rsp(work, rsp,
2127 sizeof(struct smb2_tree_disconnect_rsp));
2129 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
2130 smb2_set_err_rsp(work);
2134 if (!tcon || test_and_set_bit(TREE_CONN_EXPIRE, &tcon->status)) {
2135 ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
2137 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2138 smb2_set_err_rsp(work);
2142 ksmbd_close_tree_conn_fds(work);
2143 ksmbd_tree_conn_disconnect(sess, tcon);
2149 * smb2_session_logoff() - handler for session log off request
2150 * @work: smb work containing request buffer
2154 int smb2_session_logoff(struct ksmbd_work *work)
2156 struct ksmbd_conn *conn = work->conn;
2157 struct smb2_logoff_req *req;
2158 struct smb2_logoff_rsp *rsp;
2159 struct ksmbd_session *sess;
2163 WORK_BUFFERS(work, req, rsp);
2165 ksmbd_debug(SMB, "request\n");
2167 sess_id = le64_to_cpu(req->hdr.SessionId);
2169 rsp->StructureSize = cpu_to_le16(4);
2170 err = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_logoff_rsp));
2172 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
2173 smb2_set_err_rsp(work);
2177 ksmbd_all_conn_set_status(sess_id, KSMBD_SESS_NEED_RECONNECT);
2178 ksmbd_close_session_fds(work);
2179 ksmbd_conn_wait_idle(conn, sess_id);
2182 * Re-lookup session to validate if session is deleted
2183 * while waiting request complete
2185 sess = ksmbd_session_lookup_all(conn, sess_id);
2186 if (ksmbd_tree_conn_session_logoff(sess)) {
2187 ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
2188 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2189 smb2_set_err_rsp(work);
2193 ksmbd_destroy_file_table(&sess->file_table);
2194 sess->state = SMB2_SESSION_EXPIRED;
2196 ksmbd_free_user(sess->user);
2198 ksmbd_all_conn_set_status(sess_id, KSMBD_SESS_NEED_NEGOTIATE);
2203 * create_smb2_pipe() - create IPC pipe
2204 * @work: smb work containing request buffer
2206 * Return: 0 on success, otherwise error
2208 static noinline int create_smb2_pipe(struct ksmbd_work *work)
2210 struct smb2_create_rsp *rsp;
2211 struct smb2_create_req *req;
2216 WORK_BUFFERS(work, req, rsp);
2218 name = smb_strndup_from_utf16(req->Buffer, le16_to_cpu(req->NameLength),
2219 1, work->conn->local_nls);
2221 rsp->hdr.Status = STATUS_NO_MEMORY;
2222 err = PTR_ERR(name);
2226 id = ksmbd_session_rpc_open(work->sess, name);
2228 pr_err("Unable to open RPC pipe: %d\n", id);
2233 rsp->hdr.Status = STATUS_SUCCESS;
2234 rsp->StructureSize = cpu_to_le16(89);
2235 rsp->OplockLevel = SMB2_OPLOCK_LEVEL_NONE;
2237 rsp->CreateAction = cpu_to_le32(FILE_OPENED);
2239 rsp->CreationTime = cpu_to_le64(0);
2240 rsp->LastAccessTime = cpu_to_le64(0);
2241 rsp->ChangeTime = cpu_to_le64(0);
2242 rsp->AllocationSize = cpu_to_le64(0);
2243 rsp->EndofFile = cpu_to_le64(0);
2244 rsp->FileAttributes = FILE_ATTRIBUTE_NORMAL_LE;
2246 rsp->VolatileFileId = id;
2247 rsp->PersistentFileId = 0;
2248 rsp->CreateContextsOffset = 0;
2249 rsp->CreateContextsLength = 0;
2251 err = ksmbd_iov_pin_rsp(work, rsp, offsetof(struct smb2_create_rsp, Buffer));
2261 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2265 rsp->hdr.Status = STATUS_NO_MEMORY;
2272 smb2_set_err_rsp(work);
2277 * smb2_set_ea() - handler for setting extended attributes using set
2279 * @eabuf: set info command buffer
2280 * @buf_len: set info command buffer length
2281 * @path: dentry path for get ea
2283 * Return: 0 on success, otherwise error
2285 static int smb2_set_ea(struct smb2_ea_info *eabuf, unsigned int buf_len,
2286 const struct path *path)
2288 struct mnt_idmap *idmap = mnt_idmap(path->mnt);
2289 char *attr_name = NULL, *value;
2291 unsigned int next = 0;
2293 if (buf_len < sizeof(struct smb2_ea_info) + eabuf->EaNameLength +
2294 le16_to_cpu(eabuf->EaValueLength))
2297 attr_name = kmalloc(XATTR_NAME_MAX + 1, GFP_KERNEL);
2302 if (!eabuf->EaNameLength)
2306 "name : <%s>, name_len : %u, value_len : %u, next : %u\n",
2307 eabuf->name, eabuf->EaNameLength,
2308 le16_to_cpu(eabuf->EaValueLength),
2309 le32_to_cpu(eabuf->NextEntryOffset));
2311 if (eabuf->EaNameLength >
2312 (XATTR_NAME_MAX - XATTR_USER_PREFIX_LEN)) {
2317 memcpy(attr_name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN);
2318 memcpy(&attr_name[XATTR_USER_PREFIX_LEN], eabuf->name,
2319 eabuf->EaNameLength);
2320 attr_name[XATTR_USER_PREFIX_LEN + eabuf->EaNameLength] = '\0';
2321 value = (char *)&eabuf->name + eabuf->EaNameLength + 1;
2323 if (!eabuf->EaValueLength) {
2324 rc = ksmbd_vfs_casexattr_len(idmap,
2327 XATTR_USER_PREFIX_LEN +
2328 eabuf->EaNameLength);
2330 /* delete the EA only when it exits */
2332 rc = ksmbd_vfs_remove_xattr(idmap,
2338 "remove xattr failed(%d)\n",
2344 /* if the EA doesn't exist, just do nothing. */
2347 rc = ksmbd_vfs_setxattr(idmap, path, attr_name, value,
2348 le16_to_cpu(eabuf->EaValueLength), 0);
2351 "ksmbd_vfs_setxattr is failed(%d)\n",
2358 next = le32_to_cpu(eabuf->NextEntryOffset);
2359 if (next == 0 || buf_len < next)
2362 eabuf = (struct smb2_ea_info *)((char *)eabuf + next);
2363 if (buf_len < sizeof(struct smb2_ea_info)) {
2368 if (buf_len < sizeof(struct smb2_ea_info) + eabuf->EaNameLength +
2369 le16_to_cpu(eabuf->EaValueLength)) {
2373 } while (next != 0);
2379 static noinline int smb2_set_stream_name_xattr(const struct path *path,
2380 struct ksmbd_file *fp,
2381 char *stream_name, int s_type)
2383 struct mnt_idmap *idmap = mnt_idmap(path->mnt);
2384 size_t xattr_stream_size;
2385 char *xattr_stream_name;
2388 rc = ksmbd_vfs_xattr_stream_name(stream_name,
2395 fp->stream.name = xattr_stream_name;
2396 fp->stream.size = xattr_stream_size;
2398 /* Check if there is stream prefix in xattr space */
2399 rc = ksmbd_vfs_casexattr_len(idmap,
2406 if (fp->cdoption == FILE_OPEN_LE) {
2407 ksmbd_debug(SMB, "XATTR stream name lookup failed: %d\n", rc);
2411 rc = ksmbd_vfs_setxattr(idmap, path, xattr_stream_name, NULL, 0, 0);
2413 pr_err("Failed to store XATTR stream name :%d\n", rc);
2417 static int smb2_remove_smb_xattrs(const struct path *path)
2419 struct mnt_idmap *idmap = mnt_idmap(path->mnt);
2420 char *name, *xattr_list = NULL;
2421 ssize_t xattr_list_len;
2424 xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
2425 if (xattr_list_len < 0) {
2427 } else if (!xattr_list_len) {
2428 ksmbd_debug(SMB, "empty xattr in the file\n");
2432 for (name = xattr_list; name - xattr_list < xattr_list_len;
2433 name += strlen(name) + 1) {
2434 ksmbd_debug(SMB, "%s, len %zd\n", name, strlen(name));
2436 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN) &&
2437 !strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
2438 STREAM_PREFIX_LEN)) {
2439 err = ksmbd_vfs_remove_xattr(idmap, path,
2442 ksmbd_debug(SMB, "remove xattr failed : %s\n",
2451 static int smb2_create_truncate(const struct path *path)
2453 int rc = vfs_truncate(path, 0);
2456 pr_err("vfs_truncate failed, rc %d\n", rc);
2460 rc = smb2_remove_smb_xattrs(path);
2461 if (rc == -EOPNOTSUPP)
2465 "ksmbd_truncate_stream_name_xattr failed, rc %d\n",
2470 static void smb2_new_xattrs(struct ksmbd_tree_connect *tcon, const struct path *path,
2471 struct ksmbd_file *fp)
2473 struct xattr_dos_attrib da = {0};
2476 if (!test_share_config_flag(tcon->share_conf,
2477 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2481 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
2482 da.itime = da.create_time = fp->create_time;
2483 da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
2484 XATTR_DOSINFO_ITIME;
2486 rc = ksmbd_vfs_set_dos_attrib_xattr(mnt_idmap(path->mnt), path, &da);
2488 ksmbd_debug(SMB, "failed to store file attribute into xattr\n");
2491 static void smb2_update_xattrs(struct ksmbd_tree_connect *tcon,
2492 const struct path *path, struct ksmbd_file *fp)
2494 struct xattr_dos_attrib da;
2497 fp->f_ci->m_fattr &= ~(FILE_ATTRIBUTE_HIDDEN_LE | FILE_ATTRIBUTE_SYSTEM_LE);
2499 /* get FileAttributes from XATTR_NAME_DOS_ATTRIBUTE */
2500 if (!test_share_config_flag(tcon->share_conf,
2501 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2504 rc = ksmbd_vfs_get_dos_attrib_xattr(mnt_idmap(path->mnt),
2507 fp->f_ci->m_fattr = cpu_to_le32(da.attr);
2508 fp->create_time = da.create_time;
2509 fp->itime = da.itime;
2513 static int smb2_creat(struct ksmbd_work *work, struct path *parent_path,
2514 struct path *path, char *name, int open_flags,
2515 umode_t posix_mode, bool is_dir)
2517 struct ksmbd_tree_connect *tcon = work->tcon;
2518 struct ksmbd_share_config *share = tcon->share_conf;
2522 if (!(open_flags & O_CREAT))
2525 ksmbd_debug(SMB, "file does not exist, so creating\n");
2526 if (is_dir == true) {
2527 ksmbd_debug(SMB, "creating directory\n");
2529 mode = share_config_directory_mode(share, posix_mode);
2530 rc = ksmbd_vfs_mkdir(work, name, mode);
2534 ksmbd_debug(SMB, "creating regular file\n");
2536 mode = share_config_create_mode(share, posix_mode);
2537 rc = ksmbd_vfs_create(work, name, mode);
2542 rc = ksmbd_vfs_kern_path_locked(work, name, 0, parent_path, path, 0);
2544 pr_err("cannot get linux path (%s), err = %d\n",
2551 static int smb2_create_sd_buffer(struct ksmbd_work *work,
2552 struct smb2_create_req *req,
2553 const struct path *path)
2555 struct create_context *context;
2556 struct create_sd_buf_req *sd_buf;
2558 if (!req->CreateContextsOffset)
2561 /* Parse SD BUFFER create contexts */
2562 context = smb2_find_context_vals(req, SMB2_CREATE_SD_BUFFER, 4);
2565 else if (IS_ERR(context))
2566 return PTR_ERR(context);
2569 "Set ACLs using SMB2_CREATE_SD_BUFFER context\n");
2570 sd_buf = (struct create_sd_buf_req *)context;
2571 if (le16_to_cpu(context->DataOffset) +
2572 le32_to_cpu(context->DataLength) <
2573 sizeof(struct create_sd_buf_req))
2575 return set_info_sec(work->conn, work->tcon, path, &sd_buf->ntsd,
2576 le32_to_cpu(sd_buf->ccontext.DataLength), true);
2579 static void ksmbd_acls_fattr(struct smb_fattr *fattr,
2580 struct mnt_idmap *idmap,
2581 struct inode *inode)
2583 vfsuid_t vfsuid = i_uid_into_vfsuid(idmap, inode);
2584 vfsgid_t vfsgid = i_gid_into_vfsgid(idmap, inode);
2586 fattr->cf_uid = vfsuid_into_kuid(vfsuid);
2587 fattr->cf_gid = vfsgid_into_kgid(vfsgid);
2588 fattr->cf_mode = inode->i_mode;
2589 fattr->cf_acls = NULL;
2590 fattr->cf_dacls = NULL;
2592 if (IS_ENABLED(CONFIG_FS_POSIX_ACL)) {
2593 fattr->cf_acls = get_inode_acl(inode, ACL_TYPE_ACCESS);
2594 if (S_ISDIR(inode->i_mode))
2595 fattr->cf_dacls = get_inode_acl(inode, ACL_TYPE_DEFAULT);
2600 * smb2_open() - handler for smb file open request
2601 * @work: smb work containing request buffer
2603 * Return: 0 on success, otherwise error
2605 int smb2_open(struct ksmbd_work *work)
2607 struct ksmbd_conn *conn = work->conn;
2608 struct ksmbd_session *sess = work->sess;
2609 struct ksmbd_tree_connect *tcon = work->tcon;
2610 struct smb2_create_req *req;
2611 struct smb2_create_rsp *rsp;
2612 struct path path, parent_path;
2613 struct ksmbd_share_config *share = tcon->share_conf;
2614 struct ksmbd_file *fp = NULL;
2615 struct file *filp = NULL;
2616 struct mnt_idmap *idmap = NULL;
2618 struct create_context *context;
2619 struct lease_ctx_info *lc = NULL;
2620 struct create_ea_buf_req *ea_buf = NULL;
2621 struct oplock_info *opinfo;
2622 __le32 *next_ptr = NULL;
2623 int req_op_level = 0, open_flags = 0, may_flags = 0, file_info = 0;
2625 int contxt_cnt = 0, query_disk_id = 0;
2626 int maximal_access_ctxt = 0, posix_ctxt = 0;
2630 char *stream_name = NULL;
2631 bool file_present = false, created = false, already_permitted = false;
2632 int share_ret, need_truncate = 0;
2634 umode_t posix_mode = 0;
2635 __le32 daccess, maximal_access = 0;
2638 WORK_BUFFERS(work, req, rsp);
2640 if (req->hdr.NextCommand && !work->next_smb2_rcv_hdr_off &&
2641 (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
2642 ksmbd_debug(SMB, "invalid flag in chained command\n");
2643 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2644 smb2_set_err_rsp(work);
2648 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
2649 ksmbd_debug(SMB, "IPC pipe create request\n");
2650 return create_smb2_pipe(work);
2653 if (req->NameLength) {
2654 if ((req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
2655 *(char *)req->Buffer == '\\') {
2656 pr_err("not allow directory name included leading slash\n");
2661 name = smb2_get_name(req->Buffer,
2662 le16_to_cpu(req->NameLength),
2663 work->conn->local_nls);
2672 ksmbd_debug(SMB, "converted name = %s\n", name);
2673 if (strchr(name, ':')) {
2674 if (!test_share_config_flag(work->tcon->share_conf,
2675 KSMBD_SHARE_FLAG_STREAMS)) {
2679 rc = parse_stream_name(name, &stream_name, &s_type);
2684 rc = ksmbd_validate_filename(name);
2688 if (ksmbd_share_veto_filename(share, name)) {
2690 ksmbd_debug(SMB, "Reject open(), vetoed file: %s\n",
2695 name = kstrdup("", GFP_KERNEL);
2702 req_op_level = req->RequestedOplockLevel;
2703 if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE)
2704 lc = parse_lease_state(req);
2706 if (le32_to_cpu(req->ImpersonationLevel) > le32_to_cpu(IL_DELEGATE)) {
2707 pr_err("Invalid impersonationlevel : 0x%x\n",
2708 le32_to_cpu(req->ImpersonationLevel));
2710 rsp->hdr.Status = STATUS_BAD_IMPERSONATION_LEVEL;
2714 if (req->CreateOptions && !(req->CreateOptions & CREATE_OPTIONS_MASK_LE)) {
2715 pr_err("Invalid create options : 0x%x\n",
2716 le32_to_cpu(req->CreateOptions));
2720 if (req->CreateOptions & FILE_SEQUENTIAL_ONLY_LE &&
2721 req->CreateOptions & FILE_RANDOM_ACCESS_LE)
2722 req->CreateOptions = ~(FILE_SEQUENTIAL_ONLY_LE);
2724 if (req->CreateOptions &
2725 (FILE_OPEN_BY_FILE_ID_LE | CREATE_TREE_CONNECTION |
2726 FILE_RESERVE_OPFILTER_LE)) {
2731 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
2732 if (req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE) {
2735 } else if (req->CreateOptions & FILE_NO_COMPRESSION_LE) {
2736 req->CreateOptions = ~(FILE_NO_COMPRESSION_LE);
2741 if (le32_to_cpu(req->CreateDisposition) >
2742 le32_to_cpu(FILE_OVERWRITE_IF_LE)) {
2743 pr_err("Invalid create disposition : 0x%x\n",
2744 le32_to_cpu(req->CreateDisposition));
2749 if (!(req->DesiredAccess & DESIRED_ACCESS_MASK)) {
2750 pr_err("Invalid desired access : 0x%x\n",
2751 le32_to_cpu(req->DesiredAccess));
2756 if (req->FileAttributes && !(req->FileAttributes & FILE_ATTRIBUTE_MASK_LE)) {
2757 pr_err("Invalid file attribute : 0x%x\n",
2758 le32_to_cpu(req->FileAttributes));
2763 if (req->CreateContextsOffset) {
2764 /* Parse non-durable handle create contexts */
2765 context = smb2_find_context_vals(req, SMB2_CREATE_EA_BUFFER, 4);
2766 if (IS_ERR(context)) {
2767 rc = PTR_ERR(context);
2769 } else if (context) {
2770 ea_buf = (struct create_ea_buf_req *)context;
2771 if (le16_to_cpu(context->DataOffset) +
2772 le32_to_cpu(context->DataLength) <
2773 sizeof(struct create_ea_buf_req)) {
2777 if (req->CreateOptions & FILE_NO_EA_KNOWLEDGE_LE) {
2778 rsp->hdr.Status = STATUS_ACCESS_DENIED;
2784 context = smb2_find_context_vals(req,
2785 SMB2_CREATE_QUERY_MAXIMAL_ACCESS_REQUEST, 4);
2786 if (IS_ERR(context)) {
2787 rc = PTR_ERR(context);
2789 } else if (context) {
2791 "get query maximal access context\n");
2792 maximal_access_ctxt = 1;
2795 context = smb2_find_context_vals(req,
2796 SMB2_CREATE_TIMEWARP_REQUEST, 4);
2797 if (IS_ERR(context)) {
2798 rc = PTR_ERR(context);
2800 } else if (context) {
2801 ksmbd_debug(SMB, "get timewarp context\n");
2806 if (tcon->posix_extensions) {
2807 context = smb2_find_context_vals(req,
2808 SMB2_CREATE_TAG_POSIX, 16);
2809 if (IS_ERR(context)) {
2810 rc = PTR_ERR(context);
2812 } else if (context) {
2813 struct create_posix *posix =
2814 (struct create_posix *)context;
2815 if (le16_to_cpu(context->DataOffset) +
2816 le32_to_cpu(context->DataLength) <
2817 sizeof(struct create_posix) - 4) {
2821 ksmbd_debug(SMB, "get posix context\n");
2823 posix_mode = le32_to_cpu(posix->Mode);
2829 if (ksmbd_override_fsids(work)) {
2834 rc = ksmbd_vfs_kern_path_locked(work, name, LOOKUP_NO_SYMLINKS,
2835 &parent_path, &path, 1);
2837 file_present = true;
2839 if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE) {
2841 * If file exists with under flags, return access
2844 if (req->CreateDisposition == FILE_OVERWRITE_IF_LE ||
2845 req->CreateDisposition == FILE_OPEN_IF_LE) {
2850 if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
2852 "User does not have write permission\n");
2856 } else if (d_is_symlink(path.dentry)) {
2861 file_present = true;
2862 idmap = mnt_idmap(path.mnt);
2866 ksmbd_debug(SMB, "can not get linux path for %s, rc = %d\n",
2872 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
2873 if (s_type == DATA_STREAM) {
2875 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2878 if (file_present && S_ISDIR(d_inode(path.dentry)->i_mode) &&
2879 s_type == DATA_STREAM) {
2881 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
2885 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE &&
2886 req->FileAttributes & FILE_ATTRIBUTE_NORMAL_LE) {
2887 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2895 if (file_present && req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE &&
2896 S_ISDIR(d_inode(path.dentry)->i_mode) &&
2897 !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2898 ksmbd_debug(SMB, "open() argument is a directory: %s, %x\n",
2899 name, req->CreateOptions);
2900 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
2905 if (file_present && (req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
2906 !(req->CreateDisposition == FILE_CREATE_LE) &&
2907 !S_ISDIR(d_inode(path.dentry)->i_mode)) {
2908 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2913 if (!stream_name && file_present &&
2914 req->CreateDisposition == FILE_CREATE_LE) {
2919 daccess = smb_map_generic_desired_access(req->DesiredAccess);
2921 if (file_present && !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2922 rc = smb_check_perm_dacl(conn, &path, &daccess,
2928 if (daccess & FILE_MAXIMAL_ACCESS_LE) {
2929 if (!file_present) {
2930 daccess = cpu_to_le32(GENERIC_ALL_FLAGS);
2932 ksmbd_vfs_query_maximal_access(idmap,
2935 already_permitted = true;
2937 maximal_access = daccess;
2940 open_flags = smb2_create_open_flags(file_present, daccess,
2941 req->CreateDisposition,
2944 if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
2945 if (open_flags & O_CREAT) {
2947 "User does not have write permission\n");
2953 /*create file if not present */
2954 if (!file_present) {
2955 rc = smb2_creat(work, &parent_path, &path, name, open_flags,
2957 req->CreateOptions & FILE_DIRECTORY_FILE_LE);
2959 if (rc == -ENOENT) {
2961 rsp->hdr.Status = STATUS_OBJECT_PATH_NOT_FOUND;
2967 idmap = mnt_idmap(path.mnt);
2969 if (le32_to_cpu(ea_buf->ccontext.DataLength) <
2970 sizeof(struct smb2_ea_info)) {
2975 rc = smb2_set_ea(&ea_buf->ea,
2976 le32_to_cpu(ea_buf->ccontext.DataLength),
2978 if (rc == -EOPNOTSUPP)
2983 } else if (!already_permitted) {
2984 /* FILE_READ_ATTRIBUTE is allowed without inode_permission,
2985 * because execute(search) permission on a parent directory,
2986 * is already granted.
2988 if (daccess & ~(FILE_READ_ATTRIBUTES_LE | FILE_READ_CONTROL_LE)) {
2989 rc = inode_permission(idmap,
2990 d_inode(path.dentry),
2995 if ((daccess & FILE_DELETE_LE) ||
2996 (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2997 rc = inode_permission(idmap,
2998 d_inode(path.dentry->d_parent),
2999 MAY_EXEC | MAY_WRITE);
3006 rc = ksmbd_query_inode_status(d_inode(path.dentry->d_parent));
3007 if (rc == KSMBD_INODE_STATUS_PENDING_DELETE) {
3013 filp = dentry_open(&path, open_flags, current_cred());
3016 pr_err("dentry open for dir failed, rc %d\n", rc);
3021 if (!(open_flags & O_TRUNC))
3022 file_info = FILE_OPENED;
3024 file_info = FILE_OVERWRITTEN;
3026 if ((req->CreateDisposition & FILE_CREATE_MASK_LE) ==
3028 file_info = FILE_SUPERSEDED;
3029 } else if (open_flags & O_CREAT) {
3030 file_info = FILE_CREATED;
3033 ksmbd_vfs_set_fadvise(filp, req->CreateOptions);
3035 /* Obtain Volatile-ID */
3036 fp = ksmbd_open_fd(work, filp);
3044 /* Get Persistent-ID */
3045 ksmbd_open_durable_fd(fp);
3046 if (!has_file_id(fp->persistent_id)) {
3051 fp->cdoption = req->CreateDisposition;
3052 fp->daccess = daccess;
3053 fp->saccess = req->ShareAccess;
3054 fp->coption = req->CreateOptions;
3056 /* Set default windows and posix acls if creating new file */
3059 struct inode *inode = d_inode(path.dentry);
3061 posix_acl_rc = ksmbd_vfs_inherit_posix_acl(idmap,
3063 d_inode(path.dentry->d_parent));
3065 ksmbd_debug(SMB, "inherit posix acl failed : %d\n", posix_acl_rc);
3067 if (test_share_config_flag(work->tcon->share_conf,
3068 KSMBD_SHARE_FLAG_ACL_XATTR)) {
3069 rc = smb_inherit_dacl(conn, &path, sess->user->uid,
3074 rc = smb2_create_sd_buffer(work, req, &path);
3077 ksmbd_vfs_set_init_posix_acl(idmap,
3080 if (test_share_config_flag(work->tcon->share_conf,
3081 KSMBD_SHARE_FLAG_ACL_XATTR)) {
3082 struct smb_fattr fattr;
3083 struct smb_ntsd *pntsd;
3084 int pntsd_size, ace_num = 0;
3086 ksmbd_acls_fattr(&fattr, idmap, inode);
3088 ace_num = fattr.cf_acls->a_count;
3090 ace_num += fattr.cf_dacls->a_count;
3092 pntsd = kmalloc(sizeof(struct smb_ntsd) +
3093 sizeof(struct smb_sid) * 3 +
3094 sizeof(struct smb_acl) +
3095 sizeof(struct smb_ace) * ace_num * 2,
3098 posix_acl_release(fattr.cf_acls);
3099 posix_acl_release(fattr.cf_dacls);
3103 rc = build_sec_desc(idmap,
3108 &pntsd_size, &fattr);
3109 posix_acl_release(fattr.cf_acls);
3110 posix_acl_release(fattr.cf_dacls);
3116 rc = ksmbd_vfs_set_sd_xattr(conn,
3123 pr_err("failed to store ntacl in xattr : %d\n",
3132 rc = smb2_set_stream_name_xattr(&path,
3138 file_info = FILE_CREATED;
3141 fp->attrib_only = !(req->DesiredAccess & ~(FILE_READ_ATTRIBUTES_LE |
3142 FILE_WRITE_ATTRIBUTES_LE | FILE_SYNCHRONIZE_LE));
3143 if (!S_ISDIR(file_inode(filp)->i_mode) && open_flags & O_TRUNC &&
3144 !fp->attrib_only && !stream_name) {
3145 smb_break_all_oplock(work, fp);
3149 /* fp should be searchable through ksmbd_inode.m_fp_list
3150 * after daccess, saccess, attrib_only, and stream are
3153 write_lock(&fp->f_ci->m_lock);
3154 list_add(&fp->node, &fp->f_ci->m_fp_list);
3155 write_unlock(&fp->f_ci->m_lock);
3157 /* Check delete pending among previous fp before oplock break */
3158 if (ksmbd_inode_pending_delete(fp)) {
3163 share_ret = ksmbd_smb_check_shared_mode(fp->filp, fp);
3164 if (!test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_OPLOCKS) ||
3165 (req_op_level == SMB2_OPLOCK_LEVEL_LEASE &&
3166 !(conn->vals->capabilities & SMB2_GLOBAL_CAP_LEASING))) {
3167 if (share_ret < 0 && !S_ISDIR(file_inode(fp->filp)->i_mode)) {
3172 if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE) {
3173 req_op_level = smb2_map_lease_to_oplock(lc->req_state);
3175 "lease req for(%s) req oplock state 0x%x, lease state 0x%x\n",
3176 name, req_op_level, lc->req_state);
3177 rc = find_same_lease_key(sess, fp->f_ci, lc);
3180 } else if (open_flags == O_RDONLY &&
3181 (req_op_level == SMB2_OPLOCK_LEVEL_BATCH ||
3182 req_op_level == SMB2_OPLOCK_LEVEL_EXCLUSIVE))
3183 req_op_level = SMB2_OPLOCK_LEVEL_II;
3185 rc = smb_grant_oplock(work, req_op_level,
3186 fp->persistent_id, fp,
3187 le32_to_cpu(req->hdr.Id.SyncId.TreeId),
3193 if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)
3194 ksmbd_fd_set_delete_on_close(fp, file_info);
3196 if (need_truncate) {
3197 rc = smb2_create_truncate(&path);
3202 if (req->CreateContextsOffset) {
3203 struct create_alloc_size_req *az_req;
3205 az_req = (struct create_alloc_size_req *)smb2_find_context_vals(req,
3206 SMB2_CREATE_ALLOCATION_SIZE, 4);
3207 if (IS_ERR(az_req)) {
3208 rc = PTR_ERR(az_req);
3210 } else if (az_req) {
3214 if (le16_to_cpu(az_req->ccontext.DataOffset) +
3215 le32_to_cpu(az_req->ccontext.DataLength) <
3216 sizeof(struct create_alloc_size_req)) {
3220 alloc_size = le64_to_cpu(az_req->AllocationSize);
3222 "request smb2 create allocate size : %llu\n",
3224 smb_break_all_levII_oplock(work, fp, 1);
3225 err = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
3229 "vfs_fallocate is failed : %d\n",
3233 context = smb2_find_context_vals(req, SMB2_CREATE_QUERY_ON_DISK_ID, 4);
3234 if (IS_ERR(context)) {
3235 rc = PTR_ERR(context);
3237 } else if (context) {
3238 ksmbd_debug(SMB, "get query on disk id context\n");
3243 rc = ksmbd_vfs_getattr(&path, &stat);
3247 if (stat.result_mask & STATX_BTIME)
3248 fp->create_time = ksmbd_UnixTimeToNT(stat.btime);
3250 fp->create_time = ksmbd_UnixTimeToNT(stat.ctime);
3251 if (req->FileAttributes || fp->f_ci->m_fattr == 0)
3253 cpu_to_le32(smb2_get_dos_mode(&stat, le32_to_cpu(req->FileAttributes)));
3256 smb2_update_xattrs(tcon, &path, fp);
3258 smb2_new_xattrs(tcon, &path, fp);
3260 memcpy(fp->client_guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE);
3262 rsp->StructureSize = cpu_to_le16(89);
3264 opinfo = rcu_dereference(fp->f_opinfo);
3265 rsp->OplockLevel = opinfo != NULL ? opinfo->level : 0;
3268 rsp->CreateAction = cpu_to_le32(file_info);
3269 rsp->CreationTime = cpu_to_le64(fp->create_time);
3270 time = ksmbd_UnixTimeToNT(stat.atime);
3271 rsp->LastAccessTime = cpu_to_le64(time);
3272 time = ksmbd_UnixTimeToNT(stat.mtime);
3273 rsp->LastWriteTime = cpu_to_le64(time);
3274 time = ksmbd_UnixTimeToNT(stat.ctime);
3275 rsp->ChangeTime = cpu_to_le64(time);
3276 rsp->AllocationSize = S_ISDIR(stat.mode) ? 0 :
3277 cpu_to_le64(stat.blocks << 9);
3278 rsp->EndofFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
3279 rsp->FileAttributes = fp->f_ci->m_fattr;
3283 rsp->PersistentFileId = fp->persistent_id;
3284 rsp->VolatileFileId = fp->volatile_id;
3286 rsp->CreateContextsOffset = 0;
3287 rsp->CreateContextsLength = 0;
3288 iov_len = offsetof(struct smb2_create_rsp, Buffer);
3290 /* If lease is request send lease context response */
3291 if (opinfo && opinfo->is_lease) {
3292 struct create_context *lease_ccontext;
3294 ksmbd_debug(SMB, "lease granted on(%s) lease state 0x%x\n",
3295 name, opinfo->o_lease->state);
3296 rsp->OplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
3298 lease_ccontext = (struct create_context *)rsp->Buffer;
3300 create_lease_buf(rsp->Buffer, opinfo->o_lease);
3301 le32_add_cpu(&rsp->CreateContextsLength,
3302 conn->vals->create_lease_size);
3303 iov_len += conn->vals->create_lease_size;
3304 next_ptr = &lease_ccontext->Next;
3305 next_off = conn->vals->create_lease_size;
3308 if (maximal_access_ctxt) {
3309 struct create_context *mxac_ccontext;
3311 if (maximal_access == 0)
3312 ksmbd_vfs_query_maximal_access(idmap,
3315 mxac_ccontext = (struct create_context *)(rsp->Buffer +
3316 le32_to_cpu(rsp->CreateContextsLength));
3318 create_mxac_rsp_buf(rsp->Buffer +
3319 le32_to_cpu(rsp->CreateContextsLength),
3320 le32_to_cpu(maximal_access));
3321 le32_add_cpu(&rsp->CreateContextsLength,
3322 conn->vals->create_mxac_size);
3323 iov_len += conn->vals->create_mxac_size;
3325 *next_ptr = cpu_to_le32(next_off);
3326 next_ptr = &mxac_ccontext->Next;
3327 next_off = conn->vals->create_mxac_size;
3330 if (query_disk_id) {
3331 struct create_context *disk_id_ccontext;
3333 disk_id_ccontext = (struct create_context *)(rsp->Buffer +
3334 le32_to_cpu(rsp->CreateContextsLength));
3336 create_disk_id_rsp_buf(rsp->Buffer +
3337 le32_to_cpu(rsp->CreateContextsLength),
3338 stat.ino, tcon->id);
3339 le32_add_cpu(&rsp->CreateContextsLength,
3340 conn->vals->create_disk_id_size);
3341 iov_len += conn->vals->create_disk_id_size;
3343 *next_ptr = cpu_to_le32(next_off);
3344 next_ptr = &disk_id_ccontext->Next;
3345 next_off = conn->vals->create_disk_id_size;
3350 create_posix_rsp_buf(rsp->Buffer +
3351 le32_to_cpu(rsp->CreateContextsLength),
3353 le32_add_cpu(&rsp->CreateContextsLength,
3354 conn->vals->create_posix_size);
3355 iov_len += conn->vals->create_posix_size;
3357 *next_ptr = cpu_to_le32(next_off);
3360 if (contxt_cnt > 0) {
3361 rsp->CreateContextsOffset =
3362 cpu_to_le32(offsetof(struct smb2_create_rsp, Buffer));
3366 if (file_present || created) {
3367 inode_unlock(d_inode(parent_path.dentry));
3369 path_put(&parent_path);
3371 ksmbd_revert_fsids(work);
3374 rc = ksmbd_iov_pin_rsp(work, (void *)rsp, iov_len);
3377 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
3378 else if (rc == -EOPNOTSUPP)
3379 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
3380 else if (rc == -EACCES || rc == -ESTALE || rc == -EXDEV)
3381 rsp->hdr.Status = STATUS_ACCESS_DENIED;
3382 else if (rc == -ENOENT)
3383 rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
3384 else if (rc == -EPERM)
3385 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
3386 else if (rc == -EBUSY)
3387 rsp->hdr.Status = STATUS_DELETE_PENDING;
3388 else if (rc == -EBADF)
3389 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
3390 else if (rc == -ENOEXEC)
3391 rsp->hdr.Status = STATUS_DUPLICATE_OBJECTID;
3392 else if (rc == -ENXIO)
3393 rsp->hdr.Status = STATUS_NO_SUCH_DEVICE;
3394 else if (rc == -EEXIST)
3395 rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
3396 else if (rc == -EMFILE)
3397 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
3398 if (!rsp->hdr.Status)
3399 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
3402 ksmbd_fd_put(work, fp);
3403 smb2_set_err_rsp(work);
3404 ksmbd_debug(SMB, "Error response: %x\n", rsp->hdr.Status);
3413 static int readdir_info_level_struct_sz(int info_level)
3415 switch (info_level) {
3416 case FILE_FULL_DIRECTORY_INFORMATION:
3417 return sizeof(struct file_full_directory_info);
3418 case FILE_BOTH_DIRECTORY_INFORMATION:
3419 return sizeof(struct file_both_directory_info);
3420 case FILE_DIRECTORY_INFORMATION:
3421 return sizeof(struct file_directory_info);
3422 case FILE_NAMES_INFORMATION:
3423 return sizeof(struct file_names_info);
3424 case FILEID_FULL_DIRECTORY_INFORMATION:
3425 return sizeof(struct file_id_full_dir_info);
3426 case FILEID_BOTH_DIRECTORY_INFORMATION:
3427 return sizeof(struct file_id_both_directory_info);
3428 case SMB_FIND_FILE_POSIX_INFO:
3429 return sizeof(struct smb2_posix_info);
3435 static int dentry_name(struct ksmbd_dir_info *d_info, int info_level)
3437 switch (info_level) {
3438 case FILE_FULL_DIRECTORY_INFORMATION:
3440 struct file_full_directory_info *ffdinfo;
3442 ffdinfo = (struct file_full_directory_info *)d_info->rptr;
3443 d_info->rptr += le32_to_cpu(ffdinfo->NextEntryOffset);
3444 d_info->name = ffdinfo->FileName;
3445 d_info->name_len = le32_to_cpu(ffdinfo->FileNameLength);
3448 case FILE_BOTH_DIRECTORY_INFORMATION:
3450 struct file_both_directory_info *fbdinfo;
3452 fbdinfo = (struct file_both_directory_info *)d_info->rptr;
3453 d_info->rptr += le32_to_cpu(fbdinfo->NextEntryOffset);
3454 d_info->name = fbdinfo->FileName;
3455 d_info->name_len = le32_to_cpu(fbdinfo->FileNameLength);
3458 case FILE_DIRECTORY_INFORMATION:
3460 struct file_directory_info *fdinfo;
3462 fdinfo = (struct file_directory_info *)d_info->rptr;
3463 d_info->rptr += le32_to_cpu(fdinfo->NextEntryOffset);
3464 d_info->name = fdinfo->FileName;
3465 d_info->name_len = le32_to_cpu(fdinfo->FileNameLength);
3468 case FILE_NAMES_INFORMATION:
3470 struct file_names_info *fninfo;
3472 fninfo = (struct file_names_info *)d_info->rptr;
3473 d_info->rptr += le32_to_cpu(fninfo->NextEntryOffset);
3474 d_info->name = fninfo->FileName;
3475 d_info->name_len = le32_to_cpu(fninfo->FileNameLength);
3478 case FILEID_FULL_DIRECTORY_INFORMATION:
3480 struct file_id_full_dir_info *dinfo;
3482 dinfo = (struct file_id_full_dir_info *)d_info->rptr;
3483 d_info->rptr += le32_to_cpu(dinfo->NextEntryOffset);
3484 d_info->name = dinfo->FileName;
3485 d_info->name_len = le32_to_cpu(dinfo->FileNameLength);
3488 case FILEID_BOTH_DIRECTORY_INFORMATION:
3490 struct file_id_both_directory_info *fibdinfo;
3492 fibdinfo = (struct file_id_both_directory_info *)d_info->rptr;
3493 d_info->rptr += le32_to_cpu(fibdinfo->NextEntryOffset);
3494 d_info->name = fibdinfo->FileName;
3495 d_info->name_len = le32_to_cpu(fibdinfo->FileNameLength);
3498 case SMB_FIND_FILE_POSIX_INFO:
3500 struct smb2_posix_info *posix_info;
3502 posix_info = (struct smb2_posix_info *)d_info->rptr;
3503 d_info->rptr += le32_to_cpu(posix_info->NextEntryOffset);
3504 d_info->name = posix_info->name;
3505 d_info->name_len = le32_to_cpu(posix_info->name_len);
3514 * smb2_populate_readdir_entry() - encode directory entry in smb2 response
3516 * @conn: connection instance
3517 * @info_level: smb information level
3518 * @d_info: structure included variables for query dir
3519 * @ksmbd_kstat: ksmbd wrapper of dirent stat information
3521 * if directory has many entries, find first can't read it fully.
3522 * find next might be called multiple times to read remaining dir entries
3524 * Return: 0 on success, otherwise error
3526 static int smb2_populate_readdir_entry(struct ksmbd_conn *conn, int info_level,
3527 struct ksmbd_dir_info *d_info,
3528 struct ksmbd_kstat *ksmbd_kstat)
3530 int next_entry_offset = 0;
3534 int struct_sz, rc = 0;
3536 conv_name = ksmbd_convert_dir_info_name(d_info,
3542 /* Somehow the name has only terminating NULL bytes */
3545 goto free_conv_name;
3548 struct_sz = readdir_info_level_struct_sz(info_level) + conv_len;
3549 next_entry_offset = ALIGN(struct_sz, KSMBD_DIR_INFO_ALIGNMENT);
3550 d_info->last_entry_off_align = next_entry_offset - struct_sz;
3552 if (next_entry_offset > d_info->out_buf_len) {
3553 d_info->out_buf_len = 0;
3555 goto free_conv_name;
3558 kstat = d_info->wptr;
3559 if (info_level != FILE_NAMES_INFORMATION)
3560 kstat = ksmbd_vfs_init_kstat(&d_info->wptr, ksmbd_kstat);
3562 switch (info_level) {
3563 case FILE_FULL_DIRECTORY_INFORMATION:
3565 struct file_full_directory_info *ffdinfo;
3567 ffdinfo = (struct file_full_directory_info *)kstat;
3568 ffdinfo->FileNameLength = cpu_to_le32(conv_len);
3570 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3571 if (ffdinfo->EaSize)
3572 ffdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3573 if (d_info->hide_dot_file && d_info->name[0] == '.')
3574 ffdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3575 memcpy(ffdinfo->FileName, conv_name, conv_len);
3576 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3579 case FILE_BOTH_DIRECTORY_INFORMATION:
3581 struct file_both_directory_info *fbdinfo;
3583 fbdinfo = (struct file_both_directory_info *)kstat;
3584 fbdinfo->FileNameLength = cpu_to_le32(conv_len);
3586 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3587 if (fbdinfo->EaSize)
3588 fbdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3589 fbdinfo->ShortNameLength = 0;
3590 fbdinfo->Reserved = 0;
3591 if (d_info->hide_dot_file && d_info->name[0] == '.')
3592 fbdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3593 memcpy(fbdinfo->FileName, conv_name, conv_len);
3594 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3597 case FILE_DIRECTORY_INFORMATION:
3599 struct file_directory_info *fdinfo;
3601 fdinfo = (struct file_directory_info *)kstat;
3602 fdinfo->FileNameLength = cpu_to_le32(conv_len);
3603 if (d_info->hide_dot_file && d_info->name[0] == '.')
3604 fdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3605 memcpy(fdinfo->FileName, conv_name, conv_len);
3606 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3609 case FILE_NAMES_INFORMATION:
3611 struct file_names_info *fninfo;
3613 fninfo = (struct file_names_info *)kstat;
3614 fninfo->FileNameLength = cpu_to_le32(conv_len);
3615 memcpy(fninfo->FileName, conv_name, conv_len);
3616 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3619 case FILEID_FULL_DIRECTORY_INFORMATION:
3621 struct file_id_full_dir_info *dinfo;
3623 dinfo = (struct file_id_full_dir_info *)kstat;
3624 dinfo->FileNameLength = cpu_to_le32(conv_len);
3626 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3628 dinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3629 dinfo->Reserved = 0;
3630 dinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
3631 if (d_info->hide_dot_file && d_info->name[0] == '.')
3632 dinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3633 memcpy(dinfo->FileName, conv_name, conv_len);
3634 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3637 case FILEID_BOTH_DIRECTORY_INFORMATION:
3639 struct file_id_both_directory_info *fibdinfo;
3641 fibdinfo = (struct file_id_both_directory_info *)kstat;
3642 fibdinfo->FileNameLength = cpu_to_le32(conv_len);
3644 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3645 if (fibdinfo->EaSize)
3646 fibdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3647 fibdinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
3648 fibdinfo->ShortNameLength = 0;
3649 fibdinfo->Reserved = 0;
3650 fibdinfo->Reserved2 = cpu_to_le16(0);
3651 if (d_info->hide_dot_file && d_info->name[0] == '.')
3652 fibdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3653 memcpy(fibdinfo->FileName, conv_name, conv_len);
3654 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3657 case SMB_FIND_FILE_POSIX_INFO:
3659 struct smb2_posix_info *posix_info;
3662 posix_info = (struct smb2_posix_info *)kstat;
3663 posix_info->Ignored = 0;
3664 posix_info->CreationTime = cpu_to_le64(ksmbd_kstat->create_time);
3665 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->ctime);
3666 posix_info->ChangeTime = cpu_to_le64(time);
3667 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->atime);
3668 posix_info->LastAccessTime = cpu_to_le64(time);
3669 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->mtime);
3670 posix_info->LastWriteTime = cpu_to_le64(time);
3671 posix_info->EndOfFile = cpu_to_le64(ksmbd_kstat->kstat->size);
3672 posix_info->AllocationSize = cpu_to_le64(ksmbd_kstat->kstat->blocks << 9);
3673 posix_info->DeviceId = cpu_to_le32(ksmbd_kstat->kstat->rdev);
3674 posix_info->HardLinks = cpu_to_le32(ksmbd_kstat->kstat->nlink);
3675 posix_info->Mode = cpu_to_le32(ksmbd_kstat->kstat->mode & 0777);
3676 posix_info->Inode = cpu_to_le64(ksmbd_kstat->kstat->ino);
3677 posix_info->DosAttributes =
3678 S_ISDIR(ksmbd_kstat->kstat->mode) ?
3679 FILE_ATTRIBUTE_DIRECTORY_LE : FILE_ATTRIBUTE_ARCHIVE_LE;
3680 if (d_info->hide_dot_file && d_info->name[0] == '.')
3681 posix_info->DosAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3683 * SidBuffer(32) contain two sids(Domain sid(16), UNIX group sid(16)).
3684 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) +
3685 * sub_auth(4 * 1(num_subauth)) + RID(4).
3687 id_to_sid(from_kuid_munged(&init_user_ns, ksmbd_kstat->kstat->uid),
3688 SIDUNIX_USER, (struct smb_sid *)&posix_info->SidBuffer[0]);
3689 id_to_sid(from_kgid_munged(&init_user_ns, ksmbd_kstat->kstat->gid),
3690 SIDUNIX_GROUP, (struct smb_sid *)&posix_info->SidBuffer[16]);
3691 memcpy(posix_info->name, conv_name, conv_len);
3692 posix_info->name_len = cpu_to_le32(conv_len);
3693 posix_info->NextEntryOffset = cpu_to_le32(next_entry_offset);
3697 } /* switch (info_level) */
3699 d_info->last_entry_offset = d_info->data_count;
3700 d_info->data_count += next_entry_offset;
3701 d_info->out_buf_len -= next_entry_offset;
3702 d_info->wptr += next_entry_offset;
3705 "info_level : %d, buf_len :%d, next_offset : %d, data_count : %d\n",
3706 info_level, d_info->out_buf_len,
3707 next_entry_offset, d_info->data_count);
3714 struct smb2_query_dir_private {
3715 struct ksmbd_work *work;
3716 char *search_pattern;
3717 struct ksmbd_file *dir_fp;
3719 struct ksmbd_dir_info *d_info;
3723 static void lock_dir(struct ksmbd_file *dir_fp)
3725 struct dentry *dir = dir_fp->filp->f_path.dentry;
3727 inode_lock_nested(d_inode(dir), I_MUTEX_PARENT);
3730 static void unlock_dir(struct ksmbd_file *dir_fp)
3732 struct dentry *dir = dir_fp->filp->f_path.dentry;
3734 inode_unlock(d_inode(dir));
3737 static int process_query_dir_entries(struct smb2_query_dir_private *priv)
3739 struct mnt_idmap *idmap = file_mnt_idmap(priv->dir_fp->filp);
3741 struct ksmbd_kstat ksmbd_kstat;
3745 for (i = 0; i < priv->d_info->num_entry; i++) {
3746 struct dentry *dent;
3748 if (dentry_name(priv->d_info, priv->info_level))
3751 lock_dir(priv->dir_fp);
3752 dent = lookup_one(idmap, priv->d_info->name,
3753 priv->dir_fp->filp->f_path.dentry,
3754 priv->d_info->name_len);
3755 unlock_dir(priv->dir_fp);
3758 ksmbd_debug(SMB, "Cannot lookup `%s' [%ld]\n",
3763 if (unlikely(d_is_negative(dent))) {
3765 ksmbd_debug(SMB, "Negative dentry `%s'\n",
3766 priv->d_info->name);
3770 ksmbd_kstat.kstat = &kstat;
3771 if (priv->info_level != FILE_NAMES_INFORMATION)
3772 ksmbd_vfs_fill_dentry_attrs(priv->work,
3777 rc = smb2_populate_readdir_entry(priv->work->conn,
3788 static int reserve_populate_dentry(struct ksmbd_dir_info *d_info,
3793 int next_entry_offset;
3795 struct_sz = readdir_info_level_struct_sz(info_level);
3796 if (struct_sz == -EOPNOTSUPP)
3799 conv_len = (d_info->name_len + 1) * 2;
3800 next_entry_offset = ALIGN(struct_sz + conv_len,
3801 KSMBD_DIR_INFO_ALIGNMENT);
3803 if (next_entry_offset > d_info->out_buf_len) {
3804 d_info->out_buf_len = 0;
3808 switch (info_level) {
3809 case FILE_FULL_DIRECTORY_INFORMATION:
3811 struct file_full_directory_info *ffdinfo;
3813 ffdinfo = (struct file_full_directory_info *)d_info->wptr;
3814 memcpy(ffdinfo->FileName, d_info->name, d_info->name_len);
3815 ffdinfo->FileName[d_info->name_len] = 0x00;
3816 ffdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3817 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3820 case FILE_BOTH_DIRECTORY_INFORMATION:
3822 struct file_both_directory_info *fbdinfo;
3824 fbdinfo = (struct file_both_directory_info *)d_info->wptr;
3825 memcpy(fbdinfo->FileName, d_info->name, d_info->name_len);
3826 fbdinfo->FileName[d_info->name_len] = 0x00;
3827 fbdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3828 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3831 case FILE_DIRECTORY_INFORMATION:
3833 struct file_directory_info *fdinfo;
3835 fdinfo = (struct file_directory_info *)d_info->wptr;
3836 memcpy(fdinfo->FileName, d_info->name, d_info->name_len);
3837 fdinfo->FileName[d_info->name_len] = 0x00;
3838 fdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3839 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3842 case FILE_NAMES_INFORMATION:
3844 struct file_names_info *fninfo;
3846 fninfo = (struct file_names_info *)d_info->wptr;
3847 memcpy(fninfo->FileName, d_info->name, d_info->name_len);
3848 fninfo->FileName[d_info->name_len] = 0x00;
3849 fninfo->FileNameLength = cpu_to_le32(d_info->name_len);
3850 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3853 case FILEID_FULL_DIRECTORY_INFORMATION:
3855 struct file_id_full_dir_info *dinfo;
3857 dinfo = (struct file_id_full_dir_info *)d_info->wptr;
3858 memcpy(dinfo->FileName, d_info->name, d_info->name_len);
3859 dinfo->FileName[d_info->name_len] = 0x00;
3860 dinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3861 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3864 case FILEID_BOTH_DIRECTORY_INFORMATION:
3866 struct file_id_both_directory_info *fibdinfo;
3868 fibdinfo = (struct file_id_both_directory_info *)d_info->wptr;
3869 memcpy(fibdinfo->FileName, d_info->name, d_info->name_len);
3870 fibdinfo->FileName[d_info->name_len] = 0x00;
3871 fibdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3872 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3875 case SMB_FIND_FILE_POSIX_INFO:
3877 struct smb2_posix_info *posix_info;
3879 posix_info = (struct smb2_posix_info *)d_info->wptr;
3880 memcpy(posix_info->name, d_info->name, d_info->name_len);
3881 posix_info->name[d_info->name_len] = 0x00;
3882 posix_info->name_len = cpu_to_le32(d_info->name_len);
3883 posix_info->NextEntryOffset =
3884 cpu_to_le32(next_entry_offset);
3887 } /* switch (info_level) */
3889 d_info->num_entry++;
3890 d_info->out_buf_len -= next_entry_offset;
3891 d_info->wptr += next_entry_offset;
3895 static bool __query_dir(struct dir_context *ctx, const char *name, int namlen,
3896 loff_t offset, u64 ino, unsigned int d_type)
3898 struct ksmbd_readdir_data *buf;
3899 struct smb2_query_dir_private *priv;
3900 struct ksmbd_dir_info *d_info;
3903 buf = container_of(ctx, struct ksmbd_readdir_data, ctx);
3904 priv = buf->private;
3905 d_info = priv->d_info;
3907 /* dot and dotdot entries are already reserved */
3908 if (!strcmp(".", name) || !strcmp("..", name))
3910 if (ksmbd_share_veto_filename(priv->work->tcon->share_conf, name))
3912 if (!match_pattern(name, namlen, priv->search_pattern))
3915 d_info->name = name;
3916 d_info->name_len = namlen;
3917 rc = reserve_populate_dentry(d_info, priv->info_level);
3920 if (d_info->flags & SMB2_RETURN_SINGLE_ENTRY)
3921 d_info->out_buf_len = 0;
3925 static int verify_info_level(int info_level)
3927 switch (info_level) {
3928 case FILE_FULL_DIRECTORY_INFORMATION:
3929 case FILE_BOTH_DIRECTORY_INFORMATION:
3930 case FILE_DIRECTORY_INFORMATION:
3931 case FILE_NAMES_INFORMATION:
3932 case FILEID_FULL_DIRECTORY_INFORMATION:
3933 case FILEID_BOTH_DIRECTORY_INFORMATION:
3934 case SMB_FIND_FILE_POSIX_INFO:
3943 static int smb2_resp_buf_len(struct ksmbd_work *work, unsigned short hdr2_len)
3947 free_len = (int)(work->response_sz -
3948 (get_rfc1002_len(work->response_buf) + 4)) - hdr2_len;
3952 static int smb2_calc_max_out_buf_len(struct ksmbd_work *work,
3953 unsigned short hdr2_len,
3954 unsigned int out_buf_len)
3958 if (out_buf_len > work->conn->vals->max_trans_size)
3961 free_len = smb2_resp_buf_len(work, hdr2_len);
3965 return min_t(int, out_buf_len, free_len);
3968 int smb2_query_dir(struct ksmbd_work *work)
3970 struct ksmbd_conn *conn = work->conn;
3971 struct smb2_query_directory_req *req;
3972 struct smb2_query_directory_rsp *rsp;
3973 struct ksmbd_share_config *share = work->tcon->share_conf;
3974 struct ksmbd_file *dir_fp = NULL;
3975 struct ksmbd_dir_info d_info;
3977 char *srch_ptr = NULL;
3978 unsigned char srch_flag;
3980 struct smb2_query_dir_private query_dir_private = {NULL, };
3982 WORK_BUFFERS(work, req, rsp);
3984 if (ksmbd_override_fsids(work)) {
3985 rsp->hdr.Status = STATUS_NO_MEMORY;
3986 smb2_set_err_rsp(work);
3990 rc = verify_info_level(req->FileInformationClass);
3996 dir_fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
4002 if (!(dir_fp->daccess & FILE_LIST_DIRECTORY_LE) ||
4003 inode_permission(file_mnt_idmap(dir_fp->filp),
4004 file_inode(dir_fp->filp),
4005 MAY_READ | MAY_EXEC)) {
4006 pr_err("no right to enumerate directory (%pD)\n", dir_fp->filp);
4011 if (!S_ISDIR(file_inode(dir_fp->filp)->i_mode)) {
4012 pr_err("can't do query dir for a file\n");
4017 srch_flag = req->Flags;
4018 srch_ptr = smb_strndup_from_utf16(req->Buffer,
4019 le16_to_cpu(req->FileNameLength), 1,
4021 if (IS_ERR(srch_ptr)) {
4022 ksmbd_debug(SMB, "Search Pattern not found\n");
4026 ksmbd_debug(SMB, "Search pattern is %s\n", srch_ptr);
4029 if (srch_flag & SMB2_REOPEN || srch_flag & SMB2_RESTART_SCANS) {
4030 ksmbd_debug(SMB, "Restart directory scan\n");
4031 generic_file_llseek(dir_fp->filp, 0, SEEK_SET);
4034 memset(&d_info, 0, sizeof(struct ksmbd_dir_info));
4035 d_info.wptr = (char *)rsp->Buffer;
4036 d_info.rptr = (char *)rsp->Buffer;
4037 d_info.out_buf_len =
4038 smb2_calc_max_out_buf_len(work, 8,
4039 le32_to_cpu(req->OutputBufferLength));
4040 if (d_info.out_buf_len < 0) {
4044 d_info.flags = srch_flag;
4047 * reserve dot and dotdot entries in head of buffer
4050 rc = ksmbd_populate_dot_dotdot_entries(work, req->FileInformationClass,
4051 dir_fp, &d_info, srch_ptr,
4052 smb2_populate_readdir_entry);
4058 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_HIDE_DOT_FILES))
4059 d_info.hide_dot_file = true;
4061 buffer_sz = d_info.out_buf_len;
4062 d_info.rptr = d_info.wptr;
4063 query_dir_private.work = work;
4064 query_dir_private.search_pattern = srch_ptr;
4065 query_dir_private.dir_fp = dir_fp;
4066 query_dir_private.d_info = &d_info;
4067 query_dir_private.info_level = req->FileInformationClass;
4068 dir_fp->readdir_data.private = &query_dir_private;
4069 set_ctx_actor(&dir_fp->readdir_data.ctx, __query_dir);
4071 rc = iterate_dir(dir_fp->filp, &dir_fp->readdir_data.ctx);
4073 * req->OutputBufferLength is too small to contain even one entry.
4074 * In this case, it immediately returns OutputBufferLength 0 to client.
4076 if (!d_info.out_buf_len && !d_info.num_entry)
4078 if (rc > 0 || rc == -ENOSPC)
4083 d_info.wptr = d_info.rptr;
4084 d_info.out_buf_len = buffer_sz;
4085 rc = process_query_dir_entries(&query_dir_private);
4089 if (!d_info.data_count && d_info.out_buf_len >= 0) {
4090 if (srch_flag & SMB2_RETURN_SINGLE_ENTRY && !is_asterisk(srch_ptr)) {
4091 rsp->hdr.Status = STATUS_NO_SUCH_FILE;
4093 dir_fp->dot_dotdot[0] = dir_fp->dot_dotdot[1] = 0;
4094 rsp->hdr.Status = STATUS_NO_MORE_FILES;
4096 rsp->StructureSize = cpu_to_le16(9);
4097 rsp->OutputBufferOffset = cpu_to_le16(0);
4098 rsp->OutputBufferLength = cpu_to_le32(0);
4100 rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
4101 sizeof(struct smb2_query_directory_rsp));
4106 ((struct file_directory_info *)
4107 ((char *)rsp->Buffer + d_info.last_entry_offset))
4108 ->NextEntryOffset = 0;
4109 if (d_info.data_count >= d_info.last_entry_off_align)
4110 d_info.data_count -= d_info.last_entry_off_align;
4112 rsp->StructureSize = cpu_to_le16(9);
4113 rsp->OutputBufferOffset = cpu_to_le16(72);
4114 rsp->OutputBufferLength = cpu_to_le32(d_info.data_count);
4115 rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
4116 offsetof(struct smb2_query_directory_rsp, Buffer) +
4123 ksmbd_fd_put(work, dir_fp);
4124 ksmbd_revert_fsids(work);
4128 pr_err("error while processing smb2 query dir rc = %d\n", rc);
4133 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
4134 else if (rc == -EACCES)
4135 rsp->hdr.Status = STATUS_ACCESS_DENIED;
4136 else if (rc == -ENOENT)
4137 rsp->hdr.Status = STATUS_NO_SUCH_FILE;
4138 else if (rc == -EBADF)
4139 rsp->hdr.Status = STATUS_FILE_CLOSED;
4140 else if (rc == -ENOMEM)
4141 rsp->hdr.Status = STATUS_NO_MEMORY;
4142 else if (rc == -EFAULT)
4143 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
4144 else if (rc == -EIO)
4145 rsp->hdr.Status = STATUS_FILE_CORRUPT_ERROR;
4146 if (!rsp->hdr.Status)
4147 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
4149 smb2_set_err_rsp(work);
4150 ksmbd_fd_put(work, dir_fp);
4151 ksmbd_revert_fsids(work);
4156 * buffer_check_err() - helper function to check buffer errors
4157 * @reqOutputBufferLength: max buffer length expected in command response
4158 * @rsp: query info response buffer contains output buffer length
4159 * @rsp_org: base response buffer pointer in case of chained response
4161 * Return: 0 on success, otherwise error
4163 static int buffer_check_err(int reqOutputBufferLength,
4164 struct smb2_query_info_rsp *rsp,
4167 if (reqOutputBufferLength < le32_to_cpu(rsp->OutputBufferLength)) {
4168 pr_err("Invalid Buffer Size Requested\n");
4169 rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
4170 *(__be32 *)rsp_org = cpu_to_be32(sizeof(struct smb2_hdr));
4176 static void get_standard_info_pipe(struct smb2_query_info_rsp *rsp,
4179 struct smb2_file_standard_info *sinfo;
4181 sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
4183 sinfo->AllocationSize = cpu_to_le64(4096);
4184 sinfo->EndOfFile = cpu_to_le64(0);
4185 sinfo->NumberOfLinks = cpu_to_le32(1);
4186 sinfo->DeletePending = 1;
4187 sinfo->Directory = 0;
4188 rsp->OutputBufferLength =
4189 cpu_to_le32(sizeof(struct smb2_file_standard_info));
4192 static void get_internal_info_pipe(struct smb2_query_info_rsp *rsp, u64 num,
4195 struct smb2_file_internal_info *file_info;
4197 file_info = (struct smb2_file_internal_info *)rsp->Buffer;
4199 /* any unique number */
4200 file_info->IndexNumber = cpu_to_le64(num | (1ULL << 63));
4201 rsp->OutputBufferLength =
4202 cpu_to_le32(sizeof(struct smb2_file_internal_info));
4205 static int smb2_get_info_file_pipe(struct ksmbd_session *sess,
4206 struct smb2_query_info_req *req,
4207 struct smb2_query_info_rsp *rsp,
4214 * Windows can sometime send query file info request on
4215 * pipe without opening it, checking error condition here
4217 id = req->VolatileFileId;
4218 if (!ksmbd_session_rpc_method(sess, id))
4221 ksmbd_debug(SMB, "FileInfoClass %u, FileId 0x%llx\n",
4222 req->FileInfoClass, req->VolatileFileId);
4224 switch (req->FileInfoClass) {
4225 case FILE_STANDARD_INFORMATION:
4226 get_standard_info_pipe(rsp, rsp_org);
4227 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4230 case FILE_INTERNAL_INFORMATION:
4231 get_internal_info_pipe(rsp, id, rsp_org);
4232 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4236 ksmbd_debug(SMB, "smb2_info_file_pipe for %u not supported\n",
4237 req->FileInfoClass);
4244 * smb2_get_ea() - handler for smb2 get extended attribute command
4245 * @work: smb work containing query info command buffer
4246 * @fp: ksmbd_file pointer
4247 * @req: get extended attribute request
4248 * @rsp: response buffer pointer
4249 * @rsp_org: base response buffer pointer in case of chained response
4251 * Return: 0 on success, otherwise error
4253 static int smb2_get_ea(struct ksmbd_work *work, struct ksmbd_file *fp,
4254 struct smb2_query_info_req *req,
4255 struct smb2_query_info_rsp *rsp, void *rsp_org)
4257 struct smb2_ea_info *eainfo, *prev_eainfo;
4258 char *name, *ptr, *xattr_list = NULL, *buf;
4259 int rc, name_len, value_len, xattr_list_len, idx;
4260 ssize_t buf_free_len, alignment_bytes, next_offset, rsp_data_cnt = 0;
4261 struct smb2_ea_info_req *ea_req = NULL;
4262 const struct path *path;
4263 struct mnt_idmap *idmap = file_mnt_idmap(fp->filp);
4265 if (!(fp->daccess & FILE_READ_EA_LE)) {
4266 pr_err("Not permitted to read ext attr : 0x%x\n",
4271 path = &fp->filp->f_path;
4272 /* single EA entry is requested with given user.* name */
4273 if (req->InputBufferLength) {
4274 if (le32_to_cpu(req->InputBufferLength) <
4275 sizeof(struct smb2_ea_info_req))
4278 ea_req = (struct smb2_ea_info_req *)req->Buffer;
4280 /* need to send all EAs, if no specific EA is requested*/
4281 if (le32_to_cpu(req->Flags) & SL_RETURN_SINGLE_ENTRY)
4283 "All EAs are requested but need to send single EA entry in rsp flags 0x%x\n",
4284 le32_to_cpu(req->Flags));
4288 smb2_calc_max_out_buf_len(work, 8,
4289 le32_to_cpu(req->OutputBufferLength));
4290 if (buf_free_len < 0)
4293 rc = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
4295 rsp->hdr.Status = STATUS_INVALID_HANDLE;
4297 } else if (!rc) { /* there is no EA in the file */
4298 ksmbd_debug(SMB, "no ea data in the file\n");
4301 xattr_list_len = rc;
4303 ptr = (char *)rsp->Buffer;
4304 eainfo = (struct smb2_ea_info *)ptr;
4305 prev_eainfo = eainfo;
4308 while (idx < xattr_list_len) {
4309 name = xattr_list + idx;
4310 name_len = strlen(name);
4312 ksmbd_debug(SMB, "%s, len %d\n", name, name_len);
4313 idx += name_len + 1;
4316 * CIFS does not support EA other than user.* namespace,
4317 * still keep the framework generic, to list other attrs
4320 if (strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4323 if (!strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
4327 if (req->InputBufferLength &&
4328 strncmp(&name[XATTR_USER_PREFIX_LEN], ea_req->name,
4329 ea_req->EaNameLength))
4332 if (!strncmp(&name[XATTR_USER_PREFIX_LEN],
4333 DOS_ATTRIBUTE_PREFIX, DOS_ATTRIBUTE_PREFIX_LEN))
4336 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4337 name_len -= XATTR_USER_PREFIX_LEN;
4339 ptr = eainfo->name + name_len + 1;
4340 buf_free_len -= (offsetof(struct smb2_ea_info, name) +
4342 /* bailout if xattr can't fit in buf_free_len */
4343 value_len = ksmbd_vfs_getxattr(idmap, path->dentry,
4345 if (value_len <= 0) {
4347 rsp->hdr.Status = STATUS_INVALID_HANDLE;
4351 buf_free_len -= value_len;
4352 if (buf_free_len < 0) {
4357 memcpy(ptr, buf, value_len);
4362 eainfo->EaNameLength = name_len;
4364 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4365 memcpy(eainfo->name, &name[XATTR_USER_PREFIX_LEN],
4368 memcpy(eainfo->name, name, name_len);
4370 eainfo->name[name_len] = '\0';
4371 eainfo->EaValueLength = cpu_to_le16(value_len);
4372 next_offset = offsetof(struct smb2_ea_info, name) +
4373 name_len + 1 + value_len;
4375 /* align next xattr entry at 4 byte bundary */
4376 alignment_bytes = ((next_offset + 3) & ~3) - next_offset;
4377 if (alignment_bytes) {
4378 memset(ptr, '\0', alignment_bytes);
4379 ptr += alignment_bytes;
4380 next_offset += alignment_bytes;
4381 buf_free_len -= alignment_bytes;
4383 eainfo->NextEntryOffset = cpu_to_le32(next_offset);
4384 prev_eainfo = eainfo;
4385 eainfo = (struct smb2_ea_info *)ptr;
4386 rsp_data_cnt += next_offset;
4388 if (req->InputBufferLength) {
4389 ksmbd_debug(SMB, "single entry requested\n");
4394 /* no more ea entries */
4395 prev_eainfo->NextEntryOffset = 0;
4398 if (rsp_data_cnt == 0)
4399 rsp->hdr.Status = STATUS_NO_EAS_ON_FILE;
4400 rsp->OutputBufferLength = cpu_to_le32(rsp_data_cnt);
4406 static void get_file_access_info(struct smb2_query_info_rsp *rsp,
4407 struct ksmbd_file *fp, void *rsp_org)
4409 struct smb2_file_access_info *file_info;
4411 file_info = (struct smb2_file_access_info *)rsp->Buffer;
4412 file_info->AccessFlags = fp->daccess;
4413 rsp->OutputBufferLength =
4414 cpu_to_le32(sizeof(struct smb2_file_access_info));
4417 static int get_file_basic_info(struct smb2_query_info_rsp *rsp,
4418 struct ksmbd_file *fp, void *rsp_org)
4420 struct smb2_file_basic_info *basic_info;
4424 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4425 pr_err("no right to read the attributes : 0x%x\n",
4430 basic_info = (struct smb2_file_basic_info *)rsp->Buffer;
4431 generic_fillattr(file_mnt_idmap(fp->filp), STATX_BASIC_STATS,
4432 file_inode(fp->filp), &stat);
4433 basic_info->CreationTime = cpu_to_le64(fp->create_time);
4434 time = ksmbd_UnixTimeToNT(stat.atime);
4435 basic_info->LastAccessTime = cpu_to_le64(time);
4436 time = ksmbd_UnixTimeToNT(stat.mtime);
4437 basic_info->LastWriteTime = cpu_to_le64(time);
4438 time = ksmbd_UnixTimeToNT(stat.ctime);
4439 basic_info->ChangeTime = cpu_to_le64(time);
4440 basic_info->Attributes = fp->f_ci->m_fattr;
4441 basic_info->Pad1 = 0;
4442 rsp->OutputBufferLength =
4443 cpu_to_le32(sizeof(struct smb2_file_basic_info));
4447 static void get_file_standard_info(struct smb2_query_info_rsp *rsp,
4448 struct ksmbd_file *fp, void *rsp_org)
4450 struct smb2_file_standard_info *sinfo;
4451 unsigned int delete_pending;
4452 struct inode *inode;
4455 inode = file_inode(fp->filp);
4456 generic_fillattr(file_mnt_idmap(fp->filp), STATX_BASIC_STATS, inode, &stat);
4458 sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
4459 delete_pending = ksmbd_inode_pending_delete(fp);
4461 sinfo->AllocationSize = cpu_to_le64(inode->i_blocks << 9);
4462 sinfo->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4463 sinfo->NumberOfLinks = cpu_to_le32(get_nlink(&stat) - delete_pending);
4464 sinfo->DeletePending = delete_pending;
4465 sinfo->Directory = S_ISDIR(stat.mode) ? 1 : 0;
4466 rsp->OutputBufferLength =
4467 cpu_to_le32(sizeof(struct smb2_file_standard_info));
4470 static void get_file_alignment_info(struct smb2_query_info_rsp *rsp,
4473 struct smb2_file_alignment_info *file_info;
4475 file_info = (struct smb2_file_alignment_info *)rsp->Buffer;
4476 file_info->AlignmentRequirement = 0;
4477 rsp->OutputBufferLength =
4478 cpu_to_le32(sizeof(struct smb2_file_alignment_info));
4481 static int get_file_all_info(struct ksmbd_work *work,
4482 struct smb2_query_info_rsp *rsp,
4483 struct ksmbd_file *fp,
4486 struct ksmbd_conn *conn = work->conn;
4487 struct smb2_file_all_info *file_info;
4488 unsigned int delete_pending;
4489 struct inode *inode;
4495 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4496 ksmbd_debug(SMB, "no right to read the attributes : 0x%x\n",
4501 filename = convert_to_nt_pathname(work->tcon->share_conf, &fp->filp->f_path);
4502 if (IS_ERR(filename))
4503 return PTR_ERR(filename);
4505 inode = file_inode(fp->filp);
4506 generic_fillattr(file_mnt_idmap(fp->filp), STATX_BASIC_STATS, inode, &stat);
4508 ksmbd_debug(SMB, "filename = %s\n", filename);
4509 delete_pending = ksmbd_inode_pending_delete(fp);
4510 file_info = (struct smb2_file_all_info *)rsp->Buffer;
4512 file_info->CreationTime = cpu_to_le64(fp->create_time);
4513 time = ksmbd_UnixTimeToNT(stat.atime);
4514 file_info->LastAccessTime = cpu_to_le64(time);
4515 time = ksmbd_UnixTimeToNT(stat.mtime);
4516 file_info->LastWriteTime = cpu_to_le64(time);
4517 time = ksmbd_UnixTimeToNT(stat.ctime);
4518 file_info->ChangeTime = cpu_to_le64(time);
4519 file_info->Attributes = fp->f_ci->m_fattr;
4520 file_info->Pad1 = 0;
4521 file_info->AllocationSize =
4522 cpu_to_le64(inode->i_blocks << 9);
4523 file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4524 file_info->NumberOfLinks =
4525 cpu_to_le32(get_nlink(&stat) - delete_pending);
4526 file_info->DeletePending = delete_pending;
4527 file_info->Directory = S_ISDIR(stat.mode) ? 1 : 0;
4528 file_info->Pad2 = 0;
4529 file_info->IndexNumber = cpu_to_le64(stat.ino);
4530 file_info->EASize = 0;
4531 file_info->AccessFlags = fp->daccess;
4532 file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
4533 file_info->Mode = fp->coption;
4534 file_info->AlignmentRequirement = 0;
4535 conv_len = smbConvertToUTF16((__le16 *)file_info->FileName, filename,
4536 PATH_MAX, conn->local_nls, 0);
4538 file_info->FileNameLength = cpu_to_le32(conv_len);
4539 rsp->OutputBufferLength =
4540 cpu_to_le32(sizeof(struct smb2_file_all_info) + conv_len - 1);
4545 static void get_file_alternate_info(struct ksmbd_work *work,
4546 struct smb2_query_info_rsp *rsp,
4547 struct ksmbd_file *fp,
4550 struct ksmbd_conn *conn = work->conn;
4551 struct smb2_file_alt_name_info *file_info;
4552 struct dentry *dentry = fp->filp->f_path.dentry;
4555 spin_lock(&dentry->d_lock);
4556 file_info = (struct smb2_file_alt_name_info *)rsp->Buffer;
4557 conv_len = ksmbd_extract_shortname(conn,
4558 dentry->d_name.name,
4559 file_info->FileName);
4560 spin_unlock(&dentry->d_lock);
4561 file_info->FileNameLength = cpu_to_le32(conv_len);
4562 rsp->OutputBufferLength =
4563 cpu_to_le32(sizeof(struct smb2_file_alt_name_info) + conv_len);
4566 static void get_file_stream_info(struct ksmbd_work *work,
4567 struct smb2_query_info_rsp *rsp,
4568 struct ksmbd_file *fp,
4571 struct ksmbd_conn *conn = work->conn;
4572 struct smb2_file_stream_info *file_info;
4573 char *stream_name, *xattr_list = NULL, *stream_buf;
4575 const struct path *path = &fp->filp->f_path;
4576 ssize_t xattr_list_len;
4577 int nbytes = 0, streamlen, stream_name_len, next, idx = 0;
4579 struct smb2_query_info_req *req = ksmbd_req_buf_next(work);
4581 generic_fillattr(file_mnt_idmap(fp->filp), STATX_BASIC_STATS,
4582 file_inode(fp->filp), &stat);
4583 file_info = (struct smb2_file_stream_info *)rsp->Buffer;
4586 smb2_calc_max_out_buf_len(work, 8,
4587 le32_to_cpu(req->OutputBufferLength));
4588 if (buf_free_len < 0)
4591 xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
4592 if (xattr_list_len < 0) {
4594 } else if (!xattr_list_len) {
4595 ksmbd_debug(SMB, "empty xattr in the file\n");
4599 while (idx < xattr_list_len) {
4600 stream_name = xattr_list + idx;
4601 streamlen = strlen(stream_name);
4602 idx += streamlen + 1;
4604 ksmbd_debug(SMB, "%s, len %d\n", stream_name, streamlen);
4606 if (strncmp(&stream_name[XATTR_USER_PREFIX_LEN],
4607 STREAM_PREFIX, STREAM_PREFIX_LEN))
4610 stream_name_len = streamlen - (XATTR_USER_PREFIX_LEN +
4612 streamlen = stream_name_len;
4616 stream_buf = kmalloc(streamlen + 1, GFP_KERNEL);
4620 streamlen = snprintf(stream_buf, streamlen + 1,
4621 ":%s", &stream_name[XATTR_NAME_STREAM_LEN]);
4623 next = sizeof(struct smb2_file_stream_info) + streamlen * 2;
4624 if (next > buf_free_len) {
4629 file_info = (struct smb2_file_stream_info *)&rsp->Buffer[nbytes];
4630 streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
4631 stream_buf, streamlen,
4632 conn->local_nls, 0);
4635 file_info->StreamNameLength = cpu_to_le32(streamlen);
4636 file_info->StreamSize = cpu_to_le64(stream_name_len);
4637 file_info->StreamAllocationSize = cpu_to_le64(stream_name_len);
4640 buf_free_len -= next;
4641 file_info->NextEntryOffset = cpu_to_le32(next);
4645 if (!S_ISDIR(stat.mode) &&
4646 buf_free_len >= sizeof(struct smb2_file_stream_info) + 7 * 2) {
4647 file_info = (struct smb2_file_stream_info *)
4648 &rsp->Buffer[nbytes];
4649 streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
4650 "::$DATA", 7, conn->local_nls, 0);
4652 file_info->StreamNameLength = cpu_to_le32(streamlen);
4653 file_info->StreamSize = cpu_to_le64(stat.size);
4654 file_info->StreamAllocationSize = cpu_to_le64(stat.blocks << 9);
4655 nbytes += sizeof(struct smb2_file_stream_info) + streamlen;
4658 /* last entry offset should be 0 */
4659 file_info->NextEntryOffset = 0;
4662 rsp->OutputBufferLength = cpu_to_le32(nbytes);
4665 static void get_file_internal_info(struct smb2_query_info_rsp *rsp,
4666 struct ksmbd_file *fp, void *rsp_org)
4668 struct smb2_file_internal_info *file_info;
4671 generic_fillattr(file_mnt_idmap(fp->filp), STATX_BASIC_STATS,
4672 file_inode(fp->filp), &stat);
4673 file_info = (struct smb2_file_internal_info *)rsp->Buffer;
4674 file_info->IndexNumber = cpu_to_le64(stat.ino);
4675 rsp->OutputBufferLength =
4676 cpu_to_le32(sizeof(struct smb2_file_internal_info));
4679 static int get_file_network_open_info(struct smb2_query_info_rsp *rsp,
4680 struct ksmbd_file *fp, void *rsp_org)
4682 struct smb2_file_ntwrk_info *file_info;
4683 struct inode *inode;
4687 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4688 pr_err("no right to read the attributes : 0x%x\n",
4693 file_info = (struct smb2_file_ntwrk_info *)rsp->Buffer;
4695 inode = file_inode(fp->filp);
4696 generic_fillattr(file_mnt_idmap(fp->filp), STATX_BASIC_STATS, inode, &stat);
4698 file_info->CreationTime = cpu_to_le64(fp->create_time);
4699 time = ksmbd_UnixTimeToNT(stat.atime);
4700 file_info->LastAccessTime = cpu_to_le64(time);
4701 time = ksmbd_UnixTimeToNT(stat.mtime);
4702 file_info->LastWriteTime = cpu_to_le64(time);
4703 time = ksmbd_UnixTimeToNT(stat.ctime);
4704 file_info->ChangeTime = cpu_to_le64(time);
4705 file_info->Attributes = fp->f_ci->m_fattr;
4706 file_info->AllocationSize =
4707 cpu_to_le64(inode->i_blocks << 9);
4708 file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4709 file_info->Reserved = cpu_to_le32(0);
4710 rsp->OutputBufferLength =
4711 cpu_to_le32(sizeof(struct smb2_file_ntwrk_info));
4715 static void get_file_ea_info(struct smb2_query_info_rsp *rsp, void *rsp_org)
4717 struct smb2_file_ea_info *file_info;
4719 file_info = (struct smb2_file_ea_info *)rsp->Buffer;
4720 file_info->EASize = 0;
4721 rsp->OutputBufferLength =
4722 cpu_to_le32(sizeof(struct smb2_file_ea_info));
4725 static void get_file_position_info(struct smb2_query_info_rsp *rsp,
4726 struct ksmbd_file *fp, void *rsp_org)
4728 struct smb2_file_pos_info *file_info;
4730 file_info = (struct smb2_file_pos_info *)rsp->Buffer;
4731 file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
4732 rsp->OutputBufferLength =
4733 cpu_to_le32(sizeof(struct smb2_file_pos_info));
4736 static void get_file_mode_info(struct smb2_query_info_rsp *rsp,
4737 struct ksmbd_file *fp, void *rsp_org)
4739 struct smb2_file_mode_info *file_info;
4741 file_info = (struct smb2_file_mode_info *)rsp->Buffer;
4742 file_info->Mode = fp->coption & FILE_MODE_INFO_MASK;
4743 rsp->OutputBufferLength =
4744 cpu_to_le32(sizeof(struct smb2_file_mode_info));
4747 static void get_file_compression_info(struct smb2_query_info_rsp *rsp,
4748 struct ksmbd_file *fp, void *rsp_org)
4750 struct smb2_file_comp_info *file_info;
4753 generic_fillattr(file_mnt_idmap(fp->filp), STATX_BASIC_STATS,
4754 file_inode(fp->filp), &stat);
4756 file_info = (struct smb2_file_comp_info *)rsp->Buffer;
4757 file_info->CompressedFileSize = cpu_to_le64(stat.blocks << 9);
4758 file_info->CompressionFormat = COMPRESSION_FORMAT_NONE;
4759 file_info->CompressionUnitShift = 0;
4760 file_info->ChunkShift = 0;
4761 file_info->ClusterShift = 0;
4762 memset(&file_info->Reserved[0], 0, 3);
4764 rsp->OutputBufferLength =
4765 cpu_to_le32(sizeof(struct smb2_file_comp_info));
4768 static int get_file_attribute_tag_info(struct smb2_query_info_rsp *rsp,
4769 struct ksmbd_file *fp, void *rsp_org)
4771 struct smb2_file_attr_tag_info *file_info;
4773 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4774 pr_err("no right to read the attributes : 0x%x\n",
4779 file_info = (struct smb2_file_attr_tag_info *)rsp->Buffer;
4780 file_info->FileAttributes = fp->f_ci->m_fattr;
4781 file_info->ReparseTag = 0;
4782 rsp->OutputBufferLength =
4783 cpu_to_le32(sizeof(struct smb2_file_attr_tag_info));
4787 static void find_file_posix_info(struct smb2_query_info_rsp *rsp,
4788 struct ksmbd_file *fp, void *rsp_org)
4790 struct smb311_posix_qinfo *file_info;
4791 struct inode *inode = file_inode(fp->filp);
4792 struct mnt_idmap *idmap = file_mnt_idmap(fp->filp);
4793 vfsuid_t vfsuid = i_uid_into_vfsuid(idmap, inode);
4794 vfsgid_t vfsgid = i_gid_into_vfsgid(idmap, inode);
4796 int out_buf_len = sizeof(struct smb311_posix_qinfo) + 32;
4798 file_info = (struct smb311_posix_qinfo *)rsp->Buffer;
4799 file_info->CreationTime = cpu_to_le64(fp->create_time);
4800 time = ksmbd_UnixTimeToNT(inode->i_atime);
4801 file_info->LastAccessTime = cpu_to_le64(time);
4802 time = ksmbd_UnixTimeToNT(inode->i_mtime);
4803 file_info->LastWriteTime = cpu_to_le64(time);
4804 time = ksmbd_UnixTimeToNT(inode_get_ctime(inode));
4805 file_info->ChangeTime = cpu_to_le64(time);
4806 file_info->DosAttributes = fp->f_ci->m_fattr;
4807 file_info->Inode = cpu_to_le64(inode->i_ino);
4808 file_info->EndOfFile = cpu_to_le64(inode->i_size);
4809 file_info->AllocationSize = cpu_to_le64(inode->i_blocks << 9);
4810 file_info->HardLinks = cpu_to_le32(inode->i_nlink);
4811 file_info->Mode = cpu_to_le32(inode->i_mode & 0777);
4812 file_info->DeviceId = cpu_to_le32(inode->i_rdev);
4815 * Sids(32) contain two sids(Domain sid(16), UNIX group sid(16)).
4816 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) +
4817 * sub_auth(4 * 1(num_subauth)) + RID(4).
4819 id_to_sid(from_kuid_munged(&init_user_ns, vfsuid_into_kuid(vfsuid)),
4820 SIDUNIX_USER, (struct smb_sid *)&file_info->Sids[0]);
4821 id_to_sid(from_kgid_munged(&init_user_ns, vfsgid_into_kgid(vfsgid)),
4822 SIDUNIX_GROUP, (struct smb_sid *)&file_info->Sids[16]);
4824 rsp->OutputBufferLength = cpu_to_le32(out_buf_len);
4827 static int smb2_get_info_file(struct ksmbd_work *work,
4828 struct smb2_query_info_req *req,
4829 struct smb2_query_info_rsp *rsp)
4831 struct ksmbd_file *fp;
4832 int fileinfoclass = 0;
4834 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
4836 if (test_share_config_flag(work->tcon->share_conf,
4837 KSMBD_SHARE_FLAG_PIPE)) {
4838 /* smb2 info file called for pipe */
4839 return smb2_get_info_file_pipe(work->sess, req, rsp,
4840 work->response_buf);
4843 if (work->next_smb2_rcv_hdr_off) {
4844 if (!has_file_id(req->VolatileFileId)) {
4845 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
4846 work->compound_fid);
4847 id = work->compound_fid;
4848 pid = work->compound_pfid;
4852 if (!has_file_id(id)) {
4853 id = req->VolatileFileId;
4854 pid = req->PersistentFileId;
4857 fp = ksmbd_lookup_fd_slow(work, id, pid);
4861 fileinfoclass = req->FileInfoClass;
4863 switch (fileinfoclass) {
4864 case FILE_ACCESS_INFORMATION:
4865 get_file_access_info(rsp, fp, work->response_buf);
4868 case FILE_BASIC_INFORMATION:
4869 rc = get_file_basic_info(rsp, fp, work->response_buf);
4872 case FILE_STANDARD_INFORMATION:
4873 get_file_standard_info(rsp, fp, work->response_buf);
4876 case FILE_ALIGNMENT_INFORMATION:
4877 get_file_alignment_info(rsp, work->response_buf);
4880 case FILE_ALL_INFORMATION:
4881 rc = get_file_all_info(work, rsp, fp, work->response_buf);
4884 case FILE_ALTERNATE_NAME_INFORMATION:
4885 get_file_alternate_info(work, rsp, fp, work->response_buf);
4888 case FILE_STREAM_INFORMATION:
4889 get_file_stream_info(work, rsp, fp, work->response_buf);
4892 case FILE_INTERNAL_INFORMATION:
4893 get_file_internal_info(rsp, fp, work->response_buf);
4896 case FILE_NETWORK_OPEN_INFORMATION:
4897 rc = get_file_network_open_info(rsp, fp, work->response_buf);
4900 case FILE_EA_INFORMATION:
4901 get_file_ea_info(rsp, work->response_buf);
4904 case FILE_FULL_EA_INFORMATION:
4905 rc = smb2_get_ea(work, fp, req, rsp, work->response_buf);
4908 case FILE_POSITION_INFORMATION:
4909 get_file_position_info(rsp, fp, work->response_buf);
4912 case FILE_MODE_INFORMATION:
4913 get_file_mode_info(rsp, fp, work->response_buf);
4916 case FILE_COMPRESSION_INFORMATION:
4917 get_file_compression_info(rsp, fp, work->response_buf);
4920 case FILE_ATTRIBUTE_TAG_INFORMATION:
4921 rc = get_file_attribute_tag_info(rsp, fp, work->response_buf);
4923 case SMB_FIND_FILE_POSIX_INFO:
4924 if (!work->tcon->posix_extensions) {
4925 pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
4928 find_file_posix_info(rsp, fp, work->response_buf);
4932 ksmbd_debug(SMB, "fileinfoclass %d not supported yet\n",
4937 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4938 rsp, work->response_buf);
4939 ksmbd_fd_put(work, fp);
4943 static int smb2_get_info_filesystem(struct ksmbd_work *work,
4944 struct smb2_query_info_req *req,
4945 struct smb2_query_info_rsp *rsp)
4947 struct ksmbd_session *sess = work->sess;
4948 struct ksmbd_conn *conn = work->conn;
4949 struct ksmbd_share_config *share = work->tcon->share_conf;
4950 int fsinfoclass = 0;
4951 struct kstatfs stfs;
4958 rc = kern_path(share->path, LOOKUP_NO_SYMLINKS, &path);
4960 pr_err("cannot create vfs path\n");
4964 rc = vfs_statfs(&path, &stfs);
4966 pr_err("cannot do stat of path %s\n", share->path);
4971 fsinfoclass = req->FileInfoClass;
4973 switch (fsinfoclass) {
4974 case FS_DEVICE_INFORMATION:
4976 struct filesystem_device_info *info;
4978 info = (struct filesystem_device_info *)rsp->Buffer;
4980 info->DeviceType = cpu_to_le32(stfs.f_type);
4981 info->DeviceCharacteristics = cpu_to_le32(0x00000020);
4982 rsp->OutputBufferLength = cpu_to_le32(8);
4985 case FS_ATTRIBUTE_INFORMATION:
4987 struct filesystem_attribute_info *info;
4990 info = (struct filesystem_attribute_info *)rsp->Buffer;
4991 info->Attributes = cpu_to_le32(FILE_SUPPORTS_OBJECT_IDS |
4992 FILE_PERSISTENT_ACLS |
4993 FILE_UNICODE_ON_DISK |
4994 FILE_CASE_PRESERVED_NAMES |
4995 FILE_CASE_SENSITIVE_SEARCH |
4996 FILE_SUPPORTS_BLOCK_REFCOUNTING);
4998 info->Attributes |= cpu_to_le32(server_conf.share_fake_fscaps);
5000 if (test_share_config_flag(work->tcon->share_conf,
5001 KSMBD_SHARE_FLAG_STREAMS))
5002 info->Attributes |= cpu_to_le32(FILE_NAMED_STREAMS);
5004 info->MaxPathNameComponentLength = cpu_to_le32(stfs.f_namelen);
5005 len = smbConvertToUTF16((__le16 *)info->FileSystemName,
5006 "NTFS", PATH_MAX, conn->local_nls, 0);
5008 info->FileSystemNameLen = cpu_to_le32(len);
5009 sz = sizeof(struct filesystem_attribute_info) - 2 + len;
5010 rsp->OutputBufferLength = cpu_to_le32(sz);
5013 case FS_VOLUME_INFORMATION:
5015 struct filesystem_vol_info *info;
5017 unsigned int serial_crc = 0;
5019 info = (struct filesystem_vol_info *)(rsp->Buffer);
5020 info->VolumeCreationTime = 0;
5021 serial_crc = crc32_le(serial_crc, share->name,
5022 strlen(share->name));
5023 serial_crc = crc32_le(serial_crc, share->path,
5024 strlen(share->path));
5025 serial_crc = crc32_le(serial_crc, ksmbd_netbios_name(),
5026 strlen(ksmbd_netbios_name()));
5027 /* Taking dummy value of serial number*/
5028 info->SerialNumber = cpu_to_le32(serial_crc);
5029 len = smbConvertToUTF16((__le16 *)info->VolumeLabel,
5030 share->name, PATH_MAX,
5031 conn->local_nls, 0);
5033 info->VolumeLabelSize = cpu_to_le32(len);
5035 sz = sizeof(struct filesystem_vol_info) - 2 + len;
5036 rsp->OutputBufferLength = cpu_to_le32(sz);
5039 case FS_SIZE_INFORMATION:
5041 struct filesystem_info *info;
5043 info = (struct filesystem_info *)(rsp->Buffer);
5044 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
5045 info->FreeAllocationUnits = cpu_to_le64(stfs.f_bfree);
5046 info->SectorsPerAllocationUnit = cpu_to_le32(1);
5047 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
5048 rsp->OutputBufferLength = cpu_to_le32(24);
5051 case FS_FULL_SIZE_INFORMATION:
5053 struct smb2_fs_full_size_info *info;
5055 info = (struct smb2_fs_full_size_info *)(rsp->Buffer);
5056 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
5057 info->CallerAvailableAllocationUnits =
5058 cpu_to_le64(stfs.f_bavail);
5059 info->ActualAvailableAllocationUnits =
5060 cpu_to_le64(stfs.f_bfree);
5061 info->SectorsPerAllocationUnit = cpu_to_le32(1);
5062 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
5063 rsp->OutputBufferLength = cpu_to_le32(32);
5066 case FS_OBJECT_ID_INFORMATION:
5068 struct object_id_info *info;
5070 info = (struct object_id_info *)(rsp->Buffer);
5072 if (!user_guest(sess->user))
5073 memcpy(info->objid, user_passkey(sess->user), 16);
5075 memset(info->objid, 0, 16);
5077 info->extended_info.magic = cpu_to_le32(EXTENDED_INFO_MAGIC);
5078 info->extended_info.version = cpu_to_le32(1);
5079 info->extended_info.release = cpu_to_le32(1);
5080 info->extended_info.rel_date = 0;
5081 memcpy(info->extended_info.version_string, "1.1.0", strlen("1.1.0"));
5082 rsp->OutputBufferLength = cpu_to_le32(64);
5085 case FS_SECTOR_SIZE_INFORMATION:
5087 struct smb3_fs_ss_info *info;
5088 unsigned int sector_size =
5089 min_t(unsigned int, path.mnt->mnt_sb->s_blocksize, 4096);
5091 info = (struct smb3_fs_ss_info *)(rsp->Buffer);
5093 info->LogicalBytesPerSector = cpu_to_le32(sector_size);
5094 info->PhysicalBytesPerSectorForAtomicity =
5095 cpu_to_le32(sector_size);
5096 info->PhysicalBytesPerSectorForPerf = cpu_to_le32(sector_size);
5097 info->FSEffPhysicalBytesPerSectorForAtomicity =
5098 cpu_to_le32(sector_size);
5099 info->Flags = cpu_to_le32(SSINFO_FLAGS_ALIGNED_DEVICE |
5100 SSINFO_FLAGS_PARTITION_ALIGNED_ON_DEVICE);
5101 info->ByteOffsetForSectorAlignment = 0;
5102 info->ByteOffsetForPartitionAlignment = 0;
5103 rsp->OutputBufferLength = cpu_to_le32(28);
5106 case FS_CONTROL_INFORMATION:
5109 * TODO : The current implementation is based on
5110 * test result with win7(NTFS) server. It's need to
5111 * modify this to get valid Quota values
5114 struct smb2_fs_control_info *info;
5116 info = (struct smb2_fs_control_info *)(rsp->Buffer);
5117 info->FreeSpaceStartFiltering = 0;
5118 info->FreeSpaceThreshold = 0;
5119 info->FreeSpaceStopFiltering = 0;
5120 info->DefaultQuotaThreshold = cpu_to_le64(SMB2_NO_FID);
5121 info->DefaultQuotaLimit = cpu_to_le64(SMB2_NO_FID);
5123 rsp->OutputBufferLength = cpu_to_le32(48);
5126 case FS_POSIX_INFORMATION:
5128 struct filesystem_posix_info *info;
5130 if (!work->tcon->posix_extensions) {
5131 pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
5134 info = (struct filesystem_posix_info *)(rsp->Buffer);
5135 info->OptimalTransferSize = cpu_to_le32(stfs.f_bsize);
5136 info->BlockSize = cpu_to_le32(stfs.f_bsize);
5137 info->TotalBlocks = cpu_to_le64(stfs.f_blocks);
5138 info->BlocksAvail = cpu_to_le64(stfs.f_bfree);
5139 info->UserBlocksAvail = cpu_to_le64(stfs.f_bavail);
5140 info->TotalFileNodes = cpu_to_le64(stfs.f_files);
5141 info->FreeFileNodes = cpu_to_le64(stfs.f_ffree);
5142 rsp->OutputBufferLength = cpu_to_le32(56);
5150 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
5151 rsp, work->response_buf);
5156 static int smb2_get_info_sec(struct ksmbd_work *work,
5157 struct smb2_query_info_req *req,
5158 struct smb2_query_info_rsp *rsp)
5160 struct ksmbd_file *fp;
5161 struct mnt_idmap *idmap;
5162 struct smb_ntsd *pntsd = (struct smb_ntsd *)rsp->Buffer, *ppntsd = NULL;
5163 struct smb_fattr fattr = {{0}};
5164 struct inode *inode;
5165 __u32 secdesclen = 0;
5166 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
5167 int addition_info = le32_to_cpu(req->AdditionalInformation);
5168 int rc = 0, ppntsd_size = 0;
5170 if (addition_info & ~(OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO |
5171 PROTECTED_DACL_SECINFO |
5172 UNPROTECTED_DACL_SECINFO)) {
5173 ksmbd_debug(SMB, "Unsupported addition info: 0x%x)\n",
5176 pntsd->revision = cpu_to_le16(1);
5177 pntsd->type = cpu_to_le16(SELF_RELATIVE | DACL_PROTECTED);
5178 pntsd->osidoffset = 0;
5179 pntsd->gsidoffset = 0;
5180 pntsd->sacloffset = 0;
5181 pntsd->dacloffset = 0;
5183 secdesclen = sizeof(struct smb_ntsd);
5184 rsp->OutputBufferLength = cpu_to_le32(secdesclen);
5189 if (work->next_smb2_rcv_hdr_off) {
5190 if (!has_file_id(req->VolatileFileId)) {
5191 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
5192 work->compound_fid);
5193 id = work->compound_fid;
5194 pid = work->compound_pfid;
5198 if (!has_file_id(id)) {
5199 id = req->VolatileFileId;
5200 pid = req->PersistentFileId;
5203 fp = ksmbd_lookup_fd_slow(work, id, pid);
5207 idmap = file_mnt_idmap(fp->filp);
5208 inode = file_inode(fp->filp);
5209 ksmbd_acls_fattr(&fattr, idmap, inode);
5211 if (test_share_config_flag(work->tcon->share_conf,
5212 KSMBD_SHARE_FLAG_ACL_XATTR))
5213 ppntsd_size = ksmbd_vfs_get_sd_xattr(work->conn, idmap,
5214 fp->filp->f_path.dentry,
5217 /* Check if sd buffer size exceeds response buffer size */
5218 if (smb2_resp_buf_len(work, 8) > ppntsd_size)
5219 rc = build_sec_desc(idmap, pntsd, ppntsd, ppntsd_size,
5220 addition_info, &secdesclen, &fattr);
5221 posix_acl_release(fattr.cf_acls);
5222 posix_acl_release(fattr.cf_dacls);
5224 ksmbd_fd_put(work, fp);
5228 rsp->OutputBufferLength = cpu_to_le32(secdesclen);
5233 * smb2_query_info() - handler for smb2 query info command
5234 * @work: smb work containing query info request buffer
5236 * Return: 0 on success, otherwise error
5238 int smb2_query_info(struct ksmbd_work *work)
5240 struct smb2_query_info_req *req;
5241 struct smb2_query_info_rsp *rsp;
5244 WORK_BUFFERS(work, req, rsp);
5246 ksmbd_debug(SMB, "GOT query info request\n");
5248 switch (req->InfoType) {
5249 case SMB2_O_INFO_FILE:
5250 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
5251 rc = smb2_get_info_file(work, req, rsp);
5253 case SMB2_O_INFO_FILESYSTEM:
5254 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILESYSTEM\n");
5255 rc = smb2_get_info_filesystem(work, req, rsp);
5257 case SMB2_O_INFO_SECURITY:
5258 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
5259 rc = smb2_get_info_sec(work, req, rsp);
5262 ksmbd_debug(SMB, "InfoType %d not supported yet\n",
5268 rsp->StructureSize = cpu_to_le16(9);
5269 rsp->OutputBufferOffset = cpu_to_le16(72);
5270 rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
5271 offsetof(struct smb2_query_info_rsp, Buffer) +
5272 le32_to_cpu(rsp->OutputBufferLength));
5277 rsp->hdr.Status = STATUS_ACCESS_DENIED;
5278 else if (rc == -ENOENT)
5279 rsp->hdr.Status = STATUS_FILE_CLOSED;
5280 else if (rc == -EIO)
5281 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
5282 else if (rc == -ENOMEM)
5283 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
5284 else if (rc == -EOPNOTSUPP || rsp->hdr.Status == 0)
5285 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
5286 smb2_set_err_rsp(work);
5288 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n",
5296 * smb2_close_pipe() - handler for closing IPC pipe
5297 * @work: smb work containing close request buffer
5301 static noinline int smb2_close_pipe(struct ksmbd_work *work)
5304 struct smb2_close_req *req;
5305 struct smb2_close_rsp *rsp;
5307 WORK_BUFFERS(work, req, rsp);
5309 id = req->VolatileFileId;
5310 ksmbd_session_rpc_close(work->sess, id);
5312 rsp->StructureSize = cpu_to_le16(60);
5315 rsp->CreationTime = 0;
5316 rsp->LastAccessTime = 0;
5317 rsp->LastWriteTime = 0;
5318 rsp->ChangeTime = 0;
5319 rsp->AllocationSize = 0;
5321 rsp->Attributes = 0;
5323 return ksmbd_iov_pin_rsp(work, (void *)rsp,
5324 sizeof(struct smb2_close_rsp));
5328 * smb2_close() - handler for smb2 close file command
5329 * @work: smb work containing close request buffer
5333 int smb2_close(struct ksmbd_work *work)
5335 u64 volatile_id = KSMBD_NO_FID;
5337 struct smb2_close_req *req;
5338 struct smb2_close_rsp *rsp;
5339 struct ksmbd_conn *conn = work->conn;
5340 struct ksmbd_file *fp;
5341 struct inode *inode;
5345 WORK_BUFFERS(work, req, rsp);
5347 if (test_share_config_flag(work->tcon->share_conf,
5348 KSMBD_SHARE_FLAG_PIPE)) {
5349 ksmbd_debug(SMB, "IPC pipe close request\n");
5350 return smb2_close_pipe(work);
5353 sess_id = le64_to_cpu(req->hdr.SessionId);
5354 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5355 sess_id = work->compound_sid;
5357 work->compound_sid = 0;
5358 if (check_session_id(conn, sess_id)) {
5359 work->compound_sid = sess_id;
5361 rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
5362 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5363 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
5368 if (work->next_smb2_rcv_hdr_off &&
5369 !has_file_id(req->VolatileFileId)) {
5370 if (!has_file_id(work->compound_fid)) {
5371 /* file already closed, return FILE_CLOSED */
5372 ksmbd_debug(SMB, "file already closed\n");
5373 rsp->hdr.Status = STATUS_FILE_CLOSED;
5378 "Compound request set FID = %llu:%llu\n",
5380 work->compound_pfid);
5381 volatile_id = work->compound_fid;
5383 /* file closed, stored id is not valid anymore */
5384 work->compound_fid = KSMBD_NO_FID;
5385 work->compound_pfid = KSMBD_NO_FID;
5388 volatile_id = req->VolatileFileId;
5390 ksmbd_debug(SMB, "volatile_id = %llu\n", volatile_id);
5392 rsp->StructureSize = cpu_to_le16(60);
5395 if (req->Flags == SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB) {
5396 fp = ksmbd_lookup_fd_fast(work, volatile_id);
5402 inode = file_inode(fp->filp);
5403 rsp->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB;
5404 rsp->AllocationSize = S_ISDIR(inode->i_mode) ? 0 :
5405 cpu_to_le64(inode->i_blocks << 9);
5406 rsp->EndOfFile = cpu_to_le64(inode->i_size);
5407 rsp->Attributes = fp->f_ci->m_fattr;
5408 rsp->CreationTime = cpu_to_le64(fp->create_time);
5409 time = ksmbd_UnixTimeToNT(inode->i_atime);
5410 rsp->LastAccessTime = cpu_to_le64(time);
5411 time = ksmbd_UnixTimeToNT(inode->i_mtime);
5412 rsp->LastWriteTime = cpu_to_le64(time);
5413 time = ksmbd_UnixTimeToNT(inode_get_ctime(inode));
5414 rsp->ChangeTime = cpu_to_le64(time);
5415 ksmbd_fd_put(work, fp);
5418 rsp->AllocationSize = 0;
5420 rsp->Attributes = 0;
5421 rsp->CreationTime = 0;
5422 rsp->LastAccessTime = 0;
5423 rsp->LastWriteTime = 0;
5424 rsp->ChangeTime = 0;
5427 err = ksmbd_close_fd(work, volatile_id);
5430 err = ksmbd_iov_pin_rsp(work, (void *)rsp,
5431 sizeof(struct smb2_close_rsp));
5434 if (rsp->hdr.Status == 0)
5435 rsp->hdr.Status = STATUS_FILE_CLOSED;
5436 smb2_set_err_rsp(work);
5443 * smb2_echo() - handler for smb2 echo(ping) command
5444 * @work: smb work containing echo request buffer
5448 int smb2_echo(struct ksmbd_work *work)
5450 struct smb2_echo_rsp *rsp = smb2_get_msg(work->response_buf);
5452 if (work->next_smb2_rcv_hdr_off)
5453 rsp = ksmbd_resp_buf_next(work);
5455 rsp->StructureSize = cpu_to_le16(4);
5457 return ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_echo_rsp));
5460 static int smb2_rename(struct ksmbd_work *work,
5461 struct ksmbd_file *fp,
5462 struct smb2_file_rename_info *file_info,
5463 struct nls_table *local_nls)
5465 struct ksmbd_share_config *share = fp->tcon->share_conf;
5466 char *new_name = NULL;
5469 ksmbd_debug(SMB, "setting FILE_RENAME_INFO\n");
5470 new_name = smb2_get_name(file_info->FileName,
5471 le32_to_cpu(file_info->FileNameLength),
5473 if (IS_ERR(new_name))
5474 return PTR_ERR(new_name);
5476 if (strchr(new_name, ':')) {
5478 char *xattr_stream_name, *stream_name = NULL;
5479 size_t xattr_stream_size;
5482 rc = parse_stream_name(new_name, &stream_name, &s_type);
5486 len = strlen(new_name);
5487 if (len > 0 && new_name[len - 1] != '/') {
5488 pr_err("not allow base filename in rename\n");
5493 rc = ksmbd_vfs_xattr_stream_name(stream_name,
5500 rc = ksmbd_vfs_setxattr(file_mnt_idmap(fp->filp),
5505 pr_err("failed to store stream name in xattr: %d\n",
5514 ksmbd_debug(SMB, "new name %s\n", new_name);
5515 if (ksmbd_share_veto_filename(share, new_name)) {
5517 ksmbd_debug(SMB, "Can't rename vetoed file: %s\n", new_name);
5521 if (!file_info->ReplaceIfExists)
5522 flags = RENAME_NOREPLACE;
5524 rc = ksmbd_vfs_rename(work, &fp->filp->f_path, new_name, flags);
5530 static int smb2_create_link(struct ksmbd_work *work,
5531 struct ksmbd_share_config *share,
5532 struct smb2_file_link_info *file_info,
5533 unsigned int buf_len, struct file *filp,
5534 struct nls_table *local_nls)
5536 char *link_name = NULL, *target_name = NULL, *pathname = NULL;
5537 struct path path, parent_path;
5538 bool file_present = false;
5541 if (buf_len < (u64)sizeof(struct smb2_file_link_info) +
5542 le32_to_cpu(file_info->FileNameLength))
5545 ksmbd_debug(SMB, "setting FILE_LINK_INFORMATION\n");
5546 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
5550 link_name = smb2_get_name(file_info->FileName,
5551 le32_to_cpu(file_info->FileNameLength),
5553 if (IS_ERR(link_name) || S_ISDIR(file_inode(filp)->i_mode)) {
5558 ksmbd_debug(SMB, "link name is %s\n", link_name);
5559 target_name = file_path(filp, pathname, PATH_MAX);
5560 if (IS_ERR(target_name)) {
5565 ksmbd_debug(SMB, "target name is %s\n", target_name);
5566 rc = ksmbd_vfs_kern_path_locked(work, link_name, LOOKUP_NO_SYMLINKS,
5567 &parent_path, &path, 0);
5572 file_present = true;
5574 if (file_info->ReplaceIfExists) {
5576 rc = ksmbd_vfs_remove_file(work, &path);
5579 ksmbd_debug(SMB, "cannot delete %s\n",
5587 ksmbd_debug(SMB, "link already exists\n");
5592 rc = ksmbd_vfs_link(work, target_name, link_name);
5597 inode_unlock(d_inode(parent_path.dentry));
5599 path_put(&parent_path);
5601 if (!IS_ERR(link_name))
5607 static int set_file_basic_info(struct ksmbd_file *fp,
5608 struct smb2_file_basic_info *file_info,
5609 struct ksmbd_share_config *share)
5613 struct inode *inode;
5614 struct mnt_idmap *idmap;
5617 if (!(fp->daccess & FILE_WRITE_ATTRIBUTES_LE))
5622 inode = file_inode(filp);
5623 idmap = file_mnt_idmap(filp);
5625 if (file_info->CreationTime)
5626 fp->create_time = le64_to_cpu(file_info->CreationTime);
5628 if (file_info->LastAccessTime) {
5629 attrs.ia_atime = ksmbd_NTtimeToUnix(file_info->LastAccessTime);
5630 attrs.ia_valid |= (ATTR_ATIME | ATTR_ATIME_SET);
5633 attrs.ia_valid |= ATTR_CTIME;
5634 if (file_info->ChangeTime)
5635 attrs.ia_ctime = ksmbd_NTtimeToUnix(file_info->ChangeTime);
5637 attrs.ia_ctime = inode_get_ctime(inode);
5639 if (file_info->LastWriteTime) {
5640 attrs.ia_mtime = ksmbd_NTtimeToUnix(file_info->LastWriteTime);
5641 attrs.ia_valid |= (ATTR_MTIME | ATTR_MTIME_SET);
5644 if (file_info->Attributes) {
5645 if (!S_ISDIR(inode->i_mode) &&
5646 file_info->Attributes & FILE_ATTRIBUTE_DIRECTORY_LE) {
5647 pr_err("can't change a file to a directory\n");
5651 if (!(S_ISDIR(inode->i_mode) && file_info->Attributes == FILE_ATTRIBUTE_NORMAL_LE))
5652 fp->f_ci->m_fattr = file_info->Attributes |
5653 (fp->f_ci->m_fattr & FILE_ATTRIBUTE_DIRECTORY_LE);
5656 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_STORE_DOS_ATTRS) &&
5657 (file_info->CreationTime || file_info->Attributes)) {
5658 struct xattr_dos_attrib da = {0};
5661 da.itime = fp->itime;
5662 da.create_time = fp->create_time;
5663 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
5664 da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
5665 XATTR_DOSINFO_ITIME;
5667 rc = ksmbd_vfs_set_dos_attrib_xattr(idmap, &filp->f_path, &da);
5670 "failed to restore file attribute in EA\n");
5674 if (attrs.ia_valid) {
5675 struct dentry *dentry = filp->f_path.dentry;
5676 struct inode *inode = d_inode(dentry);
5678 if (IS_IMMUTABLE(inode) || IS_APPEND(inode))
5682 inode_set_ctime_to_ts(inode, attrs.ia_ctime);
5683 attrs.ia_valid &= ~ATTR_CTIME;
5684 rc = notify_change(idmap, dentry, &attrs, NULL);
5685 inode_unlock(inode);
5690 static int set_file_allocation_info(struct ksmbd_work *work,
5691 struct ksmbd_file *fp,
5692 struct smb2_file_alloc_info *file_alloc_info)
5695 * TODO : It's working fine only when store dos attributes
5696 * is not yes. need to implement a logic which works
5697 * properly with any smb.conf option
5701 struct inode *inode;
5704 if (!(fp->daccess & FILE_WRITE_DATA_LE))
5707 alloc_blks = (le64_to_cpu(file_alloc_info->AllocationSize) + 511) >> 9;
5708 inode = file_inode(fp->filp);
5710 if (alloc_blks > inode->i_blocks) {
5711 smb_break_all_levII_oplock(work, fp, 1);
5712 rc = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
5714 if (rc && rc != -EOPNOTSUPP) {
5715 pr_err("vfs_fallocate is failed : %d\n", rc);
5718 } else if (alloc_blks < inode->i_blocks) {
5722 * Allocation size could be smaller than original one
5723 * which means allocated blocks in file should be
5724 * deallocated. use truncate to cut out it, but inode
5725 * size is also updated with truncate offset.
5726 * inode size is retained by backup inode size.
5728 size = i_size_read(inode);
5729 rc = ksmbd_vfs_truncate(work, fp, alloc_blks * 512);
5731 pr_err("truncate failed!, err %d\n", rc);
5734 if (size < alloc_blks * 512)
5735 i_size_write(inode, size);
5740 static int set_end_of_file_info(struct ksmbd_work *work, struct ksmbd_file *fp,
5741 struct smb2_file_eof_info *file_eof_info)
5744 struct inode *inode;
5747 if (!(fp->daccess & FILE_WRITE_DATA_LE))
5750 newsize = le64_to_cpu(file_eof_info->EndOfFile);
5751 inode = file_inode(fp->filp);
5754 * If FILE_END_OF_FILE_INFORMATION of set_info_file is called
5755 * on FAT32 shared device, truncate execution time is too long
5756 * and network error could cause from windows client. because
5757 * truncate of some filesystem like FAT32 fill zero data in
5760 if (inode->i_sb->s_magic != MSDOS_SUPER_MAGIC) {
5761 ksmbd_debug(SMB, "truncated to newsize %lld\n", newsize);
5762 rc = ksmbd_vfs_truncate(work, fp, newsize);
5764 ksmbd_debug(SMB, "truncate failed!, err %d\n", rc);
5773 static int set_rename_info(struct ksmbd_work *work, struct ksmbd_file *fp,
5774 struct smb2_file_rename_info *rename_info,
5775 unsigned int buf_len)
5777 if (!(fp->daccess & FILE_DELETE_LE)) {
5778 pr_err("no right to delete : 0x%x\n", fp->daccess);
5782 if (buf_len < (u64)sizeof(struct smb2_file_rename_info) +
5783 le32_to_cpu(rename_info->FileNameLength))
5786 if (!le32_to_cpu(rename_info->FileNameLength))
5789 return smb2_rename(work, fp, rename_info, work->conn->local_nls);
5792 static int set_file_disposition_info(struct ksmbd_file *fp,
5793 struct smb2_file_disposition_info *file_info)
5795 struct inode *inode;
5797 if (!(fp->daccess & FILE_DELETE_LE)) {
5798 pr_err("no right to delete : 0x%x\n", fp->daccess);
5802 inode = file_inode(fp->filp);
5803 if (file_info->DeletePending) {
5804 if (S_ISDIR(inode->i_mode) &&
5805 ksmbd_vfs_empty_dir(fp) == -ENOTEMPTY)
5807 ksmbd_set_inode_pending_delete(fp);
5809 ksmbd_clear_inode_pending_delete(fp);
5814 static int set_file_position_info(struct ksmbd_file *fp,
5815 struct smb2_file_pos_info *file_info)
5817 loff_t current_byte_offset;
5818 unsigned long sector_size;
5819 struct inode *inode;
5821 inode = file_inode(fp->filp);
5822 current_byte_offset = le64_to_cpu(file_info->CurrentByteOffset);
5823 sector_size = inode->i_sb->s_blocksize;
5825 if (current_byte_offset < 0 ||
5826 (fp->coption == FILE_NO_INTERMEDIATE_BUFFERING_LE &&
5827 current_byte_offset & (sector_size - 1))) {
5828 pr_err("CurrentByteOffset is not valid : %llu\n",
5829 current_byte_offset);
5833 fp->filp->f_pos = current_byte_offset;
5837 static int set_file_mode_info(struct ksmbd_file *fp,
5838 struct smb2_file_mode_info *file_info)
5842 mode = file_info->Mode;
5844 if ((mode & ~FILE_MODE_INFO_MASK)) {
5845 pr_err("Mode is not valid : 0x%x\n", le32_to_cpu(mode));
5850 * TODO : need to implement consideration for
5851 * FILE_SYNCHRONOUS_IO_ALERT and FILE_SYNCHRONOUS_IO_NONALERT
5853 ksmbd_vfs_set_fadvise(fp->filp, mode);
5859 * smb2_set_info_file() - handler for smb2 set info command
5860 * @work: smb work containing set info command buffer
5861 * @fp: ksmbd_file pointer
5862 * @req: request buffer pointer
5863 * @share: ksmbd_share_config pointer
5865 * Return: 0 on success, otherwise error
5866 * TODO: need to implement an error handling for STATUS_INFO_LENGTH_MISMATCH
5868 static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp,
5869 struct smb2_set_info_req *req,
5870 struct ksmbd_share_config *share)
5872 unsigned int buf_len = le32_to_cpu(req->BufferLength);
5874 switch (req->FileInfoClass) {
5875 case FILE_BASIC_INFORMATION:
5877 if (buf_len < sizeof(struct smb2_file_basic_info))
5880 return set_file_basic_info(fp, (struct smb2_file_basic_info *)req->Buffer, share);
5882 case FILE_ALLOCATION_INFORMATION:
5884 if (buf_len < sizeof(struct smb2_file_alloc_info))
5887 return set_file_allocation_info(work, fp,
5888 (struct smb2_file_alloc_info *)req->Buffer);
5890 case FILE_END_OF_FILE_INFORMATION:
5892 if (buf_len < sizeof(struct smb2_file_eof_info))
5895 return set_end_of_file_info(work, fp,
5896 (struct smb2_file_eof_info *)req->Buffer);
5898 case FILE_RENAME_INFORMATION:
5900 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
5902 "User does not have write permission\n");
5906 if (buf_len < sizeof(struct smb2_file_rename_info))
5909 return set_rename_info(work, fp,
5910 (struct smb2_file_rename_info *)req->Buffer,
5913 case FILE_LINK_INFORMATION:
5915 if (buf_len < sizeof(struct smb2_file_link_info))
5918 return smb2_create_link(work, work->tcon->share_conf,
5919 (struct smb2_file_link_info *)req->Buffer,
5921 work->conn->local_nls);
5923 case FILE_DISPOSITION_INFORMATION:
5925 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
5927 "User does not have write permission\n");
5931 if (buf_len < sizeof(struct smb2_file_disposition_info))
5934 return set_file_disposition_info(fp,
5935 (struct smb2_file_disposition_info *)req->Buffer);
5937 case FILE_FULL_EA_INFORMATION:
5939 if (!(fp->daccess & FILE_WRITE_EA_LE)) {
5940 pr_err("Not permitted to write ext attr: 0x%x\n",
5945 if (buf_len < sizeof(struct smb2_ea_info))
5948 return smb2_set_ea((struct smb2_ea_info *)req->Buffer,
5949 buf_len, &fp->filp->f_path);
5951 case FILE_POSITION_INFORMATION:
5953 if (buf_len < sizeof(struct smb2_file_pos_info))
5956 return set_file_position_info(fp, (struct smb2_file_pos_info *)req->Buffer);
5958 case FILE_MODE_INFORMATION:
5960 if (buf_len < sizeof(struct smb2_file_mode_info))
5963 return set_file_mode_info(fp, (struct smb2_file_mode_info *)req->Buffer);
5967 pr_err("Unimplemented Fileinfoclass :%d\n", req->FileInfoClass);
5971 static int smb2_set_info_sec(struct ksmbd_file *fp, int addition_info,
5972 char *buffer, int buf_len)
5974 struct smb_ntsd *pntsd = (struct smb_ntsd *)buffer;
5976 fp->saccess |= FILE_SHARE_DELETE_LE;
5978 return set_info_sec(fp->conn, fp->tcon, &fp->filp->f_path, pntsd,
5983 * smb2_set_info() - handler for smb2 set info command handler
5984 * @work: smb work containing set info request buffer
5986 * Return: 0 on success, otherwise error
5988 int smb2_set_info(struct ksmbd_work *work)
5990 struct smb2_set_info_req *req;
5991 struct smb2_set_info_rsp *rsp;
5992 struct ksmbd_file *fp;
5994 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
5996 ksmbd_debug(SMB, "Received set info request\n");
5998 if (work->next_smb2_rcv_hdr_off) {
5999 req = ksmbd_req_buf_next(work);
6000 rsp = ksmbd_resp_buf_next(work);
6001 if (!has_file_id(req->VolatileFileId)) {
6002 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
6003 work->compound_fid);
6004 id = work->compound_fid;
6005 pid = work->compound_pfid;
6008 req = smb2_get_msg(work->request_buf);
6009 rsp = smb2_get_msg(work->response_buf);
6012 if (!has_file_id(id)) {
6013 id = req->VolatileFileId;
6014 pid = req->PersistentFileId;
6017 fp = ksmbd_lookup_fd_slow(work, id, pid);
6019 ksmbd_debug(SMB, "Invalid id for close: %u\n", id);
6024 switch (req->InfoType) {
6025 case SMB2_O_INFO_FILE:
6026 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
6027 rc = smb2_set_info_file(work, fp, req, work->tcon->share_conf);
6029 case SMB2_O_INFO_SECURITY:
6030 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
6031 if (ksmbd_override_fsids(work)) {
6035 rc = smb2_set_info_sec(fp,
6036 le32_to_cpu(req->AdditionalInformation),
6038 le32_to_cpu(req->BufferLength));
6039 ksmbd_revert_fsids(work);
6048 rsp->StructureSize = cpu_to_le16(2);
6049 rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
6050 sizeof(struct smb2_set_info_rsp));
6053 ksmbd_fd_put(work, fp);
6057 if (rc == -EACCES || rc == -EPERM || rc == -EXDEV)
6058 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6059 else if (rc == -EINVAL)
6060 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6061 else if (rc == -ESHARE)
6062 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6063 else if (rc == -ENOENT)
6064 rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
6065 else if (rc == -EBUSY || rc == -ENOTEMPTY)
6066 rsp->hdr.Status = STATUS_DIRECTORY_NOT_EMPTY;
6067 else if (rc == -EAGAIN)
6068 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6069 else if (rc == -EBADF || rc == -ESTALE)
6070 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6071 else if (rc == -EEXIST)
6072 rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
6073 else if (rsp->hdr.Status == 0 || rc == -EOPNOTSUPP)
6074 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
6075 smb2_set_err_rsp(work);
6076 ksmbd_fd_put(work, fp);
6077 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n", rc);
6082 * smb2_read_pipe() - handler for smb2 read from IPC pipe
6083 * @work: smb work containing read IPC pipe command buffer
6085 * Return: 0 on success, otherwise error
6087 static noinline int smb2_read_pipe(struct ksmbd_work *work)
6089 int nbytes = 0, err;
6091 struct ksmbd_rpc_command *rpc_resp;
6092 struct smb2_read_req *req;
6093 struct smb2_read_rsp *rsp;
6095 WORK_BUFFERS(work, req, rsp);
6097 id = req->VolatileFileId;
6099 rpc_resp = ksmbd_rpc_read(work->sess, id);
6101 void *aux_payload_buf;
6103 if (rpc_resp->flags != KSMBD_RPC_OK) {
6109 kvmalloc(rpc_resp->payload_sz, GFP_KERNEL);
6110 if (!aux_payload_buf) {
6115 memcpy(aux_payload_buf, rpc_resp->payload, rpc_resp->payload_sz);
6117 nbytes = rpc_resp->payload_sz;
6119 err = ksmbd_iov_pin_rsp_read(work, (void *)rsp,
6120 offsetof(struct smb2_read_rsp, Buffer),
6121 aux_payload_buf, nbytes);
6125 err = ksmbd_iov_pin_rsp(work, (void *)rsp,
6126 offsetof(struct smb2_read_rsp, Buffer));
6131 rsp->StructureSize = cpu_to_le16(17);
6132 rsp->DataOffset = 80;
6134 rsp->DataLength = cpu_to_le32(nbytes);
6135 rsp->DataRemaining = 0;
6140 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
6141 smb2_set_err_rsp(work);
6146 static int smb2_set_remote_key_for_rdma(struct ksmbd_work *work,
6147 struct smb2_buffer_desc_v1 *desc,
6149 __le16 ChannelInfoLength)
6151 unsigned int i, ch_count;
6153 if (work->conn->dialect == SMB30_PROT_ID &&
6154 Channel != SMB2_CHANNEL_RDMA_V1)
6157 ch_count = le16_to_cpu(ChannelInfoLength) / sizeof(*desc);
6158 if (ksmbd_debug_types & KSMBD_DEBUG_RDMA) {
6159 for (i = 0; i < ch_count; i++) {
6160 pr_info("RDMA r/w request %#x: token %#x, length %#x\n",
6162 le32_to_cpu(desc[i].token),
6163 le32_to_cpu(desc[i].length));
6169 work->need_invalidate_rkey =
6170 (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE);
6171 if (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE)
6172 work->remote_key = le32_to_cpu(desc->token);
6176 static ssize_t smb2_read_rdma_channel(struct ksmbd_work *work,
6177 struct smb2_read_req *req, void *data_buf,
6182 err = ksmbd_conn_rdma_write(work->conn, data_buf, length,
6183 (struct smb2_buffer_desc_v1 *)
6184 ((char *)req + le16_to_cpu(req->ReadChannelInfoOffset)),
6185 le16_to_cpu(req->ReadChannelInfoLength));
6193 * smb2_read() - handler for smb2 read from file
6194 * @work: smb work containing read command buffer
6196 * Return: 0 on success, otherwise error
6198 int smb2_read(struct ksmbd_work *work)
6200 struct ksmbd_conn *conn = work->conn;
6201 struct smb2_read_req *req;
6202 struct smb2_read_rsp *rsp;
6203 struct ksmbd_file *fp = NULL;
6205 size_t length, mincount;
6206 ssize_t nbytes = 0, remain_bytes = 0;
6208 bool is_rdma_channel = false;
6209 unsigned int max_read_size = conn->vals->max_read_size;
6210 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
6211 void *aux_payload_buf;
6213 if (test_share_config_flag(work->tcon->share_conf,
6214 KSMBD_SHARE_FLAG_PIPE)) {
6215 ksmbd_debug(SMB, "IPC pipe read request\n");
6216 return smb2_read_pipe(work);
6219 if (work->next_smb2_rcv_hdr_off) {
6220 req = ksmbd_req_buf_next(work);
6221 rsp = ksmbd_resp_buf_next(work);
6222 if (!has_file_id(req->VolatileFileId)) {
6223 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
6224 work->compound_fid);
6225 id = work->compound_fid;
6226 pid = work->compound_pfid;
6229 req = smb2_get_msg(work->request_buf);
6230 rsp = smb2_get_msg(work->response_buf);
6233 if (!has_file_id(id)) {
6234 id = req->VolatileFileId;
6235 pid = req->PersistentFileId;
6238 if (req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE ||
6239 req->Channel == SMB2_CHANNEL_RDMA_V1) {
6240 is_rdma_channel = true;
6241 max_read_size = get_smbd_max_read_write_size();
6244 if (is_rdma_channel == true) {
6245 unsigned int ch_offset = le16_to_cpu(req->ReadChannelInfoOffset);
6247 if (ch_offset < offsetof(struct smb2_read_req, Buffer)) {
6251 err = smb2_set_remote_key_for_rdma(work,
6252 (struct smb2_buffer_desc_v1 *)
6253 ((char *)req + ch_offset),
6255 req->ReadChannelInfoLength);
6260 fp = ksmbd_lookup_fd_slow(work, id, pid);
6266 if (!(fp->daccess & (FILE_READ_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
6267 pr_err("Not permitted to read : 0x%x\n", fp->daccess);
6272 offset = le64_to_cpu(req->Offset);
6273 length = le32_to_cpu(req->Length);
6274 mincount = le32_to_cpu(req->MinimumCount);
6276 if (length > max_read_size) {
6277 ksmbd_debug(SMB, "limiting read size to max size(%u)\n",
6283 ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
6284 fp->filp, offset, length);
6286 aux_payload_buf = kvzalloc(length, GFP_KERNEL);
6287 if (!aux_payload_buf) {
6292 nbytes = ksmbd_vfs_read(work, fp, length, &offset, aux_payload_buf);
6298 if ((nbytes == 0 && length != 0) || nbytes < mincount) {
6299 kvfree(aux_payload_buf);
6300 rsp->hdr.Status = STATUS_END_OF_FILE;
6301 smb2_set_err_rsp(work);
6302 ksmbd_fd_put(work, fp);
6306 ksmbd_debug(SMB, "nbytes %zu, offset %lld mincount %zu\n",
6307 nbytes, offset, mincount);
6309 if (is_rdma_channel == true) {
6310 /* write data to the client using rdma channel */
6311 remain_bytes = smb2_read_rdma_channel(work, req,
6314 kvfree(aux_payload_buf);
6317 if (remain_bytes < 0) {
6318 err = (int)remain_bytes;
6323 rsp->StructureSize = cpu_to_le16(17);
6324 rsp->DataOffset = 80;
6326 rsp->DataLength = cpu_to_le32(nbytes);
6327 rsp->DataRemaining = cpu_to_le32(remain_bytes);
6329 err = ksmbd_iov_pin_rsp_read(work, (void *)rsp,
6330 offsetof(struct smb2_read_rsp, Buffer),
6331 aux_payload_buf, nbytes);
6334 ksmbd_fd_put(work, fp);
6340 rsp->hdr.Status = STATUS_INVALID_DEVICE_REQUEST;
6341 else if (err == -EAGAIN)
6342 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6343 else if (err == -ENOENT)
6344 rsp->hdr.Status = STATUS_FILE_CLOSED;
6345 else if (err == -EACCES)
6346 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6347 else if (err == -ESHARE)
6348 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6349 else if (err == -EINVAL)
6350 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6352 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6354 smb2_set_err_rsp(work);
6356 ksmbd_fd_put(work, fp);
6361 * smb2_write_pipe() - handler for smb2 write on IPC pipe
6362 * @work: smb work containing write IPC pipe command buffer
6364 * Return: 0 on success, otherwise error
6366 static noinline int smb2_write_pipe(struct ksmbd_work *work)
6368 struct smb2_write_req *req;
6369 struct smb2_write_rsp *rsp;
6370 struct ksmbd_rpc_command *rpc_resp;
6372 int err = 0, ret = 0;
6376 WORK_BUFFERS(work, req, rsp);
6378 length = le32_to_cpu(req->Length);
6379 id = req->VolatileFileId;
6381 if ((u64)le16_to_cpu(req->DataOffset) + length >
6382 get_rfc1002_len(work->request_buf)) {
6383 pr_err("invalid write data offset %u, smb_len %u\n",
6384 le16_to_cpu(req->DataOffset),
6385 get_rfc1002_len(work->request_buf));
6390 data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
6391 le16_to_cpu(req->DataOffset));
6393 rpc_resp = ksmbd_rpc_write(work->sess, id, data_buf, length);
6395 if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
6396 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
6398 smb2_set_err_rsp(work);
6401 if (rpc_resp->flags != KSMBD_RPC_OK) {
6402 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6403 smb2_set_err_rsp(work);
6410 rsp->StructureSize = cpu_to_le16(17);
6411 rsp->DataOffset = 0;
6413 rsp->DataLength = cpu_to_le32(length);
6414 rsp->DataRemaining = 0;
6416 err = ksmbd_iov_pin_rsp(work, (void *)rsp,
6417 offsetof(struct smb2_write_rsp, Buffer));
6420 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6421 smb2_set_err_rsp(work);
6427 static ssize_t smb2_write_rdma_channel(struct ksmbd_work *work,
6428 struct smb2_write_req *req,
6429 struct ksmbd_file *fp,
6430 loff_t offset, size_t length, bool sync)
6436 data_buf = kvzalloc(length, GFP_KERNEL);
6440 ret = ksmbd_conn_rdma_read(work->conn, data_buf, length,
6441 (struct smb2_buffer_desc_v1 *)
6442 ((char *)req + le16_to_cpu(req->WriteChannelInfoOffset)),
6443 le16_to_cpu(req->WriteChannelInfoLength));
6449 ret = ksmbd_vfs_write(work, fp, data_buf, length, &offset, sync, &nbytes);
6458 * smb2_write() - handler for smb2 write from file
6459 * @work: smb work containing write command buffer
6461 * Return: 0 on success, otherwise error
6463 int smb2_write(struct ksmbd_work *work)
6465 struct smb2_write_req *req;
6466 struct smb2_write_rsp *rsp;
6467 struct ksmbd_file *fp = NULL;
6472 bool writethrough = false, is_rdma_channel = false;
6474 unsigned int max_write_size = work->conn->vals->max_write_size;
6476 WORK_BUFFERS(work, req, rsp);
6478 if (test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_PIPE)) {
6479 ksmbd_debug(SMB, "IPC pipe write request\n");
6480 return smb2_write_pipe(work);
6483 offset = le64_to_cpu(req->Offset);
6484 length = le32_to_cpu(req->Length);
6486 if (req->Channel == SMB2_CHANNEL_RDMA_V1 ||
6487 req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE) {
6488 is_rdma_channel = true;
6489 max_write_size = get_smbd_max_read_write_size();
6490 length = le32_to_cpu(req->RemainingBytes);
6493 if (is_rdma_channel == true) {
6494 unsigned int ch_offset = le16_to_cpu(req->WriteChannelInfoOffset);
6496 if (req->Length != 0 || req->DataOffset != 0 ||
6497 ch_offset < offsetof(struct smb2_write_req, Buffer)) {
6501 err = smb2_set_remote_key_for_rdma(work,
6502 (struct smb2_buffer_desc_v1 *)
6503 ((char *)req + ch_offset),
6505 req->WriteChannelInfoLength);
6510 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
6511 ksmbd_debug(SMB, "User does not have write permission\n");
6516 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
6522 if (!(fp->daccess & (FILE_WRITE_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
6523 pr_err("Not permitted to write : 0x%x\n", fp->daccess);
6528 if (length > max_write_size) {
6529 ksmbd_debug(SMB, "limiting write size to max size(%u)\n",
6535 ksmbd_debug(SMB, "flags %u\n", le32_to_cpu(req->Flags));
6536 if (le32_to_cpu(req->Flags) & SMB2_WRITEFLAG_WRITE_THROUGH)
6537 writethrough = true;
6539 if (is_rdma_channel == false) {
6540 if (le16_to_cpu(req->DataOffset) <
6541 offsetof(struct smb2_write_req, Buffer)) {
6546 data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
6547 le16_to_cpu(req->DataOffset));
6549 ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
6550 fp->filp, offset, length);
6551 err = ksmbd_vfs_write(work, fp, data_buf, length, &offset,
6552 writethrough, &nbytes);
6556 /* read data from the client using rdma channel, and
6559 nbytes = smb2_write_rdma_channel(work, req, fp, offset, length,
6567 rsp->StructureSize = cpu_to_le16(17);
6568 rsp->DataOffset = 0;
6570 rsp->DataLength = cpu_to_le32(nbytes);
6571 rsp->DataRemaining = 0;
6573 err = ksmbd_iov_pin_rsp(work, rsp, offsetof(struct smb2_write_rsp, Buffer));
6576 ksmbd_fd_put(work, fp);
6581 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6582 else if (err == -ENOSPC || err == -EFBIG)
6583 rsp->hdr.Status = STATUS_DISK_FULL;
6584 else if (err == -ENOENT)
6585 rsp->hdr.Status = STATUS_FILE_CLOSED;
6586 else if (err == -EACCES)
6587 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6588 else if (err == -ESHARE)
6589 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6590 else if (err == -EINVAL)
6591 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6593 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6595 smb2_set_err_rsp(work);
6596 ksmbd_fd_put(work, fp);
6601 * smb2_flush() - handler for smb2 flush file - fsync
6602 * @work: smb work containing flush command buffer
6604 * Return: 0 on success, otherwise error
6606 int smb2_flush(struct ksmbd_work *work)
6608 struct smb2_flush_req *req;
6609 struct smb2_flush_rsp *rsp;
6612 WORK_BUFFERS(work, req, rsp);
6614 ksmbd_debug(SMB, "SMB2_FLUSH called for fid %llu\n", req->VolatileFileId);
6616 err = ksmbd_vfs_fsync(work, req->VolatileFileId, req->PersistentFileId);
6620 rsp->StructureSize = cpu_to_le16(4);
6622 return ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_flush_rsp));
6625 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6626 smb2_set_err_rsp(work);
6631 * smb2_cancel() - handler for smb2 cancel command
6632 * @work: smb work containing cancel command buffer
6634 * Return: 0 on success, otherwise error
6636 int smb2_cancel(struct ksmbd_work *work)
6638 struct ksmbd_conn *conn = work->conn;
6639 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
6640 struct smb2_hdr *chdr;
6641 struct ksmbd_work *iter;
6642 struct list_head *command_list;
6644 if (work->next_smb2_rcv_hdr_off)
6645 hdr = ksmbd_resp_buf_next(work);
6647 ksmbd_debug(SMB, "smb2 cancel called on mid %llu, async flags 0x%x\n",
6648 hdr->MessageId, hdr->Flags);
6650 if (hdr->Flags & SMB2_FLAGS_ASYNC_COMMAND) {
6651 command_list = &conn->async_requests;
6653 spin_lock(&conn->request_lock);
6654 list_for_each_entry(iter, command_list,
6655 async_request_entry) {
6656 chdr = smb2_get_msg(iter->request_buf);
6658 if (iter->async_id !=
6659 le64_to_cpu(hdr->Id.AsyncId))
6663 "smb2 with AsyncId %llu cancelled command = 0x%x\n",
6664 le64_to_cpu(hdr->Id.AsyncId),
6665 le16_to_cpu(chdr->Command));
6666 iter->state = KSMBD_WORK_CANCELLED;
6667 if (iter->cancel_fn)
6668 iter->cancel_fn(iter->cancel_argv);
6671 spin_unlock(&conn->request_lock);
6673 command_list = &conn->requests;
6675 spin_lock(&conn->request_lock);
6676 list_for_each_entry(iter, command_list, request_entry) {
6677 chdr = smb2_get_msg(iter->request_buf);
6679 if (chdr->MessageId != hdr->MessageId ||
6684 "smb2 with mid %llu cancelled command = 0x%x\n",
6685 le64_to_cpu(hdr->MessageId),
6686 le16_to_cpu(chdr->Command));
6687 iter->state = KSMBD_WORK_CANCELLED;
6690 spin_unlock(&conn->request_lock);
6693 /* For SMB2_CANCEL command itself send no response*/
6694 work->send_no_response = 1;
6698 struct file_lock *smb_flock_init(struct file *f)
6700 struct file_lock *fl;
6702 fl = locks_alloc_lock();
6706 locks_init_lock(fl);
6709 fl->fl_pid = current->tgid;
6711 fl->fl_flags = FL_POSIX;
6713 fl->fl_lmops = NULL;
6719 static int smb2_set_flock_flags(struct file_lock *flock, int flags)
6723 /* Checking for wrong flag combination during lock request*/
6725 case SMB2_LOCKFLAG_SHARED:
6726 ksmbd_debug(SMB, "received shared request\n");
6728 flock->fl_type = F_RDLCK;
6729 flock->fl_flags |= FL_SLEEP;
6731 case SMB2_LOCKFLAG_EXCLUSIVE:
6732 ksmbd_debug(SMB, "received exclusive request\n");
6734 flock->fl_type = F_WRLCK;
6735 flock->fl_flags |= FL_SLEEP;
6737 case SMB2_LOCKFLAG_SHARED | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
6739 "received shared & fail immediately request\n");
6741 flock->fl_type = F_RDLCK;
6743 case SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
6745 "received exclusive & fail immediately request\n");
6747 flock->fl_type = F_WRLCK;
6749 case SMB2_LOCKFLAG_UNLOCK:
6750 ksmbd_debug(SMB, "received unlock request\n");
6751 flock->fl_type = F_UNLCK;
6759 static struct ksmbd_lock *smb2_lock_init(struct file_lock *flock,
6760 unsigned int cmd, int flags,
6761 struct list_head *lock_list)
6763 struct ksmbd_lock *lock;
6765 lock = kzalloc(sizeof(struct ksmbd_lock), GFP_KERNEL);
6771 lock->start = flock->fl_start;
6772 lock->end = flock->fl_end;
6773 lock->flags = flags;
6774 if (lock->start == lock->end)
6776 INIT_LIST_HEAD(&lock->clist);
6777 INIT_LIST_HEAD(&lock->flist);
6778 INIT_LIST_HEAD(&lock->llist);
6779 list_add_tail(&lock->llist, lock_list);
6784 static void smb2_remove_blocked_lock(void **argv)
6786 struct file_lock *flock = (struct file_lock *)argv[0];
6788 ksmbd_vfs_posix_lock_unblock(flock);
6789 wake_up(&flock->fl_wait);
6792 static inline bool lock_defer_pending(struct file_lock *fl)
6794 /* check pending lock waiters */
6795 return waitqueue_active(&fl->fl_wait);
6799 * smb2_lock() - handler for smb2 file lock command
6800 * @work: smb work containing lock command buffer
6802 * Return: 0 on success, otherwise error
6804 int smb2_lock(struct ksmbd_work *work)
6806 struct smb2_lock_req *req;
6807 struct smb2_lock_rsp *rsp;
6808 struct smb2_lock_element *lock_ele;
6809 struct ksmbd_file *fp = NULL;
6810 struct file_lock *flock = NULL;
6811 struct file *filp = NULL;
6815 int err = -EIO, i, rc = 0;
6816 u64 lock_start, lock_length;
6817 struct ksmbd_lock *smb_lock = NULL, *cmp_lock, *tmp, *tmp2;
6818 struct ksmbd_conn *conn;
6820 LIST_HEAD(lock_list);
6821 LIST_HEAD(rollback_list);
6824 WORK_BUFFERS(work, req, rsp);
6826 ksmbd_debug(SMB, "Received lock request\n");
6827 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
6829 ksmbd_debug(SMB, "Invalid file id for lock : %llu\n", req->VolatileFileId);
6835 lock_count = le16_to_cpu(req->LockCount);
6836 lock_ele = req->locks;
6838 ksmbd_debug(SMB, "lock count is %d\n", lock_count);
6844 for (i = 0; i < lock_count; i++) {
6845 flags = le32_to_cpu(lock_ele[i].Flags);
6847 flock = smb_flock_init(filp);
6851 cmd = smb2_set_flock_flags(flock, flags);
6853 lock_start = le64_to_cpu(lock_ele[i].Offset);
6854 lock_length = le64_to_cpu(lock_ele[i].Length);
6855 if (lock_start > U64_MAX - lock_length) {
6856 pr_err("Invalid lock range requested\n");
6857 rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
6858 locks_free_lock(flock);
6862 if (lock_start > OFFSET_MAX)
6863 flock->fl_start = OFFSET_MAX;
6865 flock->fl_start = lock_start;
6867 lock_length = le64_to_cpu(lock_ele[i].Length);
6868 if (lock_length > OFFSET_MAX - flock->fl_start)
6869 lock_length = OFFSET_MAX - flock->fl_start;
6871 flock->fl_end = flock->fl_start + lock_length;
6873 if (flock->fl_end < flock->fl_start) {
6875 "the end offset(%llx) is smaller than the start offset(%llx)\n",
6876 flock->fl_end, flock->fl_start);
6877 rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
6878 locks_free_lock(flock);
6882 /* Check conflict locks in one request */
6883 list_for_each_entry(cmp_lock, &lock_list, llist) {
6884 if (cmp_lock->fl->fl_start <= flock->fl_start &&
6885 cmp_lock->fl->fl_end >= flock->fl_end) {
6886 if (cmp_lock->fl->fl_type != F_UNLCK &&
6887 flock->fl_type != F_UNLCK) {
6888 pr_err("conflict two locks in one request\n");
6890 locks_free_lock(flock);
6896 smb_lock = smb2_lock_init(flock, cmd, flags, &lock_list);
6899 locks_free_lock(flock);
6904 list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
6905 if (smb_lock->cmd < 0) {
6910 if (!(smb_lock->flags & SMB2_LOCKFLAG_MASK)) {
6915 if ((prior_lock & (SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_SHARED) &&
6916 smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) ||
6917 (prior_lock == SMB2_LOCKFLAG_UNLOCK &&
6918 !(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK))) {
6923 prior_lock = smb_lock->flags;
6925 if (!(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) &&
6926 !(smb_lock->flags & SMB2_LOCKFLAG_FAIL_IMMEDIATELY))
6930 /* check locks in connection list */
6931 down_read(&conn_list_lock);
6932 list_for_each_entry(conn, &conn_list, conns_list) {
6933 spin_lock(&conn->llist_lock);
6934 list_for_each_entry_safe(cmp_lock, tmp2, &conn->lock_list, clist) {
6935 if (file_inode(cmp_lock->fl->fl_file) !=
6936 file_inode(smb_lock->fl->fl_file))
6939 if (smb_lock->fl->fl_type == F_UNLCK) {
6940 if (cmp_lock->fl->fl_file == smb_lock->fl->fl_file &&
6941 cmp_lock->start == smb_lock->start &&
6942 cmp_lock->end == smb_lock->end &&
6943 !lock_defer_pending(cmp_lock->fl)) {
6945 list_del(&cmp_lock->flist);
6946 list_del(&cmp_lock->clist);
6947 spin_unlock(&conn->llist_lock);
6948 up_read(&conn_list_lock);
6950 locks_free_lock(cmp_lock->fl);
6957 if (cmp_lock->fl->fl_file == smb_lock->fl->fl_file) {
6958 if (smb_lock->flags & SMB2_LOCKFLAG_SHARED)
6961 if (cmp_lock->flags & SMB2_LOCKFLAG_SHARED)
6965 /* check zero byte lock range */
6966 if (cmp_lock->zero_len && !smb_lock->zero_len &&
6967 cmp_lock->start > smb_lock->start &&
6968 cmp_lock->start < smb_lock->end) {
6969 spin_unlock(&conn->llist_lock);
6970 up_read(&conn_list_lock);
6971 pr_err("previous lock conflict with zero byte lock range\n");
6975 if (smb_lock->zero_len && !cmp_lock->zero_len &&
6976 smb_lock->start > cmp_lock->start &&
6977 smb_lock->start < cmp_lock->end) {
6978 spin_unlock(&conn->llist_lock);
6979 up_read(&conn_list_lock);
6980 pr_err("current lock conflict with zero byte lock range\n");
6984 if (((cmp_lock->start <= smb_lock->start &&
6985 cmp_lock->end > smb_lock->start) ||
6986 (cmp_lock->start < smb_lock->end &&
6987 cmp_lock->end >= smb_lock->end)) &&
6988 !cmp_lock->zero_len && !smb_lock->zero_len) {
6989 spin_unlock(&conn->llist_lock);
6990 up_read(&conn_list_lock);
6991 pr_err("Not allow lock operation on exclusive lock range\n");
6995 spin_unlock(&conn->llist_lock);
6997 up_read(&conn_list_lock);
6999 if (smb_lock->fl->fl_type == F_UNLCK && nolock) {
7000 pr_err("Try to unlock nolocked range\n");
7001 rsp->hdr.Status = STATUS_RANGE_NOT_LOCKED;
7006 if (smb_lock->zero_len) {
7011 flock = smb_lock->fl;
7012 list_del(&smb_lock->llist);
7014 rc = vfs_lock_file(filp, smb_lock->cmd, flock, NULL);
7016 if (flags & SMB2_LOCKFLAG_UNLOCK) {
7018 ksmbd_debug(SMB, "File unlocked\n");
7019 } else if (rc == -ENOENT) {
7020 rsp->hdr.Status = STATUS_NOT_LOCKED;
7023 locks_free_lock(flock);
7026 if (rc == FILE_LOCK_DEFERRED) {
7030 "would have to wait for getting lock\n");
7031 spin_lock(&work->conn->llist_lock);
7032 list_add_tail(&smb_lock->clist,
7033 &work->conn->lock_list);
7034 spin_unlock(&work->conn->llist_lock);
7035 list_add(&smb_lock->llist, &rollback_list);
7037 argv = kmalloc(sizeof(void *), GFP_KERNEL);
7044 rc = setup_async_work(work,
7045 smb2_remove_blocked_lock,
7051 spin_lock(&fp->f_lock);
7052 list_add(&work->fp_entry, &fp->blocked_works);
7053 spin_unlock(&fp->f_lock);
7055 smb2_send_interim_resp(work, STATUS_PENDING);
7057 ksmbd_vfs_posix_lock_wait(flock);
7059 spin_lock(&fp->f_lock);
7060 list_del(&work->fp_entry);
7061 spin_unlock(&fp->f_lock);
7063 if (work->state != KSMBD_WORK_ACTIVE) {
7064 list_del(&smb_lock->llist);
7065 spin_lock(&work->conn->llist_lock);
7066 list_del(&smb_lock->clist);
7067 spin_unlock(&work->conn->llist_lock);
7068 locks_free_lock(flock);
7070 if (work->state == KSMBD_WORK_CANCELLED) {
7074 smb2_send_interim_resp(work,
7076 work->send_no_response = 1;
7081 STATUS_RANGE_NOT_LOCKED;
7086 list_del(&smb_lock->llist);
7087 spin_lock(&work->conn->llist_lock);
7088 list_del(&smb_lock->clist);
7089 spin_unlock(&work->conn->llist_lock);
7090 release_async_work(work);
7093 spin_lock(&work->conn->llist_lock);
7094 list_add_tail(&smb_lock->clist,
7095 &work->conn->lock_list);
7096 list_add_tail(&smb_lock->flist,
7098 spin_unlock(&work->conn->llist_lock);
7099 list_add(&smb_lock->llist, &rollback_list);
7100 ksmbd_debug(SMB, "successful in taking lock\n");
7107 if (atomic_read(&fp->f_ci->op_count) > 1)
7108 smb_break_all_oplock(work, fp);
7110 rsp->StructureSize = cpu_to_le16(4);
7111 ksmbd_debug(SMB, "successful in taking lock\n");
7112 rsp->hdr.Status = STATUS_SUCCESS;
7114 err = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_lock_rsp));
7118 ksmbd_fd_put(work, fp);
7122 list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
7123 locks_free_lock(smb_lock->fl);
7124 list_del(&smb_lock->llist);
7128 list_for_each_entry_safe(smb_lock, tmp, &rollback_list, llist) {
7129 struct file_lock *rlock = NULL;
7131 rlock = smb_flock_init(filp);
7132 rlock->fl_type = F_UNLCK;
7133 rlock->fl_start = smb_lock->start;
7134 rlock->fl_end = smb_lock->end;
7136 rc = vfs_lock_file(filp, F_SETLK, rlock, NULL);
7138 pr_err("rollback unlock fail : %d\n", rc);
7140 list_del(&smb_lock->llist);
7141 spin_lock(&work->conn->llist_lock);
7142 if (!list_empty(&smb_lock->flist))
7143 list_del(&smb_lock->flist);
7144 list_del(&smb_lock->clist);
7145 spin_unlock(&work->conn->llist_lock);
7147 locks_free_lock(smb_lock->fl);
7148 locks_free_lock(rlock);
7152 ksmbd_debug(SMB, "failed in taking lock(flags : %x), err : %d\n", flags, err);
7154 if (!rsp->hdr.Status) {
7156 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7157 else if (err == -ENOMEM)
7158 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
7159 else if (err == -ENOENT)
7160 rsp->hdr.Status = STATUS_FILE_CLOSED;
7162 rsp->hdr.Status = STATUS_LOCK_NOT_GRANTED;
7165 smb2_set_err_rsp(work);
7166 ksmbd_fd_put(work, fp);
7170 static int fsctl_copychunk(struct ksmbd_work *work,
7171 struct copychunk_ioctl_req *ci_req,
7172 unsigned int cnt_code,
7173 unsigned int input_count,
7174 unsigned long long volatile_id,
7175 unsigned long long persistent_id,
7176 struct smb2_ioctl_rsp *rsp)
7178 struct copychunk_ioctl_rsp *ci_rsp;
7179 struct ksmbd_file *src_fp = NULL, *dst_fp = NULL;
7180 struct srv_copychunk *chunks;
7181 unsigned int i, chunk_count, chunk_count_written = 0;
7182 unsigned int chunk_size_written = 0;
7183 loff_t total_size_written = 0;
7186 ci_rsp = (struct copychunk_ioctl_rsp *)&rsp->Buffer[0];
7188 rsp->VolatileFileId = volatile_id;
7189 rsp->PersistentFileId = persistent_id;
7190 ci_rsp->ChunksWritten =
7191 cpu_to_le32(ksmbd_server_side_copy_max_chunk_count());
7192 ci_rsp->ChunkBytesWritten =
7193 cpu_to_le32(ksmbd_server_side_copy_max_chunk_size());
7194 ci_rsp->TotalBytesWritten =
7195 cpu_to_le32(ksmbd_server_side_copy_max_total_size());
7197 chunks = (struct srv_copychunk *)&ci_req->Chunks[0];
7198 chunk_count = le32_to_cpu(ci_req->ChunkCount);
7199 if (chunk_count == 0)
7201 total_size_written = 0;
7203 /* verify the SRV_COPYCHUNK_COPY packet */
7204 if (chunk_count > ksmbd_server_side_copy_max_chunk_count() ||
7205 input_count < offsetof(struct copychunk_ioctl_req, Chunks) +
7206 chunk_count * sizeof(struct srv_copychunk)) {
7207 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7211 for (i = 0; i < chunk_count; i++) {
7212 if (le32_to_cpu(chunks[i].Length) == 0 ||
7213 le32_to_cpu(chunks[i].Length) > ksmbd_server_side_copy_max_chunk_size())
7215 total_size_written += le32_to_cpu(chunks[i].Length);
7218 if (i < chunk_count ||
7219 total_size_written > ksmbd_server_side_copy_max_total_size()) {
7220 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7224 src_fp = ksmbd_lookup_foreign_fd(work,
7225 le64_to_cpu(ci_req->ResumeKey[0]));
7226 dst_fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
7229 src_fp->persistent_id != le64_to_cpu(ci_req->ResumeKey[1])) {
7230 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
7235 rsp->hdr.Status = STATUS_FILE_CLOSED;
7240 * FILE_READ_DATA should only be included in
7241 * the FSCTL_COPYCHUNK case
7243 if (cnt_code == FSCTL_COPYCHUNK &&
7244 !(dst_fp->daccess & (FILE_READ_DATA_LE | FILE_GENERIC_READ_LE))) {
7245 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7249 ret = ksmbd_vfs_copy_file_ranges(work, src_fp, dst_fp,
7250 chunks, chunk_count,
7251 &chunk_count_written,
7252 &chunk_size_written,
7253 &total_size_written);
7256 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7258 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
7259 else if (ret == -EBADF)
7260 rsp->hdr.Status = STATUS_INVALID_HANDLE;
7261 else if (ret == -EFBIG || ret == -ENOSPC)
7262 rsp->hdr.Status = STATUS_DISK_FULL;
7263 else if (ret == -EINVAL)
7264 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7265 else if (ret == -EISDIR)
7266 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
7267 else if (ret == -E2BIG)
7268 rsp->hdr.Status = STATUS_INVALID_VIEW_SIZE;
7270 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
7273 ci_rsp->ChunksWritten = cpu_to_le32(chunk_count_written);
7274 ci_rsp->ChunkBytesWritten = cpu_to_le32(chunk_size_written);
7275 ci_rsp->TotalBytesWritten = cpu_to_le32(total_size_written);
7277 ksmbd_fd_put(work, src_fp);
7278 ksmbd_fd_put(work, dst_fp);
7282 static __be32 idev_ipv4_address(struct in_device *idev)
7286 struct in_ifaddr *ifa;
7289 in_dev_for_each_ifa_rcu(ifa, idev) {
7290 if (ifa->ifa_flags & IFA_F_SECONDARY)
7293 addr = ifa->ifa_address;
7300 static int fsctl_query_iface_info_ioctl(struct ksmbd_conn *conn,
7301 struct smb2_ioctl_rsp *rsp,
7302 unsigned int out_buf_len)
7304 struct network_interface_info_ioctl_rsp *nii_rsp = NULL;
7306 struct net_device *netdev;
7307 struct sockaddr_storage_rsp *sockaddr_storage;
7309 unsigned long long speed;
7312 for_each_netdev(&init_net, netdev) {
7313 bool ipv4_set = false;
7315 if (netdev->type == ARPHRD_LOOPBACK)
7318 flags = dev_get_flags(netdev);
7319 if (!(flags & IFF_RUNNING))
7323 nbytes + sizeof(struct network_interface_info_ioctl_rsp)) {
7328 nii_rsp = (struct network_interface_info_ioctl_rsp *)
7329 &rsp->Buffer[nbytes];
7330 nii_rsp->IfIndex = cpu_to_le32(netdev->ifindex);
7332 nii_rsp->Capability = 0;
7333 if (netdev->real_num_tx_queues > 1)
7334 nii_rsp->Capability |= cpu_to_le32(RSS_CAPABLE);
7335 if (ksmbd_rdma_capable_netdev(netdev))
7336 nii_rsp->Capability |= cpu_to_le32(RDMA_CAPABLE);
7338 nii_rsp->Next = cpu_to_le32(152);
7339 nii_rsp->Reserved = 0;
7341 if (netdev->ethtool_ops->get_link_ksettings) {
7342 struct ethtool_link_ksettings cmd;
7344 netdev->ethtool_ops->get_link_ksettings(netdev, &cmd);
7345 speed = cmd.base.speed;
7347 ksmbd_debug(SMB, "%s %s\n", netdev->name,
7348 "speed is unknown, defaulting to 1Gb/sec");
7353 nii_rsp->LinkSpeed = cpu_to_le64(speed);
7355 sockaddr_storage = (struct sockaddr_storage_rsp *)
7356 nii_rsp->SockAddr_Storage;
7357 memset(sockaddr_storage, 0, 128);
7360 struct in_device *idev;
7362 sockaddr_storage->Family = cpu_to_le16(INTERNETWORK);
7363 sockaddr_storage->addr4.Port = 0;
7365 idev = __in_dev_get_rtnl(netdev);
7368 sockaddr_storage->addr4.IPv4address =
7369 idev_ipv4_address(idev);
7370 nbytes += sizeof(struct network_interface_info_ioctl_rsp);
7374 struct inet6_dev *idev6;
7375 struct inet6_ifaddr *ifa;
7376 __u8 *ipv6_addr = sockaddr_storage->addr6.IPv6address;
7378 sockaddr_storage->Family = cpu_to_le16(INTERNETWORKV6);
7379 sockaddr_storage->addr6.Port = 0;
7380 sockaddr_storage->addr6.FlowInfo = 0;
7382 idev6 = __in6_dev_get(netdev);
7386 list_for_each_entry(ifa, &idev6->addr_list, if_list) {
7387 if (ifa->flags & (IFA_F_TENTATIVE |
7390 memcpy(ipv6_addr, ifa->addr.s6_addr, 16);
7393 sockaddr_storage->addr6.ScopeId = 0;
7394 nbytes += sizeof(struct network_interface_info_ioctl_rsp);
7399 /* zero if this is last one */
7403 rsp->PersistentFileId = SMB2_NO_FID;
7404 rsp->VolatileFileId = SMB2_NO_FID;
7408 static int fsctl_validate_negotiate_info(struct ksmbd_conn *conn,
7409 struct validate_negotiate_info_req *neg_req,
7410 struct validate_negotiate_info_rsp *neg_rsp,
7411 unsigned int in_buf_len)
7416 if (in_buf_len < offsetof(struct validate_negotiate_info_req, Dialects) +
7417 le16_to_cpu(neg_req->DialectCount) * sizeof(__le16))
7420 dialect = ksmbd_lookup_dialect_by_id(neg_req->Dialects,
7421 neg_req->DialectCount);
7422 if (dialect == BAD_PROT_ID || dialect != conn->dialect) {
7427 if (strncmp(neg_req->Guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE)) {
7432 if (le16_to_cpu(neg_req->SecurityMode) != conn->cli_sec_mode) {
7437 if (le32_to_cpu(neg_req->Capabilities) != conn->cli_cap) {
7442 neg_rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
7443 memset(neg_rsp->Guid, 0, SMB2_CLIENT_GUID_SIZE);
7444 neg_rsp->SecurityMode = cpu_to_le16(conn->srv_sec_mode);
7445 neg_rsp->Dialect = cpu_to_le16(conn->dialect);
7450 static int fsctl_query_allocated_ranges(struct ksmbd_work *work, u64 id,
7451 struct file_allocated_range_buffer *qar_req,
7452 struct file_allocated_range_buffer *qar_rsp,
7453 unsigned int in_count, unsigned int *out_count)
7455 struct ksmbd_file *fp;
7456 loff_t start, length;
7463 start = le64_to_cpu(qar_req->file_offset);
7464 length = le64_to_cpu(qar_req->length);
7466 if (start < 0 || length < 0)
7469 fp = ksmbd_lookup_fd_fast(work, id);
7473 ret = ksmbd_vfs_fqar_lseek(fp, start, length,
7474 qar_rsp, in_count, out_count);
7475 if (ret && ret != -E2BIG)
7478 ksmbd_fd_put(work, fp);
7482 static int fsctl_pipe_transceive(struct ksmbd_work *work, u64 id,
7483 unsigned int out_buf_len,
7484 struct smb2_ioctl_req *req,
7485 struct smb2_ioctl_rsp *rsp)
7487 struct ksmbd_rpc_command *rpc_resp;
7488 char *data_buf = (char *)&req->Buffer[0];
7491 rpc_resp = ksmbd_rpc_ioctl(work->sess, id, data_buf,
7492 le32_to_cpu(req->InputCount));
7494 if (rpc_resp->flags == KSMBD_RPC_SOME_NOT_MAPPED) {
7496 * set STATUS_SOME_NOT_MAPPED response
7497 * for unknown domain sid.
7499 rsp->hdr.Status = STATUS_SOME_NOT_MAPPED;
7500 } else if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
7501 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7503 } else if (rpc_resp->flags != KSMBD_RPC_OK) {
7504 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7508 nbytes = rpc_resp->payload_sz;
7509 if (rpc_resp->payload_sz > out_buf_len) {
7510 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
7511 nbytes = out_buf_len;
7514 if (!rpc_resp->payload_sz) {
7516 STATUS_UNEXPECTED_IO_ERROR;
7520 memcpy((char *)rsp->Buffer, rpc_resp->payload, nbytes);
7527 static inline int fsctl_set_sparse(struct ksmbd_work *work, u64 id,
7528 struct file_sparse *sparse)
7530 struct ksmbd_file *fp;
7531 struct mnt_idmap *idmap;
7535 fp = ksmbd_lookup_fd_fast(work, id);
7538 idmap = file_mnt_idmap(fp->filp);
7540 old_fattr = fp->f_ci->m_fattr;
7541 if (sparse->SetSparse)
7542 fp->f_ci->m_fattr |= FILE_ATTRIBUTE_SPARSE_FILE_LE;
7544 fp->f_ci->m_fattr &= ~FILE_ATTRIBUTE_SPARSE_FILE_LE;
7546 if (fp->f_ci->m_fattr != old_fattr &&
7547 test_share_config_flag(work->tcon->share_conf,
7548 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS)) {
7549 struct xattr_dos_attrib da;
7551 ret = ksmbd_vfs_get_dos_attrib_xattr(idmap,
7552 fp->filp->f_path.dentry, &da);
7556 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
7557 ret = ksmbd_vfs_set_dos_attrib_xattr(idmap,
7558 &fp->filp->f_path, &da);
7560 fp->f_ci->m_fattr = old_fattr;
7564 ksmbd_fd_put(work, fp);
7568 static int fsctl_request_resume_key(struct ksmbd_work *work,
7569 struct smb2_ioctl_req *req,
7570 struct resume_key_ioctl_rsp *key_rsp)
7572 struct ksmbd_file *fp;
7574 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
7578 memset(key_rsp, 0, sizeof(*key_rsp));
7579 key_rsp->ResumeKey[0] = req->VolatileFileId;
7580 key_rsp->ResumeKey[1] = req->PersistentFileId;
7581 ksmbd_fd_put(work, fp);
7587 * smb2_ioctl() - handler for smb2 ioctl command
7588 * @work: smb work containing ioctl command buffer
7590 * Return: 0 on success, otherwise error
7592 int smb2_ioctl(struct ksmbd_work *work)
7594 struct smb2_ioctl_req *req;
7595 struct smb2_ioctl_rsp *rsp;
7596 unsigned int cnt_code, nbytes = 0, out_buf_len, in_buf_len;
7597 u64 id = KSMBD_NO_FID;
7598 struct ksmbd_conn *conn = work->conn;
7601 if (work->next_smb2_rcv_hdr_off) {
7602 req = ksmbd_req_buf_next(work);
7603 rsp = ksmbd_resp_buf_next(work);
7604 if (!has_file_id(req->VolatileFileId)) {
7605 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
7606 work->compound_fid);
7607 id = work->compound_fid;
7610 req = smb2_get_msg(work->request_buf);
7611 rsp = smb2_get_msg(work->response_buf);
7614 if (!has_file_id(id))
7615 id = req->VolatileFileId;
7617 if (req->Flags != cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL)) {
7618 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7622 cnt_code = le32_to_cpu(req->CtlCode);
7623 ret = smb2_calc_max_out_buf_len(work, 48,
7624 le32_to_cpu(req->MaxOutputResponse));
7626 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7629 out_buf_len = (unsigned int)ret;
7630 in_buf_len = le32_to_cpu(req->InputCount);
7633 case FSCTL_DFS_GET_REFERRALS:
7634 case FSCTL_DFS_GET_REFERRALS_EX:
7635 /* Not support DFS yet */
7636 rsp->hdr.Status = STATUS_FS_DRIVER_REQUIRED;
7638 case FSCTL_CREATE_OR_GET_OBJECT_ID:
7640 struct file_object_buf_type1_ioctl_rsp *obj_buf;
7642 nbytes = sizeof(struct file_object_buf_type1_ioctl_rsp);
7643 obj_buf = (struct file_object_buf_type1_ioctl_rsp *)
7647 * TODO: This is dummy implementation to pass smbtorture
7648 * Need to check correct response later
7650 memset(obj_buf->ObjectId, 0x0, 16);
7651 memset(obj_buf->BirthVolumeId, 0x0, 16);
7652 memset(obj_buf->BirthObjectId, 0x0, 16);
7653 memset(obj_buf->DomainId, 0x0, 16);
7657 case FSCTL_PIPE_TRANSCEIVE:
7658 out_buf_len = min_t(u32, KSMBD_IPC_MAX_PAYLOAD, out_buf_len);
7659 nbytes = fsctl_pipe_transceive(work, id, out_buf_len, req, rsp);
7661 case FSCTL_VALIDATE_NEGOTIATE_INFO:
7662 if (conn->dialect < SMB30_PROT_ID) {
7667 if (in_buf_len < offsetof(struct validate_negotiate_info_req,
7673 if (out_buf_len < sizeof(struct validate_negotiate_info_rsp)) {
7678 ret = fsctl_validate_negotiate_info(conn,
7679 (struct validate_negotiate_info_req *)&req->Buffer[0],
7680 (struct validate_negotiate_info_rsp *)&rsp->Buffer[0],
7685 nbytes = sizeof(struct validate_negotiate_info_rsp);
7686 rsp->PersistentFileId = SMB2_NO_FID;
7687 rsp->VolatileFileId = SMB2_NO_FID;
7689 case FSCTL_QUERY_NETWORK_INTERFACE_INFO:
7690 ret = fsctl_query_iface_info_ioctl(conn, rsp, out_buf_len);
7695 case FSCTL_REQUEST_RESUME_KEY:
7696 if (out_buf_len < sizeof(struct resume_key_ioctl_rsp)) {
7701 ret = fsctl_request_resume_key(work, req,
7702 (struct resume_key_ioctl_rsp *)&rsp->Buffer[0]);
7705 rsp->PersistentFileId = req->PersistentFileId;
7706 rsp->VolatileFileId = req->VolatileFileId;
7707 nbytes = sizeof(struct resume_key_ioctl_rsp);
7709 case FSCTL_COPYCHUNK:
7710 case FSCTL_COPYCHUNK_WRITE:
7711 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7713 "User does not have write permission\n");
7718 if (in_buf_len < sizeof(struct copychunk_ioctl_req)) {
7723 if (out_buf_len < sizeof(struct copychunk_ioctl_rsp)) {
7728 nbytes = sizeof(struct copychunk_ioctl_rsp);
7729 rsp->VolatileFileId = req->VolatileFileId;
7730 rsp->PersistentFileId = req->PersistentFileId;
7731 fsctl_copychunk(work,
7732 (struct copychunk_ioctl_req *)&req->Buffer[0],
7733 le32_to_cpu(req->CtlCode),
7734 le32_to_cpu(req->InputCount),
7735 req->VolatileFileId,
7736 req->PersistentFileId,
7739 case FSCTL_SET_SPARSE:
7740 if (in_buf_len < sizeof(struct file_sparse)) {
7745 ret = fsctl_set_sparse(work, id,
7746 (struct file_sparse *)&req->Buffer[0]);
7750 case FSCTL_SET_ZERO_DATA:
7752 struct file_zero_data_information *zero_data;
7753 struct ksmbd_file *fp;
7754 loff_t off, len, bfz;
7756 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7758 "User does not have write permission\n");
7763 if (in_buf_len < sizeof(struct file_zero_data_information)) {
7769 (struct file_zero_data_information *)&req->Buffer[0];
7771 off = le64_to_cpu(zero_data->FileOffset);
7772 bfz = le64_to_cpu(zero_data->BeyondFinalZero);
7773 if (off < 0 || bfz < 0 || off > bfz) {
7780 fp = ksmbd_lookup_fd_fast(work, id);
7786 ret = ksmbd_vfs_zero_data(work, fp, off, len);
7787 ksmbd_fd_put(work, fp);
7793 case FSCTL_QUERY_ALLOCATED_RANGES:
7794 if (in_buf_len < sizeof(struct file_allocated_range_buffer)) {
7799 ret = fsctl_query_allocated_ranges(work, id,
7800 (struct file_allocated_range_buffer *)&req->Buffer[0],
7801 (struct file_allocated_range_buffer *)&rsp->Buffer[0],
7803 sizeof(struct file_allocated_range_buffer), &nbytes);
7804 if (ret == -E2BIG) {
7805 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
7806 } else if (ret < 0) {
7811 nbytes *= sizeof(struct file_allocated_range_buffer);
7813 case FSCTL_GET_REPARSE_POINT:
7815 struct reparse_data_buffer *reparse_ptr;
7816 struct ksmbd_file *fp;
7818 reparse_ptr = (struct reparse_data_buffer *)&rsp->Buffer[0];
7819 fp = ksmbd_lookup_fd_fast(work, id);
7821 pr_err("not found fp!!\n");
7826 reparse_ptr->ReparseTag =
7827 smb2_get_reparse_tag_special_file(file_inode(fp->filp)->i_mode);
7828 reparse_ptr->ReparseDataLength = 0;
7829 ksmbd_fd_put(work, fp);
7830 nbytes = sizeof(struct reparse_data_buffer);
7833 case FSCTL_DUPLICATE_EXTENTS_TO_FILE:
7835 struct ksmbd_file *fp_in, *fp_out = NULL;
7836 struct duplicate_extents_to_file *dup_ext;
7837 loff_t src_off, dst_off, length, cloned;
7839 if (in_buf_len < sizeof(struct duplicate_extents_to_file)) {
7844 dup_ext = (struct duplicate_extents_to_file *)&req->Buffer[0];
7846 fp_in = ksmbd_lookup_fd_slow(work, dup_ext->VolatileFileHandle,
7847 dup_ext->PersistentFileHandle);
7849 pr_err("not found file handle in duplicate extent to file\n");
7854 fp_out = ksmbd_lookup_fd_fast(work, id);
7856 pr_err("not found fp\n");
7861 src_off = le64_to_cpu(dup_ext->SourceFileOffset);
7862 dst_off = le64_to_cpu(dup_ext->TargetFileOffset);
7863 length = le64_to_cpu(dup_ext->ByteCount);
7865 * XXX: It is not clear if FSCTL_DUPLICATE_EXTENTS_TO_FILE
7866 * should fall back to vfs_copy_file_range(). This could be
7867 * beneficial when re-exporting nfs/smb mount, but note that
7868 * this can result in partial copy that returns an error status.
7869 * If/when FSCTL_DUPLICATE_EXTENTS_TO_FILE_EX is implemented,
7870 * fall back to vfs_copy_file_range(), should be avoided when
7871 * the flag DUPLICATE_EXTENTS_DATA_EX_SOURCE_ATOMIC is set.
7873 cloned = vfs_clone_file_range(fp_in->filp, src_off,
7874 fp_out->filp, dst_off, length, 0);
7875 if (cloned == -EXDEV || cloned == -EOPNOTSUPP) {
7878 } else if (cloned != length) {
7879 cloned = vfs_copy_file_range(fp_in->filp, src_off,
7880 fp_out->filp, dst_off,
7882 if (cloned != length) {
7891 ksmbd_fd_put(work, fp_in);
7892 ksmbd_fd_put(work, fp_out);
7898 ksmbd_debug(SMB, "not implemented yet ioctl command 0x%x\n",
7904 rsp->CtlCode = cpu_to_le32(cnt_code);
7905 rsp->InputCount = cpu_to_le32(0);
7906 rsp->InputOffset = cpu_to_le32(112);
7907 rsp->OutputOffset = cpu_to_le32(112);
7908 rsp->OutputCount = cpu_to_le32(nbytes);
7909 rsp->StructureSize = cpu_to_le16(49);
7910 rsp->Reserved = cpu_to_le16(0);
7911 rsp->Flags = cpu_to_le32(0);
7912 rsp->Reserved2 = cpu_to_le32(0);
7913 ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_ioctl_rsp) + nbytes);
7919 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7920 else if (ret == -ENOENT)
7921 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
7922 else if (ret == -EOPNOTSUPP)
7923 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7924 else if (ret == -ENOSPC)
7925 rsp->hdr.Status = STATUS_BUFFER_TOO_SMALL;
7926 else if (ret < 0 || rsp->hdr.Status == 0)
7927 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7928 smb2_set_err_rsp(work);
7933 * smb20_oplock_break_ack() - handler for smb2.0 oplock break command
7934 * @work: smb work containing oplock break command buffer
7938 static void smb20_oplock_break_ack(struct ksmbd_work *work)
7940 struct smb2_oplock_break *req;
7941 struct smb2_oplock_break *rsp;
7942 struct ksmbd_file *fp;
7943 struct oplock_info *opinfo = NULL;
7946 u64 volatile_id, persistent_id;
7947 char req_oplevel = 0, rsp_oplevel = 0;
7948 unsigned int oplock_change_type;
7950 WORK_BUFFERS(work, req, rsp);
7952 volatile_id = req->VolatileFid;
7953 persistent_id = req->PersistentFid;
7954 req_oplevel = req->OplockLevel;
7955 ksmbd_debug(OPLOCK, "v_id %llu, p_id %llu request oplock level %d\n",
7956 volatile_id, persistent_id, req_oplevel);
7958 fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
7960 rsp->hdr.Status = STATUS_FILE_CLOSED;
7961 smb2_set_err_rsp(work);
7965 opinfo = opinfo_get(fp);
7967 pr_err("unexpected null oplock_info\n");
7968 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
7969 smb2_set_err_rsp(work);
7970 ksmbd_fd_put(work, fp);
7974 if (opinfo->level == SMB2_OPLOCK_LEVEL_NONE) {
7975 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
7979 if (opinfo->op_state == OPLOCK_STATE_NONE) {
7980 ksmbd_debug(SMB, "unexpected oplock state 0x%x\n", opinfo->op_state);
7981 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
7985 if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
7986 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
7987 (req_oplevel != SMB2_OPLOCK_LEVEL_II &&
7988 req_oplevel != SMB2_OPLOCK_LEVEL_NONE)) {
7989 err = STATUS_INVALID_OPLOCK_PROTOCOL;
7990 oplock_change_type = OPLOCK_WRITE_TO_NONE;
7991 } else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
7992 req_oplevel != SMB2_OPLOCK_LEVEL_NONE) {
7993 err = STATUS_INVALID_OPLOCK_PROTOCOL;
7994 oplock_change_type = OPLOCK_READ_TO_NONE;
7995 } else if (req_oplevel == SMB2_OPLOCK_LEVEL_II ||
7996 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
7997 err = STATUS_INVALID_DEVICE_STATE;
7998 if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
7999 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
8000 req_oplevel == SMB2_OPLOCK_LEVEL_II) {
8001 oplock_change_type = OPLOCK_WRITE_TO_READ;
8002 } else if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
8003 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
8004 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
8005 oplock_change_type = OPLOCK_WRITE_TO_NONE;
8006 } else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
8007 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
8008 oplock_change_type = OPLOCK_READ_TO_NONE;
8010 oplock_change_type = 0;
8013 oplock_change_type = 0;
8016 switch (oplock_change_type) {
8017 case OPLOCK_WRITE_TO_READ:
8018 ret = opinfo_write_to_read(opinfo);
8019 rsp_oplevel = SMB2_OPLOCK_LEVEL_II;
8021 case OPLOCK_WRITE_TO_NONE:
8022 ret = opinfo_write_to_none(opinfo);
8023 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
8025 case OPLOCK_READ_TO_NONE:
8026 ret = opinfo_read_to_none(opinfo);
8027 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
8030 pr_err("unknown oplock change 0x%x -> 0x%x\n",
8031 opinfo->level, rsp_oplevel);
8035 rsp->hdr.Status = err;
8040 ksmbd_fd_put(work, fp);
8041 opinfo->op_state = OPLOCK_STATE_NONE;
8042 wake_up_interruptible_all(&opinfo->oplock_q);
8044 rsp->StructureSize = cpu_to_le16(24);
8045 rsp->OplockLevel = rsp_oplevel;
8048 rsp->VolatileFid = volatile_id;
8049 rsp->PersistentFid = persistent_id;
8050 ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_oplock_break));
8055 opinfo->op_state = OPLOCK_STATE_NONE;
8056 wake_up_interruptible_all(&opinfo->oplock_q);
8059 ksmbd_fd_put(work, fp);
8060 smb2_set_err_rsp(work);
8063 static int check_lease_state(struct lease *lease, __le32 req_state)
8065 if ((lease->new_state ==
8066 (SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE)) &&
8067 !(req_state & SMB2_LEASE_WRITE_CACHING_LE)) {
8068 lease->new_state = req_state;
8072 if (lease->new_state == req_state)
8079 * smb21_lease_break_ack() - handler for smb2.1 lease break command
8080 * @work: smb work containing lease break command buffer
8084 static void smb21_lease_break_ack(struct ksmbd_work *work)
8086 struct ksmbd_conn *conn = work->conn;
8087 struct smb2_lease_ack *req;
8088 struct smb2_lease_ack *rsp;
8089 struct oplock_info *opinfo;
8092 unsigned int lease_change_type;
8094 struct lease *lease;
8096 WORK_BUFFERS(work, req, rsp);
8098 ksmbd_debug(OPLOCK, "smb21 lease break, lease state(0x%x)\n",
8099 le32_to_cpu(req->LeaseState));
8100 opinfo = lookup_lease_in_table(conn, req->LeaseKey);
8102 ksmbd_debug(OPLOCK, "file not opened\n");
8103 smb2_set_err_rsp(work);
8104 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8107 lease = opinfo->o_lease;
8109 if (opinfo->op_state == OPLOCK_STATE_NONE) {
8110 pr_err("unexpected lease break state 0x%x\n",
8112 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8116 if (check_lease_state(lease, req->LeaseState)) {
8117 rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
8119 "req lease state: 0x%x, expected state: 0x%x\n",
8120 req->LeaseState, lease->new_state);
8124 if (!atomic_read(&opinfo->breaking_cnt)) {
8125 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8129 /* check for bad lease state */
8130 if (req->LeaseState &
8131 (~(SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE))) {
8132 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8133 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8134 lease_change_type = OPLOCK_WRITE_TO_NONE;
8136 lease_change_type = OPLOCK_READ_TO_NONE;
8137 ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8138 le32_to_cpu(lease->state),
8139 le32_to_cpu(req->LeaseState));
8140 } else if (lease->state == SMB2_LEASE_READ_CACHING_LE &&
8141 req->LeaseState != SMB2_LEASE_NONE_LE) {
8142 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8143 lease_change_type = OPLOCK_READ_TO_NONE;
8144 ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8145 le32_to_cpu(lease->state),
8146 le32_to_cpu(req->LeaseState));
8148 /* valid lease state changes */
8149 err = STATUS_INVALID_DEVICE_STATE;
8150 if (req->LeaseState == SMB2_LEASE_NONE_LE) {
8151 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8152 lease_change_type = OPLOCK_WRITE_TO_NONE;
8154 lease_change_type = OPLOCK_READ_TO_NONE;
8155 } else if (req->LeaseState & SMB2_LEASE_READ_CACHING_LE) {
8156 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8157 lease_change_type = OPLOCK_WRITE_TO_READ;
8159 lease_change_type = OPLOCK_READ_HANDLE_TO_READ;
8161 lease_change_type = 0;
8165 switch (lease_change_type) {
8166 case OPLOCK_WRITE_TO_READ:
8167 ret = opinfo_write_to_read(opinfo);
8169 case OPLOCK_READ_HANDLE_TO_READ:
8170 ret = opinfo_read_handle_to_read(opinfo);
8172 case OPLOCK_WRITE_TO_NONE:
8173 ret = opinfo_write_to_none(opinfo);
8175 case OPLOCK_READ_TO_NONE:
8176 ret = opinfo_read_to_none(opinfo);
8179 ksmbd_debug(OPLOCK, "unknown lease change 0x%x -> 0x%x\n",
8180 le32_to_cpu(lease->state),
8181 le32_to_cpu(req->LeaseState));
8184 lease_state = lease->state;
8185 opinfo->op_state = OPLOCK_STATE_NONE;
8186 wake_up_interruptible_all(&opinfo->oplock_q);
8187 atomic_dec(&opinfo->breaking_cnt);
8188 wake_up_interruptible_all(&opinfo->oplock_brk);
8192 rsp->hdr.Status = err;
8196 rsp->StructureSize = cpu_to_le16(36);
8199 memcpy(rsp->LeaseKey, req->LeaseKey, 16);
8200 rsp->LeaseState = lease_state;
8201 rsp->LeaseDuration = 0;
8202 ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_lease_ack));
8207 opinfo->op_state = OPLOCK_STATE_NONE;
8208 wake_up_interruptible_all(&opinfo->oplock_q);
8209 atomic_dec(&opinfo->breaking_cnt);
8210 wake_up_interruptible_all(&opinfo->oplock_brk);
8213 smb2_set_err_rsp(work);
8217 * smb2_oplock_break() - dispatcher for smb2.0 and 2.1 oplock/lease break
8218 * @work: smb work containing oplock/lease break command buffer
8222 int smb2_oplock_break(struct ksmbd_work *work)
8224 struct smb2_oplock_break *req;
8225 struct smb2_oplock_break *rsp;
8227 WORK_BUFFERS(work, req, rsp);
8229 switch (le16_to_cpu(req->StructureSize)) {
8230 case OP_BREAK_STRUCT_SIZE_20:
8231 smb20_oplock_break_ack(work);
8233 case OP_BREAK_STRUCT_SIZE_21:
8234 smb21_lease_break_ack(work);
8237 ksmbd_debug(OPLOCK, "invalid break cmd %d\n",
8238 le16_to_cpu(req->StructureSize));
8239 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8240 smb2_set_err_rsp(work);
8247 * smb2_notify() - handler for smb2 notify request
8248 * @work: smb work containing notify command buffer
8252 int smb2_notify(struct ksmbd_work *work)
8254 struct smb2_change_notify_req *req;
8255 struct smb2_change_notify_rsp *rsp;
8257 WORK_BUFFERS(work, req, rsp);
8259 if (work->next_smb2_rcv_hdr_off && req->hdr.NextCommand) {
8260 rsp->hdr.Status = STATUS_INTERNAL_ERROR;
8261 smb2_set_err_rsp(work);
8265 smb2_set_err_rsp(work);
8266 rsp->hdr.Status = STATUS_NOT_IMPLEMENTED;
8271 * smb2_is_sign_req() - handler for checking packet signing status
8272 * @work: smb work containing notify command buffer
8273 * @command: SMB2 command id
8275 * Return: true if packed is signed, false otherwise
8277 bool smb2_is_sign_req(struct ksmbd_work *work, unsigned int command)
8279 struct smb2_hdr *rcv_hdr2 = smb2_get_msg(work->request_buf);
8281 if ((rcv_hdr2->Flags & SMB2_FLAGS_SIGNED) &&
8282 command != SMB2_NEGOTIATE_HE &&
8283 command != SMB2_SESSION_SETUP_HE &&
8284 command != SMB2_OPLOCK_BREAK_HE)
8291 * smb2_check_sign_req() - handler for req packet sign processing
8292 * @work: smb work containing notify command buffer
8294 * Return: 1 on success, 0 otherwise
8296 int smb2_check_sign_req(struct ksmbd_work *work)
8298 struct smb2_hdr *hdr;
8299 char signature_req[SMB2_SIGNATURE_SIZE];
8300 char signature[SMB2_HMACSHA256_SIZE];
8304 hdr = smb2_get_msg(work->request_buf);
8305 if (work->next_smb2_rcv_hdr_off)
8306 hdr = ksmbd_req_buf_next(work);
8308 if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8309 len = get_rfc1002_len(work->request_buf);
8310 else if (hdr->NextCommand)
8311 len = le32_to_cpu(hdr->NextCommand);
8313 len = get_rfc1002_len(work->request_buf) -
8314 work->next_smb2_rcv_hdr_off;
8316 memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8317 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8319 iov[0].iov_base = (char *)&hdr->ProtocolId;
8320 iov[0].iov_len = len;
8322 if (ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, 1,
8326 if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8327 pr_err("bad smb2 signature\n");
8335 * smb2_set_sign_rsp() - handler for rsp packet sign processing
8336 * @work: smb work containing notify command buffer
8339 void smb2_set_sign_rsp(struct ksmbd_work *work)
8341 struct smb2_hdr *hdr;
8342 char signature[SMB2_HMACSHA256_SIZE];
8346 hdr = ksmbd_resp_buf_curr(work);
8347 hdr->Flags |= SMB2_FLAGS_SIGNED;
8348 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8350 if (hdr->Command == SMB2_READ) {
8351 iov = &work->iov[work->iov_idx - 1];
8354 iov = &work->iov[work->iov_idx];
8357 if (!ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, n_vec,
8359 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
8363 * smb3_check_sign_req() - handler for req packet sign processing
8364 * @work: smb work containing notify command buffer
8366 * Return: 1 on success, 0 otherwise
8368 int smb3_check_sign_req(struct ksmbd_work *work)
8370 struct ksmbd_conn *conn = work->conn;
8372 struct smb2_hdr *hdr;
8373 struct channel *chann;
8374 char signature_req[SMB2_SIGNATURE_SIZE];
8375 char signature[SMB2_CMACAES_SIZE];
8379 hdr = smb2_get_msg(work->request_buf);
8380 if (work->next_smb2_rcv_hdr_off)
8381 hdr = ksmbd_req_buf_next(work);
8383 if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8384 len = get_rfc1002_len(work->request_buf);
8385 else if (hdr->NextCommand)
8386 len = le32_to_cpu(hdr->NextCommand);
8388 len = get_rfc1002_len(work->request_buf) -
8389 work->next_smb2_rcv_hdr_off;
8391 if (le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8392 signing_key = work->sess->smb3signingkey;
8394 chann = lookup_chann_list(work->sess, conn);
8398 signing_key = chann->smb3signingkey;
8402 pr_err("SMB3 signing key is not generated\n");
8406 memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8407 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8408 iov[0].iov_base = (char *)&hdr->ProtocolId;
8409 iov[0].iov_len = len;
8411 if (ksmbd_sign_smb3_pdu(conn, signing_key, iov, 1, signature))
8414 if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8415 pr_err("bad smb2 signature\n");
8423 * smb3_set_sign_rsp() - handler for rsp packet sign processing
8424 * @work: smb work containing notify command buffer
8427 void smb3_set_sign_rsp(struct ksmbd_work *work)
8429 struct ksmbd_conn *conn = work->conn;
8430 struct smb2_hdr *hdr;
8431 struct channel *chann;
8432 char signature[SMB2_CMACAES_SIZE];
8437 hdr = ksmbd_resp_buf_curr(work);
8439 if (conn->binding == false &&
8440 le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8441 signing_key = work->sess->smb3signingkey;
8443 chann = lookup_chann_list(work->sess, work->conn);
8447 signing_key = chann->smb3signingkey;
8453 hdr->Flags |= SMB2_FLAGS_SIGNED;
8454 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8456 if (hdr->Command == SMB2_READ) {
8457 iov = &work->iov[work->iov_idx - 1];
8460 iov = &work->iov[work->iov_idx];
8463 if (!ksmbd_sign_smb3_pdu(conn, signing_key, iov, n_vec,
8465 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
8469 * smb3_preauth_hash_rsp() - handler for computing preauth hash on response
8470 * @work: smb work containing response buffer
8473 void smb3_preauth_hash_rsp(struct ksmbd_work *work)
8475 struct ksmbd_conn *conn = work->conn;
8476 struct ksmbd_session *sess = work->sess;
8477 struct smb2_hdr *req, *rsp;
8479 if (conn->dialect != SMB311_PROT_ID)
8482 WORK_BUFFERS(work, req, rsp);
8484 if (le16_to_cpu(req->Command) == SMB2_NEGOTIATE_HE &&
8486 ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
8487 conn->preauth_info->Preauth_HashValue);
8489 if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE && sess) {
8492 if (conn->binding) {
8493 struct preauth_session *preauth_sess;
8495 preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
8498 hash_value = preauth_sess->Preauth_HashValue;
8500 hash_value = sess->Preauth_HashValue;
8504 ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
8509 static void fill_transform_hdr(void *tr_buf, char *old_buf, __le16 cipher_type)
8511 struct smb2_transform_hdr *tr_hdr = tr_buf + 4;
8512 struct smb2_hdr *hdr = smb2_get_msg(old_buf);
8513 unsigned int orig_len = get_rfc1002_len(old_buf);
8515 /* tr_buf must be cleared by the caller */
8516 tr_hdr->ProtocolId = SMB2_TRANSFORM_PROTO_NUM;
8517 tr_hdr->OriginalMessageSize = cpu_to_le32(orig_len);
8518 tr_hdr->Flags = cpu_to_le16(TRANSFORM_FLAG_ENCRYPTED);
8519 if (cipher_type == SMB2_ENCRYPTION_AES128_GCM ||
8520 cipher_type == SMB2_ENCRYPTION_AES256_GCM)
8521 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_GCM_NONCE);
8523 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_CCM_NONCE);
8524 memcpy(&tr_hdr->SessionId, &hdr->SessionId, 8);
8525 inc_rfc1001_len(tr_buf, sizeof(struct smb2_transform_hdr));
8526 inc_rfc1001_len(tr_buf, orig_len);
8529 int smb3_encrypt_resp(struct ksmbd_work *work)
8531 struct kvec *iov = work->iov;
8535 tr_buf = kzalloc(sizeof(struct smb2_transform_hdr) + 4, GFP_KERNEL);
8539 /* fill transform header */
8540 fill_transform_hdr(tr_buf, work->response_buf, work->conn->cipher_type);
8542 iov[0].iov_base = tr_buf;
8543 iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
8544 work->tr_buf = tr_buf;
8546 return ksmbd_crypt_message(work, iov, work->iov_idx + 1, 1);
8549 bool smb3_is_transform_hdr(void *buf)
8551 struct smb2_transform_hdr *trhdr = smb2_get_msg(buf);
8553 return trhdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM;
8556 int smb3_decrypt_req(struct ksmbd_work *work)
8558 struct ksmbd_session *sess;
8559 char *buf = work->request_buf;
8560 unsigned int pdu_length = get_rfc1002_len(buf);
8562 int buf_data_size = pdu_length - sizeof(struct smb2_transform_hdr);
8563 struct smb2_transform_hdr *tr_hdr = smb2_get_msg(buf);
8566 if (pdu_length < sizeof(struct smb2_transform_hdr) ||
8567 buf_data_size < sizeof(struct smb2_hdr)) {
8568 pr_err("Transform message is too small (%u)\n",
8570 return -ECONNABORTED;
8573 if (buf_data_size < le32_to_cpu(tr_hdr->OriginalMessageSize)) {
8574 pr_err("Transform message is broken\n");
8575 return -ECONNABORTED;
8578 sess = ksmbd_session_lookup_all(work->conn, le64_to_cpu(tr_hdr->SessionId));
8580 pr_err("invalid session id(%llx) in transform header\n",
8581 le64_to_cpu(tr_hdr->SessionId));
8582 return -ECONNABORTED;
8585 iov[0].iov_base = buf;
8586 iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
8587 iov[1].iov_base = buf + sizeof(struct smb2_transform_hdr) + 4;
8588 iov[1].iov_len = buf_data_size;
8589 rc = ksmbd_crypt_message(work, iov, 2, 0);
8593 memmove(buf + 4, iov[1].iov_base, buf_data_size);
8594 *(__be32 *)buf = cpu_to_be32(buf_data_size);
8599 bool smb3_11_final_sess_setup_resp(struct ksmbd_work *work)
8601 struct ksmbd_conn *conn = work->conn;
8602 struct ksmbd_session *sess = work->sess;
8603 struct smb2_hdr *rsp = smb2_get_msg(work->response_buf);
8605 if (conn->dialect < SMB30_PROT_ID)
8608 if (work->next_smb2_rcv_hdr_off)
8609 rsp = ksmbd_resp_buf_next(work);
8611 if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE &&
8612 sess->user && !user_guest(sess->user) &&
8613 rsp->Status == STATUS_SUCCESS)