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 write_lock(&sess->tree_conns_lock);
1997 status.tree_conn->t_state = TREE_CONNECTED;
1998 write_unlock(&sess->tree_conns_lock);
1999 rsp->StructureSize = cpu_to_le16(16);
2001 rsp->Capabilities = 0;
2003 /* default manual caching */
2004 rsp->ShareFlags = SMB2_SHAREFLAG_MANUAL_CACHING;
2006 rc = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_tree_connect_rsp));
2008 status.ret = KSMBD_TREE_CONN_STATUS_NOMEM;
2010 if (!IS_ERR(treename))
2015 switch (status.ret) {
2016 case KSMBD_TREE_CONN_STATUS_OK:
2017 rsp->hdr.Status = STATUS_SUCCESS;
2022 case KSMBD_TREE_CONN_STATUS_NO_SHARE:
2023 rsp->hdr.Status = STATUS_BAD_NETWORK_NAME;
2026 case KSMBD_TREE_CONN_STATUS_NOMEM:
2027 rsp->hdr.Status = STATUS_NO_MEMORY;
2029 case KSMBD_TREE_CONN_STATUS_ERROR:
2030 case KSMBD_TREE_CONN_STATUS_TOO_MANY_CONNS:
2031 case KSMBD_TREE_CONN_STATUS_TOO_MANY_SESSIONS:
2032 rsp->hdr.Status = STATUS_ACCESS_DENIED;
2035 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2038 rsp->hdr.Status = STATUS_ACCESS_DENIED;
2041 if (status.ret != KSMBD_TREE_CONN_STATUS_OK)
2042 smb2_set_err_rsp(work);
2048 * smb2_create_open_flags() - convert smb open flags to unix open flags
2049 * @file_present: is file already present
2050 * @access: file access flags
2051 * @disposition: file disposition flags
2052 * @may_flags: set with MAY_ flags
2054 * Return: file open flags
2056 static int smb2_create_open_flags(bool file_present, __le32 access,
2060 int oflags = O_NONBLOCK | O_LARGEFILE;
2062 if (access & FILE_READ_DESIRED_ACCESS_LE &&
2063 access & FILE_WRITE_DESIRE_ACCESS_LE) {
2065 *may_flags = MAY_OPEN | MAY_READ | MAY_WRITE;
2066 } else if (access & FILE_WRITE_DESIRE_ACCESS_LE) {
2068 *may_flags = MAY_OPEN | MAY_WRITE;
2071 *may_flags = MAY_OPEN | MAY_READ;
2074 if (access == FILE_READ_ATTRIBUTES_LE)
2078 switch (disposition & FILE_CREATE_MASK_LE) {
2080 case FILE_CREATE_LE:
2082 case FILE_SUPERSEDE_LE:
2083 case FILE_OVERWRITE_LE:
2084 case FILE_OVERWRITE_IF_LE:
2091 switch (disposition & FILE_CREATE_MASK_LE) {
2092 case FILE_SUPERSEDE_LE:
2093 case FILE_CREATE_LE:
2094 case FILE_OPEN_IF_LE:
2095 case FILE_OVERWRITE_IF_LE:
2099 case FILE_OVERWRITE_LE:
2111 * smb2_tree_disconnect() - handler for smb tree connect request
2112 * @work: smb work containing request buffer
2116 int smb2_tree_disconnect(struct ksmbd_work *work)
2118 struct smb2_tree_disconnect_rsp *rsp;
2119 struct smb2_tree_disconnect_req *req;
2120 struct ksmbd_session *sess = work->sess;
2121 struct ksmbd_tree_connect *tcon = work->tcon;
2124 WORK_BUFFERS(work, req, rsp);
2126 ksmbd_debug(SMB, "request\n");
2129 ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
2131 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2136 ksmbd_close_tree_conn_fds(work);
2138 write_lock(&sess->tree_conns_lock);
2139 if (tcon->t_state == TREE_DISCONNECTED) {
2140 write_unlock(&sess->tree_conns_lock);
2141 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2146 WARN_ON_ONCE(atomic_dec_and_test(&tcon->refcount));
2147 tcon->t_state = TREE_DISCONNECTED;
2148 write_unlock(&sess->tree_conns_lock);
2150 err = ksmbd_tree_conn_disconnect(sess, tcon);
2152 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2158 rsp->StructureSize = cpu_to_le16(4);
2159 err = ksmbd_iov_pin_rsp(work, rsp,
2160 sizeof(struct smb2_tree_disconnect_rsp));
2162 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
2169 smb2_set_err_rsp(work);
2175 * smb2_session_logoff() - handler for session log off request
2176 * @work: smb work containing request buffer
2180 int smb2_session_logoff(struct ksmbd_work *work)
2182 struct ksmbd_conn *conn = work->conn;
2183 struct smb2_logoff_req *req;
2184 struct smb2_logoff_rsp *rsp;
2185 struct ksmbd_session *sess;
2189 WORK_BUFFERS(work, req, rsp);
2191 ksmbd_debug(SMB, "request\n");
2193 ksmbd_conn_lock(conn);
2194 if (!ksmbd_conn_good(conn)) {
2195 ksmbd_conn_unlock(conn);
2196 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2197 smb2_set_err_rsp(work);
2200 sess_id = le64_to_cpu(req->hdr.SessionId);
2201 ksmbd_all_conn_set_status(sess_id, KSMBD_SESS_NEED_RECONNECT);
2202 ksmbd_conn_unlock(conn);
2204 ksmbd_close_session_fds(work);
2205 ksmbd_conn_wait_idle(conn, sess_id);
2208 * Re-lookup session to validate if session is deleted
2209 * while waiting request complete
2211 sess = ksmbd_session_lookup_all(conn, sess_id);
2212 if (ksmbd_tree_conn_session_logoff(sess)) {
2213 ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
2214 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2215 smb2_set_err_rsp(work);
2219 ksmbd_destroy_file_table(&sess->file_table);
2220 sess->state = SMB2_SESSION_EXPIRED;
2222 ksmbd_free_user(sess->user);
2224 ksmbd_all_conn_set_status(sess_id, KSMBD_SESS_NEED_NEGOTIATE);
2226 rsp->StructureSize = cpu_to_le16(4);
2227 err = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_logoff_rsp));
2229 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
2230 smb2_set_err_rsp(work);
2237 * create_smb2_pipe() - create IPC pipe
2238 * @work: smb work containing request buffer
2240 * Return: 0 on success, otherwise error
2242 static noinline int create_smb2_pipe(struct ksmbd_work *work)
2244 struct smb2_create_rsp *rsp;
2245 struct smb2_create_req *req;
2250 WORK_BUFFERS(work, req, rsp);
2252 name = smb_strndup_from_utf16(req->Buffer, le16_to_cpu(req->NameLength),
2253 1, work->conn->local_nls);
2255 rsp->hdr.Status = STATUS_NO_MEMORY;
2256 err = PTR_ERR(name);
2260 id = ksmbd_session_rpc_open(work->sess, name);
2262 pr_err("Unable to open RPC pipe: %d\n", id);
2267 rsp->hdr.Status = STATUS_SUCCESS;
2268 rsp->StructureSize = cpu_to_le16(89);
2269 rsp->OplockLevel = SMB2_OPLOCK_LEVEL_NONE;
2271 rsp->CreateAction = cpu_to_le32(FILE_OPENED);
2273 rsp->CreationTime = cpu_to_le64(0);
2274 rsp->LastAccessTime = cpu_to_le64(0);
2275 rsp->ChangeTime = cpu_to_le64(0);
2276 rsp->AllocationSize = cpu_to_le64(0);
2277 rsp->EndofFile = cpu_to_le64(0);
2278 rsp->FileAttributes = FILE_ATTRIBUTE_NORMAL_LE;
2280 rsp->VolatileFileId = id;
2281 rsp->PersistentFileId = 0;
2282 rsp->CreateContextsOffset = 0;
2283 rsp->CreateContextsLength = 0;
2285 err = ksmbd_iov_pin_rsp(work, rsp, offsetof(struct smb2_create_rsp, Buffer));
2295 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2299 rsp->hdr.Status = STATUS_NO_MEMORY;
2306 smb2_set_err_rsp(work);
2311 * smb2_set_ea() - handler for setting extended attributes using set
2313 * @eabuf: set info command buffer
2314 * @buf_len: set info command buffer length
2315 * @path: dentry path for get ea
2317 * Return: 0 on success, otherwise error
2319 static int smb2_set_ea(struct smb2_ea_info *eabuf, unsigned int buf_len,
2320 const struct path *path)
2322 struct mnt_idmap *idmap = mnt_idmap(path->mnt);
2323 char *attr_name = NULL, *value;
2325 unsigned int next = 0;
2327 if (buf_len < sizeof(struct smb2_ea_info) + eabuf->EaNameLength +
2328 le16_to_cpu(eabuf->EaValueLength))
2331 attr_name = kmalloc(XATTR_NAME_MAX + 1, GFP_KERNEL);
2336 if (!eabuf->EaNameLength)
2340 "name : <%s>, name_len : %u, value_len : %u, next : %u\n",
2341 eabuf->name, eabuf->EaNameLength,
2342 le16_to_cpu(eabuf->EaValueLength),
2343 le32_to_cpu(eabuf->NextEntryOffset));
2345 if (eabuf->EaNameLength >
2346 (XATTR_NAME_MAX - XATTR_USER_PREFIX_LEN)) {
2351 memcpy(attr_name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN);
2352 memcpy(&attr_name[XATTR_USER_PREFIX_LEN], eabuf->name,
2353 eabuf->EaNameLength);
2354 attr_name[XATTR_USER_PREFIX_LEN + eabuf->EaNameLength] = '\0';
2355 value = (char *)&eabuf->name + eabuf->EaNameLength + 1;
2357 if (!eabuf->EaValueLength) {
2358 rc = ksmbd_vfs_casexattr_len(idmap,
2361 XATTR_USER_PREFIX_LEN +
2362 eabuf->EaNameLength);
2364 /* delete the EA only when it exits */
2366 rc = ksmbd_vfs_remove_xattr(idmap,
2372 "remove xattr failed(%d)\n",
2378 /* if the EA doesn't exist, just do nothing. */
2381 rc = ksmbd_vfs_setxattr(idmap, path, attr_name, value,
2382 le16_to_cpu(eabuf->EaValueLength), 0);
2385 "ksmbd_vfs_setxattr is failed(%d)\n",
2392 next = le32_to_cpu(eabuf->NextEntryOffset);
2393 if (next == 0 || buf_len < next)
2396 eabuf = (struct smb2_ea_info *)((char *)eabuf + next);
2397 if (buf_len < sizeof(struct smb2_ea_info)) {
2402 if (buf_len < sizeof(struct smb2_ea_info) + eabuf->EaNameLength +
2403 le16_to_cpu(eabuf->EaValueLength)) {
2407 } while (next != 0);
2413 static noinline int smb2_set_stream_name_xattr(const struct path *path,
2414 struct ksmbd_file *fp,
2415 char *stream_name, int s_type)
2417 struct mnt_idmap *idmap = mnt_idmap(path->mnt);
2418 size_t xattr_stream_size;
2419 char *xattr_stream_name;
2422 rc = ksmbd_vfs_xattr_stream_name(stream_name,
2429 fp->stream.name = xattr_stream_name;
2430 fp->stream.size = xattr_stream_size;
2432 /* Check if there is stream prefix in xattr space */
2433 rc = ksmbd_vfs_casexattr_len(idmap,
2440 if (fp->cdoption == FILE_OPEN_LE) {
2441 ksmbd_debug(SMB, "XATTR stream name lookup failed: %d\n", rc);
2445 rc = ksmbd_vfs_setxattr(idmap, path, xattr_stream_name, NULL, 0, 0);
2447 pr_err("Failed to store XATTR stream name :%d\n", rc);
2451 static int smb2_remove_smb_xattrs(const struct path *path)
2453 struct mnt_idmap *idmap = mnt_idmap(path->mnt);
2454 char *name, *xattr_list = NULL;
2455 ssize_t xattr_list_len;
2458 xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
2459 if (xattr_list_len < 0) {
2461 } else if (!xattr_list_len) {
2462 ksmbd_debug(SMB, "empty xattr in the file\n");
2466 for (name = xattr_list; name - xattr_list < xattr_list_len;
2467 name += strlen(name) + 1) {
2468 ksmbd_debug(SMB, "%s, len %zd\n", name, strlen(name));
2470 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN) &&
2471 !strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
2472 STREAM_PREFIX_LEN)) {
2473 err = ksmbd_vfs_remove_xattr(idmap, path,
2476 ksmbd_debug(SMB, "remove xattr failed : %s\n",
2485 static int smb2_create_truncate(const struct path *path)
2487 int rc = vfs_truncate(path, 0);
2490 pr_err("vfs_truncate failed, rc %d\n", rc);
2494 rc = smb2_remove_smb_xattrs(path);
2495 if (rc == -EOPNOTSUPP)
2499 "ksmbd_truncate_stream_name_xattr failed, rc %d\n",
2504 static void smb2_new_xattrs(struct ksmbd_tree_connect *tcon, const struct path *path,
2505 struct ksmbd_file *fp)
2507 struct xattr_dos_attrib da = {0};
2510 if (!test_share_config_flag(tcon->share_conf,
2511 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2515 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
2516 da.itime = da.create_time = fp->create_time;
2517 da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
2518 XATTR_DOSINFO_ITIME;
2520 rc = ksmbd_vfs_set_dos_attrib_xattr(mnt_idmap(path->mnt), path, &da);
2522 ksmbd_debug(SMB, "failed to store file attribute into xattr\n");
2525 static void smb2_update_xattrs(struct ksmbd_tree_connect *tcon,
2526 const struct path *path, struct ksmbd_file *fp)
2528 struct xattr_dos_attrib da;
2531 fp->f_ci->m_fattr &= ~(FILE_ATTRIBUTE_HIDDEN_LE | FILE_ATTRIBUTE_SYSTEM_LE);
2533 /* get FileAttributes from XATTR_NAME_DOS_ATTRIBUTE */
2534 if (!test_share_config_flag(tcon->share_conf,
2535 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2538 rc = ksmbd_vfs_get_dos_attrib_xattr(mnt_idmap(path->mnt),
2541 fp->f_ci->m_fattr = cpu_to_le32(da.attr);
2542 fp->create_time = da.create_time;
2543 fp->itime = da.itime;
2547 static int smb2_creat(struct ksmbd_work *work, struct path *parent_path,
2548 struct path *path, char *name, int open_flags,
2549 umode_t posix_mode, bool is_dir)
2551 struct ksmbd_tree_connect *tcon = work->tcon;
2552 struct ksmbd_share_config *share = tcon->share_conf;
2556 if (!(open_flags & O_CREAT))
2559 ksmbd_debug(SMB, "file does not exist, so creating\n");
2560 if (is_dir == true) {
2561 ksmbd_debug(SMB, "creating directory\n");
2563 mode = share_config_directory_mode(share, posix_mode);
2564 rc = ksmbd_vfs_mkdir(work, name, mode);
2568 ksmbd_debug(SMB, "creating regular file\n");
2570 mode = share_config_create_mode(share, posix_mode);
2571 rc = ksmbd_vfs_create(work, name, mode);
2576 rc = ksmbd_vfs_kern_path_locked(work, name, 0, parent_path, path, 0);
2578 pr_err("cannot get linux path (%s), err = %d\n",
2585 static int smb2_create_sd_buffer(struct ksmbd_work *work,
2586 struct smb2_create_req *req,
2587 const struct path *path)
2589 struct create_context *context;
2590 struct create_sd_buf_req *sd_buf;
2592 if (!req->CreateContextsOffset)
2595 /* Parse SD BUFFER create contexts */
2596 context = smb2_find_context_vals(req, SMB2_CREATE_SD_BUFFER, 4);
2599 else if (IS_ERR(context))
2600 return PTR_ERR(context);
2603 "Set ACLs using SMB2_CREATE_SD_BUFFER context\n");
2604 sd_buf = (struct create_sd_buf_req *)context;
2605 if (le16_to_cpu(context->DataOffset) +
2606 le32_to_cpu(context->DataLength) <
2607 sizeof(struct create_sd_buf_req))
2609 return set_info_sec(work->conn, work->tcon, path, &sd_buf->ntsd,
2610 le32_to_cpu(sd_buf->ccontext.DataLength), true);
2613 static void ksmbd_acls_fattr(struct smb_fattr *fattr,
2614 struct mnt_idmap *idmap,
2615 struct inode *inode)
2617 vfsuid_t vfsuid = i_uid_into_vfsuid(idmap, inode);
2618 vfsgid_t vfsgid = i_gid_into_vfsgid(idmap, inode);
2620 fattr->cf_uid = vfsuid_into_kuid(vfsuid);
2621 fattr->cf_gid = vfsgid_into_kgid(vfsgid);
2622 fattr->cf_mode = inode->i_mode;
2623 fattr->cf_acls = NULL;
2624 fattr->cf_dacls = NULL;
2626 if (IS_ENABLED(CONFIG_FS_POSIX_ACL)) {
2627 fattr->cf_acls = get_inode_acl(inode, ACL_TYPE_ACCESS);
2628 if (S_ISDIR(inode->i_mode))
2629 fattr->cf_dacls = get_inode_acl(inode, ACL_TYPE_DEFAULT);
2634 * smb2_open() - handler for smb file open request
2635 * @work: smb work containing request buffer
2637 * Return: 0 on success, otherwise error
2639 int smb2_open(struct ksmbd_work *work)
2641 struct ksmbd_conn *conn = work->conn;
2642 struct ksmbd_session *sess = work->sess;
2643 struct ksmbd_tree_connect *tcon = work->tcon;
2644 struct smb2_create_req *req;
2645 struct smb2_create_rsp *rsp;
2646 struct path path, parent_path;
2647 struct ksmbd_share_config *share = tcon->share_conf;
2648 struct ksmbd_file *fp = NULL;
2649 struct file *filp = NULL;
2650 struct mnt_idmap *idmap = NULL;
2652 struct create_context *context;
2653 struct lease_ctx_info *lc = NULL;
2654 struct create_ea_buf_req *ea_buf = NULL;
2655 struct oplock_info *opinfo;
2656 __le32 *next_ptr = NULL;
2657 int req_op_level = 0, open_flags = 0, may_flags = 0, file_info = 0;
2659 int contxt_cnt = 0, query_disk_id = 0;
2660 int maximal_access_ctxt = 0, posix_ctxt = 0;
2664 char *stream_name = NULL;
2665 bool file_present = false, created = false, already_permitted = false;
2666 int share_ret, need_truncate = 0;
2668 umode_t posix_mode = 0;
2669 __le32 daccess, maximal_access = 0;
2672 WORK_BUFFERS(work, req, rsp);
2674 if (req->hdr.NextCommand && !work->next_smb2_rcv_hdr_off &&
2675 (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
2676 ksmbd_debug(SMB, "invalid flag in chained command\n");
2677 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2678 smb2_set_err_rsp(work);
2682 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
2683 ksmbd_debug(SMB, "IPC pipe create request\n");
2684 return create_smb2_pipe(work);
2687 if (req->NameLength) {
2688 if ((req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
2689 *(char *)req->Buffer == '\\') {
2690 pr_err("not allow directory name included leading slash\n");
2695 name = smb2_get_name(req->Buffer,
2696 le16_to_cpu(req->NameLength),
2697 work->conn->local_nls);
2706 ksmbd_debug(SMB, "converted name = %s\n", name);
2707 if (strchr(name, ':')) {
2708 if (!test_share_config_flag(work->tcon->share_conf,
2709 KSMBD_SHARE_FLAG_STREAMS)) {
2713 rc = parse_stream_name(name, &stream_name, &s_type);
2718 rc = ksmbd_validate_filename(name);
2722 if (ksmbd_share_veto_filename(share, name)) {
2724 ksmbd_debug(SMB, "Reject open(), vetoed file: %s\n",
2729 name = kstrdup("", GFP_KERNEL);
2736 req_op_level = req->RequestedOplockLevel;
2737 if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE)
2738 lc = parse_lease_state(req);
2740 if (le32_to_cpu(req->ImpersonationLevel) > le32_to_cpu(IL_DELEGATE)) {
2741 pr_err("Invalid impersonationlevel : 0x%x\n",
2742 le32_to_cpu(req->ImpersonationLevel));
2744 rsp->hdr.Status = STATUS_BAD_IMPERSONATION_LEVEL;
2748 if (req->CreateOptions && !(req->CreateOptions & CREATE_OPTIONS_MASK_LE)) {
2749 pr_err("Invalid create options : 0x%x\n",
2750 le32_to_cpu(req->CreateOptions));
2754 if (req->CreateOptions & FILE_SEQUENTIAL_ONLY_LE &&
2755 req->CreateOptions & FILE_RANDOM_ACCESS_LE)
2756 req->CreateOptions = ~(FILE_SEQUENTIAL_ONLY_LE);
2758 if (req->CreateOptions &
2759 (FILE_OPEN_BY_FILE_ID_LE | CREATE_TREE_CONNECTION |
2760 FILE_RESERVE_OPFILTER_LE)) {
2765 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
2766 if (req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE) {
2769 } else if (req->CreateOptions & FILE_NO_COMPRESSION_LE) {
2770 req->CreateOptions = ~(FILE_NO_COMPRESSION_LE);
2775 if (le32_to_cpu(req->CreateDisposition) >
2776 le32_to_cpu(FILE_OVERWRITE_IF_LE)) {
2777 pr_err("Invalid create disposition : 0x%x\n",
2778 le32_to_cpu(req->CreateDisposition));
2783 if (!(req->DesiredAccess & DESIRED_ACCESS_MASK)) {
2784 pr_err("Invalid desired access : 0x%x\n",
2785 le32_to_cpu(req->DesiredAccess));
2790 if (req->FileAttributes && !(req->FileAttributes & FILE_ATTRIBUTE_MASK_LE)) {
2791 pr_err("Invalid file attribute : 0x%x\n",
2792 le32_to_cpu(req->FileAttributes));
2797 if (req->CreateContextsOffset) {
2798 /* Parse non-durable handle create contexts */
2799 context = smb2_find_context_vals(req, SMB2_CREATE_EA_BUFFER, 4);
2800 if (IS_ERR(context)) {
2801 rc = PTR_ERR(context);
2803 } else if (context) {
2804 ea_buf = (struct create_ea_buf_req *)context;
2805 if (le16_to_cpu(context->DataOffset) +
2806 le32_to_cpu(context->DataLength) <
2807 sizeof(struct create_ea_buf_req)) {
2811 if (req->CreateOptions & FILE_NO_EA_KNOWLEDGE_LE) {
2812 rsp->hdr.Status = STATUS_ACCESS_DENIED;
2818 context = smb2_find_context_vals(req,
2819 SMB2_CREATE_QUERY_MAXIMAL_ACCESS_REQUEST, 4);
2820 if (IS_ERR(context)) {
2821 rc = PTR_ERR(context);
2823 } else if (context) {
2825 "get query maximal access context\n");
2826 maximal_access_ctxt = 1;
2829 context = smb2_find_context_vals(req,
2830 SMB2_CREATE_TIMEWARP_REQUEST, 4);
2831 if (IS_ERR(context)) {
2832 rc = PTR_ERR(context);
2834 } else if (context) {
2835 ksmbd_debug(SMB, "get timewarp context\n");
2840 if (tcon->posix_extensions) {
2841 context = smb2_find_context_vals(req,
2842 SMB2_CREATE_TAG_POSIX, 16);
2843 if (IS_ERR(context)) {
2844 rc = PTR_ERR(context);
2846 } else if (context) {
2847 struct create_posix *posix =
2848 (struct create_posix *)context;
2849 if (le16_to_cpu(context->DataOffset) +
2850 le32_to_cpu(context->DataLength) <
2851 sizeof(struct create_posix) - 4) {
2855 ksmbd_debug(SMB, "get posix context\n");
2857 posix_mode = le32_to_cpu(posix->Mode);
2863 if (ksmbd_override_fsids(work)) {
2868 rc = ksmbd_vfs_kern_path_locked(work, name, LOOKUP_NO_SYMLINKS,
2869 &parent_path, &path, 1);
2871 file_present = true;
2873 if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE) {
2875 * If file exists with under flags, return access
2878 if (req->CreateDisposition == FILE_OVERWRITE_IF_LE ||
2879 req->CreateDisposition == FILE_OPEN_IF_LE) {
2884 if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
2886 "User does not have write permission\n");
2890 } else if (d_is_symlink(path.dentry)) {
2895 file_present = true;
2896 idmap = mnt_idmap(path.mnt);
2900 ksmbd_debug(SMB, "can not get linux path for %s, rc = %d\n",
2906 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
2907 if (s_type == DATA_STREAM) {
2909 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2912 if (file_present && S_ISDIR(d_inode(path.dentry)->i_mode) &&
2913 s_type == DATA_STREAM) {
2915 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
2919 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE &&
2920 req->FileAttributes & FILE_ATTRIBUTE_NORMAL_LE) {
2921 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2929 if (file_present && req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE &&
2930 S_ISDIR(d_inode(path.dentry)->i_mode) &&
2931 !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2932 ksmbd_debug(SMB, "open() argument is a directory: %s, %x\n",
2933 name, req->CreateOptions);
2934 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
2939 if (file_present && (req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
2940 !(req->CreateDisposition == FILE_CREATE_LE) &&
2941 !S_ISDIR(d_inode(path.dentry)->i_mode)) {
2942 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2947 if (!stream_name && file_present &&
2948 req->CreateDisposition == FILE_CREATE_LE) {
2953 daccess = smb_map_generic_desired_access(req->DesiredAccess);
2955 if (file_present && !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2956 rc = smb_check_perm_dacl(conn, &path, &daccess,
2962 if (daccess & FILE_MAXIMAL_ACCESS_LE) {
2963 if (!file_present) {
2964 daccess = cpu_to_le32(GENERIC_ALL_FLAGS);
2966 ksmbd_vfs_query_maximal_access(idmap,
2969 already_permitted = true;
2971 maximal_access = daccess;
2974 open_flags = smb2_create_open_flags(file_present, daccess,
2975 req->CreateDisposition,
2978 if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
2979 if (open_flags & O_CREAT) {
2981 "User does not have write permission\n");
2987 /*create file if not present */
2988 if (!file_present) {
2989 rc = smb2_creat(work, &parent_path, &path, name, open_flags,
2991 req->CreateOptions & FILE_DIRECTORY_FILE_LE);
2993 if (rc == -ENOENT) {
2995 rsp->hdr.Status = STATUS_OBJECT_PATH_NOT_FOUND;
3001 idmap = mnt_idmap(path.mnt);
3003 if (le32_to_cpu(ea_buf->ccontext.DataLength) <
3004 sizeof(struct smb2_ea_info)) {
3009 rc = smb2_set_ea(&ea_buf->ea,
3010 le32_to_cpu(ea_buf->ccontext.DataLength),
3012 if (rc == -EOPNOTSUPP)
3017 } else if (!already_permitted) {
3018 /* FILE_READ_ATTRIBUTE is allowed without inode_permission,
3019 * because execute(search) permission on a parent directory,
3020 * is already granted.
3022 if (daccess & ~(FILE_READ_ATTRIBUTES_LE | FILE_READ_CONTROL_LE)) {
3023 rc = inode_permission(idmap,
3024 d_inode(path.dentry),
3029 if ((daccess & FILE_DELETE_LE) ||
3030 (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
3031 rc = inode_permission(idmap,
3032 d_inode(path.dentry->d_parent),
3033 MAY_EXEC | MAY_WRITE);
3040 rc = ksmbd_query_inode_status(d_inode(path.dentry->d_parent));
3041 if (rc == KSMBD_INODE_STATUS_PENDING_DELETE) {
3047 filp = dentry_open(&path, open_flags, current_cred());
3050 pr_err("dentry open for dir failed, rc %d\n", rc);
3055 if (!(open_flags & O_TRUNC))
3056 file_info = FILE_OPENED;
3058 file_info = FILE_OVERWRITTEN;
3060 if ((req->CreateDisposition & FILE_CREATE_MASK_LE) ==
3062 file_info = FILE_SUPERSEDED;
3063 } else if (open_flags & O_CREAT) {
3064 file_info = FILE_CREATED;
3067 ksmbd_vfs_set_fadvise(filp, req->CreateOptions);
3069 /* Obtain Volatile-ID */
3070 fp = ksmbd_open_fd(work, filp);
3078 /* Get Persistent-ID */
3079 ksmbd_open_durable_fd(fp);
3080 if (!has_file_id(fp->persistent_id)) {
3085 fp->cdoption = req->CreateDisposition;
3086 fp->daccess = daccess;
3087 fp->saccess = req->ShareAccess;
3088 fp->coption = req->CreateOptions;
3090 /* Set default windows and posix acls if creating new file */
3093 struct inode *inode = d_inode(path.dentry);
3095 posix_acl_rc = ksmbd_vfs_inherit_posix_acl(idmap,
3097 d_inode(path.dentry->d_parent));
3099 ksmbd_debug(SMB, "inherit posix acl failed : %d\n", posix_acl_rc);
3101 if (test_share_config_flag(work->tcon->share_conf,
3102 KSMBD_SHARE_FLAG_ACL_XATTR)) {
3103 rc = smb_inherit_dacl(conn, &path, sess->user->uid,
3108 rc = smb2_create_sd_buffer(work, req, &path);
3111 ksmbd_vfs_set_init_posix_acl(idmap,
3114 if (test_share_config_flag(work->tcon->share_conf,
3115 KSMBD_SHARE_FLAG_ACL_XATTR)) {
3116 struct smb_fattr fattr;
3117 struct smb_ntsd *pntsd;
3118 int pntsd_size, ace_num = 0;
3120 ksmbd_acls_fattr(&fattr, idmap, inode);
3122 ace_num = fattr.cf_acls->a_count;
3124 ace_num += fattr.cf_dacls->a_count;
3126 pntsd = kmalloc(sizeof(struct smb_ntsd) +
3127 sizeof(struct smb_sid) * 3 +
3128 sizeof(struct smb_acl) +
3129 sizeof(struct smb_ace) * ace_num * 2,
3132 posix_acl_release(fattr.cf_acls);
3133 posix_acl_release(fattr.cf_dacls);
3137 rc = build_sec_desc(idmap,
3142 &pntsd_size, &fattr);
3143 posix_acl_release(fattr.cf_acls);
3144 posix_acl_release(fattr.cf_dacls);
3150 rc = ksmbd_vfs_set_sd_xattr(conn,
3157 pr_err("failed to store ntacl in xattr : %d\n",
3166 rc = smb2_set_stream_name_xattr(&path,
3172 file_info = FILE_CREATED;
3175 fp->attrib_only = !(req->DesiredAccess & ~(FILE_READ_ATTRIBUTES_LE |
3176 FILE_WRITE_ATTRIBUTES_LE | FILE_SYNCHRONIZE_LE));
3177 if (!S_ISDIR(file_inode(filp)->i_mode) && open_flags & O_TRUNC &&
3178 !fp->attrib_only && !stream_name) {
3179 smb_break_all_oplock(work, fp);
3183 /* fp should be searchable through ksmbd_inode.m_fp_list
3184 * after daccess, saccess, attrib_only, and stream are
3187 write_lock(&fp->f_ci->m_lock);
3188 list_add(&fp->node, &fp->f_ci->m_fp_list);
3189 write_unlock(&fp->f_ci->m_lock);
3191 /* Check delete pending among previous fp before oplock break */
3192 if (ksmbd_inode_pending_delete(fp)) {
3197 share_ret = ksmbd_smb_check_shared_mode(fp->filp, fp);
3198 if (!test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_OPLOCKS) ||
3199 (req_op_level == SMB2_OPLOCK_LEVEL_LEASE &&
3200 !(conn->vals->capabilities & SMB2_GLOBAL_CAP_LEASING))) {
3201 if (share_ret < 0 && !S_ISDIR(file_inode(fp->filp)->i_mode)) {
3206 if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE) {
3207 req_op_level = smb2_map_lease_to_oplock(lc->req_state);
3209 "lease req for(%s) req oplock state 0x%x, lease state 0x%x\n",
3210 name, req_op_level, lc->req_state);
3211 rc = find_same_lease_key(sess, fp->f_ci, lc);
3214 } else if (open_flags == O_RDONLY &&
3215 (req_op_level == SMB2_OPLOCK_LEVEL_BATCH ||
3216 req_op_level == SMB2_OPLOCK_LEVEL_EXCLUSIVE))
3217 req_op_level = SMB2_OPLOCK_LEVEL_II;
3219 rc = smb_grant_oplock(work, req_op_level,
3220 fp->persistent_id, fp,
3221 le32_to_cpu(req->hdr.Id.SyncId.TreeId),
3227 if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)
3228 ksmbd_fd_set_delete_on_close(fp, file_info);
3230 if (need_truncate) {
3231 rc = smb2_create_truncate(&path);
3236 if (req->CreateContextsOffset) {
3237 struct create_alloc_size_req *az_req;
3239 az_req = (struct create_alloc_size_req *)smb2_find_context_vals(req,
3240 SMB2_CREATE_ALLOCATION_SIZE, 4);
3241 if (IS_ERR(az_req)) {
3242 rc = PTR_ERR(az_req);
3244 } else if (az_req) {
3248 if (le16_to_cpu(az_req->ccontext.DataOffset) +
3249 le32_to_cpu(az_req->ccontext.DataLength) <
3250 sizeof(struct create_alloc_size_req)) {
3254 alloc_size = le64_to_cpu(az_req->AllocationSize);
3256 "request smb2 create allocate size : %llu\n",
3258 smb_break_all_levII_oplock(work, fp, 1);
3259 err = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
3263 "vfs_fallocate is failed : %d\n",
3267 context = smb2_find_context_vals(req, SMB2_CREATE_QUERY_ON_DISK_ID, 4);
3268 if (IS_ERR(context)) {
3269 rc = PTR_ERR(context);
3271 } else if (context) {
3272 ksmbd_debug(SMB, "get query on disk id context\n");
3277 rc = ksmbd_vfs_getattr(&path, &stat);
3281 if (stat.result_mask & STATX_BTIME)
3282 fp->create_time = ksmbd_UnixTimeToNT(stat.btime);
3284 fp->create_time = ksmbd_UnixTimeToNT(stat.ctime);
3285 if (req->FileAttributes || fp->f_ci->m_fattr == 0)
3287 cpu_to_le32(smb2_get_dos_mode(&stat, le32_to_cpu(req->FileAttributes)));
3290 smb2_update_xattrs(tcon, &path, fp);
3292 smb2_new_xattrs(tcon, &path, fp);
3294 memcpy(fp->client_guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE);
3296 rsp->StructureSize = cpu_to_le16(89);
3298 opinfo = rcu_dereference(fp->f_opinfo);
3299 rsp->OplockLevel = opinfo != NULL ? opinfo->level : 0;
3302 rsp->CreateAction = cpu_to_le32(file_info);
3303 rsp->CreationTime = cpu_to_le64(fp->create_time);
3304 time = ksmbd_UnixTimeToNT(stat.atime);
3305 rsp->LastAccessTime = cpu_to_le64(time);
3306 time = ksmbd_UnixTimeToNT(stat.mtime);
3307 rsp->LastWriteTime = cpu_to_le64(time);
3308 time = ksmbd_UnixTimeToNT(stat.ctime);
3309 rsp->ChangeTime = cpu_to_le64(time);
3310 rsp->AllocationSize = S_ISDIR(stat.mode) ? 0 :
3311 cpu_to_le64(stat.blocks << 9);
3312 rsp->EndofFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
3313 rsp->FileAttributes = fp->f_ci->m_fattr;
3317 rsp->PersistentFileId = fp->persistent_id;
3318 rsp->VolatileFileId = fp->volatile_id;
3320 rsp->CreateContextsOffset = 0;
3321 rsp->CreateContextsLength = 0;
3322 iov_len = offsetof(struct smb2_create_rsp, Buffer);
3324 /* If lease is request send lease context response */
3325 if (opinfo && opinfo->is_lease) {
3326 struct create_context *lease_ccontext;
3328 ksmbd_debug(SMB, "lease granted on(%s) lease state 0x%x\n",
3329 name, opinfo->o_lease->state);
3330 rsp->OplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
3332 lease_ccontext = (struct create_context *)rsp->Buffer;
3334 create_lease_buf(rsp->Buffer, opinfo->o_lease);
3335 le32_add_cpu(&rsp->CreateContextsLength,
3336 conn->vals->create_lease_size);
3337 iov_len += conn->vals->create_lease_size;
3338 next_ptr = &lease_ccontext->Next;
3339 next_off = conn->vals->create_lease_size;
3342 if (maximal_access_ctxt) {
3343 struct create_context *mxac_ccontext;
3345 if (maximal_access == 0)
3346 ksmbd_vfs_query_maximal_access(idmap,
3349 mxac_ccontext = (struct create_context *)(rsp->Buffer +
3350 le32_to_cpu(rsp->CreateContextsLength));
3352 create_mxac_rsp_buf(rsp->Buffer +
3353 le32_to_cpu(rsp->CreateContextsLength),
3354 le32_to_cpu(maximal_access));
3355 le32_add_cpu(&rsp->CreateContextsLength,
3356 conn->vals->create_mxac_size);
3357 iov_len += conn->vals->create_mxac_size;
3359 *next_ptr = cpu_to_le32(next_off);
3360 next_ptr = &mxac_ccontext->Next;
3361 next_off = conn->vals->create_mxac_size;
3364 if (query_disk_id) {
3365 struct create_context *disk_id_ccontext;
3367 disk_id_ccontext = (struct create_context *)(rsp->Buffer +
3368 le32_to_cpu(rsp->CreateContextsLength));
3370 create_disk_id_rsp_buf(rsp->Buffer +
3371 le32_to_cpu(rsp->CreateContextsLength),
3372 stat.ino, tcon->id);
3373 le32_add_cpu(&rsp->CreateContextsLength,
3374 conn->vals->create_disk_id_size);
3375 iov_len += conn->vals->create_disk_id_size;
3377 *next_ptr = cpu_to_le32(next_off);
3378 next_ptr = &disk_id_ccontext->Next;
3379 next_off = conn->vals->create_disk_id_size;
3384 create_posix_rsp_buf(rsp->Buffer +
3385 le32_to_cpu(rsp->CreateContextsLength),
3387 le32_add_cpu(&rsp->CreateContextsLength,
3388 conn->vals->create_posix_size);
3389 iov_len += conn->vals->create_posix_size;
3391 *next_ptr = cpu_to_le32(next_off);
3394 if (contxt_cnt > 0) {
3395 rsp->CreateContextsOffset =
3396 cpu_to_le32(offsetof(struct smb2_create_rsp, Buffer));
3400 if (file_present || created) {
3401 inode_unlock(d_inode(parent_path.dentry));
3403 path_put(&parent_path);
3405 ksmbd_revert_fsids(work);
3408 ksmbd_update_fstate(&work->sess->file_table, fp, FP_INITED);
3409 rc = ksmbd_iov_pin_rsp(work, (void *)rsp, iov_len);
3413 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
3414 else if (rc == -EOPNOTSUPP)
3415 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
3416 else if (rc == -EACCES || rc == -ESTALE || rc == -EXDEV)
3417 rsp->hdr.Status = STATUS_ACCESS_DENIED;
3418 else if (rc == -ENOENT)
3419 rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
3420 else if (rc == -EPERM)
3421 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
3422 else if (rc == -EBUSY)
3423 rsp->hdr.Status = STATUS_DELETE_PENDING;
3424 else if (rc == -EBADF)
3425 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
3426 else if (rc == -ENOEXEC)
3427 rsp->hdr.Status = STATUS_DUPLICATE_OBJECTID;
3428 else if (rc == -ENXIO)
3429 rsp->hdr.Status = STATUS_NO_SUCH_DEVICE;
3430 else if (rc == -EEXIST)
3431 rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
3432 else if (rc == -EMFILE)
3433 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
3434 if (!rsp->hdr.Status)
3435 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
3438 ksmbd_fd_put(work, fp);
3439 smb2_set_err_rsp(work);
3440 ksmbd_debug(SMB, "Error response: %x\n", rsp->hdr.Status);
3449 static int readdir_info_level_struct_sz(int info_level)
3451 switch (info_level) {
3452 case FILE_FULL_DIRECTORY_INFORMATION:
3453 return sizeof(struct file_full_directory_info);
3454 case FILE_BOTH_DIRECTORY_INFORMATION:
3455 return sizeof(struct file_both_directory_info);
3456 case FILE_DIRECTORY_INFORMATION:
3457 return sizeof(struct file_directory_info);
3458 case FILE_NAMES_INFORMATION:
3459 return sizeof(struct file_names_info);
3460 case FILEID_FULL_DIRECTORY_INFORMATION:
3461 return sizeof(struct file_id_full_dir_info);
3462 case FILEID_BOTH_DIRECTORY_INFORMATION:
3463 return sizeof(struct file_id_both_directory_info);
3464 case SMB_FIND_FILE_POSIX_INFO:
3465 return sizeof(struct smb2_posix_info);
3471 static int dentry_name(struct ksmbd_dir_info *d_info, int info_level)
3473 switch (info_level) {
3474 case FILE_FULL_DIRECTORY_INFORMATION:
3476 struct file_full_directory_info *ffdinfo;
3478 ffdinfo = (struct file_full_directory_info *)d_info->rptr;
3479 d_info->rptr += le32_to_cpu(ffdinfo->NextEntryOffset);
3480 d_info->name = ffdinfo->FileName;
3481 d_info->name_len = le32_to_cpu(ffdinfo->FileNameLength);
3484 case FILE_BOTH_DIRECTORY_INFORMATION:
3486 struct file_both_directory_info *fbdinfo;
3488 fbdinfo = (struct file_both_directory_info *)d_info->rptr;
3489 d_info->rptr += le32_to_cpu(fbdinfo->NextEntryOffset);
3490 d_info->name = fbdinfo->FileName;
3491 d_info->name_len = le32_to_cpu(fbdinfo->FileNameLength);
3494 case FILE_DIRECTORY_INFORMATION:
3496 struct file_directory_info *fdinfo;
3498 fdinfo = (struct file_directory_info *)d_info->rptr;
3499 d_info->rptr += le32_to_cpu(fdinfo->NextEntryOffset);
3500 d_info->name = fdinfo->FileName;
3501 d_info->name_len = le32_to_cpu(fdinfo->FileNameLength);
3504 case FILE_NAMES_INFORMATION:
3506 struct file_names_info *fninfo;
3508 fninfo = (struct file_names_info *)d_info->rptr;
3509 d_info->rptr += le32_to_cpu(fninfo->NextEntryOffset);
3510 d_info->name = fninfo->FileName;
3511 d_info->name_len = le32_to_cpu(fninfo->FileNameLength);
3514 case FILEID_FULL_DIRECTORY_INFORMATION:
3516 struct file_id_full_dir_info *dinfo;
3518 dinfo = (struct file_id_full_dir_info *)d_info->rptr;
3519 d_info->rptr += le32_to_cpu(dinfo->NextEntryOffset);
3520 d_info->name = dinfo->FileName;
3521 d_info->name_len = le32_to_cpu(dinfo->FileNameLength);
3524 case FILEID_BOTH_DIRECTORY_INFORMATION:
3526 struct file_id_both_directory_info *fibdinfo;
3528 fibdinfo = (struct file_id_both_directory_info *)d_info->rptr;
3529 d_info->rptr += le32_to_cpu(fibdinfo->NextEntryOffset);
3530 d_info->name = fibdinfo->FileName;
3531 d_info->name_len = le32_to_cpu(fibdinfo->FileNameLength);
3534 case SMB_FIND_FILE_POSIX_INFO:
3536 struct smb2_posix_info *posix_info;
3538 posix_info = (struct smb2_posix_info *)d_info->rptr;
3539 d_info->rptr += le32_to_cpu(posix_info->NextEntryOffset);
3540 d_info->name = posix_info->name;
3541 d_info->name_len = le32_to_cpu(posix_info->name_len);
3550 * smb2_populate_readdir_entry() - encode directory entry in smb2 response
3552 * @conn: connection instance
3553 * @info_level: smb information level
3554 * @d_info: structure included variables for query dir
3555 * @ksmbd_kstat: ksmbd wrapper of dirent stat information
3557 * if directory has many entries, find first can't read it fully.
3558 * find next might be called multiple times to read remaining dir entries
3560 * Return: 0 on success, otherwise error
3562 static int smb2_populate_readdir_entry(struct ksmbd_conn *conn, int info_level,
3563 struct ksmbd_dir_info *d_info,
3564 struct ksmbd_kstat *ksmbd_kstat)
3566 int next_entry_offset = 0;
3570 int struct_sz, rc = 0;
3572 conv_name = ksmbd_convert_dir_info_name(d_info,
3578 /* Somehow the name has only terminating NULL bytes */
3581 goto free_conv_name;
3584 struct_sz = readdir_info_level_struct_sz(info_level) + conv_len;
3585 next_entry_offset = ALIGN(struct_sz, KSMBD_DIR_INFO_ALIGNMENT);
3586 d_info->last_entry_off_align = next_entry_offset - struct_sz;
3588 if (next_entry_offset > d_info->out_buf_len) {
3589 d_info->out_buf_len = 0;
3591 goto free_conv_name;
3594 kstat = d_info->wptr;
3595 if (info_level != FILE_NAMES_INFORMATION)
3596 kstat = ksmbd_vfs_init_kstat(&d_info->wptr, ksmbd_kstat);
3598 switch (info_level) {
3599 case FILE_FULL_DIRECTORY_INFORMATION:
3601 struct file_full_directory_info *ffdinfo;
3603 ffdinfo = (struct file_full_directory_info *)kstat;
3604 ffdinfo->FileNameLength = cpu_to_le32(conv_len);
3606 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3607 if (ffdinfo->EaSize)
3608 ffdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3609 if (d_info->hide_dot_file && d_info->name[0] == '.')
3610 ffdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3611 memcpy(ffdinfo->FileName, conv_name, conv_len);
3612 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3615 case FILE_BOTH_DIRECTORY_INFORMATION:
3617 struct file_both_directory_info *fbdinfo;
3619 fbdinfo = (struct file_both_directory_info *)kstat;
3620 fbdinfo->FileNameLength = cpu_to_le32(conv_len);
3622 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3623 if (fbdinfo->EaSize)
3624 fbdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3625 fbdinfo->ShortNameLength = 0;
3626 fbdinfo->Reserved = 0;
3627 if (d_info->hide_dot_file && d_info->name[0] == '.')
3628 fbdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3629 memcpy(fbdinfo->FileName, conv_name, conv_len);
3630 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3633 case FILE_DIRECTORY_INFORMATION:
3635 struct file_directory_info *fdinfo;
3637 fdinfo = (struct file_directory_info *)kstat;
3638 fdinfo->FileNameLength = cpu_to_le32(conv_len);
3639 if (d_info->hide_dot_file && d_info->name[0] == '.')
3640 fdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3641 memcpy(fdinfo->FileName, conv_name, conv_len);
3642 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3645 case FILE_NAMES_INFORMATION:
3647 struct file_names_info *fninfo;
3649 fninfo = (struct file_names_info *)kstat;
3650 fninfo->FileNameLength = cpu_to_le32(conv_len);
3651 memcpy(fninfo->FileName, conv_name, conv_len);
3652 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3655 case FILEID_FULL_DIRECTORY_INFORMATION:
3657 struct file_id_full_dir_info *dinfo;
3659 dinfo = (struct file_id_full_dir_info *)kstat;
3660 dinfo->FileNameLength = cpu_to_le32(conv_len);
3662 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3664 dinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3665 dinfo->Reserved = 0;
3666 dinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
3667 if (d_info->hide_dot_file && d_info->name[0] == '.')
3668 dinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3669 memcpy(dinfo->FileName, conv_name, conv_len);
3670 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3673 case FILEID_BOTH_DIRECTORY_INFORMATION:
3675 struct file_id_both_directory_info *fibdinfo;
3677 fibdinfo = (struct file_id_both_directory_info *)kstat;
3678 fibdinfo->FileNameLength = cpu_to_le32(conv_len);
3680 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3681 if (fibdinfo->EaSize)
3682 fibdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3683 fibdinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
3684 fibdinfo->ShortNameLength = 0;
3685 fibdinfo->Reserved = 0;
3686 fibdinfo->Reserved2 = cpu_to_le16(0);
3687 if (d_info->hide_dot_file && d_info->name[0] == '.')
3688 fibdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3689 memcpy(fibdinfo->FileName, conv_name, conv_len);
3690 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3693 case SMB_FIND_FILE_POSIX_INFO:
3695 struct smb2_posix_info *posix_info;
3698 posix_info = (struct smb2_posix_info *)kstat;
3699 posix_info->Ignored = 0;
3700 posix_info->CreationTime = cpu_to_le64(ksmbd_kstat->create_time);
3701 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->ctime);
3702 posix_info->ChangeTime = cpu_to_le64(time);
3703 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->atime);
3704 posix_info->LastAccessTime = cpu_to_le64(time);
3705 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->mtime);
3706 posix_info->LastWriteTime = cpu_to_le64(time);
3707 posix_info->EndOfFile = cpu_to_le64(ksmbd_kstat->kstat->size);
3708 posix_info->AllocationSize = cpu_to_le64(ksmbd_kstat->kstat->blocks << 9);
3709 posix_info->DeviceId = cpu_to_le32(ksmbd_kstat->kstat->rdev);
3710 posix_info->HardLinks = cpu_to_le32(ksmbd_kstat->kstat->nlink);
3711 posix_info->Mode = cpu_to_le32(ksmbd_kstat->kstat->mode & 0777);
3712 posix_info->Inode = cpu_to_le64(ksmbd_kstat->kstat->ino);
3713 posix_info->DosAttributes =
3714 S_ISDIR(ksmbd_kstat->kstat->mode) ?
3715 FILE_ATTRIBUTE_DIRECTORY_LE : FILE_ATTRIBUTE_ARCHIVE_LE;
3716 if (d_info->hide_dot_file && d_info->name[0] == '.')
3717 posix_info->DosAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3719 * SidBuffer(32) contain two sids(Domain sid(16), UNIX group sid(16)).
3720 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) +
3721 * sub_auth(4 * 1(num_subauth)) + RID(4).
3723 id_to_sid(from_kuid_munged(&init_user_ns, ksmbd_kstat->kstat->uid),
3724 SIDUNIX_USER, (struct smb_sid *)&posix_info->SidBuffer[0]);
3725 id_to_sid(from_kgid_munged(&init_user_ns, ksmbd_kstat->kstat->gid),
3726 SIDUNIX_GROUP, (struct smb_sid *)&posix_info->SidBuffer[16]);
3727 memcpy(posix_info->name, conv_name, conv_len);
3728 posix_info->name_len = cpu_to_le32(conv_len);
3729 posix_info->NextEntryOffset = cpu_to_le32(next_entry_offset);
3733 } /* switch (info_level) */
3735 d_info->last_entry_offset = d_info->data_count;
3736 d_info->data_count += next_entry_offset;
3737 d_info->out_buf_len -= next_entry_offset;
3738 d_info->wptr += next_entry_offset;
3741 "info_level : %d, buf_len :%d, next_offset : %d, data_count : %d\n",
3742 info_level, d_info->out_buf_len,
3743 next_entry_offset, d_info->data_count);
3750 struct smb2_query_dir_private {
3751 struct ksmbd_work *work;
3752 char *search_pattern;
3753 struct ksmbd_file *dir_fp;
3755 struct ksmbd_dir_info *d_info;
3759 static void lock_dir(struct ksmbd_file *dir_fp)
3761 struct dentry *dir = dir_fp->filp->f_path.dentry;
3763 inode_lock_nested(d_inode(dir), I_MUTEX_PARENT);
3766 static void unlock_dir(struct ksmbd_file *dir_fp)
3768 struct dentry *dir = dir_fp->filp->f_path.dentry;
3770 inode_unlock(d_inode(dir));
3773 static int process_query_dir_entries(struct smb2_query_dir_private *priv)
3775 struct mnt_idmap *idmap = file_mnt_idmap(priv->dir_fp->filp);
3777 struct ksmbd_kstat ksmbd_kstat;
3781 for (i = 0; i < priv->d_info->num_entry; i++) {
3782 struct dentry *dent;
3784 if (dentry_name(priv->d_info, priv->info_level))
3787 lock_dir(priv->dir_fp);
3788 dent = lookup_one(idmap, priv->d_info->name,
3789 priv->dir_fp->filp->f_path.dentry,
3790 priv->d_info->name_len);
3791 unlock_dir(priv->dir_fp);
3794 ksmbd_debug(SMB, "Cannot lookup `%s' [%ld]\n",
3799 if (unlikely(d_is_negative(dent))) {
3801 ksmbd_debug(SMB, "Negative dentry `%s'\n",
3802 priv->d_info->name);
3806 ksmbd_kstat.kstat = &kstat;
3807 if (priv->info_level != FILE_NAMES_INFORMATION)
3808 ksmbd_vfs_fill_dentry_attrs(priv->work,
3813 rc = smb2_populate_readdir_entry(priv->work->conn,
3824 static int reserve_populate_dentry(struct ksmbd_dir_info *d_info,
3829 int next_entry_offset;
3831 struct_sz = readdir_info_level_struct_sz(info_level);
3832 if (struct_sz == -EOPNOTSUPP)
3835 conv_len = (d_info->name_len + 1) * 2;
3836 next_entry_offset = ALIGN(struct_sz + conv_len,
3837 KSMBD_DIR_INFO_ALIGNMENT);
3839 if (next_entry_offset > d_info->out_buf_len) {
3840 d_info->out_buf_len = 0;
3844 switch (info_level) {
3845 case FILE_FULL_DIRECTORY_INFORMATION:
3847 struct file_full_directory_info *ffdinfo;
3849 ffdinfo = (struct file_full_directory_info *)d_info->wptr;
3850 memcpy(ffdinfo->FileName, d_info->name, d_info->name_len);
3851 ffdinfo->FileName[d_info->name_len] = 0x00;
3852 ffdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3853 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3856 case FILE_BOTH_DIRECTORY_INFORMATION:
3858 struct file_both_directory_info *fbdinfo;
3860 fbdinfo = (struct file_both_directory_info *)d_info->wptr;
3861 memcpy(fbdinfo->FileName, d_info->name, d_info->name_len);
3862 fbdinfo->FileName[d_info->name_len] = 0x00;
3863 fbdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3864 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3867 case FILE_DIRECTORY_INFORMATION:
3869 struct file_directory_info *fdinfo;
3871 fdinfo = (struct file_directory_info *)d_info->wptr;
3872 memcpy(fdinfo->FileName, d_info->name, d_info->name_len);
3873 fdinfo->FileName[d_info->name_len] = 0x00;
3874 fdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3875 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3878 case FILE_NAMES_INFORMATION:
3880 struct file_names_info *fninfo;
3882 fninfo = (struct file_names_info *)d_info->wptr;
3883 memcpy(fninfo->FileName, d_info->name, d_info->name_len);
3884 fninfo->FileName[d_info->name_len] = 0x00;
3885 fninfo->FileNameLength = cpu_to_le32(d_info->name_len);
3886 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3889 case FILEID_FULL_DIRECTORY_INFORMATION:
3891 struct file_id_full_dir_info *dinfo;
3893 dinfo = (struct file_id_full_dir_info *)d_info->wptr;
3894 memcpy(dinfo->FileName, d_info->name, d_info->name_len);
3895 dinfo->FileName[d_info->name_len] = 0x00;
3896 dinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3897 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3900 case FILEID_BOTH_DIRECTORY_INFORMATION:
3902 struct file_id_both_directory_info *fibdinfo;
3904 fibdinfo = (struct file_id_both_directory_info *)d_info->wptr;
3905 memcpy(fibdinfo->FileName, d_info->name, d_info->name_len);
3906 fibdinfo->FileName[d_info->name_len] = 0x00;
3907 fibdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3908 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3911 case SMB_FIND_FILE_POSIX_INFO:
3913 struct smb2_posix_info *posix_info;
3915 posix_info = (struct smb2_posix_info *)d_info->wptr;
3916 memcpy(posix_info->name, d_info->name, d_info->name_len);
3917 posix_info->name[d_info->name_len] = 0x00;
3918 posix_info->name_len = cpu_to_le32(d_info->name_len);
3919 posix_info->NextEntryOffset =
3920 cpu_to_le32(next_entry_offset);
3923 } /* switch (info_level) */
3925 d_info->num_entry++;
3926 d_info->out_buf_len -= next_entry_offset;
3927 d_info->wptr += next_entry_offset;
3931 static bool __query_dir(struct dir_context *ctx, const char *name, int namlen,
3932 loff_t offset, u64 ino, unsigned int d_type)
3934 struct ksmbd_readdir_data *buf;
3935 struct smb2_query_dir_private *priv;
3936 struct ksmbd_dir_info *d_info;
3939 buf = container_of(ctx, struct ksmbd_readdir_data, ctx);
3940 priv = buf->private;
3941 d_info = priv->d_info;
3943 /* dot and dotdot entries are already reserved */
3944 if (!strcmp(".", name) || !strcmp("..", name))
3946 if (ksmbd_share_veto_filename(priv->work->tcon->share_conf, name))
3948 if (!match_pattern(name, namlen, priv->search_pattern))
3951 d_info->name = name;
3952 d_info->name_len = namlen;
3953 rc = reserve_populate_dentry(d_info, priv->info_level);
3956 if (d_info->flags & SMB2_RETURN_SINGLE_ENTRY)
3957 d_info->out_buf_len = 0;
3961 static int verify_info_level(int info_level)
3963 switch (info_level) {
3964 case FILE_FULL_DIRECTORY_INFORMATION:
3965 case FILE_BOTH_DIRECTORY_INFORMATION:
3966 case FILE_DIRECTORY_INFORMATION:
3967 case FILE_NAMES_INFORMATION:
3968 case FILEID_FULL_DIRECTORY_INFORMATION:
3969 case FILEID_BOTH_DIRECTORY_INFORMATION:
3970 case SMB_FIND_FILE_POSIX_INFO:
3979 static int smb2_resp_buf_len(struct ksmbd_work *work, unsigned short hdr2_len)
3983 free_len = (int)(work->response_sz -
3984 (get_rfc1002_len(work->response_buf) + 4)) - hdr2_len;
3988 static int smb2_calc_max_out_buf_len(struct ksmbd_work *work,
3989 unsigned short hdr2_len,
3990 unsigned int out_buf_len)
3994 if (out_buf_len > work->conn->vals->max_trans_size)
3997 free_len = smb2_resp_buf_len(work, hdr2_len);
4001 return min_t(int, out_buf_len, free_len);
4004 int smb2_query_dir(struct ksmbd_work *work)
4006 struct ksmbd_conn *conn = work->conn;
4007 struct smb2_query_directory_req *req;
4008 struct smb2_query_directory_rsp *rsp;
4009 struct ksmbd_share_config *share = work->tcon->share_conf;
4010 struct ksmbd_file *dir_fp = NULL;
4011 struct ksmbd_dir_info d_info;
4013 char *srch_ptr = NULL;
4014 unsigned char srch_flag;
4016 struct smb2_query_dir_private query_dir_private = {NULL, };
4018 WORK_BUFFERS(work, req, rsp);
4020 if (ksmbd_override_fsids(work)) {
4021 rsp->hdr.Status = STATUS_NO_MEMORY;
4022 smb2_set_err_rsp(work);
4026 rc = verify_info_level(req->FileInformationClass);
4032 dir_fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
4038 if (!(dir_fp->daccess & FILE_LIST_DIRECTORY_LE) ||
4039 inode_permission(file_mnt_idmap(dir_fp->filp),
4040 file_inode(dir_fp->filp),
4041 MAY_READ | MAY_EXEC)) {
4042 pr_err("no right to enumerate directory (%pD)\n", dir_fp->filp);
4047 if (!S_ISDIR(file_inode(dir_fp->filp)->i_mode)) {
4048 pr_err("can't do query dir for a file\n");
4053 srch_flag = req->Flags;
4054 srch_ptr = smb_strndup_from_utf16(req->Buffer,
4055 le16_to_cpu(req->FileNameLength), 1,
4057 if (IS_ERR(srch_ptr)) {
4058 ksmbd_debug(SMB, "Search Pattern not found\n");
4062 ksmbd_debug(SMB, "Search pattern is %s\n", srch_ptr);
4065 if (srch_flag & SMB2_REOPEN || srch_flag & SMB2_RESTART_SCANS) {
4066 ksmbd_debug(SMB, "Restart directory scan\n");
4067 generic_file_llseek(dir_fp->filp, 0, SEEK_SET);
4070 memset(&d_info, 0, sizeof(struct ksmbd_dir_info));
4071 d_info.wptr = (char *)rsp->Buffer;
4072 d_info.rptr = (char *)rsp->Buffer;
4073 d_info.out_buf_len =
4074 smb2_calc_max_out_buf_len(work, 8,
4075 le32_to_cpu(req->OutputBufferLength));
4076 if (d_info.out_buf_len < 0) {
4080 d_info.flags = srch_flag;
4083 * reserve dot and dotdot entries in head of buffer
4086 rc = ksmbd_populate_dot_dotdot_entries(work, req->FileInformationClass,
4087 dir_fp, &d_info, srch_ptr,
4088 smb2_populate_readdir_entry);
4094 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_HIDE_DOT_FILES))
4095 d_info.hide_dot_file = true;
4097 buffer_sz = d_info.out_buf_len;
4098 d_info.rptr = d_info.wptr;
4099 query_dir_private.work = work;
4100 query_dir_private.search_pattern = srch_ptr;
4101 query_dir_private.dir_fp = dir_fp;
4102 query_dir_private.d_info = &d_info;
4103 query_dir_private.info_level = req->FileInformationClass;
4104 dir_fp->readdir_data.private = &query_dir_private;
4105 set_ctx_actor(&dir_fp->readdir_data.ctx, __query_dir);
4107 rc = iterate_dir(dir_fp->filp, &dir_fp->readdir_data.ctx);
4109 * req->OutputBufferLength is too small to contain even one entry.
4110 * In this case, it immediately returns OutputBufferLength 0 to client.
4112 if (!d_info.out_buf_len && !d_info.num_entry)
4114 if (rc > 0 || rc == -ENOSPC)
4119 d_info.wptr = d_info.rptr;
4120 d_info.out_buf_len = buffer_sz;
4121 rc = process_query_dir_entries(&query_dir_private);
4125 if (!d_info.data_count && d_info.out_buf_len >= 0) {
4126 if (srch_flag & SMB2_RETURN_SINGLE_ENTRY && !is_asterisk(srch_ptr)) {
4127 rsp->hdr.Status = STATUS_NO_SUCH_FILE;
4129 dir_fp->dot_dotdot[0] = dir_fp->dot_dotdot[1] = 0;
4130 rsp->hdr.Status = STATUS_NO_MORE_FILES;
4132 rsp->StructureSize = cpu_to_le16(9);
4133 rsp->OutputBufferOffset = cpu_to_le16(0);
4134 rsp->OutputBufferLength = cpu_to_le32(0);
4136 rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
4137 sizeof(struct smb2_query_directory_rsp));
4142 ((struct file_directory_info *)
4143 ((char *)rsp->Buffer + d_info.last_entry_offset))
4144 ->NextEntryOffset = 0;
4145 if (d_info.data_count >= d_info.last_entry_off_align)
4146 d_info.data_count -= d_info.last_entry_off_align;
4148 rsp->StructureSize = cpu_to_le16(9);
4149 rsp->OutputBufferOffset = cpu_to_le16(72);
4150 rsp->OutputBufferLength = cpu_to_le32(d_info.data_count);
4151 rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
4152 offsetof(struct smb2_query_directory_rsp, Buffer) +
4159 ksmbd_fd_put(work, dir_fp);
4160 ksmbd_revert_fsids(work);
4164 pr_err("error while processing smb2 query dir rc = %d\n", rc);
4169 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
4170 else if (rc == -EACCES)
4171 rsp->hdr.Status = STATUS_ACCESS_DENIED;
4172 else if (rc == -ENOENT)
4173 rsp->hdr.Status = STATUS_NO_SUCH_FILE;
4174 else if (rc == -EBADF)
4175 rsp->hdr.Status = STATUS_FILE_CLOSED;
4176 else if (rc == -ENOMEM)
4177 rsp->hdr.Status = STATUS_NO_MEMORY;
4178 else if (rc == -EFAULT)
4179 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
4180 else if (rc == -EIO)
4181 rsp->hdr.Status = STATUS_FILE_CORRUPT_ERROR;
4182 if (!rsp->hdr.Status)
4183 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
4185 smb2_set_err_rsp(work);
4186 ksmbd_fd_put(work, dir_fp);
4187 ksmbd_revert_fsids(work);
4192 * buffer_check_err() - helper function to check buffer errors
4193 * @reqOutputBufferLength: max buffer length expected in command response
4194 * @rsp: query info response buffer contains output buffer length
4195 * @rsp_org: base response buffer pointer in case of chained response
4197 * Return: 0 on success, otherwise error
4199 static int buffer_check_err(int reqOutputBufferLength,
4200 struct smb2_query_info_rsp *rsp,
4203 if (reqOutputBufferLength < le32_to_cpu(rsp->OutputBufferLength)) {
4204 pr_err("Invalid Buffer Size Requested\n");
4205 rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
4206 *(__be32 *)rsp_org = cpu_to_be32(sizeof(struct smb2_hdr));
4212 static void get_standard_info_pipe(struct smb2_query_info_rsp *rsp,
4215 struct smb2_file_standard_info *sinfo;
4217 sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
4219 sinfo->AllocationSize = cpu_to_le64(4096);
4220 sinfo->EndOfFile = cpu_to_le64(0);
4221 sinfo->NumberOfLinks = cpu_to_le32(1);
4222 sinfo->DeletePending = 1;
4223 sinfo->Directory = 0;
4224 rsp->OutputBufferLength =
4225 cpu_to_le32(sizeof(struct smb2_file_standard_info));
4228 static void get_internal_info_pipe(struct smb2_query_info_rsp *rsp, u64 num,
4231 struct smb2_file_internal_info *file_info;
4233 file_info = (struct smb2_file_internal_info *)rsp->Buffer;
4235 /* any unique number */
4236 file_info->IndexNumber = cpu_to_le64(num | (1ULL << 63));
4237 rsp->OutputBufferLength =
4238 cpu_to_le32(sizeof(struct smb2_file_internal_info));
4241 static int smb2_get_info_file_pipe(struct ksmbd_session *sess,
4242 struct smb2_query_info_req *req,
4243 struct smb2_query_info_rsp *rsp,
4250 * Windows can sometime send query file info request on
4251 * pipe without opening it, checking error condition here
4253 id = req->VolatileFileId;
4254 if (!ksmbd_session_rpc_method(sess, id))
4257 ksmbd_debug(SMB, "FileInfoClass %u, FileId 0x%llx\n",
4258 req->FileInfoClass, req->VolatileFileId);
4260 switch (req->FileInfoClass) {
4261 case FILE_STANDARD_INFORMATION:
4262 get_standard_info_pipe(rsp, rsp_org);
4263 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4266 case FILE_INTERNAL_INFORMATION:
4267 get_internal_info_pipe(rsp, id, rsp_org);
4268 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4272 ksmbd_debug(SMB, "smb2_info_file_pipe for %u not supported\n",
4273 req->FileInfoClass);
4280 * smb2_get_ea() - handler for smb2 get extended attribute command
4281 * @work: smb work containing query info command buffer
4282 * @fp: ksmbd_file pointer
4283 * @req: get extended attribute request
4284 * @rsp: response buffer pointer
4285 * @rsp_org: base response buffer pointer in case of chained response
4287 * Return: 0 on success, otherwise error
4289 static int smb2_get_ea(struct ksmbd_work *work, struct ksmbd_file *fp,
4290 struct smb2_query_info_req *req,
4291 struct smb2_query_info_rsp *rsp, void *rsp_org)
4293 struct smb2_ea_info *eainfo, *prev_eainfo;
4294 char *name, *ptr, *xattr_list = NULL, *buf;
4295 int rc, name_len, value_len, xattr_list_len, idx;
4296 ssize_t buf_free_len, alignment_bytes, next_offset, rsp_data_cnt = 0;
4297 struct smb2_ea_info_req *ea_req = NULL;
4298 const struct path *path;
4299 struct mnt_idmap *idmap = file_mnt_idmap(fp->filp);
4301 if (!(fp->daccess & FILE_READ_EA_LE)) {
4302 pr_err("Not permitted to read ext attr : 0x%x\n",
4307 path = &fp->filp->f_path;
4308 /* single EA entry is requested with given user.* name */
4309 if (req->InputBufferLength) {
4310 if (le32_to_cpu(req->InputBufferLength) <
4311 sizeof(struct smb2_ea_info_req))
4314 ea_req = (struct smb2_ea_info_req *)req->Buffer;
4316 /* need to send all EAs, if no specific EA is requested*/
4317 if (le32_to_cpu(req->Flags) & SL_RETURN_SINGLE_ENTRY)
4319 "All EAs are requested but need to send single EA entry in rsp flags 0x%x\n",
4320 le32_to_cpu(req->Flags));
4324 smb2_calc_max_out_buf_len(work, 8,
4325 le32_to_cpu(req->OutputBufferLength));
4326 if (buf_free_len < 0)
4329 rc = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
4331 rsp->hdr.Status = STATUS_INVALID_HANDLE;
4333 } else if (!rc) { /* there is no EA in the file */
4334 ksmbd_debug(SMB, "no ea data in the file\n");
4337 xattr_list_len = rc;
4339 ptr = (char *)rsp->Buffer;
4340 eainfo = (struct smb2_ea_info *)ptr;
4341 prev_eainfo = eainfo;
4344 while (idx < xattr_list_len) {
4345 name = xattr_list + idx;
4346 name_len = strlen(name);
4348 ksmbd_debug(SMB, "%s, len %d\n", name, name_len);
4349 idx += name_len + 1;
4352 * CIFS does not support EA other than user.* namespace,
4353 * still keep the framework generic, to list other attrs
4356 if (strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4359 if (!strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
4363 if (req->InputBufferLength &&
4364 strncmp(&name[XATTR_USER_PREFIX_LEN], ea_req->name,
4365 ea_req->EaNameLength))
4368 if (!strncmp(&name[XATTR_USER_PREFIX_LEN],
4369 DOS_ATTRIBUTE_PREFIX, DOS_ATTRIBUTE_PREFIX_LEN))
4372 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4373 name_len -= XATTR_USER_PREFIX_LEN;
4375 ptr = eainfo->name + name_len + 1;
4376 buf_free_len -= (offsetof(struct smb2_ea_info, name) +
4378 /* bailout if xattr can't fit in buf_free_len */
4379 value_len = ksmbd_vfs_getxattr(idmap, path->dentry,
4381 if (value_len <= 0) {
4383 rsp->hdr.Status = STATUS_INVALID_HANDLE;
4387 buf_free_len -= value_len;
4388 if (buf_free_len < 0) {
4393 memcpy(ptr, buf, value_len);
4398 eainfo->EaNameLength = name_len;
4400 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4401 memcpy(eainfo->name, &name[XATTR_USER_PREFIX_LEN],
4404 memcpy(eainfo->name, name, name_len);
4406 eainfo->name[name_len] = '\0';
4407 eainfo->EaValueLength = cpu_to_le16(value_len);
4408 next_offset = offsetof(struct smb2_ea_info, name) +
4409 name_len + 1 + value_len;
4411 /* align next xattr entry at 4 byte bundary */
4412 alignment_bytes = ((next_offset + 3) & ~3) - next_offset;
4413 if (alignment_bytes) {
4414 memset(ptr, '\0', alignment_bytes);
4415 ptr += alignment_bytes;
4416 next_offset += alignment_bytes;
4417 buf_free_len -= alignment_bytes;
4419 eainfo->NextEntryOffset = cpu_to_le32(next_offset);
4420 prev_eainfo = eainfo;
4421 eainfo = (struct smb2_ea_info *)ptr;
4422 rsp_data_cnt += next_offset;
4424 if (req->InputBufferLength) {
4425 ksmbd_debug(SMB, "single entry requested\n");
4430 /* no more ea entries */
4431 prev_eainfo->NextEntryOffset = 0;
4434 if (rsp_data_cnt == 0)
4435 rsp->hdr.Status = STATUS_NO_EAS_ON_FILE;
4436 rsp->OutputBufferLength = cpu_to_le32(rsp_data_cnt);
4442 static void get_file_access_info(struct smb2_query_info_rsp *rsp,
4443 struct ksmbd_file *fp, void *rsp_org)
4445 struct smb2_file_access_info *file_info;
4447 file_info = (struct smb2_file_access_info *)rsp->Buffer;
4448 file_info->AccessFlags = fp->daccess;
4449 rsp->OutputBufferLength =
4450 cpu_to_le32(sizeof(struct smb2_file_access_info));
4453 static int get_file_basic_info(struct smb2_query_info_rsp *rsp,
4454 struct ksmbd_file *fp, void *rsp_org)
4456 struct smb2_file_basic_info *basic_info;
4460 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4461 pr_err("no right to read the attributes : 0x%x\n",
4466 basic_info = (struct smb2_file_basic_info *)rsp->Buffer;
4467 generic_fillattr(file_mnt_idmap(fp->filp), STATX_BASIC_STATS,
4468 file_inode(fp->filp), &stat);
4469 basic_info->CreationTime = cpu_to_le64(fp->create_time);
4470 time = ksmbd_UnixTimeToNT(stat.atime);
4471 basic_info->LastAccessTime = cpu_to_le64(time);
4472 time = ksmbd_UnixTimeToNT(stat.mtime);
4473 basic_info->LastWriteTime = cpu_to_le64(time);
4474 time = ksmbd_UnixTimeToNT(stat.ctime);
4475 basic_info->ChangeTime = cpu_to_le64(time);
4476 basic_info->Attributes = fp->f_ci->m_fattr;
4477 basic_info->Pad1 = 0;
4478 rsp->OutputBufferLength =
4479 cpu_to_le32(sizeof(struct smb2_file_basic_info));
4483 static void get_file_standard_info(struct smb2_query_info_rsp *rsp,
4484 struct ksmbd_file *fp, void *rsp_org)
4486 struct smb2_file_standard_info *sinfo;
4487 unsigned int delete_pending;
4488 struct inode *inode;
4491 inode = file_inode(fp->filp);
4492 generic_fillattr(file_mnt_idmap(fp->filp), STATX_BASIC_STATS, inode, &stat);
4494 sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
4495 delete_pending = ksmbd_inode_pending_delete(fp);
4497 sinfo->AllocationSize = cpu_to_le64(inode->i_blocks << 9);
4498 sinfo->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4499 sinfo->NumberOfLinks = cpu_to_le32(get_nlink(&stat) - delete_pending);
4500 sinfo->DeletePending = delete_pending;
4501 sinfo->Directory = S_ISDIR(stat.mode) ? 1 : 0;
4502 rsp->OutputBufferLength =
4503 cpu_to_le32(sizeof(struct smb2_file_standard_info));
4506 static void get_file_alignment_info(struct smb2_query_info_rsp *rsp,
4509 struct smb2_file_alignment_info *file_info;
4511 file_info = (struct smb2_file_alignment_info *)rsp->Buffer;
4512 file_info->AlignmentRequirement = 0;
4513 rsp->OutputBufferLength =
4514 cpu_to_le32(sizeof(struct smb2_file_alignment_info));
4517 static int get_file_all_info(struct ksmbd_work *work,
4518 struct smb2_query_info_rsp *rsp,
4519 struct ksmbd_file *fp,
4522 struct ksmbd_conn *conn = work->conn;
4523 struct smb2_file_all_info *file_info;
4524 unsigned int delete_pending;
4525 struct inode *inode;
4531 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4532 ksmbd_debug(SMB, "no right to read the attributes : 0x%x\n",
4537 filename = convert_to_nt_pathname(work->tcon->share_conf, &fp->filp->f_path);
4538 if (IS_ERR(filename))
4539 return PTR_ERR(filename);
4541 inode = file_inode(fp->filp);
4542 generic_fillattr(file_mnt_idmap(fp->filp), STATX_BASIC_STATS, inode, &stat);
4544 ksmbd_debug(SMB, "filename = %s\n", filename);
4545 delete_pending = ksmbd_inode_pending_delete(fp);
4546 file_info = (struct smb2_file_all_info *)rsp->Buffer;
4548 file_info->CreationTime = cpu_to_le64(fp->create_time);
4549 time = ksmbd_UnixTimeToNT(stat.atime);
4550 file_info->LastAccessTime = cpu_to_le64(time);
4551 time = ksmbd_UnixTimeToNT(stat.mtime);
4552 file_info->LastWriteTime = cpu_to_le64(time);
4553 time = ksmbd_UnixTimeToNT(stat.ctime);
4554 file_info->ChangeTime = cpu_to_le64(time);
4555 file_info->Attributes = fp->f_ci->m_fattr;
4556 file_info->Pad1 = 0;
4557 file_info->AllocationSize =
4558 cpu_to_le64(inode->i_blocks << 9);
4559 file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4560 file_info->NumberOfLinks =
4561 cpu_to_le32(get_nlink(&stat) - delete_pending);
4562 file_info->DeletePending = delete_pending;
4563 file_info->Directory = S_ISDIR(stat.mode) ? 1 : 0;
4564 file_info->Pad2 = 0;
4565 file_info->IndexNumber = cpu_to_le64(stat.ino);
4566 file_info->EASize = 0;
4567 file_info->AccessFlags = fp->daccess;
4568 file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
4569 file_info->Mode = fp->coption;
4570 file_info->AlignmentRequirement = 0;
4571 conv_len = smbConvertToUTF16((__le16 *)file_info->FileName, filename,
4572 PATH_MAX, conn->local_nls, 0);
4574 file_info->FileNameLength = cpu_to_le32(conv_len);
4575 rsp->OutputBufferLength =
4576 cpu_to_le32(sizeof(struct smb2_file_all_info) + conv_len - 1);
4581 static void get_file_alternate_info(struct ksmbd_work *work,
4582 struct smb2_query_info_rsp *rsp,
4583 struct ksmbd_file *fp,
4586 struct ksmbd_conn *conn = work->conn;
4587 struct smb2_file_alt_name_info *file_info;
4588 struct dentry *dentry = fp->filp->f_path.dentry;
4591 spin_lock(&dentry->d_lock);
4592 file_info = (struct smb2_file_alt_name_info *)rsp->Buffer;
4593 conv_len = ksmbd_extract_shortname(conn,
4594 dentry->d_name.name,
4595 file_info->FileName);
4596 spin_unlock(&dentry->d_lock);
4597 file_info->FileNameLength = cpu_to_le32(conv_len);
4598 rsp->OutputBufferLength =
4599 cpu_to_le32(sizeof(struct smb2_file_alt_name_info) + conv_len);
4602 static void get_file_stream_info(struct ksmbd_work *work,
4603 struct smb2_query_info_rsp *rsp,
4604 struct ksmbd_file *fp,
4607 struct ksmbd_conn *conn = work->conn;
4608 struct smb2_file_stream_info *file_info;
4609 char *stream_name, *xattr_list = NULL, *stream_buf;
4611 const struct path *path = &fp->filp->f_path;
4612 ssize_t xattr_list_len;
4613 int nbytes = 0, streamlen, stream_name_len, next, idx = 0;
4615 struct smb2_query_info_req *req = ksmbd_req_buf_next(work);
4617 generic_fillattr(file_mnt_idmap(fp->filp), STATX_BASIC_STATS,
4618 file_inode(fp->filp), &stat);
4619 file_info = (struct smb2_file_stream_info *)rsp->Buffer;
4622 smb2_calc_max_out_buf_len(work, 8,
4623 le32_to_cpu(req->OutputBufferLength));
4624 if (buf_free_len < 0)
4627 xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
4628 if (xattr_list_len < 0) {
4630 } else if (!xattr_list_len) {
4631 ksmbd_debug(SMB, "empty xattr in the file\n");
4635 while (idx < xattr_list_len) {
4636 stream_name = xattr_list + idx;
4637 streamlen = strlen(stream_name);
4638 idx += streamlen + 1;
4640 ksmbd_debug(SMB, "%s, len %d\n", stream_name, streamlen);
4642 if (strncmp(&stream_name[XATTR_USER_PREFIX_LEN],
4643 STREAM_PREFIX, STREAM_PREFIX_LEN))
4646 stream_name_len = streamlen - (XATTR_USER_PREFIX_LEN +
4648 streamlen = stream_name_len;
4652 stream_buf = kmalloc(streamlen + 1, GFP_KERNEL);
4656 streamlen = snprintf(stream_buf, streamlen + 1,
4657 ":%s", &stream_name[XATTR_NAME_STREAM_LEN]);
4659 next = sizeof(struct smb2_file_stream_info) + streamlen * 2;
4660 if (next > buf_free_len) {
4665 file_info = (struct smb2_file_stream_info *)&rsp->Buffer[nbytes];
4666 streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
4667 stream_buf, streamlen,
4668 conn->local_nls, 0);
4671 file_info->StreamNameLength = cpu_to_le32(streamlen);
4672 file_info->StreamSize = cpu_to_le64(stream_name_len);
4673 file_info->StreamAllocationSize = cpu_to_le64(stream_name_len);
4676 buf_free_len -= next;
4677 file_info->NextEntryOffset = cpu_to_le32(next);
4681 if (!S_ISDIR(stat.mode) &&
4682 buf_free_len >= sizeof(struct smb2_file_stream_info) + 7 * 2) {
4683 file_info = (struct smb2_file_stream_info *)
4684 &rsp->Buffer[nbytes];
4685 streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
4686 "::$DATA", 7, conn->local_nls, 0);
4688 file_info->StreamNameLength = cpu_to_le32(streamlen);
4689 file_info->StreamSize = cpu_to_le64(stat.size);
4690 file_info->StreamAllocationSize = cpu_to_le64(stat.blocks << 9);
4691 nbytes += sizeof(struct smb2_file_stream_info) + streamlen;
4694 /* last entry offset should be 0 */
4695 file_info->NextEntryOffset = 0;
4698 rsp->OutputBufferLength = cpu_to_le32(nbytes);
4701 static void get_file_internal_info(struct smb2_query_info_rsp *rsp,
4702 struct ksmbd_file *fp, void *rsp_org)
4704 struct smb2_file_internal_info *file_info;
4707 generic_fillattr(file_mnt_idmap(fp->filp), STATX_BASIC_STATS,
4708 file_inode(fp->filp), &stat);
4709 file_info = (struct smb2_file_internal_info *)rsp->Buffer;
4710 file_info->IndexNumber = cpu_to_le64(stat.ino);
4711 rsp->OutputBufferLength =
4712 cpu_to_le32(sizeof(struct smb2_file_internal_info));
4715 static int get_file_network_open_info(struct smb2_query_info_rsp *rsp,
4716 struct ksmbd_file *fp, void *rsp_org)
4718 struct smb2_file_ntwrk_info *file_info;
4719 struct inode *inode;
4723 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4724 pr_err("no right to read the attributes : 0x%x\n",
4729 file_info = (struct smb2_file_ntwrk_info *)rsp->Buffer;
4731 inode = file_inode(fp->filp);
4732 generic_fillattr(file_mnt_idmap(fp->filp), STATX_BASIC_STATS, inode, &stat);
4734 file_info->CreationTime = cpu_to_le64(fp->create_time);
4735 time = ksmbd_UnixTimeToNT(stat.atime);
4736 file_info->LastAccessTime = cpu_to_le64(time);
4737 time = ksmbd_UnixTimeToNT(stat.mtime);
4738 file_info->LastWriteTime = cpu_to_le64(time);
4739 time = ksmbd_UnixTimeToNT(stat.ctime);
4740 file_info->ChangeTime = cpu_to_le64(time);
4741 file_info->Attributes = fp->f_ci->m_fattr;
4742 file_info->AllocationSize =
4743 cpu_to_le64(inode->i_blocks << 9);
4744 file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4745 file_info->Reserved = cpu_to_le32(0);
4746 rsp->OutputBufferLength =
4747 cpu_to_le32(sizeof(struct smb2_file_ntwrk_info));
4751 static void get_file_ea_info(struct smb2_query_info_rsp *rsp, void *rsp_org)
4753 struct smb2_file_ea_info *file_info;
4755 file_info = (struct smb2_file_ea_info *)rsp->Buffer;
4756 file_info->EASize = 0;
4757 rsp->OutputBufferLength =
4758 cpu_to_le32(sizeof(struct smb2_file_ea_info));
4761 static void get_file_position_info(struct smb2_query_info_rsp *rsp,
4762 struct ksmbd_file *fp, void *rsp_org)
4764 struct smb2_file_pos_info *file_info;
4766 file_info = (struct smb2_file_pos_info *)rsp->Buffer;
4767 file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
4768 rsp->OutputBufferLength =
4769 cpu_to_le32(sizeof(struct smb2_file_pos_info));
4772 static void get_file_mode_info(struct smb2_query_info_rsp *rsp,
4773 struct ksmbd_file *fp, void *rsp_org)
4775 struct smb2_file_mode_info *file_info;
4777 file_info = (struct smb2_file_mode_info *)rsp->Buffer;
4778 file_info->Mode = fp->coption & FILE_MODE_INFO_MASK;
4779 rsp->OutputBufferLength =
4780 cpu_to_le32(sizeof(struct smb2_file_mode_info));
4783 static void get_file_compression_info(struct smb2_query_info_rsp *rsp,
4784 struct ksmbd_file *fp, void *rsp_org)
4786 struct smb2_file_comp_info *file_info;
4789 generic_fillattr(file_mnt_idmap(fp->filp), STATX_BASIC_STATS,
4790 file_inode(fp->filp), &stat);
4792 file_info = (struct smb2_file_comp_info *)rsp->Buffer;
4793 file_info->CompressedFileSize = cpu_to_le64(stat.blocks << 9);
4794 file_info->CompressionFormat = COMPRESSION_FORMAT_NONE;
4795 file_info->CompressionUnitShift = 0;
4796 file_info->ChunkShift = 0;
4797 file_info->ClusterShift = 0;
4798 memset(&file_info->Reserved[0], 0, 3);
4800 rsp->OutputBufferLength =
4801 cpu_to_le32(sizeof(struct smb2_file_comp_info));
4804 static int get_file_attribute_tag_info(struct smb2_query_info_rsp *rsp,
4805 struct ksmbd_file *fp, void *rsp_org)
4807 struct smb2_file_attr_tag_info *file_info;
4809 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4810 pr_err("no right to read the attributes : 0x%x\n",
4815 file_info = (struct smb2_file_attr_tag_info *)rsp->Buffer;
4816 file_info->FileAttributes = fp->f_ci->m_fattr;
4817 file_info->ReparseTag = 0;
4818 rsp->OutputBufferLength =
4819 cpu_to_le32(sizeof(struct smb2_file_attr_tag_info));
4823 static void find_file_posix_info(struct smb2_query_info_rsp *rsp,
4824 struct ksmbd_file *fp, void *rsp_org)
4826 struct smb311_posix_qinfo *file_info;
4827 struct inode *inode = file_inode(fp->filp);
4828 struct mnt_idmap *idmap = file_mnt_idmap(fp->filp);
4829 vfsuid_t vfsuid = i_uid_into_vfsuid(idmap, inode);
4830 vfsgid_t vfsgid = i_gid_into_vfsgid(idmap, inode);
4832 int out_buf_len = sizeof(struct smb311_posix_qinfo) + 32;
4834 file_info = (struct smb311_posix_qinfo *)rsp->Buffer;
4835 file_info->CreationTime = cpu_to_le64(fp->create_time);
4836 time = ksmbd_UnixTimeToNT(inode->i_atime);
4837 file_info->LastAccessTime = cpu_to_le64(time);
4838 time = ksmbd_UnixTimeToNT(inode->i_mtime);
4839 file_info->LastWriteTime = cpu_to_le64(time);
4840 time = ksmbd_UnixTimeToNT(inode_get_ctime(inode));
4841 file_info->ChangeTime = cpu_to_le64(time);
4842 file_info->DosAttributes = fp->f_ci->m_fattr;
4843 file_info->Inode = cpu_to_le64(inode->i_ino);
4844 file_info->EndOfFile = cpu_to_le64(inode->i_size);
4845 file_info->AllocationSize = cpu_to_le64(inode->i_blocks << 9);
4846 file_info->HardLinks = cpu_to_le32(inode->i_nlink);
4847 file_info->Mode = cpu_to_le32(inode->i_mode & 0777);
4848 file_info->DeviceId = cpu_to_le32(inode->i_rdev);
4851 * Sids(32) contain two sids(Domain sid(16), UNIX group sid(16)).
4852 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) +
4853 * sub_auth(4 * 1(num_subauth)) + RID(4).
4855 id_to_sid(from_kuid_munged(&init_user_ns, vfsuid_into_kuid(vfsuid)),
4856 SIDUNIX_USER, (struct smb_sid *)&file_info->Sids[0]);
4857 id_to_sid(from_kgid_munged(&init_user_ns, vfsgid_into_kgid(vfsgid)),
4858 SIDUNIX_GROUP, (struct smb_sid *)&file_info->Sids[16]);
4860 rsp->OutputBufferLength = cpu_to_le32(out_buf_len);
4863 static int smb2_get_info_file(struct ksmbd_work *work,
4864 struct smb2_query_info_req *req,
4865 struct smb2_query_info_rsp *rsp)
4867 struct ksmbd_file *fp;
4868 int fileinfoclass = 0;
4870 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
4872 if (test_share_config_flag(work->tcon->share_conf,
4873 KSMBD_SHARE_FLAG_PIPE)) {
4874 /* smb2 info file called for pipe */
4875 return smb2_get_info_file_pipe(work->sess, req, rsp,
4876 work->response_buf);
4879 if (work->next_smb2_rcv_hdr_off) {
4880 if (!has_file_id(req->VolatileFileId)) {
4881 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
4882 work->compound_fid);
4883 id = work->compound_fid;
4884 pid = work->compound_pfid;
4888 if (!has_file_id(id)) {
4889 id = req->VolatileFileId;
4890 pid = req->PersistentFileId;
4893 fp = ksmbd_lookup_fd_slow(work, id, pid);
4897 fileinfoclass = req->FileInfoClass;
4899 switch (fileinfoclass) {
4900 case FILE_ACCESS_INFORMATION:
4901 get_file_access_info(rsp, fp, work->response_buf);
4904 case FILE_BASIC_INFORMATION:
4905 rc = get_file_basic_info(rsp, fp, work->response_buf);
4908 case FILE_STANDARD_INFORMATION:
4909 get_file_standard_info(rsp, fp, work->response_buf);
4912 case FILE_ALIGNMENT_INFORMATION:
4913 get_file_alignment_info(rsp, work->response_buf);
4916 case FILE_ALL_INFORMATION:
4917 rc = get_file_all_info(work, rsp, fp, work->response_buf);
4920 case FILE_ALTERNATE_NAME_INFORMATION:
4921 get_file_alternate_info(work, rsp, fp, work->response_buf);
4924 case FILE_STREAM_INFORMATION:
4925 get_file_stream_info(work, rsp, fp, work->response_buf);
4928 case FILE_INTERNAL_INFORMATION:
4929 get_file_internal_info(rsp, fp, work->response_buf);
4932 case FILE_NETWORK_OPEN_INFORMATION:
4933 rc = get_file_network_open_info(rsp, fp, work->response_buf);
4936 case FILE_EA_INFORMATION:
4937 get_file_ea_info(rsp, work->response_buf);
4940 case FILE_FULL_EA_INFORMATION:
4941 rc = smb2_get_ea(work, fp, req, rsp, work->response_buf);
4944 case FILE_POSITION_INFORMATION:
4945 get_file_position_info(rsp, fp, work->response_buf);
4948 case FILE_MODE_INFORMATION:
4949 get_file_mode_info(rsp, fp, work->response_buf);
4952 case FILE_COMPRESSION_INFORMATION:
4953 get_file_compression_info(rsp, fp, work->response_buf);
4956 case FILE_ATTRIBUTE_TAG_INFORMATION:
4957 rc = get_file_attribute_tag_info(rsp, fp, work->response_buf);
4959 case SMB_FIND_FILE_POSIX_INFO:
4960 if (!work->tcon->posix_extensions) {
4961 pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
4964 find_file_posix_info(rsp, fp, work->response_buf);
4968 ksmbd_debug(SMB, "fileinfoclass %d not supported yet\n",
4973 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4974 rsp, work->response_buf);
4975 ksmbd_fd_put(work, fp);
4979 static int smb2_get_info_filesystem(struct ksmbd_work *work,
4980 struct smb2_query_info_req *req,
4981 struct smb2_query_info_rsp *rsp)
4983 struct ksmbd_session *sess = work->sess;
4984 struct ksmbd_conn *conn = work->conn;
4985 struct ksmbd_share_config *share = work->tcon->share_conf;
4986 int fsinfoclass = 0;
4987 struct kstatfs stfs;
4994 rc = kern_path(share->path, LOOKUP_NO_SYMLINKS, &path);
4996 pr_err("cannot create vfs path\n");
5000 rc = vfs_statfs(&path, &stfs);
5002 pr_err("cannot do stat of path %s\n", share->path);
5007 fsinfoclass = req->FileInfoClass;
5009 switch (fsinfoclass) {
5010 case FS_DEVICE_INFORMATION:
5012 struct filesystem_device_info *info;
5014 info = (struct filesystem_device_info *)rsp->Buffer;
5016 info->DeviceType = cpu_to_le32(stfs.f_type);
5017 info->DeviceCharacteristics = cpu_to_le32(0x00000020);
5018 rsp->OutputBufferLength = cpu_to_le32(8);
5021 case FS_ATTRIBUTE_INFORMATION:
5023 struct filesystem_attribute_info *info;
5026 info = (struct filesystem_attribute_info *)rsp->Buffer;
5027 info->Attributes = cpu_to_le32(FILE_SUPPORTS_OBJECT_IDS |
5028 FILE_PERSISTENT_ACLS |
5029 FILE_UNICODE_ON_DISK |
5030 FILE_CASE_PRESERVED_NAMES |
5031 FILE_CASE_SENSITIVE_SEARCH |
5032 FILE_SUPPORTS_BLOCK_REFCOUNTING);
5034 info->Attributes |= cpu_to_le32(server_conf.share_fake_fscaps);
5036 if (test_share_config_flag(work->tcon->share_conf,
5037 KSMBD_SHARE_FLAG_STREAMS))
5038 info->Attributes |= cpu_to_le32(FILE_NAMED_STREAMS);
5040 info->MaxPathNameComponentLength = cpu_to_le32(stfs.f_namelen);
5041 len = smbConvertToUTF16((__le16 *)info->FileSystemName,
5042 "NTFS", PATH_MAX, conn->local_nls, 0);
5044 info->FileSystemNameLen = cpu_to_le32(len);
5045 sz = sizeof(struct filesystem_attribute_info) - 2 + len;
5046 rsp->OutputBufferLength = cpu_to_le32(sz);
5049 case FS_VOLUME_INFORMATION:
5051 struct filesystem_vol_info *info;
5053 unsigned int serial_crc = 0;
5055 info = (struct filesystem_vol_info *)(rsp->Buffer);
5056 info->VolumeCreationTime = 0;
5057 serial_crc = crc32_le(serial_crc, share->name,
5058 strlen(share->name));
5059 serial_crc = crc32_le(serial_crc, share->path,
5060 strlen(share->path));
5061 serial_crc = crc32_le(serial_crc, ksmbd_netbios_name(),
5062 strlen(ksmbd_netbios_name()));
5063 /* Taking dummy value of serial number*/
5064 info->SerialNumber = cpu_to_le32(serial_crc);
5065 len = smbConvertToUTF16((__le16 *)info->VolumeLabel,
5066 share->name, PATH_MAX,
5067 conn->local_nls, 0);
5069 info->VolumeLabelSize = cpu_to_le32(len);
5071 sz = sizeof(struct filesystem_vol_info) - 2 + len;
5072 rsp->OutputBufferLength = cpu_to_le32(sz);
5075 case FS_SIZE_INFORMATION:
5077 struct filesystem_info *info;
5079 info = (struct filesystem_info *)(rsp->Buffer);
5080 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
5081 info->FreeAllocationUnits = cpu_to_le64(stfs.f_bfree);
5082 info->SectorsPerAllocationUnit = cpu_to_le32(1);
5083 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
5084 rsp->OutputBufferLength = cpu_to_le32(24);
5087 case FS_FULL_SIZE_INFORMATION:
5089 struct smb2_fs_full_size_info *info;
5091 info = (struct smb2_fs_full_size_info *)(rsp->Buffer);
5092 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
5093 info->CallerAvailableAllocationUnits =
5094 cpu_to_le64(stfs.f_bavail);
5095 info->ActualAvailableAllocationUnits =
5096 cpu_to_le64(stfs.f_bfree);
5097 info->SectorsPerAllocationUnit = cpu_to_le32(1);
5098 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
5099 rsp->OutputBufferLength = cpu_to_le32(32);
5102 case FS_OBJECT_ID_INFORMATION:
5104 struct object_id_info *info;
5106 info = (struct object_id_info *)(rsp->Buffer);
5108 if (!user_guest(sess->user))
5109 memcpy(info->objid, user_passkey(sess->user), 16);
5111 memset(info->objid, 0, 16);
5113 info->extended_info.magic = cpu_to_le32(EXTENDED_INFO_MAGIC);
5114 info->extended_info.version = cpu_to_le32(1);
5115 info->extended_info.release = cpu_to_le32(1);
5116 info->extended_info.rel_date = 0;
5117 memcpy(info->extended_info.version_string, "1.1.0", strlen("1.1.0"));
5118 rsp->OutputBufferLength = cpu_to_le32(64);
5121 case FS_SECTOR_SIZE_INFORMATION:
5123 struct smb3_fs_ss_info *info;
5124 unsigned int sector_size =
5125 min_t(unsigned int, path.mnt->mnt_sb->s_blocksize, 4096);
5127 info = (struct smb3_fs_ss_info *)(rsp->Buffer);
5129 info->LogicalBytesPerSector = cpu_to_le32(sector_size);
5130 info->PhysicalBytesPerSectorForAtomicity =
5131 cpu_to_le32(sector_size);
5132 info->PhysicalBytesPerSectorForPerf = cpu_to_le32(sector_size);
5133 info->FSEffPhysicalBytesPerSectorForAtomicity =
5134 cpu_to_le32(sector_size);
5135 info->Flags = cpu_to_le32(SSINFO_FLAGS_ALIGNED_DEVICE |
5136 SSINFO_FLAGS_PARTITION_ALIGNED_ON_DEVICE);
5137 info->ByteOffsetForSectorAlignment = 0;
5138 info->ByteOffsetForPartitionAlignment = 0;
5139 rsp->OutputBufferLength = cpu_to_le32(28);
5142 case FS_CONTROL_INFORMATION:
5145 * TODO : The current implementation is based on
5146 * test result with win7(NTFS) server. It's need to
5147 * modify this to get valid Quota values
5150 struct smb2_fs_control_info *info;
5152 info = (struct smb2_fs_control_info *)(rsp->Buffer);
5153 info->FreeSpaceStartFiltering = 0;
5154 info->FreeSpaceThreshold = 0;
5155 info->FreeSpaceStopFiltering = 0;
5156 info->DefaultQuotaThreshold = cpu_to_le64(SMB2_NO_FID);
5157 info->DefaultQuotaLimit = cpu_to_le64(SMB2_NO_FID);
5159 rsp->OutputBufferLength = cpu_to_le32(48);
5162 case FS_POSIX_INFORMATION:
5164 struct filesystem_posix_info *info;
5166 if (!work->tcon->posix_extensions) {
5167 pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
5170 info = (struct filesystem_posix_info *)(rsp->Buffer);
5171 info->OptimalTransferSize = cpu_to_le32(stfs.f_bsize);
5172 info->BlockSize = cpu_to_le32(stfs.f_bsize);
5173 info->TotalBlocks = cpu_to_le64(stfs.f_blocks);
5174 info->BlocksAvail = cpu_to_le64(stfs.f_bfree);
5175 info->UserBlocksAvail = cpu_to_le64(stfs.f_bavail);
5176 info->TotalFileNodes = cpu_to_le64(stfs.f_files);
5177 info->FreeFileNodes = cpu_to_le64(stfs.f_ffree);
5178 rsp->OutputBufferLength = cpu_to_le32(56);
5186 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
5187 rsp, work->response_buf);
5192 static int smb2_get_info_sec(struct ksmbd_work *work,
5193 struct smb2_query_info_req *req,
5194 struct smb2_query_info_rsp *rsp)
5196 struct ksmbd_file *fp;
5197 struct mnt_idmap *idmap;
5198 struct smb_ntsd *pntsd = (struct smb_ntsd *)rsp->Buffer, *ppntsd = NULL;
5199 struct smb_fattr fattr = {{0}};
5200 struct inode *inode;
5201 __u32 secdesclen = 0;
5202 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
5203 int addition_info = le32_to_cpu(req->AdditionalInformation);
5204 int rc = 0, ppntsd_size = 0;
5206 if (addition_info & ~(OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO |
5207 PROTECTED_DACL_SECINFO |
5208 UNPROTECTED_DACL_SECINFO)) {
5209 ksmbd_debug(SMB, "Unsupported addition info: 0x%x)\n",
5212 pntsd->revision = cpu_to_le16(1);
5213 pntsd->type = cpu_to_le16(SELF_RELATIVE | DACL_PROTECTED);
5214 pntsd->osidoffset = 0;
5215 pntsd->gsidoffset = 0;
5216 pntsd->sacloffset = 0;
5217 pntsd->dacloffset = 0;
5219 secdesclen = sizeof(struct smb_ntsd);
5220 rsp->OutputBufferLength = cpu_to_le32(secdesclen);
5225 if (work->next_smb2_rcv_hdr_off) {
5226 if (!has_file_id(req->VolatileFileId)) {
5227 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
5228 work->compound_fid);
5229 id = work->compound_fid;
5230 pid = work->compound_pfid;
5234 if (!has_file_id(id)) {
5235 id = req->VolatileFileId;
5236 pid = req->PersistentFileId;
5239 fp = ksmbd_lookup_fd_slow(work, id, pid);
5243 idmap = file_mnt_idmap(fp->filp);
5244 inode = file_inode(fp->filp);
5245 ksmbd_acls_fattr(&fattr, idmap, inode);
5247 if (test_share_config_flag(work->tcon->share_conf,
5248 KSMBD_SHARE_FLAG_ACL_XATTR))
5249 ppntsd_size = ksmbd_vfs_get_sd_xattr(work->conn, idmap,
5250 fp->filp->f_path.dentry,
5253 /* Check if sd buffer size exceeds response buffer size */
5254 if (smb2_resp_buf_len(work, 8) > ppntsd_size)
5255 rc = build_sec_desc(idmap, pntsd, ppntsd, ppntsd_size,
5256 addition_info, &secdesclen, &fattr);
5257 posix_acl_release(fattr.cf_acls);
5258 posix_acl_release(fattr.cf_dacls);
5260 ksmbd_fd_put(work, fp);
5264 rsp->OutputBufferLength = cpu_to_le32(secdesclen);
5269 * smb2_query_info() - handler for smb2 query info command
5270 * @work: smb work containing query info request buffer
5272 * Return: 0 on success, otherwise error
5274 int smb2_query_info(struct ksmbd_work *work)
5276 struct smb2_query_info_req *req;
5277 struct smb2_query_info_rsp *rsp;
5280 WORK_BUFFERS(work, req, rsp);
5282 ksmbd_debug(SMB, "GOT query info request\n");
5284 switch (req->InfoType) {
5285 case SMB2_O_INFO_FILE:
5286 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
5287 rc = smb2_get_info_file(work, req, rsp);
5289 case SMB2_O_INFO_FILESYSTEM:
5290 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILESYSTEM\n");
5291 rc = smb2_get_info_filesystem(work, req, rsp);
5293 case SMB2_O_INFO_SECURITY:
5294 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
5295 rc = smb2_get_info_sec(work, req, rsp);
5298 ksmbd_debug(SMB, "InfoType %d not supported yet\n",
5304 rsp->StructureSize = cpu_to_le16(9);
5305 rsp->OutputBufferOffset = cpu_to_le16(72);
5306 rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
5307 offsetof(struct smb2_query_info_rsp, Buffer) +
5308 le32_to_cpu(rsp->OutputBufferLength));
5313 rsp->hdr.Status = STATUS_ACCESS_DENIED;
5314 else if (rc == -ENOENT)
5315 rsp->hdr.Status = STATUS_FILE_CLOSED;
5316 else if (rc == -EIO)
5317 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
5318 else if (rc == -ENOMEM)
5319 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
5320 else if (rc == -EOPNOTSUPP || rsp->hdr.Status == 0)
5321 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
5322 smb2_set_err_rsp(work);
5324 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n",
5332 * smb2_close_pipe() - handler for closing IPC pipe
5333 * @work: smb work containing close request buffer
5337 static noinline int smb2_close_pipe(struct ksmbd_work *work)
5340 struct smb2_close_req *req;
5341 struct smb2_close_rsp *rsp;
5343 WORK_BUFFERS(work, req, rsp);
5345 id = req->VolatileFileId;
5346 ksmbd_session_rpc_close(work->sess, id);
5348 rsp->StructureSize = cpu_to_le16(60);
5351 rsp->CreationTime = 0;
5352 rsp->LastAccessTime = 0;
5353 rsp->LastWriteTime = 0;
5354 rsp->ChangeTime = 0;
5355 rsp->AllocationSize = 0;
5357 rsp->Attributes = 0;
5359 return ksmbd_iov_pin_rsp(work, (void *)rsp,
5360 sizeof(struct smb2_close_rsp));
5364 * smb2_close() - handler for smb2 close file command
5365 * @work: smb work containing close request buffer
5369 int smb2_close(struct ksmbd_work *work)
5371 u64 volatile_id = KSMBD_NO_FID;
5373 struct smb2_close_req *req;
5374 struct smb2_close_rsp *rsp;
5375 struct ksmbd_conn *conn = work->conn;
5376 struct ksmbd_file *fp;
5377 struct inode *inode;
5381 WORK_BUFFERS(work, req, rsp);
5383 if (test_share_config_flag(work->tcon->share_conf,
5384 KSMBD_SHARE_FLAG_PIPE)) {
5385 ksmbd_debug(SMB, "IPC pipe close request\n");
5386 return smb2_close_pipe(work);
5389 sess_id = le64_to_cpu(req->hdr.SessionId);
5390 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5391 sess_id = work->compound_sid;
5393 work->compound_sid = 0;
5394 if (check_session_id(conn, sess_id)) {
5395 work->compound_sid = sess_id;
5397 rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
5398 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5399 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
5404 if (work->next_smb2_rcv_hdr_off &&
5405 !has_file_id(req->VolatileFileId)) {
5406 if (!has_file_id(work->compound_fid)) {
5407 /* file already closed, return FILE_CLOSED */
5408 ksmbd_debug(SMB, "file already closed\n");
5409 rsp->hdr.Status = STATUS_FILE_CLOSED;
5414 "Compound request set FID = %llu:%llu\n",
5416 work->compound_pfid);
5417 volatile_id = work->compound_fid;
5419 /* file closed, stored id is not valid anymore */
5420 work->compound_fid = KSMBD_NO_FID;
5421 work->compound_pfid = KSMBD_NO_FID;
5424 volatile_id = req->VolatileFileId;
5426 ksmbd_debug(SMB, "volatile_id = %llu\n", volatile_id);
5428 rsp->StructureSize = cpu_to_le16(60);
5431 if (req->Flags == SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB) {
5432 fp = ksmbd_lookup_fd_fast(work, volatile_id);
5438 inode = file_inode(fp->filp);
5439 rsp->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB;
5440 rsp->AllocationSize = S_ISDIR(inode->i_mode) ? 0 :
5441 cpu_to_le64(inode->i_blocks << 9);
5442 rsp->EndOfFile = cpu_to_le64(inode->i_size);
5443 rsp->Attributes = fp->f_ci->m_fattr;
5444 rsp->CreationTime = cpu_to_le64(fp->create_time);
5445 time = ksmbd_UnixTimeToNT(inode->i_atime);
5446 rsp->LastAccessTime = cpu_to_le64(time);
5447 time = ksmbd_UnixTimeToNT(inode->i_mtime);
5448 rsp->LastWriteTime = cpu_to_le64(time);
5449 time = ksmbd_UnixTimeToNT(inode_get_ctime(inode));
5450 rsp->ChangeTime = cpu_to_le64(time);
5451 ksmbd_fd_put(work, fp);
5454 rsp->AllocationSize = 0;
5456 rsp->Attributes = 0;
5457 rsp->CreationTime = 0;
5458 rsp->LastAccessTime = 0;
5459 rsp->LastWriteTime = 0;
5460 rsp->ChangeTime = 0;
5463 err = ksmbd_close_fd(work, volatile_id);
5466 err = ksmbd_iov_pin_rsp(work, (void *)rsp,
5467 sizeof(struct smb2_close_rsp));
5470 if (rsp->hdr.Status == 0)
5471 rsp->hdr.Status = STATUS_FILE_CLOSED;
5472 smb2_set_err_rsp(work);
5479 * smb2_echo() - handler for smb2 echo(ping) command
5480 * @work: smb work containing echo request buffer
5484 int smb2_echo(struct ksmbd_work *work)
5486 struct smb2_echo_rsp *rsp = smb2_get_msg(work->response_buf);
5488 if (work->next_smb2_rcv_hdr_off)
5489 rsp = ksmbd_resp_buf_next(work);
5491 rsp->StructureSize = cpu_to_le16(4);
5493 return ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_echo_rsp));
5496 static int smb2_rename(struct ksmbd_work *work,
5497 struct ksmbd_file *fp,
5498 struct smb2_file_rename_info *file_info,
5499 struct nls_table *local_nls)
5501 struct ksmbd_share_config *share = fp->tcon->share_conf;
5502 char *new_name = NULL;
5505 ksmbd_debug(SMB, "setting FILE_RENAME_INFO\n");
5506 new_name = smb2_get_name(file_info->FileName,
5507 le32_to_cpu(file_info->FileNameLength),
5509 if (IS_ERR(new_name))
5510 return PTR_ERR(new_name);
5512 if (strchr(new_name, ':')) {
5514 char *xattr_stream_name, *stream_name = NULL;
5515 size_t xattr_stream_size;
5518 rc = parse_stream_name(new_name, &stream_name, &s_type);
5522 len = strlen(new_name);
5523 if (len > 0 && new_name[len - 1] != '/') {
5524 pr_err("not allow base filename in rename\n");
5529 rc = ksmbd_vfs_xattr_stream_name(stream_name,
5536 rc = ksmbd_vfs_setxattr(file_mnt_idmap(fp->filp),
5541 pr_err("failed to store stream name in xattr: %d\n",
5550 ksmbd_debug(SMB, "new name %s\n", new_name);
5551 if (ksmbd_share_veto_filename(share, new_name)) {
5553 ksmbd_debug(SMB, "Can't rename vetoed file: %s\n", new_name);
5557 if (!file_info->ReplaceIfExists)
5558 flags = RENAME_NOREPLACE;
5560 rc = ksmbd_vfs_rename(work, &fp->filp->f_path, new_name, flags);
5566 static int smb2_create_link(struct ksmbd_work *work,
5567 struct ksmbd_share_config *share,
5568 struct smb2_file_link_info *file_info,
5569 unsigned int buf_len, struct file *filp,
5570 struct nls_table *local_nls)
5572 char *link_name = NULL, *target_name = NULL, *pathname = NULL;
5573 struct path path, parent_path;
5574 bool file_present = false;
5577 if (buf_len < (u64)sizeof(struct smb2_file_link_info) +
5578 le32_to_cpu(file_info->FileNameLength))
5581 ksmbd_debug(SMB, "setting FILE_LINK_INFORMATION\n");
5582 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
5586 link_name = smb2_get_name(file_info->FileName,
5587 le32_to_cpu(file_info->FileNameLength),
5589 if (IS_ERR(link_name) || S_ISDIR(file_inode(filp)->i_mode)) {
5594 ksmbd_debug(SMB, "link name is %s\n", link_name);
5595 target_name = file_path(filp, pathname, PATH_MAX);
5596 if (IS_ERR(target_name)) {
5601 ksmbd_debug(SMB, "target name is %s\n", target_name);
5602 rc = ksmbd_vfs_kern_path_locked(work, link_name, LOOKUP_NO_SYMLINKS,
5603 &parent_path, &path, 0);
5608 file_present = true;
5610 if (file_info->ReplaceIfExists) {
5612 rc = ksmbd_vfs_remove_file(work, &path);
5615 ksmbd_debug(SMB, "cannot delete %s\n",
5623 ksmbd_debug(SMB, "link already exists\n");
5628 rc = ksmbd_vfs_link(work, target_name, link_name);
5633 inode_unlock(d_inode(parent_path.dentry));
5635 path_put(&parent_path);
5637 if (!IS_ERR(link_name))
5643 static int set_file_basic_info(struct ksmbd_file *fp,
5644 struct smb2_file_basic_info *file_info,
5645 struct ksmbd_share_config *share)
5649 struct inode *inode;
5650 struct mnt_idmap *idmap;
5653 if (!(fp->daccess & FILE_WRITE_ATTRIBUTES_LE))
5658 inode = file_inode(filp);
5659 idmap = file_mnt_idmap(filp);
5661 if (file_info->CreationTime)
5662 fp->create_time = le64_to_cpu(file_info->CreationTime);
5664 if (file_info->LastAccessTime) {
5665 attrs.ia_atime = ksmbd_NTtimeToUnix(file_info->LastAccessTime);
5666 attrs.ia_valid |= (ATTR_ATIME | ATTR_ATIME_SET);
5669 attrs.ia_valid |= ATTR_CTIME;
5670 if (file_info->ChangeTime)
5671 attrs.ia_ctime = ksmbd_NTtimeToUnix(file_info->ChangeTime);
5673 attrs.ia_ctime = inode_get_ctime(inode);
5675 if (file_info->LastWriteTime) {
5676 attrs.ia_mtime = ksmbd_NTtimeToUnix(file_info->LastWriteTime);
5677 attrs.ia_valid |= (ATTR_MTIME | ATTR_MTIME_SET);
5680 if (file_info->Attributes) {
5681 if (!S_ISDIR(inode->i_mode) &&
5682 file_info->Attributes & FILE_ATTRIBUTE_DIRECTORY_LE) {
5683 pr_err("can't change a file to a directory\n");
5687 if (!(S_ISDIR(inode->i_mode) && file_info->Attributes == FILE_ATTRIBUTE_NORMAL_LE))
5688 fp->f_ci->m_fattr = file_info->Attributes |
5689 (fp->f_ci->m_fattr & FILE_ATTRIBUTE_DIRECTORY_LE);
5692 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_STORE_DOS_ATTRS) &&
5693 (file_info->CreationTime || file_info->Attributes)) {
5694 struct xattr_dos_attrib da = {0};
5697 da.itime = fp->itime;
5698 da.create_time = fp->create_time;
5699 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
5700 da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
5701 XATTR_DOSINFO_ITIME;
5703 rc = ksmbd_vfs_set_dos_attrib_xattr(idmap, &filp->f_path, &da);
5706 "failed to restore file attribute in EA\n");
5710 if (attrs.ia_valid) {
5711 struct dentry *dentry = filp->f_path.dentry;
5712 struct inode *inode = d_inode(dentry);
5714 if (IS_IMMUTABLE(inode) || IS_APPEND(inode))
5718 inode_set_ctime_to_ts(inode, attrs.ia_ctime);
5719 attrs.ia_valid &= ~ATTR_CTIME;
5720 rc = notify_change(idmap, dentry, &attrs, NULL);
5721 inode_unlock(inode);
5726 static int set_file_allocation_info(struct ksmbd_work *work,
5727 struct ksmbd_file *fp,
5728 struct smb2_file_alloc_info *file_alloc_info)
5731 * TODO : It's working fine only when store dos attributes
5732 * is not yes. need to implement a logic which works
5733 * properly with any smb.conf option
5737 struct inode *inode;
5740 if (!(fp->daccess & FILE_WRITE_DATA_LE))
5743 alloc_blks = (le64_to_cpu(file_alloc_info->AllocationSize) + 511) >> 9;
5744 inode = file_inode(fp->filp);
5746 if (alloc_blks > inode->i_blocks) {
5747 smb_break_all_levII_oplock(work, fp, 1);
5748 rc = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
5750 if (rc && rc != -EOPNOTSUPP) {
5751 pr_err("vfs_fallocate is failed : %d\n", rc);
5754 } else if (alloc_blks < inode->i_blocks) {
5758 * Allocation size could be smaller than original one
5759 * which means allocated blocks in file should be
5760 * deallocated. use truncate to cut out it, but inode
5761 * size is also updated with truncate offset.
5762 * inode size is retained by backup inode size.
5764 size = i_size_read(inode);
5765 rc = ksmbd_vfs_truncate(work, fp, alloc_blks * 512);
5767 pr_err("truncate failed!, err %d\n", rc);
5770 if (size < alloc_blks * 512)
5771 i_size_write(inode, size);
5776 static int set_end_of_file_info(struct ksmbd_work *work, struct ksmbd_file *fp,
5777 struct smb2_file_eof_info *file_eof_info)
5780 struct inode *inode;
5783 if (!(fp->daccess & FILE_WRITE_DATA_LE))
5786 newsize = le64_to_cpu(file_eof_info->EndOfFile);
5787 inode = file_inode(fp->filp);
5790 * If FILE_END_OF_FILE_INFORMATION of set_info_file is called
5791 * on FAT32 shared device, truncate execution time is too long
5792 * and network error could cause from windows client. because
5793 * truncate of some filesystem like FAT32 fill zero data in
5796 if (inode->i_sb->s_magic != MSDOS_SUPER_MAGIC) {
5797 ksmbd_debug(SMB, "truncated to newsize %lld\n", newsize);
5798 rc = ksmbd_vfs_truncate(work, fp, newsize);
5800 ksmbd_debug(SMB, "truncate failed!, err %d\n", rc);
5809 static int set_rename_info(struct ksmbd_work *work, struct ksmbd_file *fp,
5810 struct smb2_file_rename_info *rename_info,
5811 unsigned int buf_len)
5813 if (!(fp->daccess & FILE_DELETE_LE)) {
5814 pr_err("no right to delete : 0x%x\n", fp->daccess);
5818 if (buf_len < (u64)sizeof(struct smb2_file_rename_info) +
5819 le32_to_cpu(rename_info->FileNameLength))
5822 if (!le32_to_cpu(rename_info->FileNameLength))
5825 return smb2_rename(work, fp, rename_info, work->conn->local_nls);
5828 static int set_file_disposition_info(struct ksmbd_file *fp,
5829 struct smb2_file_disposition_info *file_info)
5831 struct inode *inode;
5833 if (!(fp->daccess & FILE_DELETE_LE)) {
5834 pr_err("no right to delete : 0x%x\n", fp->daccess);
5838 inode = file_inode(fp->filp);
5839 if (file_info->DeletePending) {
5840 if (S_ISDIR(inode->i_mode) &&
5841 ksmbd_vfs_empty_dir(fp) == -ENOTEMPTY)
5843 ksmbd_set_inode_pending_delete(fp);
5845 ksmbd_clear_inode_pending_delete(fp);
5850 static int set_file_position_info(struct ksmbd_file *fp,
5851 struct smb2_file_pos_info *file_info)
5853 loff_t current_byte_offset;
5854 unsigned long sector_size;
5855 struct inode *inode;
5857 inode = file_inode(fp->filp);
5858 current_byte_offset = le64_to_cpu(file_info->CurrentByteOffset);
5859 sector_size = inode->i_sb->s_blocksize;
5861 if (current_byte_offset < 0 ||
5862 (fp->coption == FILE_NO_INTERMEDIATE_BUFFERING_LE &&
5863 current_byte_offset & (sector_size - 1))) {
5864 pr_err("CurrentByteOffset is not valid : %llu\n",
5865 current_byte_offset);
5869 fp->filp->f_pos = current_byte_offset;
5873 static int set_file_mode_info(struct ksmbd_file *fp,
5874 struct smb2_file_mode_info *file_info)
5878 mode = file_info->Mode;
5880 if ((mode & ~FILE_MODE_INFO_MASK)) {
5881 pr_err("Mode is not valid : 0x%x\n", le32_to_cpu(mode));
5886 * TODO : need to implement consideration for
5887 * FILE_SYNCHRONOUS_IO_ALERT and FILE_SYNCHRONOUS_IO_NONALERT
5889 ksmbd_vfs_set_fadvise(fp->filp, mode);
5895 * smb2_set_info_file() - handler for smb2 set info command
5896 * @work: smb work containing set info command buffer
5897 * @fp: ksmbd_file pointer
5898 * @req: request buffer pointer
5899 * @share: ksmbd_share_config pointer
5901 * Return: 0 on success, otherwise error
5902 * TODO: need to implement an error handling for STATUS_INFO_LENGTH_MISMATCH
5904 static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp,
5905 struct smb2_set_info_req *req,
5906 struct ksmbd_share_config *share)
5908 unsigned int buf_len = le32_to_cpu(req->BufferLength);
5910 switch (req->FileInfoClass) {
5911 case FILE_BASIC_INFORMATION:
5913 if (buf_len < sizeof(struct smb2_file_basic_info))
5916 return set_file_basic_info(fp, (struct smb2_file_basic_info *)req->Buffer, share);
5918 case FILE_ALLOCATION_INFORMATION:
5920 if (buf_len < sizeof(struct smb2_file_alloc_info))
5923 return set_file_allocation_info(work, fp,
5924 (struct smb2_file_alloc_info *)req->Buffer);
5926 case FILE_END_OF_FILE_INFORMATION:
5928 if (buf_len < sizeof(struct smb2_file_eof_info))
5931 return set_end_of_file_info(work, fp,
5932 (struct smb2_file_eof_info *)req->Buffer);
5934 case FILE_RENAME_INFORMATION:
5936 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
5938 "User does not have write permission\n");
5942 if (buf_len < sizeof(struct smb2_file_rename_info))
5945 return set_rename_info(work, fp,
5946 (struct smb2_file_rename_info *)req->Buffer,
5949 case FILE_LINK_INFORMATION:
5951 if (buf_len < sizeof(struct smb2_file_link_info))
5954 return smb2_create_link(work, work->tcon->share_conf,
5955 (struct smb2_file_link_info *)req->Buffer,
5957 work->conn->local_nls);
5959 case FILE_DISPOSITION_INFORMATION:
5961 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
5963 "User does not have write permission\n");
5967 if (buf_len < sizeof(struct smb2_file_disposition_info))
5970 return set_file_disposition_info(fp,
5971 (struct smb2_file_disposition_info *)req->Buffer);
5973 case FILE_FULL_EA_INFORMATION:
5975 if (!(fp->daccess & FILE_WRITE_EA_LE)) {
5976 pr_err("Not permitted to write ext attr: 0x%x\n",
5981 if (buf_len < sizeof(struct smb2_ea_info))
5984 return smb2_set_ea((struct smb2_ea_info *)req->Buffer,
5985 buf_len, &fp->filp->f_path);
5987 case FILE_POSITION_INFORMATION:
5989 if (buf_len < sizeof(struct smb2_file_pos_info))
5992 return set_file_position_info(fp, (struct smb2_file_pos_info *)req->Buffer);
5994 case FILE_MODE_INFORMATION:
5996 if (buf_len < sizeof(struct smb2_file_mode_info))
5999 return set_file_mode_info(fp, (struct smb2_file_mode_info *)req->Buffer);
6003 pr_err("Unimplemented Fileinfoclass :%d\n", req->FileInfoClass);
6007 static int smb2_set_info_sec(struct ksmbd_file *fp, int addition_info,
6008 char *buffer, int buf_len)
6010 struct smb_ntsd *pntsd = (struct smb_ntsd *)buffer;
6012 fp->saccess |= FILE_SHARE_DELETE_LE;
6014 return set_info_sec(fp->conn, fp->tcon, &fp->filp->f_path, pntsd,
6019 * smb2_set_info() - handler for smb2 set info command handler
6020 * @work: smb work containing set info request buffer
6022 * Return: 0 on success, otherwise error
6024 int smb2_set_info(struct ksmbd_work *work)
6026 struct smb2_set_info_req *req;
6027 struct smb2_set_info_rsp *rsp;
6028 struct ksmbd_file *fp;
6030 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
6032 ksmbd_debug(SMB, "Received set info request\n");
6034 if (work->next_smb2_rcv_hdr_off) {
6035 req = ksmbd_req_buf_next(work);
6036 rsp = ksmbd_resp_buf_next(work);
6037 if (!has_file_id(req->VolatileFileId)) {
6038 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
6039 work->compound_fid);
6040 id = work->compound_fid;
6041 pid = work->compound_pfid;
6044 req = smb2_get_msg(work->request_buf);
6045 rsp = smb2_get_msg(work->response_buf);
6048 if (!has_file_id(id)) {
6049 id = req->VolatileFileId;
6050 pid = req->PersistentFileId;
6053 fp = ksmbd_lookup_fd_slow(work, id, pid);
6055 ksmbd_debug(SMB, "Invalid id for close: %u\n", id);
6060 switch (req->InfoType) {
6061 case SMB2_O_INFO_FILE:
6062 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
6063 rc = smb2_set_info_file(work, fp, req, work->tcon->share_conf);
6065 case SMB2_O_INFO_SECURITY:
6066 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
6067 if (ksmbd_override_fsids(work)) {
6071 rc = smb2_set_info_sec(fp,
6072 le32_to_cpu(req->AdditionalInformation),
6074 le32_to_cpu(req->BufferLength));
6075 ksmbd_revert_fsids(work);
6084 rsp->StructureSize = cpu_to_le16(2);
6085 rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
6086 sizeof(struct smb2_set_info_rsp));
6089 ksmbd_fd_put(work, fp);
6093 if (rc == -EACCES || rc == -EPERM || rc == -EXDEV)
6094 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6095 else if (rc == -EINVAL)
6096 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6097 else if (rc == -ESHARE)
6098 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6099 else if (rc == -ENOENT)
6100 rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
6101 else if (rc == -EBUSY || rc == -ENOTEMPTY)
6102 rsp->hdr.Status = STATUS_DIRECTORY_NOT_EMPTY;
6103 else if (rc == -EAGAIN)
6104 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6105 else if (rc == -EBADF || rc == -ESTALE)
6106 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6107 else if (rc == -EEXIST)
6108 rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
6109 else if (rsp->hdr.Status == 0 || rc == -EOPNOTSUPP)
6110 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
6111 smb2_set_err_rsp(work);
6112 ksmbd_fd_put(work, fp);
6113 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n", rc);
6118 * smb2_read_pipe() - handler for smb2 read from IPC pipe
6119 * @work: smb work containing read IPC pipe command buffer
6121 * Return: 0 on success, otherwise error
6123 static noinline int smb2_read_pipe(struct ksmbd_work *work)
6125 int nbytes = 0, err;
6127 struct ksmbd_rpc_command *rpc_resp;
6128 struct smb2_read_req *req;
6129 struct smb2_read_rsp *rsp;
6131 WORK_BUFFERS(work, req, rsp);
6133 id = req->VolatileFileId;
6135 rpc_resp = ksmbd_rpc_read(work->sess, id);
6137 void *aux_payload_buf;
6139 if (rpc_resp->flags != KSMBD_RPC_OK) {
6145 kvmalloc(rpc_resp->payload_sz, GFP_KERNEL);
6146 if (!aux_payload_buf) {
6151 memcpy(aux_payload_buf, rpc_resp->payload, rpc_resp->payload_sz);
6153 nbytes = rpc_resp->payload_sz;
6155 err = ksmbd_iov_pin_rsp_read(work, (void *)rsp,
6156 offsetof(struct smb2_read_rsp, Buffer),
6157 aux_payload_buf, nbytes);
6161 err = ksmbd_iov_pin_rsp(work, (void *)rsp,
6162 offsetof(struct smb2_read_rsp, Buffer));
6167 rsp->StructureSize = cpu_to_le16(17);
6168 rsp->DataOffset = 80;
6170 rsp->DataLength = cpu_to_le32(nbytes);
6171 rsp->DataRemaining = 0;
6176 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
6177 smb2_set_err_rsp(work);
6182 static int smb2_set_remote_key_for_rdma(struct ksmbd_work *work,
6183 struct smb2_buffer_desc_v1 *desc,
6185 __le16 ChannelInfoLength)
6187 unsigned int i, ch_count;
6189 if (work->conn->dialect == SMB30_PROT_ID &&
6190 Channel != SMB2_CHANNEL_RDMA_V1)
6193 ch_count = le16_to_cpu(ChannelInfoLength) / sizeof(*desc);
6194 if (ksmbd_debug_types & KSMBD_DEBUG_RDMA) {
6195 for (i = 0; i < ch_count; i++) {
6196 pr_info("RDMA r/w request %#x: token %#x, length %#x\n",
6198 le32_to_cpu(desc[i].token),
6199 le32_to_cpu(desc[i].length));
6205 work->need_invalidate_rkey =
6206 (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE);
6207 if (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE)
6208 work->remote_key = le32_to_cpu(desc->token);
6212 static ssize_t smb2_read_rdma_channel(struct ksmbd_work *work,
6213 struct smb2_read_req *req, void *data_buf,
6218 err = ksmbd_conn_rdma_write(work->conn, data_buf, length,
6219 (struct smb2_buffer_desc_v1 *)
6220 ((char *)req + le16_to_cpu(req->ReadChannelInfoOffset)),
6221 le16_to_cpu(req->ReadChannelInfoLength));
6229 * smb2_read() - handler for smb2 read from file
6230 * @work: smb work containing read command buffer
6232 * Return: 0 on success, otherwise error
6234 int smb2_read(struct ksmbd_work *work)
6236 struct ksmbd_conn *conn = work->conn;
6237 struct smb2_read_req *req;
6238 struct smb2_read_rsp *rsp;
6239 struct ksmbd_file *fp = NULL;
6241 size_t length, mincount;
6242 ssize_t nbytes = 0, remain_bytes = 0;
6244 bool is_rdma_channel = false;
6245 unsigned int max_read_size = conn->vals->max_read_size;
6246 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
6247 void *aux_payload_buf;
6249 if (test_share_config_flag(work->tcon->share_conf,
6250 KSMBD_SHARE_FLAG_PIPE)) {
6251 ksmbd_debug(SMB, "IPC pipe read request\n");
6252 return smb2_read_pipe(work);
6255 if (work->next_smb2_rcv_hdr_off) {
6256 req = ksmbd_req_buf_next(work);
6257 rsp = ksmbd_resp_buf_next(work);
6258 if (!has_file_id(req->VolatileFileId)) {
6259 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
6260 work->compound_fid);
6261 id = work->compound_fid;
6262 pid = work->compound_pfid;
6265 req = smb2_get_msg(work->request_buf);
6266 rsp = smb2_get_msg(work->response_buf);
6269 if (!has_file_id(id)) {
6270 id = req->VolatileFileId;
6271 pid = req->PersistentFileId;
6274 if (req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE ||
6275 req->Channel == SMB2_CHANNEL_RDMA_V1) {
6276 is_rdma_channel = true;
6277 max_read_size = get_smbd_max_read_write_size();
6280 if (is_rdma_channel == true) {
6281 unsigned int ch_offset = le16_to_cpu(req->ReadChannelInfoOffset);
6283 if (ch_offset < offsetof(struct smb2_read_req, Buffer)) {
6287 err = smb2_set_remote_key_for_rdma(work,
6288 (struct smb2_buffer_desc_v1 *)
6289 ((char *)req + ch_offset),
6291 req->ReadChannelInfoLength);
6296 fp = ksmbd_lookup_fd_slow(work, id, pid);
6302 if (!(fp->daccess & (FILE_READ_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
6303 pr_err("Not permitted to read : 0x%x\n", fp->daccess);
6308 offset = le64_to_cpu(req->Offset);
6309 length = le32_to_cpu(req->Length);
6310 mincount = le32_to_cpu(req->MinimumCount);
6312 if (length > max_read_size) {
6313 ksmbd_debug(SMB, "limiting read size to max size(%u)\n",
6319 ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
6320 fp->filp, offset, length);
6322 aux_payload_buf = kvzalloc(length, GFP_KERNEL);
6323 if (!aux_payload_buf) {
6328 nbytes = ksmbd_vfs_read(work, fp, length, &offset, aux_payload_buf);
6334 if ((nbytes == 0 && length != 0) || nbytes < mincount) {
6335 kvfree(aux_payload_buf);
6336 rsp->hdr.Status = STATUS_END_OF_FILE;
6337 smb2_set_err_rsp(work);
6338 ksmbd_fd_put(work, fp);
6342 ksmbd_debug(SMB, "nbytes %zu, offset %lld mincount %zu\n",
6343 nbytes, offset, mincount);
6345 if (is_rdma_channel == true) {
6346 /* write data to the client using rdma channel */
6347 remain_bytes = smb2_read_rdma_channel(work, req,
6350 kvfree(aux_payload_buf);
6351 aux_payload_buf = NULL;
6353 if (remain_bytes < 0) {
6354 err = (int)remain_bytes;
6359 rsp->StructureSize = cpu_to_le16(17);
6360 rsp->DataOffset = 80;
6362 rsp->DataLength = cpu_to_le32(nbytes);
6363 rsp->DataRemaining = cpu_to_le32(remain_bytes);
6365 err = ksmbd_iov_pin_rsp_read(work, (void *)rsp,
6366 offsetof(struct smb2_read_rsp, Buffer),
6367 aux_payload_buf, nbytes);
6370 ksmbd_fd_put(work, fp);
6376 rsp->hdr.Status = STATUS_INVALID_DEVICE_REQUEST;
6377 else if (err == -EAGAIN)
6378 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6379 else if (err == -ENOENT)
6380 rsp->hdr.Status = STATUS_FILE_CLOSED;
6381 else if (err == -EACCES)
6382 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6383 else if (err == -ESHARE)
6384 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6385 else if (err == -EINVAL)
6386 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6388 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6390 smb2_set_err_rsp(work);
6392 ksmbd_fd_put(work, fp);
6397 * smb2_write_pipe() - handler for smb2 write on IPC pipe
6398 * @work: smb work containing write IPC pipe command buffer
6400 * Return: 0 on success, otherwise error
6402 static noinline int smb2_write_pipe(struct ksmbd_work *work)
6404 struct smb2_write_req *req;
6405 struct smb2_write_rsp *rsp;
6406 struct ksmbd_rpc_command *rpc_resp;
6408 int err = 0, ret = 0;
6412 WORK_BUFFERS(work, req, rsp);
6414 length = le32_to_cpu(req->Length);
6415 id = req->VolatileFileId;
6417 if ((u64)le16_to_cpu(req->DataOffset) + length >
6418 get_rfc1002_len(work->request_buf)) {
6419 pr_err("invalid write data offset %u, smb_len %u\n",
6420 le16_to_cpu(req->DataOffset),
6421 get_rfc1002_len(work->request_buf));
6426 data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
6427 le16_to_cpu(req->DataOffset));
6429 rpc_resp = ksmbd_rpc_write(work->sess, id, data_buf, length);
6431 if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
6432 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
6434 smb2_set_err_rsp(work);
6437 if (rpc_resp->flags != KSMBD_RPC_OK) {
6438 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6439 smb2_set_err_rsp(work);
6446 rsp->StructureSize = cpu_to_le16(17);
6447 rsp->DataOffset = 0;
6449 rsp->DataLength = cpu_to_le32(length);
6450 rsp->DataRemaining = 0;
6452 err = ksmbd_iov_pin_rsp(work, (void *)rsp,
6453 offsetof(struct smb2_write_rsp, Buffer));
6456 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6457 smb2_set_err_rsp(work);
6463 static ssize_t smb2_write_rdma_channel(struct ksmbd_work *work,
6464 struct smb2_write_req *req,
6465 struct ksmbd_file *fp,
6466 loff_t offset, size_t length, bool sync)
6472 data_buf = kvzalloc(length, GFP_KERNEL);
6476 ret = ksmbd_conn_rdma_read(work->conn, data_buf, length,
6477 (struct smb2_buffer_desc_v1 *)
6478 ((char *)req + le16_to_cpu(req->WriteChannelInfoOffset)),
6479 le16_to_cpu(req->WriteChannelInfoLength));
6485 ret = ksmbd_vfs_write(work, fp, data_buf, length, &offset, sync, &nbytes);
6494 * smb2_write() - handler for smb2 write from file
6495 * @work: smb work containing write command buffer
6497 * Return: 0 on success, otherwise error
6499 int smb2_write(struct ksmbd_work *work)
6501 struct smb2_write_req *req;
6502 struct smb2_write_rsp *rsp;
6503 struct ksmbd_file *fp = NULL;
6508 bool writethrough = false, is_rdma_channel = false;
6510 unsigned int max_write_size = work->conn->vals->max_write_size;
6512 WORK_BUFFERS(work, req, rsp);
6514 if (test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_PIPE)) {
6515 ksmbd_debug(SMB, "IPC pipe write request\n");
6516 return smb2_write_pipe(work);
6519 offset = le64_to_cpu(req->Offset);
6520 length = le32_to_cpu(req->Length);
6522 if (req->Channel == SMB2_CHANNEL_RDMA_V1 ||
6523 req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE) {
6524 is_rdma_channel = true;
6525 max_write_size = get_smbd_max_read_write_size();
6526 length = le32_to_cpu(req->RemainingBytes);
6529 if (is_rdma_channel == true) {
6530 unsigned int ch_offset = le16_to_cpu(req->WriteChannelInfoOffset);
6532 if (req->Length != 0 || req->DataOffset != 0 ||
6533 ch_offset < offsetof(struct smb2_write_req, Buffer)) {
6537 err = smb2_set_remote_key_for_rdma(work,
6538 (struct smb2_buffer_desc_v1 *)
6539 ((char *)req + ch_offset),
6541 req->WriteChannelInfoLength);
6546 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
6547 ksmbd_debug(SMB, "User does not have write permission\n");
6552 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
6558 if (!(fp->daccess & (FILE_WRITE_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
6559 pr_err("Not permitted to write : 0x%x\n", fp->daccess);
6564 if (length > max_write_size) {
6565 ksmbd_debug(SMB, "limiting write size to max size(%u)\n",
6571 ksmbd_debug(SMB, "flags %u\n", le32_to_cpu(req->Flags));
6572 if (le32_to_cpu(req->Flags) & SMB2_WRITEFLAG_WRITE_THROUGH)
6573 writethrough = true;
6575 if (is_rdma_channel == false) {
6576 if (le16_to_cpu(req->DataOffset) <
6577 offsetof(struct smb2_write_req, Buffer)) {
6582 data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
6583 le16_to_cpu(req->DataOffset));
6585 ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
6586 fp->filp, offset, length);
6587 err = ksmbd_vfs_write(work, fp, data_buf, length, &offset,
6588 writethrough, &nbytes);
6592 /* read data from the client using rdma channel, and
6595 nbytes = smb2_write_rdma_channel(work, req, fp, offset, length,
6603 rsp->StructureSize = cpu_to_le16(17);
6604 rsp->DataOffset = 0;
6606 rsp->DataLength = cpu_to_le32(nbytes);
6607 rsp->DataRemaining = 0;
6609 err = ksmbd_iov_pin_rsp(work, rsp, offsetof(struct smb2_write_rsp, Buffer));
6612 ksmbd_fd_put(work, fp);
6617 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6618 else if (err == -ENOSPC || err == -EFBIG)
6619 rsp->hdr.Status = STATUS_DISK_FULL;
6620 else if (err == -ENOENT)
6621 rsp->hdr.Status = STATUS_FILE_CLOSED;
6622 else if (err == -EACCES)
6623 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6624 else if (err == -ESHARE)
6625 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6626 else if (err == -EINVAL)
6627 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6629 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6631 smb2_set_err_rsp(work);
6632 ksmbd_fd_put(work, fp);
6637 * smb2_flush() - handler for smb2 flush file - fsync
6638 * @work: smb work containing flush command buffer
6640 * Return: 0 on success, otherwise error
6642 int smb2_flush(struct ksmbd_work *work)
6644 struct smb2_flush_req *req;
6645 struct smb2_flush_rsp *rsp;
6648 WORK_BUFFERS(work, req, rsp);
6650 ksmbd_debug(SMB, "SMB2_FLUSH called for fid %llu\n", req->VolatileFileId);
6652 err = ksmbd_vfs_fsync(work, req->VolatileFileId, req->PersistentFileId);
6656 rsp->StructureSize = cpu_to_le16(4);
6658 return ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_flush_rsp));
6661 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6662 smb2_set_err_rsp(work);
6667 * smb2_cancel() - handler for smb2 cancel command
6668 * @work: smb work containing cancel command buffer
6670 * Return: 0 on success, otherwise error
6672 int smb2_cancel(struct ksmbd_work *work)
6674 struct ksmbd_conn *conn = work->conn;
6675 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
6676 struct smb2_hdr *chdr;
6677 struct ksmbd_work *iter;
6678 struct list_head *command_list;
6680 if (work->next_smb2_rcv_hdr_off)
6681 hdr = ksmbd_resp_buf_next(work);
6683 ksmbd_debug(SMB, "smb2 cancel called on mid %llu, async flags 0x%x\n",
6684 hdr->MessageId, hdr->Flags);
6686 if (hdr->Flags & SMB2_FLAGS_ASYNC_COMMAND) {
6687 command_list = &conn->async_requests;
6689 spin_lock(&conn->request_lock);
6690 list_for_each_entry(iter, command_list,
6691 async_request_entry) {
6692 chdr = smb2_get_msg(iter->request_buf);
6694 if (iter->async_id !=
6695 le64_to_cpu(hdr->Id.AsyncId))
6699 "smb2 with AsyncId %llu cancelled command = 0x%x\n",
6700 le64_to_cpu(hdr->Id.AsyncId),
6701 le16_to_cpu(chdr->Command));
6702 iter->state = KSMBD_WORK_CANCELLED;
6703 if (iter->cancel_fn)
6704 iter->cancel_fn(iter->cancel_argv);
6707 spin_unlock(&conn->request_lock);
6709 command_list = &conn->requests;
6711 spin_lock(&conn->request_lock);
6712 list_for_each_entry(iter, command_list, request_entry) {
6713 chdr = smb2_get_msg(iter->request_buf);
6715 if (chdr->MessageId != hdr->MessageId ||
6720 "smb2 with mid %llu cancelled command = 0x%x\n",
6721 le64_to_cpu(hdr->MessageId),
6722 le16_to_cpu(chdr->Command));
6723 iter->state = KSMBD_WORK_CANCELLED;
6726 spin_unlock(&conn->request_lock);
6729 /* For SMB2_CANCEL command itself send no response*/
6730 work->send_no_response = 1;
6734 struct file_lock *smb_flock_init(struct file *f)
6736 struct file_lock *fl;
6738 fl = locks_alloc_lock();
6742 locks_init_lock(fl);
6745 fl->fl_pid = current->tgid;
6747 fl->fl_flags = FL_POSIX;
6749 fl->fl_lmops = NULL;
6755 static int smb2_set_flock_flags(struct file_lock *flock, int flags)
6759 /* Checking for wrong flag combination during lock request*/
6761 case SMB2_LOCKFLAG_SHARED:
6762 ksmbd_debug(SMB, "received shared request\n");
6764 flock->fl_type = F_RDLCK;
6765 flock->fl_flags |= FL_SLEEP;
6767 case SMB2_LOCKFLAG_EXCLUSIVE:
6768 ksmbd_debug(SMB, "received exclusive request\n");
6770 flock->fl_type = F_WRLCK;
6771 flock->fl_flags |= FL_SLEEP;
6773 case SMB2_LOCKFLAG_SHARED | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
6775 "received shared & fail immediately request\n");
6777 flock->fl_type = F_RDLCK;
6779 case SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
6781 "received exclusive & fail immediately request\n");
6783 flock->fl_type = F_WRLCK;
6785 case SMB2_LOCKFLAG_UNLOCK:
6786 ksmbd_debug(SMB, "received unlock request\n");
6787 flock->fl_type = F_UNLCK;
6795 static struct ksmbd_lock *smb2_lock_init(struct file_lock *flock,
6796 unsigned int cmd, int flags,
6797 struct list_head *lock_list)
6799 struct ksmbd_lock *lock;
6801 lock = kzalloc(sizeof(struct ksmbd_lock), GFP_KERNEL);
6807 lock->start = flock->fl_start;
6808 lock->end = flock->fl_end;
6809 lock->flags = flags;
6810 if (lock->start == lock->end)
6812 INIT_LIST_HEAD(&lock->clist);
6813 INIT_LIST_HEAD(&lock->flist);
6814 INIT_LIST_HEAD(&lock->llist);
6815 list_add_tail(&lock->llist, lock_list);
6820 static void smb2_remove_blocked_lock(void **argv)
6822 struct file_lock *flock = (struct file_lock *)argv[0];
6824 ksmbd_vfs_posix_lock_unblock(flock);
6825 wake_up(&flock->fl_wait);
6828 static inline bool lock_defer_pending(struct file_lock *fl)
6830 /* check pending lock waiters */
6831 return waitqueue_active(&fl->fl_wait);
6835 * smb2_lock() - handler for smb2 file lock command
6836 * @work: smb work containing lock command buffer
6838 * Return: 0 on success, otherwise error
6840 int smb2_lock(struct ksmbd_work *work)
6842 struct smb2_lock_req *req;
6843 struct smb2_lock_rsp *rsp;
6844 struct smb2_lock_element *lock_ele;
6845 struct ksmbd_file *fp = NULL;
6846 struct file_lock *flock = NULL;
6847 struct file *filp = NULL;
6851 int err = -EIO, i, rc = 0;
6852 u64 lock_start, lock_length;
6853 struct ksmbd_lock *smb_lock = NULL, *cmp_lock, *tmp, *tmp2;
6854 struct ksmbd_conn *conn;
6856 LIST_HEAD(lock_list);
6857 LIST_HEAD(rollback_list);
6860 WORK_BUFFERS(work, req, rsp);
6862 ksmbd_debug(SMB, "Received lock request\n");
6863 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
6865 ksmbd_debug(SMB, "Invalid file id for lock : %llu\n", req->VolatileFileId);
6871 lock_count = le16_to_cpu(req->LockCount);
6872 lock_ele = req->locks;
6874 ksmbd_debug(SMB, "lock count is %d\n", lock_count);
6880 for (i = 0; i < lock_count; i++) {
6881 flags = le32_to_cpu(lock_ele[i].Flags);
6883 flock = smb_flock_init(filp);
6887 cmd = smb2_set_flock_flags(flock, flags);
6889 lock_start = le64_to_cpu(lock_ele[i].Offset);
6890 lock_length = le64_to_cpu(lock_ele[i].Length);
6891 if (lock_start > U64_MAX - lock_length) {
6892 pr_err("Invalid lock range requested\n");
6893 rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
6894 locks_free_lock(flock);
6898 if (lock_start > OFFSET_MAX)
6899 flock->fl_start = OFFSET_MAX;
6901 flock->fl_start = lock_start;
6903 lock_length = le64_to_cpu(lock_ele[i].Length);
6904 if (lock_length > OFFSET_MAX - flock->fl_start)
6905 lock_length = OFFSET_MAX - flock->fl_start;
6907 flock->fl_end = flock->fl_start + lock_length;
6909 if (flock->fl_end < flock->fl_start) {
6911 "the end offset(%llx) is smaller than the start offset(%llx)\n",
6912 flock->fl_end, flock->fl_start);
6913 rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
6914 locks_free_lock(flock);
6918 /* Check conflict locks in one request */
6919 list_for_each_entry(cmp_lock, &lock_list, llist) {
6920 if (cmp_lock->fl->fl_start <= flock->fl_start &&
6921 cmp_lock->fl->fl_end >= flock->fl_end) {
6922 if (cmp_lock->fl->fl_type != F_UNLCK &&
6923 flock->fl_type != F_UNLCK) {
6924 pr_err("conflict two locks in one request\n");
6926 locks_free_lock(flock);
6932 smb_lock = smb2_lock_init(flock, cmd, flags, &lock_list);
6935 locks_free_lock(flock);
6940 list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
6941 if (smb_lock->cmd < 0) {
6946 if (!(smb_lock->flags & SMB2_LOCKFLAG_MASK)) {
6951 if ((prior_lock & (SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_SHARED) &&
6952 smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) ||
6953 (prior_lock == SMB2_LOCKFLAG_UNLOCK &&
6954 !(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK))) {
6959 prior_lock = smb_lock->flags;
6961 if (!(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) &&
6962 !(smb_lock->flags & SMB2_LOCKFLAG_FAIL_IMMEDIATELY))
6966 /* check locks in connection list */
6967 down_read(&conn_list_lock);
6968 list_for_each_entry(conn, &conn_list, conns_list) {
6969 spin_lock(&conn->llist_lock);
6970 list_for_each_entry_safe(cmp_lock, tmp2, &conn->lock_list, clist) {
6971 if (file_inode(cmp_lock->fl->fl_file) !=
6972 file_inode(smb_lock->fl->fl_file))
6975 if (smb_lock->fl->fl_type == F_UNLCK) {
6976 if (cmp_lock->fl->fl_file == smb_lock->fl->fl_file &&
6977 cmp_lock->start == smb_lock->start &&
6978 cmp_lock->end == smb_lock->end &&
6979 !lock_defer_pending(cmp_lock->fl)) {
6981 list_del(&cmp_lock->flist);
6982 list_del(&cmp_lock->clist);
6983 spin_unlock(&conn->llist_lock);
6984 up_read(&conn_list_lock);
6986 locks_free_lock(cmp_lock->fl);
6993 if (cmp_lock->fl->fl_file == smb_lock->fl->fl_file) {
6994 if (smb_lock->flags & SMB2_LOCKFLAG_SHARED)
6997 if (cmp_lock->flags & SMB2_LOCKFLAG_SHARED)
7001 /* check zero byte lock range */
7002 if (cmp_lock->zero_len && !smb_lock->zero_len &&
7003 cmp_lock->start > smb_lock->start &&
7004 cmp_lock->start < smb_lock->end) {
7005 spin_unlock(&conn->llist_lock);
7006 up_read(&conn_list_lock);
7007 pr_err("previous lock conflict with zero byte lock range\n");
7011 if (smb_lock->zero_len && !cmp_lock->zero_len &&
7012 smb_lock->start > cmp_lock->start &&
7013 smb_lock->start < cmp_lock->end) {
7014 spin_unlock(&conn->llist_lock);
7015 up_read(&conn_list_lock);
7016 pr_err("current lock conflict with zero byte lock range\n");
7020 if (((cmp_lock->start <= smb_lock->start &&
7021 cmp_lock->end > smb_lock->start) ||
7022 (cmp_lock->start < smb_lock->end &&
7023 cmp_lock->end >= smb_lock->end)) &&
7024 !cmp_lock->zero_len && !smb_lock->zero_len) {
7025 spin_unlock(&conn->llist_lock);
7026 up_read(&conn_list_lock);
7027 pr_err("Not allow lock operation on exclusive lock range\n");
7031 spin_unlock(&conn->llist_lock);
7033 up_read(&conn_list_lock);
7035 if (smb_lock->fl->fl_type == F_UNLCK && nolock) {
7036 pr_err("Try to unlock nolocked range\n");
7037 rsp->hdr.Status = STATUS_RANGE_NOT_LOCKED;
7042 if (smb_lock->zero_len) {
7047 flock = smb_lock->fl;
7048 list_del(&smb_lock->llist);
7050 rc = vfs_lock_file(filp, smb_lock->cmd, flock, NULL);
7052 if (flags & SMB2_LOCKFLAG_UNLOCK) {
7054 ksmbd_debug(SMB, "File unlocked\n");
7055 } else if (rc == -ENOENT) {
7056 rsp->hdr.Status = STATUS_NOT_LOCKED;
7059 locks_free_lock(flock);
7062 if (rc == FILE_LOCK_DEFERRED) {
7066 "would have to wait for getting lock\n");
7067 list_add(&smb_lock->llist, &rollback_list);
7069 argv = kmalloc(sizeof(void *), GFP_KERNEL);
7076 rc = setup_async_work(work,
7077 smb2_remove_blocked_lock,
7083 spin_lock(&fp->f_lock);
7084 list_add(&work->fp_entry, &fp->blocked_works);
7085 spin_unlock(&fp->f_lock);
7087 smb2_send_interim_resp(work, STATUS_PENDING);
7089 ksmbd_vfs_posix_lock_wait(flock);
7091 spin_lock(&fp->f_lock);
7092 list_del(&work->fp_entry);
7093 spin_unlock(&fp->f_lock);
7095 if (work->state != KSMBD_WORK_ACTIVE) {
7096 list_del(&smb_lock->llist);
7097 locks_free_lock(flock);
7099 if (work->state == KSMBD_WORK_CANCELLED) {
7103 smb2_send_interim_resp(work,
7105 work->send_no_response = 1;
7110 STATUS_RANGE_NOT_LOCKED;
7115 list_del(&smb_lock->llist);
7116 release_async_work(work);
7119 list_add(&smb_lock->llist, &rollback_list);
7120 spin_lock(&work->conn->llist_lock);
7121 list_add_tail(&smb_lock->clist,
7122 &work->conn->lock_list);
7123 list_add_tail(&smb_lock->flist,
7125 spin_unlock(&work->conn->llist_lock);
7126 ksmbd_debug(SMB, "successful in taking lock\n");
7133 if (atomic_read(&fp->f_ci->op_count) > 1)
7134 smb_break_all_oplock(work, fp);
7136 rsp->StructureSize = cpu_to_le16(4);
7137 ksmbd_debug(SMB, "successful in taking lock\n");
7138 rsp->hdr.Status = STATUS_SUCCESS;
7140 err = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_lock_rsp));
7144 ksmbd_fd_put(work, fp);
7148 list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
7149 locks_free_lock(smb_lock->fl);
7150 list_del(&smb_lock->llist);
7154 list_for_each_entry_safe(smb_lock, tmp, &rollback_list, llist) {
7155 struct file_lock *rlock = NULL;
7157 rlock = smb_flock_init(filp);
7158 rlock->fl_type = F_UNLCK;
7159 rlock->fl_start = smb_lock->start;
7160 rlock->fl_end = smb_lock->end;
7162 rc = vfs_lock_file(filp, F_SETLK, rlock, NULL);
7164 pr_err("rollback unlock fail : %d\n", rc);
7166 list_del(&smb_lock->llist);
7167 spin_lock(&work->conn->llist_lock);
7168 if (!list_empty(&smb_lock->flist))
7169 list_del(&smb_lock->flist);
7170 list_del(&smb_lock->clist);
7171 spin_unlock(&work->conn->llist_lock);
7173 locks_free_lock(smb_lock->fl);
7174 locks_free_lock(rlock);
7178 ksmbd_debug(SMB, "failed in taking lock(flags : %x), err : %d\n", flags, err);
7180 if (!rsp->hdr.Status) {
7182 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7183 else if (err == -ENOMEM)
7184 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
7185 else if (err == -ENOENT)
7186 rsp->hdr.Status = STATUS_FILE_CLOSED;
7188 rsp->hdr.Status = STATUS_LOCK_NOT_GRANTED;
7191 smb2_set_err_rsp(work);
7192 ksmbd_fd_put(work, fp);
7196 static int fsctl_copychunk(struct ksmbd_work *work,
7197 struct copychunk_ioctl_req *ci_req,
7198 unsigned int cnt_code,
7199 unsigned int input_count,
7200 unsigned long long volatile_id,
7201 unsigned long long persistent_id,
7202 struct smb2_ioctl_rsp *rsp)
7204 struct copychunk_ioctl_rsp *ci_rsp;
7205 struct ksmbd_file *src_fp = NULL, *dst_fp = NULL;
7206 struct srv_copychunk *chunks;
7207 unsigned int i, chunk_count, chunk_count_written = 0;
7208 unsigned int chunk_size_written = 0;
7209 loff_t total_size_written = 0;
7212 ci_rsp = (struct copychunk_ioctl_rsp *)&rsp->Buffer[0];
7214 rsp->VolatileFileId = volatile_id;
7215 rsp->PersistentFileId = persistent_id;
7216 ci_rsp->ChunksWritten =
7217 cpu_to_le32(ksmbd_server_side_copy_max_chunk_count());
7218 ci_rsp->ChunkBytesWritten =
7219 cpu_to_le32(ksmbd_server_side_copy_max_chunk_size());
7220 ci_rsp->TotalBytesWritten =
7221 cpu_to_le32(ksmbd_server_side_copy_max_total_size());
7223 chunks = (struct srv_copychunk *)&ci_req->Chunks[0];
7224 chunk_count = le32_to_cpu(ci_req->ChunkCount);
7225 if (chunk_count == 0)
7227 total_size_written = 0;
7229 /* verify the SRV_COPYCHUNK_COPY packet */
7230 if (chunk_count > ksmbd_server_side_copy_max_chunk_count() ||
7231 input_count < offsetof(struct copychunk_ioctl_req, Chunks) +
7232 chunk_count * sizeof(struct srv_copychunk)) {
7233 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7237 for (i = 0; i < chunk_count; i++) {
7238 if (le32_to_cpu(chunks[i].Length) == 0 ||
7239 le32_to_cpu(chunks[i].Length) > ksmbd_server_side_copy_max_chunk_size())
7241 total_size_written += le32_to_cpu(chunks[i].Length);
7244 if (i < chunk_count ||
7245 total_size_written > ksmbd_server_side_copy_max_total_size()) {
7246 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7250 src_fp = ksmbd_lookup_foreign_fd(work,
7251 le64_to_cpu(ci_req->ResumeKey[0]));
7252 dst_fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
7255 src_fp->persistent_id != le64_to_cpu(ci_req->ResumeKey[1])) {
7256 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
7261 rsp->hdr.Status = STATUS_FILE_CLOSED;
7266 * FILE_READ_DATA should only be included in
7267 * the FSCTL_COPYCHUNK case
7269 if (cnt_code == FSCTL_COPYCHUNK &&
7270 !(dst_fp->daccess & (FILE_READ_DATA_LE | FILE_GENERIC_READ_LE))) {
7271 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7275 ret = ksmbd_vfs_copy_file_ranges(work, src_fp, dst_fp,
7276 chunks, chunk_count,
7277 &chunk_count_written,
7278 &chunk_size_written,
7279 &total_size_written);
7282 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7284 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
7285 else if (ret == -EBADF)
7286 rsp->hdr.Status = STATUS_INVALID_HANDLE;
7287 else if (ret == -EFBIG || ret == -ENOSPC)
7288 rsp->hdr.Status = STATUS_DISK_FULL;
7289 else if (ret == -EINVAL)
7290 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7291 else if (ret == -EISDIR)
7292 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
7293 else if (ret == -E2BIG)
7294 rsp->hdr.Status = STATUS_INVALID_VIEW_SIZE;
7296 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
7299 ci_rsp->ChunksWritten = cpu_to_le32(chunk_count_written);
7300 ci_rsp->ChunkBytesWritten = cpu_to_le32(chunk_size_written);
7301 ci_rsp->TotalBytesWritten = cpu_to_le32(total_size_written);
7303 ksmbd_fd_put(work, src_fp);
7304 ksmbd_fd_put(work, dst_fp);
7308 static __be32 idev_ipv4_address(struct in_device *idev)
7312 struct in_ifaddr *ifa;
7315 in_dev_for_each_ifa_rcu(ifa, idev) {
7316 if (ifa->ifa_flags & IFA_F_SECONDARY)
7319 addr = ifa->ifa_address;
7326 static int fsctl_query_iface_info_ioctl(struct ksmbd_conn *conn,
7327 struct smb2_ioctl_rsp *rsp,
7328 unsigned int out_buf_len)
7330 struct network_interface_info_ioctl_rsp *nii_rsp = NULL;
7332 struct net_device *netdev;
7333 struct sockaddr_storage_rsp *sockaddr_storage;
7335 unsigned long long speed;
7338 for_each_netdev(&init_net, netdev) {
7339 bool ipv4_set = false;
7341 if (netdev->type == ARPHRD_LOOPBACK)
7344 flags = dev_get_flags(netdev);
7345 if (!(flags & IFF_RUNNING))
7349 nbytes + sizeof(struct network_interface_info_ioctl_rsp)) {
7354 nii_rsp = (struct network_interface_info_ioctl_rsp *)
7355 &rsp->Buffer[nbytes];
7356 nii_rsp->IfIndex = cpu_to_le32(netdev->ifindex);
7358 nii_rsp->Capability = 0;
7359 if (netdev->real_num_tx_queues > 1)
7360 nii_rsp->Capability |= cpu_to_le32(RSS_CAPABLE);
7361 if (ksmbd_rdma_capable_netdev(netdev))
7362 nii_rsp->Capability |= cpu_to_le32(RDMA_CAPABLE);
7364 nii_rsp->Next = cpu_to_le32(152);
7365 nii_rsp->Reserved = 0;
7367 if (netdev->ethtool_ops->get_link_ksettings) {
7368 struct ethtool_link_ksettings cmd;
7370 netdev->ethtool_ops->get_link_ksettings(netdev, &cmd);
7371 speed = cmd.base.speed;
7373 ksmbd_debug(SMB, "%s %s\n", netdev->name,
7374 "speed is unknown, defaulting to 1Gb/sec");
7379 nii_rsp->LinkSpeed = cpu_to_le64(speed);
7381 sockaddr_storage = (struct sockaddr_storage_rsp *)
7382 nii_rsp->SockAddr_Storage;
7383 memset(sockaddr_storage, 0, 128);
7386 struct in_device *idev;
7388 sockaddr_storage->Family = cpu_to_le16(INTERNETWORK);
7389 sockaddr_storage->addr4.Port = 0;
7391 idev = __in_dev_get_rtnl(netdev);
7394 sockaddr_storage->addr4.IPv4address =
7395 idev_ipv4_address(idev);
7396 nbytes += sizeof(struct network_interface_info_ioctl_rsp);
7400 struct inet6_dev *idev6;
7401 struct inet6_ifaddr *ifa;
7402 __u8 *ipv6_addr = sockaddr_storage->addr6.IPv6address;
7404 sockaddr_storage->Family = cpu_to_le16(INTERNETWORKV6);
7405 sockaddr_storage->addr6.Port = 0;
7406 sockaddr_storage->addr6.FlowInfo = 0;
7408 idev6 = __in6_dev_get(netdev);
7412 list_for_each_entry(ifa, &idev6->addr_list, if_list) {
7413 if (ifa->flags & (IFA_F_TENTATIVE |
7416 memcpy(ipv6_addr, ifa->addr.s6_addr, 16);
7419 sockaddr_storage->addr6.ScopeId = 0;
7420 nbytes += sizeof(struct network_interface_info_ioctl_rsp);
7425 /* zero if this is last one */
7429 rsp->PersistentFileId = SMB2_NO_FID;
7430 rsp->VolatileFileId = SMB2_NO_FID;
7434 static int fsctl_validate_negotiate_info(struct ksmbd_conn *conn,
7435 struct validate_negotiate_info_req *neg_req,
7436 struct validate_negotiate_info_rsp *neg_rsp,
7437 unsigned int in_buf_len)
7442 if (in_buf_len < offsetof(struct validate_negotiate_info_req, Dialects) +
7443 le16_to_cpu(neg_req->DialectCount) * sizeof(__le16))
7446 dialect = ksmbd_lookup_dialect_by_id(neg_req->Dialects,
7447 neg_req->DialectCount);
7448 if (dialect == BAD_PROT_ID || dialect != conn->dialect) {
7453 if (strncmp(neg_req->Guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE)) {
7458 if (le16_to_cpu(neg_req->SecurityMode) != conn->cli_sec_mode) {
7463 if (le32_to_cpu(neg_req->Capabilities) != conn->cli_cap) {
7468 neg_rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
7469 memset(neg_rsp->Guid, 0, SMB2_CLIENT_GUID_SIZE);
7470 neg_rsp->SecurityMode = cpu_to_le16(conn->srv_sec_mode);
7471 neg_rsp->Dialect = cpu_to_le16(conn->dialect);
7476 static int fsctl_query_allocated_ranges(struct ksmbd_work *work, u64 id,
7477 struct file_allocated_range_buffer *qar_req,
7478 struct file_allocated_range_buffer *qar_rsp,
7479 unsigned int in_count, unsigned int *out_count)
7481 struct ksmbd_file *fp;
7482 loff_t start, length;
7489 start = le64_to_cpu(qar_req->file_offset);
7490 length = le64_to_cpu(qar_req->length);
7492 if (start < 0 || length < 0)
7495 fp = ksmbd_lookup_fd_fast(work, id);
7499 ret = ksmbd_vfs_fqar_lseek(fp, start, length,
7500 qar_rsp, in_count, out_count);
7501 if (ret && ret != -E2BIG)
7504 ksmbd_fd_put(work, fp);
7508 static int fsctl_pipe_transceive(struct ksmbd_work *work, u64 id,
7509 unsigned int out_buf_len,
7510 struct smb2_ioctl_req *req,
7511 struct smb2_ioctl_rsp *rsp)
7513 struct ksmbd_rpc_command *rpc_resp;
7514 char *data_buf = (char *)&req->Buffer[0];
7517 rpc_resp = ksmbd_rpc_ioctl(work->sess, id, data_buf,
7518 le32_to_cpu(req->InputCount));
7520 if (rpc_resp->flags == KSMBD_RPC_SOME_NOT_MAPPED) {
7522 * set STATUS_SOME_NOT_MAPPED response
7523 * for unknown domain sid.
7525 rsp->hdr.Status = STATUS_SOME_NOT_MAPPED;
7526 } else if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
7527 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7529 } else if (rpc_resp->flags != KSMBD_RPC_OK) {
7530 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7534 nbytes = rpc_resp->payload_sz;
7535 if (rpc_resp->payload_sz > out_buf_len) {
7536 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
7537 nbytes = out_buf_len;
7540 if (!rpc_resp->payload_sz) {
7542 STATUS_UNEXPECTED_IO_ERROR;
7546 memcpy((char *)rsp->Buffer, rpc_resp->payload, nbytes);
7553 static inline int fsctl_set_sparse(struct ksmbd_work *work, u64 id,
7554 struct file_sparse *sparse)
7556 struct ksmbd_file *fp;
7557 struct mnt_idmap *idmap;
7561 fp = ksmbd_lookup_fd_fast(work, id);
7564 idmap = file_mnt_idmap(fp->filp);
7566 old_fattr = fp->f_ci->m_fattr;
7567 if (sparse->SetSparse)
7568 fp->f_ci->m_fattr |= FILE_ATTRIBUTE_SPARSE_FILE_LE;
7570 fp->f_ci->m_fattr &= ~FILE_ATTRIBUTE_SPARSE_FILE_LE;
7572 if (fp->f_ci->m_fattr != old_fattr &&
7573 test_share_config_flag(work->tcon->share_conf,
7574 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS)) {
7575 struct xattr_dos_attrib da;
7577 ret = ksmbd_vfs_get_dos_attrib_xattr(idmap,
7578 fp->filp->f_path.dentry, &da);
7582 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
7583 ret = ksmbd_vfs_set_dos_attrib_xattr(idmap,
7584 &fp->filp->f_path, &da);
7586 fp->f_ci->m_fattr = old_fattr;
7590 ksmbd_fd_put(work, fp);
7594 static int fsctl_request_resume_key(struct ksmbd_work *work,
7595 struct smb2_ioctl_req *req,
7596 struct resume_key_ioctl_rsp *key_rsp)
7598 struct ksmbd_file *fp;
7600 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
7604 memset(key_rsp, 0, sizeof(*key_rsp));
7605 key_rsp->ResumeKey[0] = req->VolatileFileId;
7606 key_rsp->ResumeKey[1] = req->PersistentFileId;
7607 ksmbd_fd_put(work, fp);
7613 * smb2_ioctl() - handler for smb2 ioctl command
7614 * @work: smb work containing ioctl command buffer
7616 * Return: 0 on success, otherwise error
7618 int smb2_ioctl(struct ksmbd_work *work)
7620 struct smb2_ioctl_req *req;
7621 struct smb2_ioctl_rsp *rsp;
7622 unsigned int cnt_code, nbytes = 0, out_buf_len, in_buf_len;
7623 u64 id = KSMBD_NO_FID;
7624 struct ksmbd_conn *conn = work->conn;
7627 if (work->next_smb2_rcv_hdr_off) {
7628 req = ksmbd_req_buf_next(work);
7629 rsp = ksmbd_resp_buf_next(work);
7630 if (!has_file_id(req->VolatileFileId)) {
7631 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
7632 work->compound_fid);
7633 id = work->compound_fid;
7636 req = smb2_get_msg(work->request_buf);
7637 rsp = smb2_get_msg(work->response_buf);
7640 if (!has_file_id(id))
7641 id = req->VolatileFileId;
7643 if (req->Flags != cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL)) {
7644 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7648 cnt_code = le32_to_cpu(req->CtlCode);
7649 ret = smb2_calc_max_out_buf_len(work, 48,
7650 le32_to_cpu(req->MaxOutputResponse));
7652 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7655 out_buf_len = (unsigned int)ret;
7656 in_buf_len = le32_to_cpu(req->InputCount);
7659 case FSCTL_DFS_GET_REFERRALS:
7660 case FSCTL_DFS_GET_REFERRALS_EX:
7661 /* Not support DFS yet */
7662 rsp->hdr.Status = STATUS_FS_DRIVER_REQUIRED;
7664 case FSCTL_CREATE_OR_GET_OBJECT_ID:
7666 struct file_object_buf_type1_ioctl_rsp *obj_buf;
7668 nbytes = sizeof(struct file_object_buf_type1_ioctl_rsp);
7669 obj_buf = (struct file_object_buf_type1_ioctl_rsp *)
7673 * TODO: This is dummy implementation to pass smbtorture
7674 * Need to check correct response later
7676 memset(obj_buf->ObjectId, 0x0, 16);
7677 memset(obj_buf->BirthVolumeId, 0x0, 16);
7678 memset(obj_buf->BirthObjectId, 0x0, 16);
7679 memset(obj_buf->DomainId, 0x0, 16);
7683 case FSCTL_PIPE_TRANSCEIVE:
7684 out_buf_len = min_t(u32, KSMBD_IPC_MAX_PAYLOAD, out_buf_len);
7685 nbytes = fsctl_pipe_transceive(work, id, out_buf_len, req, rsp);
7687 case FSCTL_VALIDATE_NEGOTIATE_INFO:
7688 if (conn->dialect < SMB30_PROT_ID) {
7693 if (in_buf_len < offsetof(struct validate_negotiate_info_req,
7699 if (out_buf_len < sizeof(struct validate_negotiate_info_rsp)) {
7704 ret = fsctl_validate_negotiate_info(conn,
7705 (struct validate_negotiate_info_req *)&req->Buffer[0],
7706 (struct validate_negotiate_info_rsp *)&rsp->Buffer[0],
7711 nbytes = sizeof(struct validate_negotiate_info_rsp);
7712 rsp->PersistentFileId = SMB2_NO_FID;
7713 rsp->VolatileFileId = SMB2_NO_FID;
7715 case FSCTL_QUERY_NETWORK_INTERFACE_INFO:
7716 ret = fsctl_query_iface_info_ioctl(conn, rsp, out_buf_len);
7721 case FSCTL_REQUEST_RESUME_KEY:
7722 if (out_buf_len < sizeof(struct resume_key_ioctl_rsp)) {
7727 ret = fsctl_request_resume_key(work, req,
7728 (struct resume_key_ioctl_rsp *)&rsp->Buffer[0]);
7731 rsp->PersistentFileId = req->PersistentFileId;
7732 rsp->VolatileFileId = req->VolatileFileId;
7733 nbytes = sizeof(struct resume_key_ioctl_rsp);
7735 case FSCTL_COPYCHUNK:
7736 case FSCTL_COPYCHUNK_WRITE:
7737 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7739 "User does not have write permission\n");
7744 if (in_buf_len < sizeof(struct copychunk_ioctl_req)) {
7749 if (out_buf_len < sizeof(struct copychunk_ioctl_rsp)) {
7754 nbytes = sizeof(struct copychunk_ioctl_rsp);
7755 rsp->VolatileFileId = req->VolatileFileId;
7756 rsp->PersistentFileId = req->PersistentFileId;
7757 fsctl_copychunk(work,
7758 (struct copychunk_ioctl_req *)&req->Buffer[0],
7759 le32_to_cpu(req->CtlCode),
7760 le32_to_cpu(req->InputCount),
7761 req->VolatileFileId,
7762 req->PersistentFileId,
7765 case FSCTL_SET_SPARSE:
7766 if (in_buf_len < sizeof(struct file_sparse)) {
7771 ret = fsctl_set_sparse(work, id,
7772 (struct file_sparse *)&req->Buffer[0]);
7776 case FSCTL_SET_ZERO_DATA:
7778 struct file_zero_data_information *zero_data;
7779 struct ksmbd_file *fp;
7780 loff_t off, len, bfz;
7782 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7784 "User does not have write permission\n");
7789 if (in_buf_len < sizeof(struct file_zero_data_information)) {
7795 (struct file_zero_data_information *)&req->Buffer[0];
7797 off = le64_to_cpu(zero_data->FileOffset);
7798 bfz = le64_to_cpu(zero_data->BeyondFinalZero);
7799 if (off < 0 || bfz < 0 || off > bfz) {
7806 fp = ksmbd_lookup_fd_fast(work, id);
7812 ret = ksmbd_vfs_zero_data(work, fp, off, len);
7813 ksmbd_fd_put(work, fp);
7819 case FSCTL_QUERY_ALLOCATED_RANGES:
7820 if (in_buf_len < sizeof(struct file_allocated_range_buffer)) {
7825 ret = fsctl_query_allocated_ranges(work, id,
7826 (struct file_allocated_range_buffer *)&req->Buffer[0],
7827 (struct file_allocated_range_buffer *)&rsp->Buffer[0],
7829 sizeof(struct file_allocated_range_buffer), &nbytes);
7830 if (ret == -E2BIG) {
7831 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
7832 } else if (ret < 0) {
7837 nbytes *= sizeof(struct file_allocated_range_buffer);
7839 case FSCTL_GET_REPARSE_POINT:
7841 struct reparse_data_buffer *reparse_ptr;
7842 struct ksmbd_file *fp;
7844 reparse_ptr = (struct reparse_data_buffer *)&rsp->Buffer[0];
7845 fp = ksmbd_lookup_fd_fast(work, id);
7847 pr_err("not found fp!!\n");
7852 reparse_ptr->ReparseTag =
7853 smb2_get_reparse_tag_special_file(file_inode(fp->filp)->i_mode);
7854 reparse_ptr->ReparseDataLength = 0;
7855 ksmbd_fd_put(work, fp);
7856 nbytes = sizeof(struct reparse_data_buffer);
7859 case FSCTL_DUPLICATE_EXTENTS_TO_FILE:
7861 struct ksmbd_file *fp_in, *fp_out = NULL;
7862 struct duplicate_extents_to_file *dup_ext;
7863 loff_t src_off, dst_off, length, cloned;
7865 if (in_buf_len < sizeof(struct duplicate_extents_to_file)) {
7870 dup_ext = (struct duplicate_extents_to_file *)&req->Buffer[0];
7872 fp_in = ksmbd_lookup_fd_slow(work, dup_ext->VolatileFileHandle,
7873 dup_ext->PersistentFileHandle);
7875 pr_err("not found file handle in duplicate extent to file\n");
7880 fp_out = ksmbd_lookup_fd_fast(work, id);
7882 pr_err("not found fp\n");
7887 src_off = le64_to_cpu(dup_ext->SourceFileOffset);
7888 dst_off = le64_to_cpu(dup_ext->TargetFileOffset);
7889 length = le64_to_cpu(dup_ext->ByteCount);
7891 * XXX: It is not clear if FSCTL_DUPLICATE_EXTENTS_TO_FILE
7892 * should fall back to vfs_copy_file_range(). This could be
7893 * beneficial when re-exporting nfs/smb mount, but note that
7894 * this can result in partial copy that returns an error status.
7895 * If/when FSCTL_DUPLICATE_EXTENTS_TO_FILE_EX is implemented,
7896 * fall back to vfs_copy_file_range(), should be avoided when
7897 * the flag DUPLICATE_EXTENTS_DATA_EX_SOURCE_ATOMIC is set.
7899 cloned = vfs_clone_file_range(fp_in->filp, src_off,
7900 fp_out->filp, dst_off, length, 0);
7901 if (cloned == -EXDEV || cloned == -EOPNOTSUPP) {
7904 } else if (cloned != length) {
7905 cloned = vfs_copy_file_range(fp_in->filp, src_off,
7906 fp_out->filp, dst_off,
7908 if (cloned != length) {
7917 ksmbd_fd_put(work, fp_in);
7918 ksmbd_fd_put(work, fp_out);
7924 ksmbd_debug(SMB, "not implemented yet ioctl command 0x%x\n",
7930 rsp->CtlCode = cpu_to_le32(cnt_code);
7931 rsp->InputCount = cpu_to_le32(0);
7932 rsp->InputOffset = cpu_to_le32(112);
7933 rsp->OutputOffset = cpu_to_le32(112);
7934 rsp->OutputCount = cpu_to_le32(nbytes);
7935 rsp->StructureSize = cpu_to_le16(49);
7936 rsp->Reserved = cpu_to_le16(0);
7937 rsp->Flags = cpu_to_le32(0);
7938 rsp->Reserved2 = cpu_to_le32(0);
7939 ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_ioctl_rsp) + nbytes);
7945 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7946 else if (ret == -ENOENT)
7947 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
7948 else if (ret == -EOPNOTSUPP)
7949 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7950 else if (ret == -ENOSPC)
7951 rsp->hdr.Status = STATUS_BUFFER_TOO_SMALL;
7952 else if (ret < 0 || rsp->hdr.Status == 0)
7953 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7954 smb2_set_err_rsp(work);
7959 * smb20_oplock_break_ack() - handler for smb2.0 oplock break command
7960 * @work: smb work containing oplock break command buffer
7964 static void smb20_oplock_break_ack(struct ksmbd_work *work)
7966 struct smb2_oplock_break *req;
7967 struct smb2_oplock_break *rsp;
7968 struct ksmbd_file *fp;
7969 struct oplock_info *opinfo = NULL;
7972 u64 volatile_id, persistent_id;
7973 char req_oplevel = 0, rsp_oplevel = 0;
7974 unsigned int oplock_change_type;
7976 WORK_BUFFERS(work, req, rsp);
7978 volatile_id = req->VolatileFid;
7979 persistent_id = req->PersistentFid;
7980 req_oplevel = req->OplockLevel;
7981 ksmbd_debug(OPLOCK, "v_id %llu, p_id %llu request oplock level %d\n",
7982 volatile_id, persistent_id, req_oplevel);
7984 fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
7986 rsp->hdr.Status = STATUS_FILE_CLOSED;
7987 smb2_set_err_rsp(work);
7991 opinfo = opinfo_get(fp);
7993 pr_err("unexpected null oplock_info\n");
7994 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
7995 smb2_set_err_rsp(work);
7996 ksmbd_fd_put(work, fp);
8000 if (opinfo->level == SMB2_OPLOCK_LEVEL_NONE) {
8001 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
8005 if (opinfo->op_state == OPLOCK_STATE_NONE) {
8006 ksmbd_debug(SMB, "unexpected oplock state 0x%x\n", opinfo->op_state);
8007 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8011 if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
8012 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
8013 (req_oplevel != SMB2_OPLOCK_LEVEL_II &&
8014 req_oplevel != SMB2_OPLOCK_LEVEL_NONE)) {
8015 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8016 oplock_change_type = OPLOCK_WRITE_TO_NONE;
8017 } else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
8018 req_oplevel != SMB2_OPLOCK_LEVEL_NONE) {
8019 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8020 oplock_change_type = OPLOCK_READ_TO_NONE;
8021 } else if (req_oplevel == SMB2_OPLOCK_LEVEL_II ||
8022 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
8023 err = STATUS_INVALID_DEVICE_STATE;
8024 if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
8025 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
8026 req_oplevel == SMB2_OPLOCK_LEVEL_II) {
8027 oplock_change_type = OPLOCK_WRITE_TO_READ;
8028 } else if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
8029 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
8030 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
8031 oplock_change_type = OPLOCK_WRITE_TO_NONE;
8032 } else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
8033 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
8034 oplock_change_type = OPLOCK_READ_TO_NONE;
8036 oplock_change_type = 0;
8039 oplock_change_type = 0;
8042 switch (oplock_change_type) {
8043 case OPLOCK_WRITE_TO_READ:
8044 ret = opinfo_write_to_read(opinfo);
8045 rsp_oplevel = SMB2_OPLOCK_LEVEL_II;
8047 case OPLOCK_WRITE_TO_NONE:
8048 ret = opinfo_write_to_none(opinfo);
8049 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
8051 case OPLOCK_READ_TO_NONE:
8052 ret = opinfo_read_to_none(opinfo);
8053 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
8056 pr_err("unknown oplock change 0x%x -> 0x%x\n",
8057 opinfo->level, rsp_oplevel);
8061 rsp->hdr.Status = err;
8065 opinfo->op_state = OPLOCK_STATE_NONE;
8066 wake_up_interruptible_all(&opinfo->oplock_q);
8068 ksmbd_fd_put(work, fp);
8070 rsp->StructureSize = cpu_to_le16(24);
8071 rsp->OplockLevel = rsp_oplevel;
8074 rsp->VolatileFid = volatile_id;
8075 rsp->PersistentFid = persistent_id;
8076 ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_oplock_break));
8081 opinfo->op_state = OPLOCK_STATE_NONE;
8082 wake_up_interruptible_all(&opinfo->oplock_q);
8085 ksmbd_fd_put(work, fp);
8086 smb2_set_err_rsp(work);
8089 static int check_lease_state(struct lease *lease, __le32 req_state)
8091 if ((lease->new_state ==
8092 (SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE)) &&
8093 !(req_state & SMB2_LEASE_WRITE_CACHING_LE)) {
8094 lease->new_state = req_state;
8098 if (lease->new_state == req_state)
8105 * smb21_lease_break_ack() - handler for smb2.1 lease break command
8106 * @work: smb work containing lease break command buffer
8110 static void smb21_lease_break_ack(struct ksmbd_work *work)
8112 struct ksmbd_conn *conn = work->conn;
8113 struct smb2_lease_ack *req;
8114 struct smb2_lease_ack *rsp;
8115 struct oplock_info *opinfo;
8118 unsigned int lease_change_type;
8120 struct lease *lease;
8122 WORK_BUFFERS(work, req, rsp);
8124 ksmbd_debug(OPLOCK, "smb21 lease break, lease state(0x%x)\n",
8125 le32_to_cpu(req->LeaseState));
8126 opinfo = lookup_lease_in_table(conn, req->LeaseKey);
8128 ksmbd_debug(OPLOCK, "file not opened\n");
8129 smb2_set_err_rsp(work);
8130 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8133 lease = opinfo->o_lease;
8135 if (opinfo->op_state == OPLOCK_STATE_NONE) {
8136 pr_err("unexpected lease break state 0x%x\n",
8138 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8142 if (check_lease_state(lease, req->LeaseState)) {
8143 rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
8145 "req lease state: 0x%x, expected state: 0x%x\n",
8146 req->LeaseState, lease->new_state);
8150 if (!atomic_read(&opinfo->breaking_cnt)) {
8151 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8155 /* check for bad lease state */
8156 if (req->LeaseState &
8157 (~(SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE))) {
8158 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8159 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8160 lease_change_type = OPLOCK_WRITE_TO_NONE;
8162 lease_change_type = OPLOCK_READ_TO_NONE;
8163 ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8164 le32_to_cpu(lease->state),
8165 le32_to_cpu(req->LeaseState));
8166 } else if (lease->state == SMB2_LEASE_READ_CACHING_LE &&
8167 req->LeaseState != SMB2_LEASE_NONE_LE) {
8168 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8169 lease_change_type = OPLOCK_READ_TO_NONE;
8170 ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8171 le32_to_cpu(lease->state),
8172 le32_to_cpu(req->LeaseState));
8174 /* valid lease state changes */
8175 err = STATUS_INVALID_DEVICE_STATE;
8176 if (req->LeaseState == SMB2_LEASE_NONE_LE) {
8177 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8178 lease_change_type = OPLOCK_WRITE_TO_NONE;
8180 lease_change_type = OPLOCK_READ_TO_NONE;
8181 } else if (req->LeaseState & SMB2_LEASE_READ_CACHING_LE) {
8182 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8183 lease_change_type = OPLOCK_WRITE_TO_READ;
8185 lease_change_type = OPLOCK_READ_HANDLE_TO_READ;
8187 lease_change_type = 0;
8191 switch (lease_change_type) {
8192 case OPLOCK_WRITE_TO_READ:
8193 ret = opinfo_write_to_read(opinfo);
8195 case OPLOCK_READ_HANDLE_TO_READ:
8196 ret = opinfo_read_handle_to_read(opinfo);
8198 case OPLOCK_WRITE_TO_NONE:
8199 ret = opinfo_write_to_none(opinfo);
8201 case OPLOCK_READ_TO_NONE:
8202 ret = opinfo_read_to_none(opinfo);
8205 ksmbd_debug(OPLOCK, "unknown lease change 0x%x -> 0x%x\n",
8206 le32_to_cpu(lease->state),
8207 le32_to_cpu(req->LeaseState));
8210 lease_state = lease->state;
8211 opinfo->op_state = OPLOCK_STATE_NONE;
8212 wake_up_interruptible_all(&opinfo->oplock_q);
8213 atomic_dec(&opinfo->breaking_cnt);
8214 wake_up_interruptible_all(&opinfo->oplock_brk);
8218 rsp->hdr.Status = err;
8222 rsp->StructureSize = cpu_to_le16(36);
8225 memcpy(rsp->LeaseKey, req->LeaseKey, 16);
8226 rsp->LeaseState = lease_state;
8227 rsp->LeaseDuration = 0;
8228 ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_lease_ack));
8233 opinfo->op_state = OPLOCK_STATE_NONE;
8234 wake_up_interruptible_all(&opinfo->oplock_q);
8235 atomic_dec(&opinfo->breaking_cnt);
8236 wake_up_interruptible_all(&opinfo->oplock_brk);
8239 smb2_set_err_rsp(work);
8243 * smb2_oplock_break() - dispatcher for smb2.0 and 2.1 oplock/lease break
8244 * @work: smb work containing oplock/lease break command buffer
8248 int smb2_oplock_break(struct ksmbd_work *work)
8250 struct smb2_oplock_break *req;
8251 struct smb2_oplock_break *rsp;
8253 WORK_BUFFERS(work, req, rsp);
8255 switch (le16_to_cpu(req->StructureSize)) {
8256 case OP_BREAK_STRUCT_SIZE_20:
8257 smb20_oplock_break_ack(work);
8259 case OP_BREAK_STRUCT_SIZE_21:
8260 smb21_lease_break_ack(work);
8263 ksmbd_debug(OPLOCK, "invalid break cmd %d\n",
8264 le16_to_cpu(req->StructureSize));
8265 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8266 smb2_set_err_rsp(work);
8273 * smb2_notify() - handler for smb2 notify request
8274 * @work: smb work containing notify command buffer
8278 int smb2_notify(struct ksmbd_work *work)
8280 struct smb2_change_notify_req *req;
8281 struct smb2_change_notify_rsp *rsp;
8283 WORK_BUFFERS(work, req, rsp);
8285 if (work->next_smb2_rcv_hdr_off && req->hdr.NextCommand) {
8286 rsp->hdr.Status = STATUS_INTERNAL_ERROR;
8287 smb2_set_err_rsp(work);
8291 smb2_set_err_rsp(work);
8292 rsp->hdr.Status = STATUS_NOT_IMPLEMENTED;
8297 * smb2_is_sign_req() - handler for checking packet signing status
8298 * @work: smb work containing notify command buffer
8299 * @command: SMB2 command id
8301 * Return: true if packed is signed, false otherwise
8303 bool smb2_is_sign_req(struct ksmbd_work *work, unsigned int command)
8305 struct smb2_hdr *rcv_hdr2 = smb2_get_msg(work->request_buf);
8307 if ((rcv_hdr2->Flags & SMB2_FLAGS_SIGNED) &&
8308 command != SMB2_NEGOTIATE_HE &&
8309 command != SMB2_SESSION_SETUP_HE &&
8310 command != SMB2_OPLOCK_BREAK_HE)
8317 * smb2_check_sign_req() - handler for req packet sign processing
8318 * @work: smb work containing notify command buffer
8320 * Return: 1 on success, 0 otherwise
8322 int smb2_check_sign_req(struct ksmbd_work *work)
8324 struct smb2_hdr *hdr;
8325 char signature_req[SMB2_SIGNATURE_SIZE];
8326 char signature[SMB2_HMACSHA256_SIZE];
8330 hdr = smb2_get_msg(work->request_buf);
8331 if (work->next_smb2_rcv_hdr_off)
8332 hdr = ksmbd_req_buf_next(work);
8334 if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8335 len = get_rfc1002_len(work->request_buf);
8336 else if (hdr->NextCommand)
8337 len = le32_to_cpu(hdr->NextCommand);
8339 len = get_rfc1002_len(work->request_buf) -
8340 work->next_smb2_rcv_hdr_off;
8342 memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8343 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8345 iov[0].iov_base = (char *)&hdr->ProtocolId;
8346 iov[0].iov_len = len;
8348 if (ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, 1,
8352 if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8353 pr_err("bad smb2 signature\n");
8361 * smb2_set_sign_rsp() - handler for rsp packet sign processing
8362 * @work: smb work containing notify command buffer
8365 void smb2_set_sign_rsp(struct ksmbd_work *work)
8367 struct smb2_hdr *hdr;
8368 char signature[SMB2_HMACSHA256_SIZE];
8372 hdr = ksmbd_resp_buf_curr(work);
8373 hdr->Flags |= SMB2_FLAGS_SIGNED;
8374 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8376 if (hdr->Command == SMB2_READ) {
8377 iov = &work->iov[work->iov_idx - 1];
8380 iov = &work->iov[work->iov_idx];
8383 if (!ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, n_vec,
8385 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
8389 * smb3_check_sign_req() - handler for req packet sign processing
8390 * @work: smb work containing notify command buffer
8392 * Return: 1 on success, 0 otherwise
8394 int smb3_check_sign_req(struct ksmbd_work *work)
8396 struct ksmbd_conn *conn = work->conn;
8398 struct smb2_hdr *hdr;
8399 struct channel *chann;
8400 char signature_req[SMB2_SIGNATURE_SIZE];
8401 char signature[SMB2_CMACAES_SIZE];
8405 hdr = smb2_get_msg(work->request_buf);
8406 if (work->next_smb2_rcv_hdr_off)
8407 hdr = ksmbd_req_buf_next(work);
8409 if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8410 len = get_rfc1002_len(work->request_buf);
8411 else if (hdr->NextCommand)
8412 len = le32_to_cpu(hdr->NextCommand);
8414 len = get_rfc1002_len(work->request_buf) -
8415 work->next_smb2_rcv_hdr_off;
8417 if (le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8418 signing_key = work->sess->smb3signingkey;
8420 chann = lookup_chann_list(work->sess, conn);
8424 signing_key = chann->smb3signingkey;
8428 pr_err("SMB3 signing key is not generated\n");
8432 memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8433 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8434 iov[0].iov_base = (char *)&hdr->ProtocolId;
8435 iov[0].iov_len = len;
8437 if (ksmbd_sign_smb3_pdu(conn, signing_key, iov, 1, signature))
8440 if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8441 pr_err("bad smb2 signature\n");
8449 * smb3_set_sign_rsp() - handler for rsp packet sign processing
8450 * @work: smb work containing notify command buffer
8453 void smb3_set_sign_rsp(struct ksmbd_work *work)
8455 struct ksmbd_conn *conn = work->conn;
8456 struct smb2_hdr *hdr;
8457 struct channel *chann;
8458 char signature[SMB2_CMACAES_SIZE];
8463 hdr = ksmbd_resp_buf_curr(work);
8465 if (conn->binding == false &&
8466 le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8467 signing_key = work->sess->smb3signingkey;
8469 chann = lookup_chann_list(work->sess, work->conn);
8473 signing_key = chann->smb3signingkey;
8479 hdr->Flags |= SMB2_FLAGS_SIGNED;
8480 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8482 if (hdr->Command == SMB2_READ) {
8483 iov = &work->iov[work->iov_idx - 1];
8486 iov = &work->iov[work->iov_idx];
8489 if (!ksmbd_sign_smb3_pdu(conn, signing_key, iov, n_vec,
8491 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
8495 * smb3_preauth_hash_rsp() - handler for computing preauth hash on response
8496 * @work: smb work containing response buffer
8499 void smb3_preauth_hash_rsp(struct ksmbd_work *work)
8501 struct ksmbd_conn *conn = work->conn;
8502 struct ksmbd_session *sess = work->sess;
8503 struct smb2_hdr *req, *rsp;
8505 if (conn->dialect != SMB311_PROT_ID)
8508 WORK_BUFFERS(work, req, rsp);
8510 if (le16_to_cpu(req->Command) == SMB2_NEGOTIATE_HE &&
8512 ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
8513 conn->preauth_info->Preauth_HashValue);
8515 if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE && sess) {
8518 if (conn->binding) {
8519 struct preauth_session *preauth_sess;
8521 preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
8524 hash_value = preauth_sess->Preauth_HashValue;
8526 hash_value = sess->Preauth_HashValue;
8530 ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
8535 static void fill_transform_hdr(void *tr_buf, char *old_buf, __le16 cipher_type)
8537 struct smb2_transform_hdr *tr_hdr = tr_buf + 4;
8538 struct smb2_hdr *hdr = smb2_get_msg(old_buf);
8539 unsigned int orig_len = get_rfc1002_len(old_buf);
8541 /* tr_buf must be cleared by the caller */
8542 tr_hdr->ProtocolId = SMB2_TRANSFORM_PROTO_NUM;
8543 tr_hdr->OriginalMessageSize = cpu_to_le32(orig_len);
8544 tr_hdr->Flags = cpu_to_le16(TRANSFORM_FLAG_ENCRYPTED);
8545 if (cipher_type == SMB2_ENCRYPTION_AES128_GCM ||
8546 cipher_type == SMB2_ENCRYPTION_AES256_GCM)
8547 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_GCM_NONCE);
8549 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_CCM_NONCE);
8550 memcpy(&tr_hdr->SessionId, &hdr->SessionId, 8);
8551 inc_rfc1001_len(tr_buf, sizeof(struct smb2_transform_hdr));
8552 inc_rfc1001_len(tr_buf, orig_len);
8555 int smb3_encrypt_resp(struct ksmbd_work *work)
8557 struct kvec *iov = work->iov;
8561 tr_buf = kzalloc(sizeof(struct smb2_transform_hdr) + 4, GFP_KERNEL);
8565 /* fill transform header */
8566 fill_transform_hdr(tr_buf, work->response_buf, work->conn->cipher_type);
8568 iov[0].iov_base = tr_buf;
8569 iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
8570 work->tr_buf = tr_buf;
8572 return ksmbd_crypt_message(work, iov, work->iov_idx + 1, 1);
8575 bool smb3_is_transform_hdr(void *buf)
8577 struct smb2_transform_hdr *trhdr = smb2_get_msg(buf);
8579 return trhdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM;
8582 int smb3_decrypt_req(struct ksmbd_work *work)
8584 struct ksmbd_session *sess;
8585 char *buf = work->request_buf;
8586 unsigned int pdu_length = get_rfc1002_len(buf);
8588 int buf_data_size = pdu_length - sizeof(struct smb2_transform_hdr);
8589 struct smb2_transform_hdr *tr_hdr = smb2_get_msg(buf);
8592 if (pdu_length < sizeof(struct smb2_transform_hdr) ||
8593 buf_data_size < sizeof(struct smb2_hdr)) {
8594 pr_err("Transform message is too small (%u)\n",
8596 return -ECONNABORTED;
8599 if (buf_data_size < le32_to_cpu(tr_hdr->OriginalMessageSize)) {
8600 pr_err("Transform message is broken\n");
8601 return -ECONNABORTED;
8604 sess = ksmbd_session_lookup_all(work->conn, le64_to_cpu(tr_hdr->SessionId));
8606 pr_err("invalid session id(%llx) in transform header\n",
8607 le64_to_cpu(tr_hdr->SessionId));
8608 return -ECONNABORTED;
8611 iov[0].iov_base = buf;
8612 iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
8613 iov[1].iov_base = buf + sizeof(struct smb2_transform_hdr) + 4;
8614 iov[1].iov_len = buf_data_size;
8615 rc = ksmbd_crypt_message(work, iov, 2, 0);
8619 memmove(buf + 4, iov[1].iov_base, buf_data_size);
8620 *(__be32 *)buf = cpu_to_be32(buf_data_size);
8625 bool smb3_11_final_sess_setup_resp(struct ksmbd_work *work)
8627 struct ksmbd_conn *conn = work->conn;
8628 struct ksmbd_session *sess = work->sess;
8629 struct smb2_hdr *rsp = smb2_get_msg(work->response_buf);
8631 if (conn->dialect < SMB30_PROT_ID)
8634 if (work->next_smb2_rcv_hdr_off)
8635 rsp = ksmbd_resp_buf_next(work);
8637 if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE &&
8638 sess->user && !user_guest(sess->user) &&
8639 rsp->Status == STATUS_SUCCESS)