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 rsp_hdr = smb2_get_msg(work->response_buf);
235 rsp_hdr->Status = err;
239 work->next_smb2_rcv_hdr_off = 0;
240 smb2_set_err_rsp(work);
244 * init_smb2_neg_rsp() - initialize smb2 response for negotiate command
245 * @work: smb work containing smb request buffer
247 * smb2 negotiate response is sent in reply of smb1 negotiate command for
248 * dialect auto-negotiation.
250 int init_smb2_neg_rsp(struct ksmbd_work *work)
252 struct smb2_hdr *rsp_hdr;
253 struct smb2_negotiate_rsp *rsp;
254 struct ksmbd_conn *conn = work->conn;
257 rsp_hdr = smb2_get_msg(work->response_buf);
258 memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
259 rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
260 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
261 rsp_hdr->CreditRequest = cpu_to_le16(2);
262 rsp_hdr->Command = SMB2_NEGOTIATE;
263 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
264 rsp_hdr->NextCommand = 0;
265 rsp_hdr->MessageId = 0;
266 rsp_hdr->Id.SyncId.ProcessId = 0;
267 rsp_hdr->Id.SyncId.TreeId = 0;
268 rsp_hdr->SessionId = 0;
269 memset(rsp_hdr->Signature, 0, 16);
271 rsp = smb2_get_msg(work->response_buf);
273 WARN_ON(ksmbd_conn_good(conn));
275 rsp->StructureSize = cpu_to_le16(65);
276 ksmbd_debug(SMB, "conn->dialect 0x%x\n", conn->dialect);
277 rsp->DialectRevision = cpu_to_le16(conn->dialect);
278 /* Not setting conn guid rsp->ServerGUID, as it
279 * not used by client for identifying connection
281 rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
282 /* Default Max Message Size till SMB2.0, 64K*/
283 rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
284 rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
285 rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);
287 rsp->SystemTime = cpu_to_le64(ksmbd_systime());
288 rsp->ServerStartTime = 0;
290 rsp->SecurityBufferOffset = cpu_to_le16(128);
291 rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
292 ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) +
293 le16_to_cpu(rsp->SecurityBufferOffset));
294 rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
295 if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY)
296 rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
297 err = ksmbd_iov_pin_rsp(work, rsp,
298 sizeof(struct smb2_negotiate_rsp) + AUTH_GSS_LENGTH);
301 conn->use_spnego = true;
303 ksmbd_conn_set_need_negotiate(conn);
308 * smb2_set_rsp_credits() - set number of credits in response buffer
309 * @work: smb work containing smb response buffer
311 int smb2_set_rsp_credits(struct ksmbd_work *work)
313 struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
314 struct smb2_hdr *hdr = ksmbd_resp_buf_next(work);
315 struct ksmbd_conn *conn = work->conn;
316 unsigned short credits_requested, aux_max;
317 unsigned short credit_charge, credits_granted = 0;
319 if (work->send_no_response)
322 hdr->CreditCharge = req_hdr->CreditCharge;
324 if (conn->total_credits > conn->vals->max_credits) {
325 hdr->CreditRequest = 0;
326 pr_err("Total credits overflow: %d\n", conn->total_credits);
330 credit_charge = max_t(unsigned short,
331 le16_to_cpu(req_hdr->CreditCharge), 1);
332 if (credit_charge > conn->total_credits) {
333 ksmbd_debug(SMB, "Insufficient credits granted, given: %u, granted: %u\n",
334 credit_charge, conn->total_credits);
338 conn->total_credits -= credit_charge;
339 conn->outstanding_credits -= credit_charge;
340 credits_requested = max_t(unsigned short,
341 le16_to_cpu(req_hdr->CreditRequest), 1);
343 /* according to smb2.credits smbtorture, Windows server
344 * 2016 or later grant up to 8192 credits at once.
346 * TODO: Need to adjuct CreditRequest value according to
349 if (hdr->Command == SMB2_NEGOTIATE)
352 aux_max = conn->vals->max_credits - conn->total_credits;
353 credits_granted = min_t(unsigned short, credits_requested, aux_max);
355 conn->total_credits += credits_granted;
356 work->credits_granted += credits_granted;
358 if (!req_hdr->NextCommand) {
359 /* Update CreditRequest in last request */
360 hdr->CreditRequest = cpu_to_le16(work->credits_granted);
363 "credits: requested[%d] granted[%d] total_granted[%d]\n",
364 credits_requested, credits_granted,
365 conn->total_credits);
370 * init_chained_smb2_rsp() - initialize smb2 chained response
371 * @work: smb work containing smb response buffer
373 static void init_chained_smb2_rsp(struct ksmbd_work *work)
375 struct smb2_hdr *req = ksmbd_req_buf_next(work);
376 struct smb2_hdr *rsp = ksmbd_resp_buf_next(work);
377 struct smb2_hdr *rsp_hdr;
378 struct smb2_hdr *rcv_hdr;
379 int next_hdr_offset = 0;
382 /* Len of this response = updated RFC len - offset of previous cmd
383 * in the compound rsp
386 /* Storing the current local FID which may be needed by subsequent
387 * command in the compound request
389 if (req->Command == SMB2_CREATE && rsp->Status == STATUS_SUCCESS) {
390 work->compound_fid = ((struct smb2_create_rsp *)rsp)->VolatileFileId;
391 work->compound_pfid = ((struct smb2_create_rsp *)rsp)->PersistentFileId;
392 work->compound_sid = le64_to_cpu(rsp->SessionId);
395 len = get_rfc1002_len(work->response_buf) - work->next_smb2_rsp_hdr_off;
396 next_hdr_offset = le32_to_cpu(req->NextCommand);
398 new_len = ALIGN(len, 8);
399 work->iov[work->iov_idx].iov_len += (new_len - len);
400 inc_rfc1001_len(work->response_buf, new_len - len);
401 rsp->NextCommand = cpu_to_le32(new_len);
403 work->next_smb2_rcv_hdr_off += next_hdr_offset;
404 work->curr_smb2_rsp_hdr_off = work->next_smb2_rsp_hdr_off;
405 work->next_smb2_rsp_hdr_off += new_len;
407 "Compound req new_len = %d rcv off = %d rsp off = %d\n",
408 new_len, work->next_smb2_rcv_hdr_off,
409 work->next_smb2_rsp_hdr_off);
411 rsp_hdr = ksmbd_resp_buf_next(work);
412 rcv_hdr = ksmbd_req_buf_next(work);
414 if (!(rcv_hdr->Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
415 ksmbd_debug(SMB, "related flag should be set\n");
416 work->compound_fid = KSMBD_NO_FID;
417 work->compound_pfid = KSMBD_NO_FID;
419 memset((char *)rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
420 rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
421 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
422 rsp_hdr->Command = rcv_hdr->Command;
425 * Message is response. We don't grant oplock yet.
427 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR |
428 SMB2_FLAGS_RELATED_OPERATIONS);
429 rsp_hdr->NextCommand = 0;
430 rsp_hdr->MessageId = rcv_hdr->MessageId;
431 rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
432 rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
433 rsp_hdr->SessionId = rcv_hdr->SessionId;
434 memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);
438 * is_chained_smb2_message() - check for chained command
439 * @work: smb work containing smb request buffer
441 * Return: true if chained request, otherwise false
443 bool is_chained_smb2_message(struct ksmbd_work *work)
445 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
446 unsigned int len, next_cmd;
448 if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
451 hdr = ksmbd_req_buf_next(work);
452 next_cmd = le32_to_cpu(hdr->NextCommand);
454 if ((u64)work->next_smb2_rcv_hdr_off + next_cmd +
455 __SMB2_HEADER_STRUCTURE_SIZE >
456 get_rfc1002_len(work->request_buf)) {
457 pr_err("next command(%u) offset exceeds smb msg size\n",
462 if ((u64)get_rfc1002_len(work->response_buf) + MAX_CIFS_SMALL_BUFFER_SIZE >
464 pr_err("next response offset exceeds response buffer size\n");
468 ksmbd_debug(SMB, "got SMB2 chained command\n");
469 init_chained_smb2_rsp(work);
471 } else if (work->next_smb2_rcv_hdr_off) {
473 * This is last request in chained command,
474 * align response to 8 byte
476 len = ALIGN(get_rfc1002_len(work->response_buf), 8);
477 len = len - get_rfc1002_len(work->response_buf);
479 ksmbd_debug(SMB, "padding len %u\n", len);
480 work->iov[work->iov_idx].iov_len += len;
481 inc_rfc1001_len(work->response_buf, len);
483 work->curr_smb2_rsp_hdr_off = work->next_smb2_rsp_hdr_off;
489 * init_smb2_rsp_hdr() - initialize smb2 response
490 * @work: smb work containing smb request buffer
494 int init_smb2_rsp_hdr(struct ksmbd_work *work)
496 struct smb2_hdr *rsp_hdr = smb2_get_msg(work->response_buf);
497 struct smb2_hdr *rcv_hdr = smb2_get_msg(work->request_buf);
499 memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
500 rsp_hdr->ProtocolId = rcv_hdr->ProtocolId;
501 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
502 rsp_hdr->Command = rcv_hdr->Command;
505 * Message is response. We don't grant oplock yet.
507 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
508 rsp_hdr->NextCommand = 0;
509 rsp_hdr->MessageId = rcv_hdr->MessageId;
510 rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
511 rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
512 rsp_hdr->SessionId = rcv_hdr->SessionId;
513 memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);
519 * smb2_allocate_rsp_buf() - allocate smb2 response buffer
520 * @work: smb work containing smb request buffer
522 * Return: 0 on success, otherwise -ENOMEM
524 int smb2_allocate_rsp_buf(struct ksmbd_work *work)
526 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
527 size_t small_sz = MAX_CIFS_SMALL_BUFFER_SIZE;
528 size_t large_sz = small_sz + work->conn->vals->max_trans_size;
529 size_t sz = small_sz;
530 int cmd = le16_to_cpu(hdr->Command);
532 if (cmd == SMB2_IOCTL_HE || cmd == SMB2_QUERY_DIRECTORY_HE)
535 if (cmd == SMB2_QUERY_INFO_HE) {
536 struct smb2_query_info_req *req;
538 req = smb2_get_msg(work->request_buf);
539 if ((req->InfoType == SMB2_O_INFO_FILE &&
540 (req->FileInfoClass == FILE_FULL_EA_INFORMATION ||
541 req->FileInfoClass == FILE_ALL_INFORMATION)) ||
542 req->InfoType == SMB2_O_INFO_SECURITY)
546 /* allocate large response buf for chained commands */
547 if (le32_to_cpu(hdr->NextCommand) > 0)
550 work->response_buf = kvzalloc(sz, GFP_KERNEL);
551 if (!work->response_buf)
554 work->response_sz = sz;
559 * smb2_check_user_session() - check for valid session for a user
560 * @work: smb work containing smb request buffer
562 * Return: 0 on success, otherwise error
564 int smb2_check_user_session(struct ksmbd_work *work)
566 struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
567 struct ksmbd_conn *conn = work->conn;
568 unsigned int cmd = le16_to_cpu(req_hdr->Command);
569 unsigned long long sess_id;
572 * SMB2_ECHO, SMB2_NEGOTIATE, SMB2_SESSION_SETUP command do not
573 * require a session id, so no need to validate user session's for
576 if (cmd == SMB2_ECHO_HE || cmd == SMB2_NEGOTIATE_HE ||
577 cmd == SMB2_SESSION_SETUP_HE)
580 if (!ksmbd_conn_good(conn))
583 sess_id = le64_to_cpu(req_hdr->SessionId);
586 * If request is not the first in Compound request,
587 * Just validate session id in header with work->sess->id.
589 if (work->next_smb2_rcv_hdr_off) {
591 pr_err("The first operation in the compound does not have sess\n");
594 if (sess_id != ULLONG_MAX && work->sess->id != sess_id) {
595 pr_err("session id(%llu) is different with the first operation(%lld)\n",
596 sess_id, work->sess->id);
602 /* Check for validity of user session */
603 work->sess = ksmbd_session_lookup_all(conn, sess_id);
606 ksmbd_debug(SMB, "Invalid user session, Uid %llu\n", sess_id);
610 static void destroy_previous_session(struct ksmbd_conn *conn,
611 struct ksmbd_user *user, u64 id)
613 struct ksmbd_session *prev_sess = ksmbd_session_lookup_slowpath(id);
614 struct ksmbd_user *prev_user;
615 struct channel *chann;
621 prev_user = prev_sess->user;
624 strcmp(user->name, prev_user->name) ||
625 user->passkey_sz != prev_user->passkey_sz ||
626 memcmp(user->passkey, prev_user->passkey, user->passkey_sz))
629 prev_sess->state = SMB2_SESSION_EXPIRED;
630 xa_for_each(&prev_sess->ksmbd_chann_list, index, chann)
631 ksmbd_conn_set_exiting(chann->conn);
635 * smb2_get_name() - get filename string from on the wire smb format
636 * @src: source buffer
637 * @maxlen: maxlen of source string
638 * @local_nls: nls_table pointer
640 * Return: matching converted filename on success, otherwise error ptr
643 smb2_get_name(const char *src, const int maxlen, struct nls_table *local_nls)
647 name = smb_strndup_from_utf16(src, maxlen, 1, local_nls);
649 pr_err("failed to get name %ld\n", PTR_ERR(name));
653 ksmbd_conv_path_to_unix(name);
654 ksmbd_strip_last_slash(name);
658 int setup_async_work(struct ksmbd_work *work, void (*fn)(void **), void **arg)
660 struct smb2_hdr *rsp_hdr;
661 struct ksmbd_conn *conn = work->conn;
664 rsp_hdr = ksmbd_resp_buf_next(work);
665 rsp_hdr->Flags |= SMB2_FLAGS_ASYNC_COMMAND;
667 id = ksmbd_acquire_async_msg_id(&conn->async_ida);
669 pr_err("Failed to alloc async message id\n");
672 work->asynchronous = true;
674 rsp_hdr->Id.AsyncId = cpu_to_le64(id);
677 "Send interim Response to inform async request id : %d\n",
680 work->cancel_fn = fn;
681 work->cancel_argv = arg;
683 if (list_empty(&work->async_request_entry)) {
684 spin_lock(&conn->request_lock);
685 list_add_tail(&work->async_request_entry, &conn->async_requests);
686 spin_unlock(&conn->request_lock);
692 void release_async_work(struct ksmbd_work *work)
694 struct ksmbd_conn *conn = work->conn;
696 spin_lock(&conn->request_lock);
697 list_del_init(&work->async_request_entry);
698 spin_unlock(&conn->request_lock);
700 work->asynchronous = 0;
701 work->cancel_fn = NULL;
702 kfree(work->cancel_argv);
703 work->cancel_argv = NULL;
704 if (work->async_id) {
705 ksmbd_release_id(&conn->async_ida, work->async_id);
710 void smb2_send_interim_resp(struct ksmbd_work *work, __le32 status)
712 struct smb2_hdr *rsp_hdr;
713 struct ksmbd_work *in_work = ksmbd_alloc_work_struct();
715 if (allocate_interim_rsp_buf(in_work)) {
716 pr_err("smb_allocate_rsp_buf failed!\n");
717 ksmbd_free_work_struct(in_work);
721 in_work->conn = work->conn;
722 memcpy(smb2_get_msg(in_work->response_buf), ksmbd_resp_buf_next(work),
723 __SMB2_HEADER_STRUCTURE_SIZE);
725 rsp_hdr = smb2_get_msg(in_work->response_buf);
726 smb2_set_err_rsp(in_work);
727 rsp_hdr->Status = status;
729 ksmbd_conn_write(in_work);
730 ksmbd_free_work_struct(in_work);
733 static __le32 smb2_get_reparse_tag_special_file(umode_t mode)
735 if (S_ISDIR(mode) || S_ISREG(mode))
739 return IO_REPARSE_TAG_LX_SYMLINK_LE;
740 else if (S_ISFIFO(mode))
741 return IO_REPARSE_TAG_LX_FIFO_LE;
742 else if (S_ISSOCK(mode))
743 return IO_REPARSE_TAG_AF_UNIX_LE;
744 else if (S_ISCHR(mode))
745 return IO_REPARSE_TAG_LX_CHR_LE;
746 else if (S_ISBLK(mode))
747 return IO_REPARSE_TAG_LX_BLK_LE;
753 * smb2_get_dos_mode() - get file mode in dos format from unix mode
754 * @stat: kstat containing file mode
755 * @attribute: attribute flags
757 * Return: converted dos mode
759 static int smb2_get_dos_mode(struct kstat *stat, int attribute)
763 if (S_ISDIR(stat->mode)) {
764 attr = FILE_ATTRIBUTE_DIRECTORY |
765 (attribute & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM));
767 attr = (attribute & 0x00005137) | FILE_ATTRIBUTE_ARCHIVE;
768 attr &= ~(FILE_ATTRIBUTE_DIRECTORY);
769 if (S_ISREG(stat->mode) && (server_conf.share_fake_fscaps &
770 FILE_SUPPORTS_SPARSE_FILES))
771 attr |= FILE_ATTRIBUTE_SPARSE_FILE;
773 if (smb2_get_reparse_tag_special_file(stat->mode))
774 attr |= FILE_ATTRIBUTE_REPARSE_POINT;
780 static void build_preauth_ctxt(struct smb2_preauth_neg_context *pneg_ctxt,
783 pneg_ctxt->ContextType = SMB2_PREAUTH_INTEGRITY_CAPABILITIES;
784 pneg_ctxt->DataLength = cpu_to_le16(38);
785 pneg_ctxt->HashAlgorithmCount = cpu_to_le16(1);
786 pneg_ctxt->Reserved = cpu_to_le32(0);
787 pneg_ctxt->SaltLength = cpu_to_le16(SMB311_SALT_SIZE);
788 get_random_bytes(pneg_ctxt->Salt, SMB311_SALT_SIZE);
789 pneg_ctxt->HashAlgorithms = hash_id;
792 static void build_encrypt_ctxt(struct smb2_encryption_neg_context *pneg_ctxt,
795 pneg_ctxt->ContextType = SMB2_ENCRYPTION_CAPABILITIES;
796 pneg_ctxt->DataLength = cpu_to_le16(4);
797 pneg_ctxt->Reserved = cpu_to_le32(0);
798 pneg_ctxt->CipherCount = cpu_to_le16(1);
799 pneg_ctxt->Ciphers[0] = cipher_type;
802 static void build_sign_cap_ctxt(struct smb2_signing_capabilities *pneg_ctxt,
805 pneg_ctxt->ContextType = SMB2_SIGNING_CAPABILITIES;
806 pneg_ctxt->DataLength =
807 cpu_to_le16((sizeof(struct smb2_signing_capabilities) + 2)
808 - sizeof(struct smb2_neg_context));
809 pneg_ctxt->Reserved = cpu_to_le32(0);
810 pneg_ctxt->SigningAlgorithmCount = cpu_to_le16(1);
811 pneg_ctxt->SigningAlgorithms[0] = sign_algo;
814 static void build_posix_ctxt(struct smb2_posix_neg_context *pneg_ctxt)
816 pneg_ctxt->ContextType = SMB2_POSIX_EXTENSIONS_AVAILABLE;
817 pneg_ctxt->DataLength = cpu_to_le16(POSIX_CTXT_DATA_LEN);
818 /* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */
819 pneg_ctxt->Name[0] = 0x93;
820 pneg_ctxt->Name[1] = 0xAD;
821 pneg_ctxt->Name[2] = 0x25;
822 pneg_ctxt->Name[3] = 0x50;
823 pneg_ctxt->Name[4] = 0x9C;
824 pneg_ctxt->Name[5] = 0xB4;
825 pneg_ctxt->Name[6] = 0x11;
826 pneg_ctxt->Name[7] = 0xE7;
827 pneg_ctxt->Name[8] = 0xB4;
828 pneg_ctxt->Name[9] = 0x23;
829 pneg_ctxt->Name[10] = 0x83;
830 pneg_ctxt->Name[11] = 0xDE;
831 pneg_ctxt->Name[12] = 0x96;
832 pneg_ctxt->Name[13] = 0x8B;
833 pneg_ctxt->Name[14] = 0xCD;
834 pneg_ctxt->Name[15] = 0x7C;
837 static unsigned int assemble_neg_contexts(struct ksmbd_conn *conn,
838 struct smb2_negotiate_rsp *rsp)
840 char * const pneg_ctxt = (char *)rsp +
841 le32_to_cpu(rsp->NegotiateContextOffset);
842 int neg_ctxt_cnt = 1;
846 "assemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
847 build_preauth_ctxt((struct smb2_preauth_neg_context *)pneg_ctxt,
848 conn->preauth_info->Preauth_HashId);
849 ctxt_size = sizeof(struct smb2_preauth_neg_context);
851 if (conn->cipher_type) {
852 /* Round to 8 byte boundary */
853 ctxt_size = round_up(ctxt_size, 8);
855 "assemble SMB2_ENCRYPTION_CAPABILITIES context\n");
856 build_encrypt_ctxt((struct smb2_encryption_neg_context *)
857 (pneg_ctxt + ctxt_size),
860 ctxt_size += sizeof(struct smb2_encryption_neg_context) + 2;
863 /* compression context not yet supported */
864 WARN_ON(conn->compress_algorithm != SMB3_COMPRESS_NONE);
866 if (conn->posix_ext_supported) {
867 ctxt_size = round_up(ctxt_size, 8);
869 "assemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
870 build_posix_ctxt((struct smb2_posix_neg_context *)
871 (pneg_ctxt + ctxt_size));
873 ctxt_size += sizeof(struct smb2_posix_neg_context);
876 if (conn->signing_negotiated) {
877 ctxt_size = round_up(ctxt_size, 8);
879 "assemble SMB2_SIGNING_CAPABILITIES context\n");
880 build_sign_cap_ctxt((struct smb2_signing_capabilities *)
881 (pneg_ctxt + ctxt_size),
882 conn->signing_algorithm);
884 ctxt_size += sizeof(struct smb2_signing_capabilities) + 2;
887 rsp->NegotiateContextCount = cpu_to_le16(neg_ctxt_cnt);
888 return ctxt_size + AUTH_GSS_PADDING;
891 static __le32 decode_preauth_ctxt(struct ksmbd_conn *conn,
892 struct smb2_preauth_neg_context *pneg_ctxt,
896 * sizeof(smb2_preauth_neg_context) assumes SMB311_SALT_SIZE Salt,
897 * which may not be present. Only check for used HashAlgorithms[1].
900 sizeof(struct smb2_neg_context) + MIN_PREAUTH_CTXT_DATA_LEN)
901 return STATUS_INVALID_PARAMETER;
903 if (pneg_ctxt->HashAlgorithms != SMB2_PREAUTH_INTEGRITY_SHA512)
904 return STATUS_NO_PREAUTH_INTEGRITY_HASH_OVERLAP;
906 conn->preauth_info->Preauth_HashId = SMB2_PREAUTH_INTEGRITY_SHA512;
907 return STATUS_SUCCESS;
910 static void decode_encrypt_ctxt(struct ksmbd_conn *conn,
911 struct smb2_encryption_neg_context *pneg_ctxt,
917 if (sizeof(struct smb2_encryption_neg_context) > ctxt_len) {
918 pr_err("Invalid SMB2_ENCRYPTION_CAPABILITIES context size\n");
922 conn->cipher_type = 0;
924 cph_cnt = le16_to_cpu(pneg_ctxt->CipherCount);
925 cphs_size = cph_cnt * sizeof(__le16);
927 if (sizeof(struct smb2_encryption_neg_context) + cphs_size >
929 pr_err("Invalid cipher count(%d)\n", cph_cnt);
933 if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION_OFF)
936 for (i = 0; i < cph_cnt; i++) {
937 if (pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_GCM ||
938 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_CCM ||
939 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_CCM ||
940 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_GCM) {
941 ksmbd_debug(SMB, "Cipher ID = 0x%x\n",
942 pneg_ctxt->Ciphers[i]);
943 conn->cipher_type = pneg_ctxt->Ciphers[i];
950 * smb3_encryption_negotiated() - checks if server and client agreed on enabling encryption
951 * @conn: smb connection
953 * Return: true if connection should be encrypted, else false
955 bool smb3_encryption_negotiated(struct ksmbd_conn *conn)
957 if (!conn->ops->generate_encryptionkey)
961 * SMB 3.0 and 3.0.2 dialects use the SMB2_GLOBAL_CAP_ENCRYPTION flag.
962 * SMB 3.1.1 uses the cipher_type field.
964 return (conn->vals->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION) ||
968 static void decode_compress_ctxt(struct ksmbd_conn *conn,
969 struct smb2_compression_capabilities_context *pneg_ctxt)
971 conn->compress_algorithm = SMB3_COMPRESS_NONE;
974 static void decode_sign_cap_ctxt(struct ksmbd_conn *conn,
975 struct smb2_signing_capabilities *pneg_ctxt,
979 int i, sign_alos_size;
981 if (sizeof(struct smb2_signing_capabilities) > ctxt_len) {
982 pr_err("Invalid SMB2_SIGNING_CAPABILITIES context length\n");
986 conn->signing_negotiated = false;
987 sign_algo_cnt = le16_to_cpu(pneg_ctxt->SigningAlgorithmCount);
988 sign_alos_size = sign_algo_cnt * sizeof(__le16);
990 if (sizeof(struct smb2_signing_capabilities) + sign_alos_size >
992 pr_err("Invalid signing algorithm count(%d)\n", sign_algo_cnt);
996 for (i = 0; i < sign_algo_cnt; i++) {
997 if (pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_HMAC_SHA256_LE ||
998 pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_AES_CMAC_LE) {
999 ksmbd_debug(SMB, "Signing Algorithm ID = 0x%x\n",
1000 pneg_ctxt->SigningAlgorithms[i]);
1001 conn->signing_negotiated = true;
1002 conn->signing_algorithm =
1003 pneg_ctxt->SigningAlgorithms[i];
1009 static __le32 deassemble_neg_contexts(struct ksmbd_conn *conn,
1010 struct smb2_negotiate_req *req,
1011 unsigned int len_of_smb)
1013 /* +4 is to account for the RFC1001 len field */
1014 struct smb2_neg_context *pctx = (struct smb2_neg_context *)req;
1015 int i = 0, len_of_ctxts;
1016 unsigned int offset = le32_to_cpu(req->NegotiateContextOffset);
1017 unsigned int neg_ctxt_cnt = le16_to_cpu(req->NegotiateContextCount);
1018 __le32 status = STATUS_INVALID_PARAMETER;
1020 ksmbd_debug(SMB, "decoding %d negotiate contexts\n", neg_ctxt_cnt);
1021 if (len_of_smb <= offset) {
1022 ksmbd_debug(SMB, "Invalid response: negotiate context offset\n");
1026 len_of_ctxts = len_of_smb - offset;
1028 while (i++ < neg_ctxt_cnt) {
1031 if (len_of_ctxts < (int)sizeof(struct smb2_neg_context))
1034 pctx = (struct smb2_neg_context *)((char *)pctx + offset);
1035 clen = le16_to_cpu(pctx->DataLength);
1036 ctxt_len = clen + sizeof(struct smb2_neg_context);
1038 if (ctxt_len > len_of_ctxts)
1041 if (pctx->ContextType == SMB2_PREAUTH_INTEGRITY_CAPABILITIES) {
1043 "deassemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
1044 if (conn->preauth_info->Preauth_HashId)
1047 status = decode_preauth_ctxt(conn,
1048 (struct smb2_preauth_neg_context *)pctx,
1050 if (status != STATUS_SUCCESS)
1052 } else if (pctx->ContextType == SMB2_ENCRYPTION_CAPABILITIES) {
1054 "deassemble SMB2_ENCRYPTION_CAPABILITIES context\n");
1055 if (conn->cipher_type)
1058 decode_encrypt_ctxt(conn,
1059 (struct smb2_encryption_neg_context *)pctx,
1061 } else if (pctx->ContextType == SMB2_COMPRESSION_CAPABILITIES) {
1063 "deassemble SMB2_COMPRESSION_CAPABILITIES context\n");
1064 if (conn->compress_algorithm)
1067 decode_compress_ctxt(conn,
1068 (struct smb2_compression_capabilities_context *)pctx);
1069 } else if (pctx->ContextType == SMB2_NETNAME_NEGOTIATE_CONTEXT_ID) {
1071 "deassemble SMB2_NETNAME_NEGOTIATE_CONTEXT_ID context\n");
1072 } else if (pctx->ContextType == SMB2_POSIX_EXTENSIONS_AVAILABLE) {
1074 "deassemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
1075 conn->posix_ext_supported = true;
1076 } else if (pctx->ContextType == SMB2_SIGNING_CAPABILITIES) {
1078 "deassemble SMB2_SIGNING_CAPABILITIES context\n");
1080 decode_sign_cap_ctxt(conn,
1081 (struct smb2_signing_capabilities *)pctx,
1085 /* offsets must be 8 byte aligned */
1086 offset = (ctxt_len + 7) & ~0x7;
1087 len_of_ctxts -= offset;
1093 * smb2_handle_negotiate() - handler for smb2 negotiate command
1094 * @work: smb work containing smb request buffer
1098 int smb2_handle_negotiate(struct ksmbd_work *work)
1100 struct ksmbd_conn *conn = work->conn;
1101 struct smb2_negotiate_req *req = smb2_get_msg(work->request_buf);
1102 struct smb2_negotiate_rsp *rsp = smb2_get_msg(work->response_buf);
1104 unsigned int smb2_buf_len, smb2_neg_size, neg_ctxt_len = 0;
1107 ksmbd_debug(SMB, "Received negotiate request\n");
1108 conn->need_neg = false;
1109 if (ksmbd_conn_good(conn)) {
1110 pr_err("conn->tcp_status is already in CifsGood State\n");
1111 work->send_no_response = 1;
1115 smb2_buf_len = get_rfc1002_len(work->request_buf);
1116 smb2_neg_size = offsetof(struct smb2_negotiate_req, Dialects);
1117 if (smb2_neg_size > smb2_buf_len) {
1118 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1123 if (req->DialectCount == 0) {
1124 pr_err("malformed packet\n");
1125 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1130 if (conn->dialect == SMB311_PROT_ID) {
1131 unsigned int nego_ctxt_off = le32_to_cpu(req->NegotiateContextOffset);
1133 if (smb2_buf_len < nego_ctxt_off) {
1134 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1139 if (smb2_neg_size > nego_ctxt_off) {
1140 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1145 if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
1147 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1152 if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
1154 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1160 conn->cli_cap = le32_to_cpu(req->Capabilities);
1161 switch (conn->dialect) {
1162 case SMB311_PROT_ID:
1163 conn->preauth_info =
1164 kzalloc(sizeof(struct preauth_integrity_info),
1166 if (!conn->preauth_info) {
1168 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1172 status = deassemble_neg_contexts(conn, req,
1173 get_rfc1002_len(work->request_buf));
1174 if (status != STATUS_SUCCESS) {
1175 pr_err("deassemble_neg_contexts error(0x%x)\n",
1177 rsp->hdr.Status = status;
1179 kfree(conn->preauth_info);
1180 conn->preauth_info = NULL;
1184 rc = init_smb3_11_server(conn);
1186 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1187 kfree(conn->preauth_info);
1188 conn->preauth_info = NULL;
1192 ksmbd_gen_preauth_integrity_hash(conn,
1194 conn->preauth_info->Preauth_HashValue);
1195 rsp->NegotiateContextOffset =
1196 cpu_to_le32(OFFSET_OF_NEG_CONTEXT);
1197 neg_ctxt_len = assemble_neg_contexts(conn, rsp);
1199 case SMB302_PROT_ID:
1200 init_smb3_02_server(conn);
1203 init_smb3_0_server(conn);
1206 init_smb2_1_server(conn);
1211 ksmbd_debug(SMB, "Server dialect :0x%x not supported\n",
1213 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
1217 rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
1220 conn->connection_type = conn->dialect;
1222 rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
1223 rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
1224 rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);
1226 memcpy(conn->ClientGUID, req->ClientGUID,
1227 SMB2_CLIENT_GUID_SIZE);
1228 conn->cli_sec_mode = le16_to_cpu(req->SecurityMode);
1230 rsp->StructureSize = cpu_to_le16(65);
1231 rsp->DialectRevision = cpu_to_le16(conn->dialect);
1232 /* Not setting conn guid rsp->ServerGUID, as it
1233 * not used by client for identifying server
1235 memset(rsp->ServerGUID, 0, SMB2_CLIENT_GUID_SIZE);
1237 rsp->SystemTime = cpu_to_le64(ksmbd_systime());
1238 rsp->ServerStartTime = 0;
1239 ksmbd_debug(SMB, "negotiate context offset %d, count %d\n",
1240 le32_to_cpu(rsp->NegotiateContextOffset),
1241 le16_to_cpu(rsp->NegotiateContextCount));
1243 rsp->SecurityBufferOffset = cpu_to_le16(128);
1244 rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
1245 ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) +
1246 le16_to_cpu(rsp->SecurityBufferOffset));
1248 rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
1249 conn->use_spnego = true;
1251 if ((server_conf.signing == KSMBD_CONFIG_OPT_AUTO ||
1252 server_conf.signing == KSMBD_CONFIG_OPT_DISABLED) &&
1253 req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED_LE)
1255 else if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY) {
1256 server_conf.enforced_signing = true;
1257 rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
1261 conn->srv_sec_mode = le16_to_cpu(rsp->SecurityMode);
1262 ksmbd_conn_set_need_negotiate(conn);
1266 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
1269 rc = ksmbd_iov_pin_rsp(work, rsp,
1270 sizeof(struct smb2_negotiate_rsp) +
1271 AUTH_GSS_LENGTH + neg_ctxt_len);
1273 smb2_set_err_rsp(work);
1277 static int alloc_preauth_hash(struct ksmbd_session *sess,
1278 struct ksmbd_conn *conn)
1280 if (sess->Preauth_HashValue)
1283 sess->Preauth_HashValue = kmemdup(conn->preauth_info->Preauth_HashValue,
1284 PREAUTH_HASHVALUE_SIZE, GFP_KERNEL);
1285 if (!sess->Preauth_HashValue)
1291 static int generate_preauth_hash(struct ksmbd_work *work)
1293 struct ksmbd_conn *conn = work->conn;
1294 struct ksmbd_session *sess = work->sess;
1297 if (conn->dialect != SMB311_PROT_ID)
1300 if (conn->binding) {
1301 struct preauth_session *preauth_sess;
1303 preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
1304 if (!preauth_sess) {
1305 preauth_sess = ksmbd_preauth_session_alloc(conn, sess->id);
1310 preauth_hash = preauth_sess->Preauth_HashValue;
1312 if (!sess->Preauth_HashValue)
1313 if (alloc_preauth_hash(sess, conn))
1315 preauth_hash = sess->Preauth_HashValue;
1318 ksmbd_gen_preauth_integrity_hash(conn, work->request_buf, preauth_hash);
1322 static int decode_negotiation_token(struct ksmbd_conn *conn,
1323 struct negotiate_message *negblob,
1326 if (!conn->use_spnego)
1329 if (ksmbd_decode_negTokenInit((char *)negblob, sz, conn)) {
1330 if (ksmbd_decode_negTokenTarg((char *)negblob, sz, conn)) {
1331 conn->auth_mechs |= KSMBD_AUTH_NTLMSSP;
1332 conn->preferred_auth_mech = KSMBD_AUTH_NTLMSSP;
1333 conn->use_spnego = false;
1339 static int ntlm_negotiate(struct ksmbd_work *work,
1340 struct negotiate_message *negblob,
1341 size_t negblob_len, struct smb2_sess_setup_rsp *rsp)
1343 struct challenge_message *chgblob;
1344 unsigned char *spnego_blob = NULL;
1345 u16 spnego_blob_len;
1349 ksmbd_debug(SMB, "negotiate phase\n");
1350 rc = ksmbd_decode_ntlmssp_neg_blob(negblob, negblob_len, work->conn);
1354 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1356 (struct challenge_message *)((char *)&rsp->hdr.ProtocolId + sz);
1357 memset(chgblob, 0, sizeof(struct challenge_message));
1359 if (!work->conn->use_spnego) {
1360 sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
1364 rsp->SecurityBufferLength = cpu_to_le16(sz);
1368 sz = sizeof(struct challenge_message);
1369 sz += (strlen(ksmbd_netbios_name()) * 2 + 1 + 4) * 6;
1371 neg_blob = kzalloc(sz, GFP_KERNEL);
1375 chgblob = (struct challenge_message *)neg_blob;
1376 sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
1382 rc = build_spnego_ntlmssp_neg_blob(&spnego_blob, &spnego_blob_len,
1389 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1390 memcpy((char *)&rsp->hdr.ProtocolId + sz, spnego_blob, spnego_blob_len);
1391 rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
1399 static struct authenticate_message *user_authblob(struct ksmbd_conn *conn,
1400 struct smb2_sess_setup_req *req)
1404 if (conn->use_spnego && conn->mechToken)
1405 return (struct authenticate_message *)conn->mechToken;
1407 sz = le16_to_cpu(req->SecurityBufferOffset);
1408 return (struct authenticate_message *)((char *)&req->hdr.ProtocolId
1412 static struct ksmbd_user *session_user(struct ksmbd_conn *conn,
1413 struct smb2_sess_setup_req *req)
1415 struct authenticate_message *authblob;
1416 struct ksmbd_user *user;
1418 unsigned int name_off, name_len, secbuf_len;
1420 secbuf_len = le16_to_cpu(req->SecurityBufferLength);
1421 if (secbuf_len < sizeof(struct authenticate_message)) {
1422 ksmbd_debug(SMB, "blob len %d too small\n", secbuf_len);
1425 authblob = user_authblob(conn, req);
1426 name_off = le32_to_cpu(authblob->UserName.BufferOffset);
1427 name_len = le16_to_cpu(authblob->UserName.Length);
1429 if (secbuf_len < (u64)name_off + name_len)
1432 name = smb_strndup_from_utf16((const char *)authblob + name_off,
1437 pr_err("cannot allocate memory\n");
1441 ksmbd_debug(SMB, "session setup request for user %s\n", name);
1442 user = ksmbd_login_user(name);
1447 static int ntlm_authenticate(struct ksmbd_work *work,
1448 struct smb2_sess_setup_req *req,
1449 struct smb2_sess_setup_rsp *rsp)
1451 struct ksmbd_conn *conn = work->conn;
1452 struct ksmbd_session *sess = work->sess;
1453 struct channel *chann = NULL;
1454 struct ksmbd_user *user;
1458 ksmbd_debug(SMB, "authenticate phase\n");
1459 if (conn->use_spnego) {
1460 unsigned char *spnego_blob;
1461 u16 spnego_blob_len;
1463 rc = build_spnego_ntlmssp_auth_blob(&spnego_blob,
1469 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1470 memcpy((char *)&rsp->hdr.ProtocolId + sz, spnego_blob, spnego_blob_len);
1471 rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
1475 user = session_user(conn, req);
1477 ksmbd_debug(SMB, "Unknown user name or an error\n");
1481 /* Check for previous session */
1482 prev_id = le64_to_cpu(req->PreviousSessionId);
1483 if (prev_id && prev_id != sess->id)
1484 destroy_previous_session(conn, user, prev_id);
1486 if (sess->state == SMB2_SESSION_VALID) {
1488 * Reuse session if anonymous try to connect
1489 * on reauthetication.
1491 if (conn->binding == false && ksmbd_anonymous_user(user)) {
1492 ksmbd_free_user(user);
1496 if (!ksmbd_compare_user(sess->user, user)) {
1497 ksmbd_free_user(user);
1500 ksmbd_free_user(user);
1505 if (conn->binding == false && user_guest(sess->user)) {
1506 rsp->SessionFlags = SMB2_SESSION_FLAG_IS_GUEST_LE;
1508 struct authenticate_message *authblob;
1510 authblob = user_authblob(conn, req);
1511 sz = le16_to_cpu(req->SecurityBufferLength);
1512 rc = ksmbd_decode_ntlmssp_auth_blob(authblob, sz, conn, sess);
1514 set_user_flag(sess->user, KSMBD_USER_FLAG_BAD_PASSWORD);
1515 ksmbd_debug(SMB, "authentication failed\n");
1521 * If session state is SMB2_SESSION_VALID, We can assume
1522 * that it is reauthentication. And the user/password
1523 * has been verified, so return it here.
1525 if (sess->state == SMB2_SESSION_VALID) {
1527 goto binding_session;
1531 if ((rsp->SessionFlags != SMB2_SESSION_FLAG_IS_GUEST_LE &&
1532 (conn->sign || server_conf.enforced_signing)) ||
1533 (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
1536 if (smb3_encryption_negotiated(conn) &&
1537 !(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1538 rc = conn->ops->generate_encryptionkey(conn, sess);
1541 "SMB3 encryption key generation failed\n");
1545 if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION)
1546 rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
1548 * signing is disable if encryption is enable
1555 if (conn->dialect >= SMB30_PROT_ID) {
1556 chann = lookup_chann_list(sess, conn);
1558 chann = kmalloc(sizeof(struct channel), GFP_KERNEL);
1563 xa_store(&sess->ksmbd_chann_list, (long)conn, chann, GFP_KERNEL);
1567 if (conn->ops->generate_signingkey) {
1568 rc = conn->ops->generate_signingkey(sess, conn);
1570 ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
1575 if (!ksmbd_conn_lookup_dialect(conn)) {
1576 pr_err("fail to verify the dialect\n");
1582 #ifdef CONFIG_SMB_SERVER_KERBEROS5
1583 static int krb5_authenticate(struct ksmbd_work *work,
1584 struct smb2_sess_setup_req *req,
1585 struct smb2_sess_setup_rsp *rsp)
1587 struct ksmbd_conn *conn = work->conn;
1588 struct ksmbd_session *sess = work->sess;
1589 char *in_blob, *out_blob;
1590 struct channel *chann = NULL;
1592 int in_len, out_len;
1595 in_blob = (char *)&req->hdr.ProtocolId +
1596 le16_to_cpu(req->SecurityBufferOffset);
1597 in_len = le16_to_cpu(req->SecurityBufferLength);
1598 out_blob = (char *)&rsp->hdr.ProtocolId +
1599 le16_to_cpu(rsp->SecurityBufferOffset);
1600 out_len = work->response_sz -
1601 (le16_to_cpu(rsp->SecurityBufferOffset) + 4);
1603 /* Check previous session */
1604 prev_sess_id = le64_to_cpu(req->PreviousSessionId);
1605 if (prev_sess_id && prev_sess_id != sess->id)
1606 destroy_previous_session(conn, sess->user, prev_sess_id);
1608 if (sess->state == SMB2_SESSION_VALID)
1609 ksmbd_free_user(sess->user);
1611 retval = ksmbd_krb5_authenticate(sess, in_blob, in_len,
1612 out_blob, &out_len);
1614 ksmbd_debug(SMB, "krb5 authentication failed\n");
1617 rsp->SecurityBufferLength = cpu_to_le16(out_len);
1619 if ((conn->sign || server_conf.enforced_signing) ||
1620 (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
1623 if (smb3_encryption_negotiated(conn)) {
1624 retval = conn->ops->generate_encryptionkey(conn, sess);
1627 "SMB3 encryption key generation failed\n");
1631 if (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION)
1632 rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
1636 if (conn->dialect >= SMB30_PROT_ID) {
1637 chann = lookup_chann_list(sess, conn);
1639 chann = kmalloc(sizeof(struct channel), GFP_KERNEL);
1644 xa_store(&sess->ksmbd_chann_list, (long)conn, chann, GFP_KERNEL);
1648 if (conn->ops->generate_signingkey) {
1649 retval = conn->ops->generate_signingkey(sess, conn);
1651 ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
1656 if (!ksmbd_conn_lookup_dialect(conn)) {
1657 pr_err("fail to verify the dialect\n");
1663 static int krb5_authenticate(struct ksmbd_work *work,
1664 struct smb2_sess_setup_req *req,
1665 struct smb2_sess_setup_rsp *rsp)
1671 int smb2_sess_setup(struct ksmbd_work *work)
1673 struct ksmbd_conn *conn = work->conn;
1674 struct smb2_sess_setup_req *req;
1675 struct smb2_sess_setup_rsp *rsp;
1676 struct ksmbd_session *sess;
1677 struct negotiate_message *negblob;
1678 unsigned int negblob_len, negblob_off;
1681 ksmbd_debug(SMB, "Received request for session setup\n");
1683 WORK_BUFFERS(work, req, rsp);
1685 rsp->StructureSize = cpu_to_le16(9);
1686 rsp->SessionFlags = 0;
1687 rsp->SecurityBufferOffset = cpu_to_le16(72);
1688 rsp->SecurityBufferLength = 0;
1690 ksmbd_conn_lock(conn);
1691 if (!req->hdr.SessionId) {
1692 sess = ksmbd_smb2_session_create();
1697 rsp->hdr.SessionId = cpu_to_le64(sess->id);
1698 rc = ksmbd_session_register(conn, sess);
1701 } else if (conn->dialect >= SMB30_PROT_ID &&
1702 (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
1703 req->Flags & SMB2_SESSION_REQ_FLAG_BINDING) {
1704 u64 sess_id = le64_to_cpu(req->hdr.SessionId);
1706 sess = ksmbd_session_lookup_slowpath(sess_id);
1712 if (conn->dialect != sess->dialect) {
1717 if (!(req->hdr.Flags & SMB2_FLAGS_SIGNED)) {
1722 if (strncmp(conn->ClientGUID, sess->ClientGUID,
1723 SMB2_CLIENT_GUID_SIZE)) {
1728 if (sess->state == SMB2_SESSION_IN_PROGRESS) {
1733 if (sess->state == SMB2_SESSION_EXPIRED) {
1738 if (ksmbd_conn_need_reconnect(conn)) {
1744 if (ksmbd_session_lookup(conn, sess_id)) {
1749 if (user_guest(sess->user)) {
1754 conn->binding = true;
1755 } else if ((conn->dialect < SMB30_PROT_ID ||
1756 server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
1757 (req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1762 sess = ksmbd_session_lookup(conn,
1763 le64_to_cpu(req->hdr.SessionId));
1769 if (sess->state == SMB2_SESSION_EXPIRED) {
1774 if (ksmbd_conn_need_reconnect(conn)) {
1782 negblob_off = le16_to_cpu(req->SecurityBufferOffset);
1783 negblob_len = le16_to_cpu(req->SecurityBufferLength);
1784 if (negblob_off < offsetof(struct smb2_sess_setup_req, Buffer) ||
1785 negblob_len < offsetof(struct negotiate_message, NegotiateFlags)) {
1790 negblob = (struct negotiate_message *)((char *)&req->hdr.ProtocolId +
1793 if (decode_negotiation_token(conn, negblob, negblob_len) == 0) {
1794 if (conn->mechToken)
1795 negblob = (struct negotiate_message *)conn->mechToken;
1798 if (server_conf.auth_mechs & conn->auth_mechs) {
1799 rc = generate_preauth_hash(work);
1803 if (conn->preferred_auth_mech &
1804 (KSMBD_AUTH_KRB5 | KSMBD_AUTH_MSKRB5)) {
1805 rc = krb5_authenticate(work, req, rsp);
1811 if (!ksmbd_conn_need_reconnect(conn)) {
1812 ksmbd_conn_set_good(conn);
1813 sess->state = SMB2_SESSION_VALID;
1815 kfree(sess->Preauth_HashValue);
1816 sess->Preauth_HashValue = NULL;
1817 } else if (conn->preferred_auth_mech == KSMBD_AUTH_NTLMSSP) {
1818 if (negblob->MessageType == NtLmNegotiate) {
1819 rc = ntlm_negotiate(work, negblob, negblob_len, rsp);
1823 STATUS_MORE_PROCESSING_REQUIRED;
1824 } else if (negblob->MessageType == NtLmAuthenticate) {
1825 rc = ntlm_authenticate(work, req, rsp);
1829 if (!ksmbd_conn_need_reconnect(conn)) {
1830 ksmbd_conn_set_good(conn);
1831 sess->state = SMB2_SESSION_VALID;
1833 if (conn->binding) {
1834 struct preauth_session *preauth_sess;
1837 ksmbd_preauth_session_lookup(conn, sess->id);
1839 list_del(&preauth_sess->preauth_entry);
1840 kfree(preauth_sess);
1843 kfree(sess->Preauth_HashValue);
1844 sess->Preauth_HashValue = NULL;
1846 pr_info_ratelimited("Unknown NTLMSSP message type : 0x%x\n",
1847 le32_to_cpu(negblob->MessageType));
1851 /* TODO: need one more negotiation */
1852 pr_err("Not support the preferred authentication\n");
1856 pr_err("Not support authentication\n");
1862 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1863 else if (rc == -ENOENT)
1864 rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
1865 else if (rc == -EACCES)
1866 rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
1867 else if (rc == -EFAULT)
1868 rsp->hdr.Status = STATUS_NETWORK_SESSION_EXPIRED;
1869 else if (rc == -ENOMEM)
1870 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
1871 else if (rc == -EOPNOTSUPP)
1872 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
1874 rsp->hdr.Status = STATUS_LOGON_FAILURE;
1876 if (conn->use_spnego && conn->mechToken) {
1877 kfree(conn->mechToken);
1878 conn->mechToken = NULL;
1883 * SecurityBufferOffset should be set to zero
1884 * in session setup error response.
1886 rsp->SecurityBufferOffset = 0;
1889 bool try_delay = false;
1892 * To avoid dictionary attacks (repeated session setups rapidly sent) to
1893 * connect to server, ksmbd make a delay of a 5 seconds on session setup
1894 * failure to make it harder to send enough random connection requests
1895 * to break into a server.
1897 if (sess->user && sess->user->flags & KSMBD_USER_FLAG_DELAY_SESSION)
1900 sess->last_active = jiffies;
1901 sess->state = SMB2_SESSION_EXPIRED;
1903 ksmbd_conn_set_need_reconnect(conn);
1905 ksmbd_conn_set_need_negotiate(conn);
1908 smb2_set_err_rsp(work);
1910 unsigned int iov_len;
1912 if (rsp->SecurityBufferLength)
1913 iov_len = offsetof(struct smb2_sess_setup_rsp, Buffer) +
1914 le16_to_cpu(rsp->SecurityBufferLength);
1916 iov_len = sizeof(struct smb2_sess_setup_rsp);
1917 rc = ksmbd_iov_pin_rsp(work, rsp, iov_len);
1919 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
1922 ksmbd_conn_unlock(conn);
1927 * smb2_tree_connect() - handler for smb2 tree connect command
1928 * @work: smb work containing smb request buffer
1930 * Return: 0 on success, otherwise error
1932 int smb2_tree_connect(struct ksmbd_work *work)
1934 struct ksmbd_conn *conn = work->conn;
1935 struct smb2_tree_connect_req *req;
1936 struct smb2_tree_connect_rsp *rsp;
1937 struct ksmbd_session *sess = work->sess;
1938 char *treename = NULL, *name = NULL;
1939 struct ksmbd_tree_conn_status status;
1940 struct ksmbd_share_config *share;
1943 WORK_BUFFERS(work, req, rsp);
1945 treename = smb_strndup_from_utf16(req->Buffer,
1946 le16_to_cpu(req->PathLength), true,
1948 if (IS_ERR(treename)) {
1949 pr_err("treename is NULL\n");
1950 status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
1954 name = ksmbd_extract_sharename(conn->um, treename);
1956 status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
1960 ksmbd_debug(SMB, "tree connect request for tree %s treename %s\n",
1963 status = ksmbd_tree_conn_connect(conn, sess, name);
1964 if (status.ret == KSMBD_TREE_CONN_STATUS_OK)
1965 rsp->hdr.Id.SyncId.TreeId = cpu_to_le32(status.tree_conn->id);
1969 share = status.tree_conn->share_conf;
1970 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
1971 ksmbd_debug(SMB, "IPC share path request\n");
1972 rsp->ShareType = SMB2_SHARE_TYPE_PIPE;
1973 rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
1974 FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE |
1975 FILE_DELETE_LE | FILE_READ_CONTROL_LE |
1976 FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
1977 FILE_SYNCHRONIZE_LE;
1979 rsp->ShareType = SMB2_SHARE_TYPE_DISK;
1980 rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
1981 FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE;
1982 if (test_tree_conn_flag(status.tree_conn,
1983 KSMBD_TREE_CONN_FLAG_WRITABLE)) {
1984 rsp->MaximalAccess |= FILE_WRITE_DATA_LE |
1985 FILE_APPEND_DATA_LE | FILE_WRITE_EA_LE |
1986 FILE_DELETE_LE | FILE_WRITE_ATTRIBUTES_LE |
1987 FILE_DELETE_CHILD_LE | FILE_READ_CONTROL_LE |
1988 FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
1989 FILE_SYNCHRONIZE_LE;
1993 status.tree_conn->maximal_access = le32_to_cpu(rsp->MaximalAccess);
1994 if (conn->posix_ext_supported)
1995 status.tree_conn->posix_extensions = true;
1997 write_lock(&sess->tree_conns_lock);
1998 status.tree_conn->t_state = TREE_CONNECTED;
1999 write_unlock(&sess->tree_conns_lock);
2000 rsp->StructureSize = cpu_to_le16(16);
2002 rsp->Capabilities = 0;
2004 /* default manual caching */
2005 rsp->ShareFlags = SMB2_SHAREFLAG_MANUAL_CACHING;
2007 rc = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_tree_connect_rsp));
2009 status.ret = KSMBD_TREE_CONN_STATUS_NOMEM;
2011 if (!IS_ERR(treename))
2016 switch (status.ret) {
2017 case KSMBD_TREE_CONN_STATUS_OK:
2018 rsp->hdr.Status = STATUS_SUCCESS;
2023 case KSMBD_TREE_CONN_STATUS_NO_SHARE:
2024 rsp->hdr.Status = STATUS_BAD_NETWORK_NAME;
2027 case KSMBD_TREE_CONN_STATUS_NOMEM:
2028 rsp->hdr.Status = STATUS_NO_MEMORY;
2030 case KSMBD_TREE_CONN_STATUS_ERROR:
2031 case KSMBD_TREE_CONN_STATUS_TOO_MANY_CONNS:
2032 case KSMBD_TREE_CONN_STATUS_TOO_MANY_SESSIONS:
2033 rsp->hdr.Status = STATUS_ACCESS_DENIED;
2036 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2039 rsp->hdr.Status = STATUS_ACCESS_DENIED;
2042 if (status.ret != KSMBD_TREE_CONN_STATUS_OK)
2043 smb2_set_err_rsp(work);
2049 * smb2_create_open_flags() - convert smb open flags to unix open flags
2050 * @file_present: is file already present
2051 * @access: file access flags
2052 * @disposition: file disposition flags
2053 * @may_flags: set with MAY_ flags
2055 * Return: file open flags
2057 static int smb2_create_open_flags(bool file_present, __le32 access,
2061 int oflags = O_NONBLOCK | O_LARGEFILE;
2063 if (access & FILE_READ_DESIRED_ACCESS_LE &&
2064 access & FILE_WRITE_DESIRE_ACCESS_LE) {
2066 *may_flags = MAY_OPEN | MAY_READ | MAY_WRITE;
2067 } else if (access & FILE_WRITE_DESIRE_ACCESS_LE) {
2069 *may_flags = MAY_OPEN | MAY_WRITE;
2072 *may_flags = MAY_OPEN | MAY_READ;
2075 if (access == FILE_READ_ATTRIBUTES_LE)
2079 switch (disposition & FILE_CREATE_MASK_LE) {
2081 case FILE_CREATE_LE:
2083 case FILE_SUPERSEDE_LE:
2084 case FILE_OVERWRITE_LE:
2085 case FILE_OVERWRITE_IF_LE:
2092 switch (disposition & FILE_CREATE_MASK_LE) {
2093 case FILE_SUPERSEDE_LE:
2094 case FILE_CREATE_LE:
2095 case FILE_OPEN_IF_LE:
2096 case FILE_OVERWRITE_IF_LE:
2100 case FILE_OVERWRITE_LE:
2112 * smb2_tree_disconnect() - handler for smb tree connect request
2113 * @work: smb work containing request buffer
2117 int smb2_tree_disconnect(struct ksmbd_work *work)
2119 struct smb2_tree_disconnect_rsp *rsp;
2120 struct smb2_tree_disconnect_req *req;
2121 struct ksmbd_session *sess = work->sess;
2122 struct ksmbd_tree_connect *tcon = work->tcon;
2125 WORK_BUFFERS(work, req, rsp);
2127 ksmbd_debug(SMB, "request\n");
2130 ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
2132 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2137 ksmbd_close_tree_conn_fds(work);
2139 write_lock(&sess->tree_conns_lock);
2140 if (tcon->t_state == TREE_DISCONNECTED) {
2141 write_unlock(&sess->tree_conns_lock);
2142 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2147 WARN_ON_ONCE(atomic_dec_and_test(&tcon->refcount));
2148 tcon->t_state = TREE_DISCONNECTED;
2149 write_unlock(&sess->tree_conns_lock);
2151 err = ksmbd_tree_conn_disconnect(sess, tcon);
2153 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2159 rsp->StructureSize = cpu_to_le16(4);
2160 err = ksmbd_iov_pin_rsp(work, rsp,
2161 sizeof(struct smb2_tree_disconnect_rsp));
2163 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
2170 smb2_set_err_rsp(work);
2176 * smb2_session_logoff() - handler for session log off request
2177 * @work: smb work containing request buffer
2181 int smb2_session_logoff(struct ksmbd_work *work)
2183 struct ksmbd_conn *conn = work->conn;
2184 struct smb2_logoff_req *req;
2185 struct smb2_logoff_rsp *rsp;
2186 struct ksmbd_session *sess;
2190 WORK_BUFFERS(work, req, rsp);
2192 ksmbd_debug(SMB, "request\n");
2194 ksmbd_conn_lock(conn);
2195 if (!ksmbd_conn_good(conn)) {
2196 ksmbd_conn_unlock(conn);
2197 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2198 smb2_set_err_rsp(work);
2201 sess_id = le64_to_cpu(req->hdr.SessionId);
2202 ksmbd_all_conn_set_status(sess_id, KSMBD_SESS_NEED_RECONNECT);
2203 ksmbd_conn_unlock(conn);
2205 ksmbd_close_session_fds(work);
2206 ksmbd_conn_wait_idle(conn, sess_id);
2209 * Re-lookup session to validate if session is deleted
2210 * while waiting request complete
2212 sess = ksmbd_session_lookup_all(conn, sess_id);
2213 if (ksmbd_tree_conn_session_logoff(sess)) {
2214 ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
2215 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2216 smb2_set_err_rsp(work);
2220 ksmbd_destroy_file_table(&sess->file_table);
2221 sess->state = SMB2_SESSION_EXPIRED;
2223 ksmbd_free_user(sess->user);
2225 ksmbd_all_conn_set_status(sess_id, KSMBD_SESS_NEED_NEGOTIATE);
2227 rsp->StructureSize = cpu_to_le16(4);
2228 err = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_logoff_rsp));
2230 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
2231 smb2_set_err_rsp(work);
2238 * create_smb2_pipe() - create IPC pipe
2239 * @work: smb work containing request buffer
2241 * Return: 0 on success, otherwise error
2243 static noinline int create_smb2_pipe(struct ksmbd_work *work)
2245 struct smb2_create_rsp *rsp;
2246 struct smb2_create_req *req;
2251 WORK_BUFFERS(work, req, rsp);
2253 name = smb_strndup_from_utf16(req->Buffer, le16_to_cpu(req->NameLength),
2254 1, work->conn->local_nls);
2256 rsp->hdr.Status = STATUS_NO_MEMORY;
2257 err = PTR_ERR(name);
2261 id = ksmbd_session_rpc_open(work->sess, name);
2263 pr_err("Unable to open RPC pipe: %d\n", id);
2268 rsp->hdr.Status = STATUS_SUCCESS;
2269 rsp->StructureSize = cpu_to_le16(89);
2270 rsp->OplockLevel = SMB2_OPLOCK_LEVEL_NONE;
2272 rsp->CreateAction = cpu_to_le32(FILE_OPENED);
2274 rsp->CreationTime = cpu_to_le64(0);
2275 rsp->LastAccessTime = cpu_to_le64(0);
2276 rsp->ChangeTime = cpu_to_le64(0);
2277 rsp->AllocationSize = cpu_to_le64(0);
2278 rsp->EndofFile = cpu_to_le64(0);
2279 rsp->FileAttributes = FILE_ATTRIBUTE_NORMAL_LE;
2281 rsp->VolatileFileId = id;
2282 rsp->PersistentFileId = 0;
2283 rsp->CreateContextsOffset = 0;
2284 rsp->CreateContextsLength = 0;
2286 err = ksmbd_iov_pin_rsp(work, rsp, offsetof(struct smb2_create_rsp, Buffer));
2296 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2300 rsp->hdr.Status = STATUS_NO_MEMORY;
2307 smb2_set_err_rsp(work);
2312 * smb2_set_ea() - handler for setting extended attributes using set
2314 * @eabuf: set info command buffer
2315 * @buf_len: set info command buffer length
2316 * @path: dentry path for get ea
2318 * Return: 0 on success, otherwise error
2320 static int smb2_set_ea(struct smb2_ea_info *eabuf, unsigned int buf_len,
2321 const struct path *path)
2323 struct mnt_idmap *idmap = mnt_idmap(path->mnt);
2324 char *attr_name = NULL, *value;
2326 unsigned int next = 0;
2328 if (buf_len < sizeof(struct smb2_ea_info) + eabuf->EaNameLength +
2329 le16_to_cpu(eabuf->EaValueLength))
2332 attr_name = kmalloc(XATTR_NAME_MAX + 1, GFP_KERNEL);
2337 if (!eabuf->EaNameLength)
2341 "name : <%s>, name_len : %u, value_len : %u, next : %u\n",
2342 eabuf->name, eabuf->EaNameLength,
2343 le16_to_cpu(eabuf->EaValueLength),
2344 le32_to_cpu(eabuf->NextEntryOffset));
2346 if (eabuf->EaNameLength >
2347 (XATTR_NAME_MAX - XATTR_USER_PREFIX_LEN)) {
2352 memcpy(attr_name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN);
2353 memcpy(&attr_name[XATTR_USER_PREFIX_LEN], eabuf->name,
2354 eabuf->EaNameLength);
2355 attr_name[XATTR_USER_PREFIX_LEN + eabuf->EaNameLength] = '\0';
2356 value = (char *)&eabuf->name + eabuf->EaNameLength + 1;
2358 if (!eabuf->EaValueLength) {
2359 rc = ksmbd_vfs_casexattr_len(idmap,
2362 XATTR_USER_PREFIX_LEN +
2363 eabuf->EaNameLength);
2365 /* delete the EA only when it exits */
2367 rc = ksmbd_vfs_remove_xattr(idmap,
2373 "remove xattr failed(%d)\n",
2379 /* if the EA doesn't exist, just do nothing. */
2382 rc = ksmbd_vfs_setxattr(idmap, path, attr_name, value,
2383 le16_to_cpu(eabuf->EaValueLength), 0);
2386 "ksmbd_vfs_setxattr is failed(%d)\n",
2393 next = le32_to_cpu(eabuf->NextEntryOffset);
2394 if (next == 0 || buf_len < next)
2397 eabuf = (struct smb2_ea_info *)((char *)eabuf + next);
2398 if (buf_len < sizeof(struct smb2_ea_info)) {
2403 if (buf_len < sizeof(struct smb2_ea_info) + eabuf->EaNameLength +
2404 le16_to_cpu(eabuf->EaValueLength)) {
2408 } while (next != 0);
2414 static noinline int smb2_set_stream_name_xattr(const struct path *path,
2415 struct ksmbd_file *fp,
2416 char *stream_name, int s_type)
2418 struct mnt_idmap *idmap = mnt_idmap(path->mnt);
2419 size_t xattr_stream_size;
2420 char *xattr_stream_name;
2423 rc = ksmbd_vfs_xattr_stream_name(stream_name,
2430 fp->stream.name = xattr_stream_name;
2431 fp->stream.size = xattr_stream_size;
2433 /* Check if there is stream prefix in xattr space */
2434 rc = ksmbd_vfs_casexattr_len(idmap,
2441 if (fp->cdoption == FILE_OPEN_LE) {
2442 ksmbd_debug(SMB, "XATTR stream name lookup failed: %d\n", rc);
2446 rc = ksmbd_vfs_setxattr(idmap, path, xattr_stream_name, NULL, 0, 0);
2448 pr_err("Failed to store XATTR stream name :%d\n", rc);
2452 static int smb2_remove_smb_xattrs(const struct path *path)
2454 struct mnt_idmap *idmap = mnt_idmap(path->mnt);
2455 char *name, *xattr_list = NULL;
2456 ssize_t xattr_list_len;
2459 xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
2460 if (xattr_list_len < 0) {
2462 } else if (!xattr_list_len) {
2463 ksmbd_debug(SMB, "empty xattr in the file\n");
2467 for (name = xattr_list; name - xattr_list < xattr_list_len;
2468 name += strlen(name) + 1) {
2469 ksmbd_debug(SMB, "%s, len %zd\n", name, strlen(name));
2471 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN) &&
2472 !strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
2473 STREAM_PREFIX_LEN)) {
2474 err = ksmbd_vfs_remove_xattr(idmap, path,
2477 ksmbd_debug(SMB, "remove xattr failed : %s\n",
2486 static int smb2_create_truncate(const struct path *path)
2488 int rc = vfs_truncate(path, 0);
2491 pr_err("vfs_truncate failed, rc %d\n", rc);
2495 rc = smb2_remove_smb_xattrs(path);
2496 if (rc == -EOPNOTSUPP)
2500 "ksmbd_truncate_stream_name_xattr failed, rc %d\n",
2505 static void smb2_new_xattrs(struct ksmbd_tree_connect *tcon, const struct path *path,
2506 struct ksmbd_file *fp)
2508 struct xattr_dos_attrib da = {0};
2511 if (!test_share_config_flag(tcon->share_conf,
2512 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2516 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
2517 da.itime = da.create_time = fp->create_time;
2518 da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
2519 XATTR_DOSINFO_ITIME;
2521 rc = ksmbd_vfs_set_dos_attrib_xattr(mnt_idmap(path->mnt), path, &da);
2523 ksmbd_debug(SMB, "failed to store file attribute into xattr\n");
2526 static void smb2_update_xattrs(struct ksmbd_tree_connect *tcon,
2527 const struct path *path, struct ksmbd_file *fp)
2529 struct xattr_dos_attrib da;
2532 fp->f_ci->m_fattr &= ~(FILE_ATTRIBUTE_HIDDEN_LE | FILE_ATTRIBUTE_SYSTEM_LE);
2534 /* get FileAttributes from XATTR_NAME_DOS_ATTRIBUTE */
2535 if (!test_share_config_flag(tcon->share_conf,
2536 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2539 rc = ksmbd_vfs_get_dos_attrib_xattr(mnt_idmap(path->mnt),
2542 fp->f_ci->m_fattr = cpu_to_le32(da.attr);
2543 fp->create_time = da.create_time;
2544 fp->itime = da.itime;
2548 static int smb2_creat(struct ksmbd_work *work, struct path *parent_path,
2549 struct path *path, char *name, int open_flags,
2550 umode_t posix_mode, bool is_dir)
2552 struct ksmbd_tree_connect *tcon = work->tcon;
2553 struct ksmbd_share_config *share = tcon->share_conf;
2557 if (!(open_flags & O_CREAT))
2560 ksmbd_debug(SMB, "file does not exist, so creating\n");
2561 if (is_dir == true) {
2562 ksmbd_debug(SMB, "creating directory\n");
2564 mode = share_config_directory_mode(share, posix_mode);
2565 rc = ksmbd_vfs_mkdir(work, name, mode);
2569 ksmbd_debug(SMB, "creating regular file\n");
2571 mode = share_config_create_mode(share, posix_mode);
2572 rc = ksmbd_vfs_create(work, name, mode);
2577 rc = ksmbd_vfs_kern_path_locked(work, name, 0, parent_path, path, 0);
2579 pr_err("cannot get linux path (%s), err = %d\n",
2586 static int smb2_create_sd_buffer(struct ksmbd_work *work,
2587 struct smb2_create_req *req,
2588 const struct path *path)
2590 struct create_context *context;
2591 struct create_sd_buf_req *sd_buf;
2593 if (!req->CreateContextsOffset)
2596 /* Parse SD BUFFER create contexts */
2597 context = smb2_find_context_vals(req, SMB2_CREATE_SD_BUFFER, 4);
2600 else if (IS_ERR(context))
2601 return PTR_ERR(context);
2604 "Set ACLs using SMB2_CREATE_SD_BUFFER context\n");
2605 sd_buf = (struct create_sd_buf_req *)context;
2606 if (le16_to_cpu(context->DataOffset) +
2607 le32_to_cpu(context->DataLength) <
2608 sizeof(struct create_sd_buf_req))
2610 return set_info_sec(work->conn, work->tcon, path, &sd_buf->ntsd,
2611 le32_to_cpu(sd_buf->ccontext.DataLength), true);
2614 static void ksmbd_acls_fattr(struct smb_fattr *fattr,
2615 struct mnt_idmap *idmap,
2616 struct inode *inode)
2618 vfsuid_t vfsuid = i_uid_into_vfsuid(idmap, inode);
2619 vfsgid_t vfsgid = i_gid_into_vfsgid(idmap, inode);
2621 fattr->cf_uid = vfsuid_into_kuid(vfsuid);
2622 fattr->cf_gid = vfsgid_into_kgid(vfsgid);
2623 fattr->cf_mode = inode->i_mode;
2624 fattr->cf_acls = NULL;
2625 fattr->cf_dacls = NULL;
2627 if (IS_ENABLED(CONFIG_FS_POSIX_ACL)) {
2628 fattr->cf_acls = get_inode_acl(inode, ACL_TYPE_ACCESS);
2629 if (S_ISDIR(inode->i_mode))
2630 fattr->cf_dacls = get_inode_acl(inode, ACL_TYPE_DEFAULT);
2635 * smb2_open() - handler for smb file open request
2636 * @work: smb work containing request buffer
2638 * Return: 0 on success, otherwise error
2640 int smb2_open(struct ksmbd_work *work)
2642 struct ksmbd_conn *conn = work->conn;
2643 struct ksmbd_session *sess = work->sess;
2644 struct ksmbd_tree_connect *tcon = work->tcon;
2645 struct smb2_create_req *req;
2646 struct smb2_create_rsp *rsp;
2647 struct path path, parent_path;
2648 struct ksmbd_share_config *share = tcon->share_conf;
2649 struct ksmbd_file *fp = NULL;
2650 struct file *filp = NULL;
2651 struct mnt_idmap *idmap = NULL;
2653 struct create_context *context;
2654 struct lease_ctx_info *lc = NULL;
2655 struct create_ea_buf_req *ea_buf = NULL;
2656 struct oplock_info *opinfo;
2657 __le32 *next_ptr = NULL;
2658 int req_op_level = 0, open_flags = 0, may_flags = 0, file_info = 0;
2660 int contxt_cnt = 0, query_disk_id = 0;
2661 int maximal_access_ctxt = 0, posix_ctxt = 0;
2665 char *stream_name = NULL;
2666 bool file_present = false, created = false, already_permitted = false;
2667 int share_ret, need_truncate = 0;
2669 umode_t posix_mode = 0;
2670 __le32 daccess, maximal_access = 0;
2673 WORK_BUFFERS(work, req, rsp);
2675 if (req->hdr.NextCommand && !work->next_smb2_rcv_hdr_off &&
2676 (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
2677 ksmbd_debug(SMB, "invalid flag in chained command\n");
2678 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2679 smb2_set_err_rsp(work);
2683 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
2684 ksmbd_debug(SMB, "IPC pipe create request\n");
2685 return create_smb2_pipe(work);
2688 if (req->NameLength) {
2689 if ((req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
2690 *(char *)req->Buffer == '\\') {
2691 pr_err("not allow directory name included leading slash\n");
2696 name = smb2_get_name(req->Buffer,
2697 le16_to_cpu(req->NameLength),
2698 work->conn->local_nls);
2707 ksmbd_debug(SMB, "converted name = %s\n", name);
2708 if (strchr(name, ':')) {
2709 if (!test_share_config_flag(work->tcon->share_conf,
2710 KSMBD_SHARE_FLAG_STREAMS)) {
2714 rc = parse_stream_name(name, &stream_name, &s_type);
2719 rc = ksmbd_validate_filename(name);
2723 if (ksmbd_share_veto_filename(share, name)) {
2725 ksmbd_debug(SMB, "Reject open(), vetoed file: %s\n",
2730 name = kstrdup("", GFP_KERNEL);
2737 req_op_level = req->RequestedOplockLevel;
2738 if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE)
2739 lc = parse_lease_state(req);
2741 if (le32_to_cpu(req->ImpersonationLevel) > le32_to_cpu(IL_DELEGATE)) {
2742 pr_err("Invalid impersonationlevel : 0x%x\n",
2743 le32_to_cpu(req->ImpersonationLevel));
2745 rsp->hdr.Status = STATUS_BAD_IMPERSONATION_LEVEL;
2749 if (req->CreateOptions && !(req->CreateOptions & CREATE_OPTIONS_MASK_LE)) {
2750 pr_err("Invalid create options : 0x%x\n",
2751 le32_to_cpu(req->CreateOptions));
2755 if (req->CreateOptions & FILE_SEQUENTIAL_ONLY_LE &&
2756 req->CreateOptions & FILE_RANDOM_ACCESS_LE)
2757 req->CreateOptions = ~(FILE_SEQUENTIAL_ONLY_LE);
2759 if (req->CreateOptions &
2760 (FILE_OPEN_BY_FILE_ID_LE | CREATE_TREE_CONNECTION |
2761 FILE_RESERVE_OPFILTER_LE)) {
2766 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
2767 if (req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE) {
2770 } else if (req->CreateOptions & FILE_NO_COMPRESSION_LE) {
2771 req->CreateOptions = ~(FILE_NO_COMPRESSION_LE);
2776 if (le32_to_cpu(req->CreateDisposition) >
2777 le32_to_cpu(FILE_OVERWRITE_IF_LE)) {
2778 pr_err("Invalid create disposition : 0x%x\n",
2779 le32_to_cpu(req->CreateDisposition));
2784 if (!(req->DesiredAccess & DESIRED_ACCESS_MASK)) {
2785 pr_err("Invalid desired access : 0x%x\n",
2786 le32_to_cpu(req->DesiredAccess));
2791 if (req->FileAttributes && !(req->FileAttributes & FILE_ATTRIBUTE_MASK_LE)) {
2792 pr_err("Invalid file attribute : 0x%x\n",
2793 le32_to_cpu(req->FileAttributes));
2798 if (req->CreateContextsOffset) {
2799 /* Parse non-durable handle create contexts */
2800 context = smb2_find_context_vals(req, SMB2_CREATE_EA_BUFFER, 4);
2801 if (IS_ERR(context)) {
2802 rc = PTR_ERR(context);
2804 } else if (context) {
2805 ea_buf = (struct create_ea_buf_req *)context;
2806 if (le16_to_cpu(context->DataOffset) +
2807 le32_to_cpu(context->DataLength) <
2808 sizeof(struct create_ea_buf_req)) {
2812 if (req->CreateOptions & FILE_NO_EA_KNOWLEDGE_LE) {
2813 rsp->hdr.Status = STATUS_ACCESS_DENIED;
2819 context = smb2_find_context_vals(req,
2820 SMB2_CREATE_QUERY_MAXIMAL_ACCESS_REQUEST, 4);
2821 if (IS_ERR(context)) {
2822 rc = PTR_ERR(context);
2824 } else if (context) {
2826 "get query maximal access context\n");
2827 maximal_access_ctxt = 1;
2830 context = smb2_find_context_vals(req,
2831 SMB2_CREATE_TIMEWARP_REQUEST, 4);
2832 if (IS_ERR(context)) {
2833 rc = PTR_ERR(context);
2835 } else if (context) {
2836 ksmbd_debug(SMB, "get timewarp context\n");
2841 if (tcon->posix_extensions) {
2842 context = smb2_find_context_vals(req,
2843 SMB2_CREATE_TAG_POSIX, 16);
2844 if (IS_ERR(context)) {
2845 rc = PTR_ERR(context);
2847 } else if (context) {
2848 struct create_posix *posix =
2849 (struct create_posix *)context;
2850 if (le16_to_cpu(context->DataOffset) +
2851 le32_to_cpu(context->DataLength) <
2852 sizeof(struct create_posix) - 4) {
2856 ksmbd_debug(SMB, "get posix context\n");
2858 posix_mode = le32_to_cpu(posix->Mode);
2864 if (ksmbd_override_fsids(work)) {
2869 rc = ksmbd_vfs_kern_path_locked(work, name, LOOKUP_NO_SYMLINKS,
2870 &parent_path, &path, 1);
2872 file_present = true;
2874 if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE) {
2876 * If file exists with under flags, return access
2879 if (req->CreateDisposition == FILE_OVERWRITE_IF_LE ||
2880 req->CreateDisposition == FILE_OPEN_IF_LE) {
2885 if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
2887 "User does not have write permission\n");
2891 } else if (d_is_symlink(path.dentry)) {
2896 file_present = true;
2897 idmap = mnt_idmap(path.mnt);
2901 ksmbd_debug(SMB, "can not get linux path for %s, rc = %d\n",
2907 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
2908 if (s_type == DATA_STREAM) {
2910 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2913 if (file_present && S_ISDIR(d_inode(path.dentry)->i_mode) &&
2914 s_type == DATA_STREAM) {
2916 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
2920 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE &&
2921 req->FileAttributes & FILE_ATTRIBUTE_NORMAL_LE) {
2922 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2930 if (file_present && req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE &&
2931 S_ISDIR(d_inode(path.dentry)->i_mode) &&
2932 !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2933 ksmbd_debug(SMB, "open() argument is a directory: %s, %x\n",
2934 name, req->CreateOptions);
2935 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
2940 if (file_present && (req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
2941 !(req->CreateDisposition == FILE_CREATE_LE) &&
2942 !S_ISDIR(d_inode(path.dentry)->i_mode)) {
2943 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2948 if (!stream_name && file_present &&
2949 req->CreateDisposition == FILE_CREATE_LE) {
2954 daccess = smb_map_generic_desired_access(req->DesiredAccess);
2956 if (file_present && !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2957 rc = smb_check_perm_dacl(conn, &path, &daccess,
2963 if (daccess & FILE_MAXIMAL_ACCESS_LE) {
2964 if (!file_present) {
2965 daccess = cpu_to_le32(GENERIC_ALL_FLAGS);
2967 ksmbd_vfs_query_maximal_access(idmap,
2970 already_permitted = true;
2972 maximal_access = daccess;
2975 open_flags = smb2_create_open_flags(file_present, daccess,
2976 req->CreateDisposition,
2979 if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
2980 if (open_flags & O_CREAT) {
2982 "User does not have write permission\n");
2988 /*create file if not present */
2989 if (!file_present) {
2990 rc = smb2_creat(work, &parent_path, &path, name, open_flags,
2992 req->CreateOptions & FILE_DIRECTORY_FILE_LE);
2994 if (rc == -ENOENT) {
2996 rsp->hdr.Status = STATUS_OBJECT_PATH_NOT_FOUND;
3002 idmap = mnt_idmap(path.mnt);
3004 if (le32_to_cpu(ea_buf->ccontext.DataLength) <
3005 sizeof(struct smb2_ea_info)) {
3010 rc = smb2_set_ea(&ea_buf->ea,
3011 le32_to_cpu(ea_buf->ccontext.DataLength),
3013 if (rc == -EOPNOTSUPP)
3018 } else if (!already_permitted) {
3019 /* FILE_READ_ATTRIBUTE is allowed without inode_permission,
3020 * because execute(search) permission on a parent directory,
3021 * is already granted.
3023 if (daccess & ~(FILE_READ_ATTRIBUTES_LE | FILE_READ_CONTROL_LE)) {
3024 rc = inode_permission(idmap,
3025 d_inode(path.dentry),
3030 if ((daccess & FILE_DELETE_LE) ||
3031 (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
3032 rc = inode_permission(idmap,
3033 d_inode(path.dentry->d_parent),
3034 MAY_EXEC | MAY_WRITE);
3041 rc = ksmbd_query_inode_status(d_inode(path.dentry->d_parent));
3042 if (rc == KSMBD_INODE_STATUS_PENDING_DELETE) {
3048 filp = dentry_open(&path, open_flags, current_cred());
3051 pr_err("dentry open for dir failed, rc %d\n", rc);
3056 if (!(open_flags & O_TRUNC))
3057 file_info = FILE_OPENED;
3059 file_info = FILE_OVERWRITTEN;
3061 if ((req->CreateDisposition & FILE_CREATE_MASK_LE) ==
3063 file_info = FILE_SUPERSEDED;
3064 } else if (open_flags & O_CREAT) {
3065 file_info = FILE_CREATED;
3068 ksmbd_vfs_set_fadvise(filp, req->CreateOptions);
3070 /* Obtain Volatile-ID */
3071 fp = ksmbd_open_fd(work, filp);
3079 /* Get Persistent-ID */
3080 ksmbd_open_durable_fd(fp);
3081 if (!has_file_id(fp->persistent_id)) {
3086 fp->cdoption = req->CreateDisposition;
3087 fp->daccess = daccess;
3088 fp->saccess = req->ShareAccess;
3089 fp->coption = req->CreateOptions;
3091 /* Set default windows and posix acls if creating new file */
3094 struct inode *inode = d_inode(path.dentry);
3096 posix_acl_rc = ksmbd_vfs_inherit_posix_acl(idmap,
3098 d_inode(path.dentry->d_parent));
3100 ksmbd_debug(SMB, "inherit posix acl failed : %d\n", posix_acl_rc);
3102 if (test_share_config_flag(work->tcon->share_conf,
3103 KSMBD_SHARE_FLAG_ACL_XATTR)) {
3104 rc = smb_inherit_dacl(conn, &path, sess->user->uid,
3109 rc = smb2_create_sd_buffer(work, req, &path);
3112 ksmbd_vfs_set_init_posix_acl(idmap,
3115 if (test_share_config_flag(work->tcon->share_conf,
3116 KSMBD_SHARE_FLAG_ACL_XATTR)) {
3117 struct smb_fattr fattr;
3118 struct smb_ntsd *pntsd;
3119 int pntsd_size, ace_num = 0;
3121 ksmbd_acls_fattr(&fattr, idmap, inode);
3123 ace_num = fattr.cf_acls->a_count;
3125 ace_num += fattr.cf_dacls->a_count;
3127 pntsd = kmalloc(sizeof(struct smb_ntsd) +
3128 sizeof(struct smb_sid) * 3 +
3129 sizeof(struct smb_acl) +
3130 sizeof(struct smb_ace) * ace_num * 2,
3133 posix_acl_release(fattr.cf_acls);
3134 posix_acl_release(fattr.cf_dacls);
3138 rc = build_sec_desc(idmap,
3143 &pntsd_size, &fattr);
3144 posix_acl_release(fattr.cf_acls);
3145 posix_acl_release(fattr.cf_dacls);
3151 rc = ksmbd_vfs_set_sd_xattr(conn,
3158 pr_err("failed to store ntacl in xattr : %d\n",
3167 rc = smb2_set_stream_name_xattr(&path,
3173 file_info = FILE_CREATED;
3176 fp->attrib_only = !(req->DesiredAccess & ~(FILE_READ_ATTRIBUTES_LE |
3177 FILE_WRITE_ATTRIBUTES_LE | FILE_SYNCHRONIZE_LE));
3178 if (!S_ISDIR(file_inode(filp)->i_mode) && open_flags & O_TRUNC &&
3179 !fp->attrib_only && !stream_name) {
3180 smb_break_all_oplock(work, fp);
3184 /* fp should be searchable through ksmbd_inode.m_fp_list
3185 * after daccess, saccess, attrib_only, and stream are
3188 write_lock(&fp->f_ci->m_lock);
3189 list_add(&fp->node, &fp->f_ci->m_fp_list);
3190 write_unlock(&fp->f_ci->m_lock);
3192 /* Check delete pending among previous fp before oplock break */
3193 if (ksmbd_inode_pending_delete(fp)) {
3198 share_ret = ksmbd_smb_check_shared_mode(fp->filp, fp);
3199 if (!test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_OPLOCKS) ||
3200 (req_op_level == SMB2_OPLOCK_LEVEL_LEASE &&
3201 !(conn->vals->capabilities & SMB2_GLOBAL_CAP_LEASING))) {
3202 if (share_ret < 0 && !S_ISDIR(file_inode(fp->filp)->i_mode)) {
3207 if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE) {
3208 req_op_level = smb2_map_lease_to_oplock(lc->req_state);
3210 "lease req for(%s) req oplock state 0x%x, lease state 0x%x\n",
3211 name, req_op_level, lc->req_state);
3212 rc = find_same_lease_key(sess, fp->f_ci, lc);
3215 } else if (open_flags == O_RDONLY &&
3216 (req_op_level == SMB2_OPLOCK_LEVEL_BATCH ||
3217 req_op_level == SMB2_OPLOCK_LEVEL_EXCLUSIVE))
3218 req_op_level = SMB2_OPLOCK_LEVEL_II;
3220 rc = smb_grant_oplock(work, req_op_level,
3221 fp->persistent_id, fp,
3222 le32_to_cpu(req->hdr.Id.SyncId.TreeId),
3228 if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)
3229 ksmbd_fd_set_delete_on_close(fp, file_info);
3231 if (need_truncate) {
3232 rc = smb2_create_truncate(&path);
3237 if (req->CreateContextsOffset) {
3238 struct create_alloc_size_req *az_req;
3240 az_req = (struct create_alloc_size_req *)smb2_find_context_vals(req,
3241 SMB2_CREATE_ALLOCATION_SIZE, 4);
3242 if (IS_ERR(az_req)) {
3243 rc = PTR_ERR(az_req);
3245 } else if (az_req) {
3249 if (le16_to_cpu(az_req->ccontext.DataOffset) +
3250 le32_to_cpu(az_req->ccontext.DataLength) <
3251 sizeof(struct create_alloc_size_req)) {
3255 alloc_size = le64_to_cpu(az_req->AllocationSize);
3257 "request smb2 create allocate size : %llu\n",
3259 smb_break_all_levII_oplock(work, fp, 1);
3260 err = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
3264 "vfs_fallocate is failed : %d\n",
3268 context = smb2_find_context_vals(req, SMB2_CREATE_QUERY_ON_DISK_ID, 4);
3269 if (IS_ERR(context)) {
3270 rc = PTR_ERR(context);
3272 } else if (context) {
3273 ksmbd_debug(SMB, "get query on disk id context\n");
3278 rc = ksmbd_vfs_getattr(&path, &stat);
3282 if (stat.result_mask & STATX_BTIME)
3283 fp->create_time = ksmbd_UnixTimeToNT(stat.btime);
3285 fp->create_time = ksmbd_UnixTimeToNT(stat.ctime);
3286 if (req->FileAttributes || fp->f_ci->m_fattr == 0)
3288 cpu_to_le32(smb2_get_dos_mode(&stat, le32_to_cpu(req->FileAttributes)));
3291 smb2_update_xattrs(tcon, &path, fp);
3293 smb2_new_xattrs(tcon, &path, fp);
3295 memcpy(fp->client_guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE);
3297 rsp->StructureSize = cpu_to_le16(89);
3299 opinfo = rcu_dereference(fp->f_opinfo);
3300 rsp->OplockLevel = opinfo != NULL ? opinfo->level : 0;
3303 rsp->CreateAction = cpu_to_le32(file_info);
3304 rsp->CreationTime = cpu_to_le64(fp->create_time);
3305 time = ksmbd_UnixTimeToNT(stat.atime);
3306 rsp->LastAccessTime = cpu_to_le64(time);
3307 time = ksmbd_UnixTimeToNT(stat.mtime);
3308 rsp->LastWriteTime = cpu_to_le64(time);
3309 time = ksmbd_UnixTimeToNT(stat.ctime);
3310 rsp->ChangeTime = cpu_to_le64(time);
3311 rsp->AllocationSize = S_ISDIR(stat.mode) ? 0 :
3312 cpu_to_le64(stat.blocks << 9);
3313 rsp->EndofFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
3314 rsp->FileAttributes = fp->f_ci->m_fattr;
3318 rsp->PersistentFileId = fp->persistent_id;
3319 rsp->VolatileFileId = fp->volatile_id;
3321 rsp->CreateContextsOffset = 0;
3322 rsp->CreateContextsLength = 0;
3323 iov_len = offsetof(struct smb2_create_rsp, Buffer);
3325 /* If lease is request send lease context response */
3326 if (opinfo && opinfo->is_lease) {
3327 struct create_context *lease_ccontext;
3329 ksmbd_debug(SMB, "lease granted on(%s) lease state 0x%x\n",
3330 name, opinfo->o_lease->state);
3331 rsp->OplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
3333 lease_ccontext = (struct create_context *)rsp->Buffer;
3335 create_lease_buf(rsp->Buffer, opinfo->o_lease);
3336 le32_add_cpu(&rsp->CreateContextsLength,
3337 conn->vals->create_lease_size);
3338 iov_len += conn->vals->create_lease_size;
3339 next_ptr = &lease_ccontext->Next;
3340 next_off = conn->vals->create_lease_size;
3343 if (maximal_access_ctxt) {
3344 struct create_context *mxac_ccontext;
3346 if (maximal_access == 0)
3347 ksmbd_vfs_query_maximal_access(idmap,
3350 mxac_ccontext = (struct create_context *)(rsp->Buffer +
3351 le32_to_cpu(rsp->CreateContextsLength));
3353 create_mxac_rsp_buf(rsp->Buffer +
3354 le32_to_cpu(rsp->CreateContextsLength),
3355 le32_to_cpu(maximal_access));
3356 le32_add_cpu(&rsp->CreateContextsLength,
3357 conn->vals->create_mxac_size);
3358 iov_len += conn->vals->create_mxac_size;
3360 *next_ptr = cpu_to_le32(next_off);
3361 next_ptr = &mxac_ccontext->Next;
3362 next_off = conn->vals->create_mxac_size;
3365 if (query_disk_id) {
3366 struct create_context *disk_id_ccontext;
3368 disk_id_ccontext = (struct create_context *)(rsp->Buffer +
3369 le32_to_cpu(rsp->CreateContextsLength));
3371 create_disk_id_rsp_buf(rsp->Buffer +
3372 le32_to_cpu(rsp->CreateContextsLength),
3373 stat.ino, tcon->id);
3374 le32_add_cpu(&rsp->CreateContextsLength,
3375 conn->vals->create_disk_id_size);
3376 iov_len += conn->vals->create_disk_id_size;
3378 *next_ptr = cpu_to_le32(next_off);
3379 next_ptr = &disk_id_ccontext->Next;
3380 next_off = conn->vals->create_disk_id_size;
3385 create_posix_rsp_buf(rsp->Buffer +
3386 le32_to_cpu(rsp->CreateContextsLength),
3388 le32_add_cpu(&rsp->CreateContextsLength,
3389 conn->vals->create_posix_size);
3390 iov_len += conn->vals->create_posix_size;
3392 *next_ptr = cpu_to_le32(next_off);
3395 if (contxt_cnt > 0) {
3396 rsp->CreateContextsOffset =
3397 cpu_to_le32(offsetof(struct smb2_create_rsp, Buffer));
3401 if (file_present || created) {
3402 inode_unlock(d_inode(parent_path.dentry));
3404 path_put(&parent_path);
3406 ksmbd_revert_fsids(work);
3409 ksmbd_update_fstate(&work->sess->file_table, fp, FP_INITED);
3410 rc = ksmbd_iov_pin_rsp(work, (void *)rsp, iov_len);
3414 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
3415 else if (rc == -EOPNOTSUPP)
3416 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
3417 else if (rc == -EACCES || rc == -ESTALE || rc == -EXDEV)
3418 rsp->hdr.Status = STATUS_ACCESS_DENIED;
3419 else if (rc == -ENOENT)
3420 rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
3421 else if (rc == -EPERM)
3422 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
3423 else if (rc == -EBUSY)
3424 rsp->hdr.Status = STATUS_DELETE_PENDING;
3425 else if (rc == -EBADF)
3426 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
3427 else if (rc == -ENOEXEC)
3428 rsp->hdr.Status = STATUS_DUPLICATE_OBJECTID;
3429 else if (rc == -ENXIO)
3430 rsp->hdr.Status = STATUS_NO_SUCH_DEVICE;
3431 else if (rc == -EEXIST)
3432 rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
3433 else if (rc == -EMFILE)
3434 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
3435 if (!rsp->hdr.Status)
3436 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
3439 ksmbd_fd_put(work, fp);
3440 smb2_set_err_rsp(work);
3441 ksmbd_debug(SMB, "Error response: %x\n", rsp->hdr.Status);
3450 static int readdir_info_level_struct_sz(int info_level)
3452 switch (info_level) {
3453 case FILE_FULL_DIRECTORY_INFORMATION:
3454 return sizeof(struct file_full_directory_info);
3455 case FILE_BOTH_DIRECTORY_INFORMATION:
3456 return sizeof(struct file_both_directory_info);
3457 case FILE_DIRECTORY_INFORMATION:
3458 return sizeof(struct file_directory_info);
3459 case FILE_NAMES_INFORMATION:
3460 return sizeof(struct file_names_info);
3461 case FILEID_FULL_DIRECTORY_INFORMATION:
3462 return sizeof(struct file_id_full_dir_info);
3463 case FILEID_BOTH_DIRECTORY_INFORMATION:
3464 return sizeof(struct file_id_both_directory_info);
3465 case SMB_FIND_FILE_POSIX_INFO:
3466 return sizeof(struct smb2_posix_info);
3472 static int dentry_name(struct ksmbd_dir_info *d_info, int info_level)
3474 switch (info_level) {
3475 case FILE_FULL_DIRECTORY_INFORMATION:
3477 struct file_full_directory_info *ffdinfo;
3479 ffdinfo = (struct file_full_directory_info *)d_info->rptr;
3480 d_info->rptr += le32_to_cpu(ffdinfo->NextEntryOffset);
3481 d_info->name = ffdinfo->FileName;
3482 d_info->name_len = le32_to_cpu(ffdinfo->FileNameLength);
3485 case FILE_BOTH_DIRECTORY_INFORMATION:
3487 struct file_both_directory_info *fbdinfo;
3489 fbdinfo = (struct file_both_directory_info *)d_info->rptr;
3490 d_info->rptr += le32_to_cpu(fbdinfo->NextEntryOffset);
3491 d_info->name = fbdinfo->FileName;
3492 d_info->name_len = le32_to_cpu(fbdinfo->FileNameLength);
3495 case FILE_DIRECTORY_INFORMATION:
3497 struct file_directory_info *fdinfo;
3499 fdinfo = (struct file_directory_info *)d_info->rptr;
3500 d_info->rptr += le32_to_cpu(fdinfo->NextEntryOffset);
3501 d_info->name = fdinfo->FileName;
3502 d_info->name_len = le32_to_cpu(fdinfo->FileNameLength);
3505 case FILE_NAMES_INFORMATION:
3507 struct file_names_info *fninfo;
3509 fninfo = (struct file_names_info *)d_info->rptr;
3510 d_info->rptr += le32_to_cpu(fninfo->NextEntryOffset);
3511 d_info->name = fninfo->FileName;
3512 d_info->name_len = le32_to_cpu(fninfo->FileNameLength);
3515 case FILEID_FULL_DIRECTORY_INFORMATION:
3517 struct file_id_full_dir_info *dinfo;
3519 dinfo = (struct file_id_full_dir_info *)d_info->rptr;
3520 d_info->rptr += le32_to_cpu(dinfo->NextEntryOffset);
3521 d_info->name = dinfo->FileName;
3522 d_info->name_len = le32_to_cpu(dinfo->FileNameLength);
3525 case FILEID_BOTH_DIRECTORY_INFORMATION:
3527 struct file_id_both_directory_info *fibdinfo;
3529 fibdinfo = (struct file_id_both_directory_info *)d_info->rptr;
3530 d_info->rptr += le32_to_cpu(fibdinfo->NextEntryOffset);
3531 d_info->name = fibdinfo->FileName;
3532 d_info->name_len = le32_to_cpu(fibdinfo->FileNameLength);
3535 case SMB_FIND_FILE_POSIX_INFO:
3537 struct smb2_posix_info *posix_info;
3539 posix_info = (struct smb2_posix_info *)d_info->rptr;
3540 d_info->rptr += le32_to_cpu(posix_info->NextEntryOffset);
3541 d_info->name = posix_info->name;
3542 d_info->name_len = le32_to_cpu(posix_info->name_len);
3551 * smb2_populate_readdir_entry() - encode directory entry in smb2 response
3553 * @conn: connection instance
3554 * @info_level: smb information level
3555 * @d_info: structure included variables for query dir
3556 * @ksmbd_kstat: ksmbd wrapper of dirent stat information
3558 * if directory has many entries, find first can't read it fully.
3559 * find next might be called multiple times to read remaining dir entries
3561 * Return: 0 on success, otherwise error
3563 static int smb2_populate_readdir_entry(struct ksmbd_conn *conn, int info_level,
3564 struct ksmbd_dir_info *d_info,
3565 struct ksmbd_kstat *ksmbd_kstat)
3567 int next_entry_offset = 0;
3571 int struct_sz, rc = 0;
3573 conv_name = ksmbd_convert_dir_info_name(d_info,
3579 /* Somehow the name has only terminating NULL bytes */
3582 goto free_conv_name;
3585 struct_sz = readdir_info_level_struct_sz(info_level) + conv_len;
3586 next_entry_offset = ALIGN(struct_sz, KSMBD_DIR_INFO_ALIGNMENT);
3587 d_info->last_entry_off_align = next_entry_offset - struct_sz;
3589 if (next_entry_offset > d_info->out_buf_len) {
3590 d_info->out_buf_len = 0;
3592 goto free_conv_name;
3595 kstat = d_info->wptr;
3596 if (info_level != FILE_NAMES_INFORMATION)
3597 kstat = ksmbd_vfs_init_kstat(&d_info->wptr, ksmbd_kstat);
3599 switch (info_level) {
3600 case FILE_FULL_DIRECTORY_INFORMATION:
3602 struct file_full_directory_info *ffdinfo;
3604 ffdinfo = (struct file_full_directory_info *)kstat;
3605 ffdinfo->FileNameLength = cpu_to_le32(conv_len);
3607 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3608 if (ffdinfo->EaSize)
3609 ffdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3610 if (d_info->hide_dot_file && d_info->name[0] == '.')
3611 ffdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3612 memcpy(ffdinfo->FileName, conv_name, conv_len);
3613 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3616 case FILE_BOTH_DIRECTORY_INFORMATION:
3618 struct file_both_directory_info *fbdinfo;
3620 fbdinfo = (struct file_both_directory_info *)kstat;
3621 fbdinfo->FileNameLength = cpu_to_le32(conv_len);
3623 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3624 if (fbdinfo->EaSize)
3625 fbdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3626 fbdinfo->ShortNameLength = 0;
3627 fbdinfo->Reserved = 0;
3628 if (d_info->hide_dot_file && d_info->name[0] == '.')
3629 fbdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3630 memcpy(fbdinfo->FileName, conv_name, conv_len);
3631 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3634 case FILE_DIRECTORY_INFORMATION:
3636 struct file_directory_info *fdinfo;
3638 fdinfo = (struct file_directory_info *)kstat;
3639 fdinfo->FileNameLength = cpu_to_le32(conv_len);
3640 if (d_info->hide_dot_file && d_info->name[0] == '.')
3641 fdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3642 memcpy(fdinfo->FileName, conv_name, conv_len);
3643 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3646 case FILE_NAMES_INFORMATION:
3648 struct file_names_info *fninfo;
3650 fninfo = (struct file_names_info *)kstat;
3651 fninfo->FileNameLength = cpu_to_le32(conv_len);
3652 memcpy(fninfo->FileName, conv_name, conv_len);
3653 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3656 case FILEID_FULL_DIRECTORY_INFORMATION:
3658 struct file_id_full_dir_info *dinfo;
3660 dinfo = (struct file_id_full_dir_info *)kstat;
3661 dinfo->FileNameLength = cpu_to_le32(conv_len);
3663 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3665 dinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3666 dinfo->Reserved = 0;
3667 dinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
3668 if (d_info->hide_dot_file && d_info->name[0] == '.')
3669 dinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3670 memcpy(dinfo->FileName, conv_name, conv_len);
3671 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3674 case FILEID_BOTH_DIRECTORY_INFORMATION:
3676 struct file_id_both_directory_info *fibdinfo;
3678 fibdinfo = (struct file_id_both_directory_info *)kstat;
3679 fibdinfo->FileNameLength = cpu_to_le32(conv_len);
3681 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3682 if (fibdinfo->EaSize)
3683 fibdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3684 fibdinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
3685 fibdinfo->ShortNameLength = 0;
3686 fibdinfo->Reserved = 0;
3687 fibdinfo->Reserved2 = cpu_to_le16(0);
3688 if (d_info->hide_dot_file && d_info->name[0] == '.')
3689 fibdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3690 memcpy(fibdinfo->FileName, conv_name, conv_len);
3691 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3694 case SMB_FIND_FILE_POSIX_INFO:
3696 struct smb2_posix_info *posix_info;
3699 posix_info = (struct smb2_posix_info *)kstat;
3700 posix_info->Ignored = 0;
3701 posix_info->CreationTime = cpu_to_le64(ksmbd_kstat->create_time);
3702 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->ctime);
3703 posix_info->ChangeTime = cpu_to_le64(time);
3704 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->atime);
3705 posix_info->LastAccessTime = cpu_to_le64(time);
3706 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->mtime);
3707 posix_info->LastWriteTime = cpu_to_le64(time);
3708 posix_info->EndOfFile = cpu_to_le64(ksmbd_kstat->kstat->size);
3709 posix_info->AllocationSize = cpu_to_le64(ksmbd_kstat->kstat->blocks << 9);
3710 posix_info->DeviceId = cpu_to_le32(ksmbd_kstat->kstat->rdev);
3711 posix_info->HardLinks = cpu_to_le32(ksmbd_kstat->kstat->nlink);
3712 posix_info->Mode = cpu_to_le32(ksmbd_kstat->kstat->mode & 0777);
3713 posix_info->Inode = cpu_to_le64(ksmbd_kstat->kstat->ino);
3714 posix_info->DosAttributes =
3715 S_ISDIR(ksmbd_kstat->kstat->mode) ?
3716 FILE_ATTRIBUTE_DIRECTORY_LE : FILE_ATTRIBUTE_ARCHIVE_LE;
3717 if (d_info->hide_dot_file && d_info->name[0] == '.')
3718 posix_info->DosAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3720 * SidBuffer(32) contain two sids(Domain sid(16), UNIX group sid(16)).
3721 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) +
3722 * sub_auth(4 * 1(num_subauth)) + RID(4).
3724 id_to_sid(from_kuid_munged(&init_user_ns, ksmbd_kstat->kstat->uid),
3725 SIDUNIX_USER, (struct smb_sid *)&posix_info->SidBuffer[0]);
3726 id_to_sid(from_kgid_munged(&init_user_ns, ksmbd_kstat->kstat->gid),
3727 SIDUNIX_GROUP, (struct smb_sid *)&posix_info->SidBuffer[16]);
3728 memcpy(posix_info->name, conv_name, conv_len);
3729 posix_info->name_len = cpu_to_le32(conv_len);
3730 posix_info->NextEntryOffset = cpu_to_le32(next_entry_offset);
3734 } /* switch (info_level) */
3736 d_info->last_entry_offset = d_info->data_count;
3737 d_info->data_count += next_entry_offset;
3738 d_info->out_buf_len -= next_entry_offset;
3739 d_info->wptr += next_entry_offset;
3742 "info_level : %d, buf_len :%d, next_offset : %d, data_count : %d\n",
3743 info_level, d_info->out_buf_len,
3744 next_entry_offset, d_info->data_count);
3751 struct smb2_query_dir_private {
3752 struct ksmbd_work *work;
3753 char *search_pattern;
3754 struct ksmbd_file *dir_fp;
3756 struct ksmbd_dir_info *d_info;
3760 static void lock_dir(struct ksmbd_file *dir_fp)
3762 struct dentry *dir = dir_fp->filp->f_path.dentry;
3764 inode_lock_nested(d_inode(dir), I_MUTEX_PARENT);
3767 static void unlock_dir(struct ksmbd_file *dir_fp)
3769 struct dentry *dir = dir_fp->filp->f_path.dentry;
3771 inode_unlock(d_inode(dir));
3774 static int process_query_dir_entries(struct smb2_query_dir_private *priv)
3776 struct mnt_idmap *idmap = file_mnt_idmap(priv->dir_fp->filp);
3778 struct ksmbd_kstat ksmbd_kstat;
3782 for (i = 0; i < priv->d_info->num_entry; i++) {
3783 struct dentry *dent;
3785 if (dentry_name(priv->d_info, priv->info_level))
3788 lock_dir(priv->dir_fp);
3789 dent = lookup_one(idmap, priv->d_info->name,
3790 priv->dir_fp->filp->f_path.dentry,
3791 priv->d_info->name_len);
3792 unlock_dir(priv->dir_fp);
3795 ksmbd_debug(SMB, "Cannot lookup `%s' [%ld]\n",
3800 if (unlikely(d_is_negative(dent))) {
3802 ksmbd_debug(SMB, "Negative dentry `%s'\n",
3803 priv->d_info->name);
3807 ksmbd_kstat.kstat = &kstat;
3808 if (priv->info_level != FILE_NAMES_INFORMATION)
3809 ksmbd_vfs_fill_dentry_attrs(priv->work,
3814 rc = smb2_populate_readdir_entry(priv->work->conn,
3825 static int reserve_populate_dentry(struct ksmbd_dir_info *d_info,
3830 int next_entry_offset;
3832 struct_sz = readdir_info_level_struct_sz(info_level);
3833 if (struct_sz == -EOPNOTSUPP)
3836 conv_len = (d_info->name_len + 1) * 2;
3837 next_entry_offset = ALIGN(struct_sz + conv_len,
3838 KSMBD_DIR_INFO_ALIGNMENT);
3840 if (next_entry_offset > d_info->out_buf_len) {
3841 d_info->out_buf_len = 0;
3845 switch (info_level) {
3846 case FILE_FULL_DIRECTORY_INFORMATION:
3848 struct file_full_directory_info *ffdinfo;
3850 ffdinfo = (struct file_full_directory_info *)d_info->wptr;
3851 memcpy(ffdinfo->FileName, d_info->name, d_info->name_len);
3852 ffdinfo->FileName[d_info->name_len] = 0x00;
3853 ffdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3854 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3857 case FILE_BOTH_DIRECTORY_INFORMATION:
3859 struct file_both_directory_info *fbdinfo;
3861 fbdinfo = (struct file_both_directory_info *)d_info->wptr;
3862 memcpy(fbdinfo->FileName, d_info->name, d_info->name_len);
3863 fbdinfo->FileName[d_info->name_len] = 0x00;
3864 fbdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3865 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3868 case FILE_DIRECTORY_INFORMATION:
3870 struct file_directory_info *fdinfo;
3872 fdinfo = (struct file_directory_info *)d_info->wptr;
3873 memcpy(fdinfo->FileName, d_info->name, d_info->name_len);
3874 fdinfo->FileName[d_info->name_len] = 0x00;
3875 fdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3876 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3879 case FILE_NAMES_INFORMATION:
3881 struct file_names_info *fninfo;
3883 fninfo = (struct file_names_info *)d_info->wptr;
3884 memcpy(fninfo->FileName, d_info->name, d_info->name_len);
3885 fninfo->FileName[d_info->name_len] = 0x00;
3886 fninfo->FileNameLength = cpu_to_le32(d_info->name_len);
3887 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3890 case FILEID_FULL_DIRECTORY_INFORMATION:
3892 struct file_id_full_dir_info *dinfo;
3894 dinfo = (struct file_id_full_dir_info *)d_info->wptr;
3895 memcpy(dinfo->FileName, d_info->name, d_info->name_len);
3896 dinfo->FileName[d_info->name_len] = 0x00;
3897 dinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3898 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3901 case FILEID_BOTH_DIRECTORY_INFORMATION:
3903 struct file_id_both_directory_info *fibdinfo;
3905 fibdinfo = (struct file_id_both_directory_info *)d_info->wptr;
3906 memcpy(fibdinfo->FileName, d_info->name, d_info->name_len);
3907 fibdinfo->FileName[d_info->name_len] = 0x00;
3908 fibdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3909 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3912 case SMB_FIND_FILE_POSIX_INFO:
3914 struct smb2_posix_info *posix_info;
3916 posix_info = (struct smb2_posix_info *)d_info->wptr;
3917 memcpy(posix_info->name, d_info->name, d_info->name_len);
3918 posix_info->name[d_info->name_len] = 0x00;
3919 posix_info->name_len = cpu_to_le32(d_info->name_len);
3920 posix_info->NextEntryOffset =
3921 cpu_to_le32(next_entry_offset);
3924 } /* switch (info_level) */
3926 d_info->num_entry++;
3927 d_info->out_buf_len -= next_entry_offset;
3928 d_info->wptr += next_entry_offset;
3932 static bool __query_dir(struct dir_context *ctx, const char *name, int namlen,
3933 loff_t offset, u64 ino, unsigned int d_type)
3935 struct ksmbd_readdir_data *buf;
3936 struct smb2_query_dir_private *priv;
3937 struct ksmbd_dir_info *d_info;
3940 buf = container_of(ctx, struct ksmbd_readdir_data, ctx);
3941 priv = buf->private;
3942 d_info = priv->d_info;
3944 /* dot and dotdot entries are already reserved */
3945 if (!strcmp(".", name) || !strcmp("..", name))
3947 if (ksmbd_share_veto_filename(priv->work->tcon->share_conf, name))
3949 if (!match_pattern(name, namlen, priv->search_pattern))
3952 d_info->name = name;
3953 d_info->name_len = namlen;
3954 rc = reserve_populate_dentry(d_info, priv->info_level);
3957 if (d_info->flags & SMB2_RETURN_SINGLE_ENTRY)
3958 d_info->out_buf_len = 0;
3962 static int verify_info_level(int info_level)
3964 switch (info_level) {
3965 case FILE_FULL_DIRECTORY_INFORMATION:
3966 case FILE_BOTH_DIRECTORY_INFORMATION:
3967 case FILE_DIRECTORY_INFORMATION:
3968 case FILE_NAMES_INFORMATION:
3969 case FILEID_FULL_DIRECTORY_INFORMATION:
3970 case FILEID_BOTH_DIRECTORY_INFORMATION:
3971 case SMB_FIND_FILE_POSIX_INFO:
3980 static int smb2_resp_buf_len(struct ksmbd_work *work, unsigned short hdr2_len)
3984 free_len = (int)(work->response_sz -
3985 (get_rfc1002_len(work->response_buf) + 4)) - hdr2_len;
3989 static int smb2_calc_max_out_buf_len(struct ksmbd_work *work,
3990 unsigned short hdr2_len,
3991 unsigned int out_buf_len)
3995 if (out_buf_len > work->conn->vals->max_trans_size)
3998 free_len = smb2_resp_buf_len(work, hdr2_len);
4002 return min_t(int, out_buf_len, free_len);
4005 int smb2_query_dir(struct ksmbd_work *work)
4007 struct ksmbd_conn *conn = work->conn;
4008 struct smb2_query_directory_req *req;
4009 struct smb2_query_directory_rsp *rsp;
4010 struct ksmbd_share_config *share = work->tcon->share_conf;
4011 struct ksmbd_file *dir_fp = NULL;
4012 struct ksmbd_dir_info d_info;
4014 char *srch_ptr = NULL;
4015 unsigned char srch_flag;
4017 struct smb2_query_dir_private query_dir_private = {NULL, };
4019 WORK_BUFFERS(work, req, rsp);
4021 if (ksmbd_override_fsids(work)) {
4022 rsp->hdr.Status = STATUS_NO_MEMORY;
4023 smb2_set_err_rsp(work);
4027 rc = verify_info_level(req->FileInformationClass);
4033 dir_fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
4039 if (!(dir_fp->daccess & FILE_LIST_DIRECTORY_LE) ||
4040 inode_permission(file_mnt_idmap(dir_fp->filp),
4041 file_inode(dir_fp->filp),
4042 MAY_READ | MAY_EXEC)) {
4043 pr_err("no right to enumerate directory (%pD)\n", dir_fp->filp);
4048 if (!S_ISDIR(file_inode(dir_fp->filp)->i_mode)) {
4049 pr_err("can't do query dir for a file\n");
4054 srch_flag = req->Flags;
4055 srch_ptr = smb_strndup_from_utf16(req->Buffer,
4056 le16_to_cpu(req->FileNameLength), 1,
4058 if (IS_ERR(srch_ptr)) {
4059 ksmbd_debug(SMB, "Search Pattern not found\n");
4063 ksmbd_debug(SMB, "Search pattern is %s\n", srch_ptr);
4066 if (srch_flag & SMB2_REOPEN || srch_flag & SMB2_RESTART_SCANS) {
4067 ksmbd_debug(SMB, "Restart directory scan\n");
4068 generic_file_llseek(dir_fp->filp, 0, SEEK_SET);
4071 memset(&d_info, 0, sizeof(struct ksmbd_dir_info));
4072 d_info.wptr = (char *)rsp->Buffer;
4073 d_info.rptr = (char *)rsp->Buffer;
4074 d_info.out_buf_len =
4075 smb2_calc_max_out_buf_len(work, 8,
4076 le32_to_cpu(req->OutputBufferLength));
4077 if (d_info.out_buf_len < 0) {
4081 d_info.flags = srch_flag;
4084 * reserve dot and dotdot entries in head of buffer
4087 rc = ksmbd_populate_dot_dotdot_entries(work, req->FileInformationClass,
4088 dir_fp, &d_info, srch_ptr,
4089 smb2_populate_readdir_entry);
4095 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_HIDE_DOT_FILES))
4096 d_info.hide_dot_file = true;
4098 buffer_sz = d_info.out_buf_len;
4099 d_info.rptr = d_info.wptr;
4100 query_dir_private.work = work;
4101 query_dir_private.search_pattern = srch_ptr;
4102 query_dir_private.dir_fp = dir_fp;
4103 query_dir_private.d_info = &d_info;
4104 query_dir_private.info_level = req->FileInformationClass;
4105 dir_fp->readdir_data.private = &query_dir_private;
4106 set_ctx_actor(&dir_fp->readdir_data.ctx, __query_dir);
4108 rc = iterate_dir(dir_fp->filp, &dir_fp->readdir_data.ctx);
4110 * req->OutputBufferLength is too small to contain even one entry.
4111 * In this case, it immediately returns OutputBufferLength 0 to client.
4113 if (!d_info.out_buf_len && !d_info.num_entry)
4115 if (rc > 0 || rc == -ENOSPC)
4120 d_info.wptr = d_info.rptr;
4121 d_info.out_buf_len = buffer_sz;
4122 rc = process_query_dir_entries(&query_dir_private);
4126 if (!d_info.data_count && d_info.out_buf_len >= 0) {
4127 if (srch_flag & SMB2_RETURN_SINGLE_ENTRY && !is_asterisk(srch_ptr)) {
4128 rsp->hdr.Status = STATUS_NO_SUCH_FILE;
4130 dir_fp->dot_dotdot[0] = dir_fp->dot_dotdot[1] = 0;
4131 rsp->hdr.Status = STATUS_NO_MORE_FILES;
4133 rsp->StructureSize = cpu_to_le16(9);
4134 rsp->OutputBufferOffset = cpu_to_le16(0);
4135 rsp->OutputBufferLength = cpu_to_le32(0);
4137 rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
4138 sizeof(struct smb2_query_directory_rsp));
4143 ((struct file_directory_info *)
4144 ((char *)rsp->Buffer + d_info.last_entry_offset))
4145 ->NextEntryOffset = 0;
4146 if (d_info.data_count >= d_info.last_entry_off_align)
4147 d_info.data_count -= d_info.last_entry_off_align;
4149 rsp->StructureSize = cpu_to_le16(9);
4150 rsp->OutputBufferOffset = cpu_to_le16(72);
4151 rsp->OutputBufferLength = cpu_to_le32(d_info.data_count);
4152 rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
4153 offsetof(struct smb2_query_directory_rsp, Buffer) +
4160 ksmbd_fd_put(work, dir_fp);
4161 ksmbd_revert_fsids(work);
4165 pr_err("error while processing smb2 query dir rc = %d\n", rc);
4170 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
4171 else if (rc == -EACCES)
4172 rsp->hdr.Status = STATUS_ACCESS_DENIED;
4173 else if (rc == -ENOENT)
4174 rsp->hdr.Status = STATUS_NO_SUCH_FILE;
4175 else if (rc == -EBADF)
4176 rsp->hdr.Status = STATUS_FILE_CLOSED;
4177 else if (rc == -ENOMEM)
4178 rsp->hdr.Status = STATUS_NO_MEMORY;
4179 else if (rc == -EFAULT)
4180 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
4181 else if (rc == -EIO)
4182 rsp->hdr.Status = STATUS_FILE_CORRUPT_ERROR;
4183 if (!rsp->hdr.Status)
4184 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
4186 smb2_set_err_rsp(work);
4187 ksmbd_fd_put(work, dir_fp);
4188 ksmbd_revert_fsids(work);
4193 * buffer_check_err() - helper function to check buffer errors
4194 * @reqOutputBufferLength: max buffer length expected in command response
4195 * @rsp: query info response buffer contains output buffer length
4196 * @rsp_org: base response buffer pointer in case of chained response
4198 * Return: 0 on success, otherwise error
4200 static int buffer_check_err(int reqOutputBufferLength,
4201 struct smb2_query_info_rsp *rsp,
4204 if (reqOutputBufferLength < le32_to_cpu(rsp->OutputBufferLength)) {
4205 pr_err("Invalid Buffer Size Requested\n");
4206 rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
4207 *(__be32 *)rsp_org = cpu_to_be32(sizeof(struct smb2_hdr));
4213 static void get_standard_info_pipe(struct smb2_query_info_rsp *rsp,
4216 struct smb2_file_standard_info *sinfo;
4218 sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
4220 sinfo->AllocationSize = cpu_to_le64(4096);
4221 sinfo->EndOfFile = cpu_to_le64(0);
4222 sinfo->NumberOfLinks = cpu_to_le32(1);
4223 sinfo->DeletePending = 1;
4224 sinfo->Directory = 0;
4225 rsp->OutputBufferLength =
4226 cpu_to_le32(sizeof(struct smb2_file_standard_info));
4229 static void get_internal_info_pipe(struct smb2_query_info_rsp *rsp, u64 num,
4232 struct smb2_file_internal_info *file_info;
4234 file_info = (struct smb2_file_internal_info *)rsp->Buffer;
4236 /* any unique number */
4237 file_info->IndexNumber = cpu_to_le64(num | (1ULL << 63));
4238 rsp->OutputBufferLength =
4239 cpu_to_le32(sizeof(struct smb2_file_internal_info));
4242 static int smb2_get_info_file_pipe(struct ksmbd_session *sess,
4243 struct smb2_query_info_req *req,
4244 struct smb2_query_info_rsp *rsp,
4251 * Windows can sometime send query file info request on
4252 * pipe without opening it, checking error condition here
4254 id = req->VolatileFileId;
4255 if (!ksmbd_session_rpc_method(sess, id))
4258 ksmbd_debug(SMB, "FileInfoClass %u, FileId 0x%llx\n",
4259 req->FileInfoClass, req->VolatileFileId);
4261 switch (req->FileInfoClass) {
4262 case FILE_STANDARD_INFORMATION:
4263 get_standard_info_pipe(rsp, rsp_org);
4264 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4267 case FILE_INTERNAL_INFORMATION:
4268 get_internal_info_pipe(rsp, id, rsp_org);
4269 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4273 ksmbd_debug(SMB, "smb2_info_file_pipe for %u not supported\n",
4274 req->FileInfoClass);
4281 * smb2_get_ea() - handler for smb2 get extended attribute command
4282 * @work: smb work containing query info command buffer
4283 * @fp: ksmbd_file pointer
4284 * @req: get extended attribute request
4285 * @rsp: response buffer pointer
4286 * @rsp_org: base response buffer pointer in case of chained response
4288 * Return: 0 on success, otherwise error
4290 static int smb2_get_ea(struct ksmbd_work *work, struct ksmbd_file *fp,
4291 struct smb2_query_info_req *req,
4292 struct smb2_query_info_rsp *rsp, void *rsp_org)
4294 struct smb2_ea_info *eainfo, *prev_eainfo;
4295 char *name, *ptr, *xattr_list = NULL, *buf;
4296 int rc, name_len, value_len, xattr_list_len, idx;
4297 ssize_t buf_free_len, alignment_bytes, next_offset, rsp_data_cnt = 0;
4298 struct smb2_ea_info_req *ea_req = NULL;
4299 const struct path *path;
4300 struct mnt_idmap *idmap = file_mnt_idmap(fp->filp);
4302 if (!(fp->daccess & FILE_READ_EA_LE)) {
4303 pr_err("Not permitted to read ext attr : 0x%x\n",
4308 path = &fp->filp->f_path;
4309 /* single EA entry is requested with given user.* name */
4310 if (req->InputBufferLength) {
4311 if (le32_to_cpu(req->InputBufferLength) <
4312 sizeof(struct smb2_ea_info_req))
4315 ea_req = (struct smb2_ea_info_req *)req->Buffer;
4317 /* need to send all EAs, if no specific EA is requested*/
4318 if (le32_to_cpu(req->Flags) & SL_RETURN_SINGLE_ENTRY)
4320 "All EAs are requested but need to send single EA entry in rsp flags 0x%x\n",
4321 le32_to_cpu(req->Flags));
4325 smb2_calc_max_out_buf_len(work, 8,
4326 le32_to_cpu(req->OutputBufferLength));
4327 if (buf_free_len < 0)
4330 rc = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
4332 rsp->hdr.Status = STATUS_INVALID_HANDLE;
4334 } else if (!rc) { /* there is no EA in the file */
4335 ksmbd_debug(SMB, "no ea data in the file\n");
4338 xattr_list_len = rc;
4340 ptr = (char *)rsp->Buffer;
4341 eainfo = (struct smb2_ea_info *)ptr;
4342 prev_eainfo = eainfo;
4345 while (idx < xattr_list_len) {
4346 name = xattr_list + idx;
4347 name_len = strlen(name);
4349 ksmbd_debug(SMB, "%s, len %d\n", name, name_len);
4350 idx += name_len + 1;
4353 * CIFS does not support EA other than user.* namespace,
4354 * still keep the framework generic, to list other attrs
4357 if (strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4360 if (!strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
4364 if (req->InputBufferLength &&
4365 strncmp(&name[XATTR_USER_PREFIX_LEN], ea_req->name,
4366 ea_req->EaNameLength))
4369 if (!strncmp(&name[XATTR_USER_PREFIX_LEN],
4370 DOS_ATTRIBUTE_PREFIX, DOS_ATTRIBUTE_PREFIX_LEN))
4373 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4374 name_len -= XATTR_USER_PREFIX_LEN;
4376 ptr = eainfo->name + name_len + 1;
4377 buf_free_len -= (offsetof(struct smb2_ea_info, name) +
4379 /* bailout if xattr can't fit in buf_free_len */
4380 value_len = ksmbd_vfs_getxattr(idmap, path->dentry,
4382 if (value_len <= 0) {
4384 rsp->hdr.Status = STATUS_INVALID_HANDLE;
4388 buf_free_len -= value_len;
4389 if (buf_free_len < 0) {
4394 memcpy(ptr, buf, value_len);
4399 eainfo->EaNameLength = name_len;
4401 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4402 memcpy(eainfo->name, &name[XATTR_USER_PREFIX_LEN],
4405 memcpy(eainfo->name, name, name_len);
4407 eainfo->name[name_len] = '\0';
4408 eainfo->EaValueLength = cpu_to_le16(value_len);
4409 next_offset = offsetof(struct smb2_ea_info, name) +
4410 name_len + 1 + value_len;
4412 /* align next xattr entry at 4 byte bundary */
4413 alignment_bytes = ((next_offset + 3) & ~3) - next_offset;
4414 if (alignment_bytes) {
4415 memset(ptr, '\0', alignment_bytes);
4416 ptr += alignment_bytes;
4417 next_offset += alignment_bytes;
4418 buf_free_len -= alignment_bytes;
4420 eainfo->NextEntryOffset = cpu_to_le32(next_offset);
4421 prev_eainfo = eainfo;
4422 eainfo = (struct smb2_ea_info *)ptr;
4423 rsp_data_cnt += next_offset;
4425 if (req->InputBufferLength) {
4426 ksmbd_debug(SMB, "single entry requested\n");
4431 /* no more ea entries */
4432 prev_eainfo->NextEntryOffset = 0;
4435 if (rsp_data_cnt == 0)
4436 rsp->hdr.Status = STATUS_NO_EAS_ON_FILE;
4437 rsp->OutputBufferLength = cpu_to_le32(rsp_data_cnt);
4443 static void get_file_access_info(struct smb2_query_info_rsp *rsp,
4444 struct ksmbd_file *fp, void *rsp_org)
4446 struct smb2_file_access_info *file_info;
4448 file_info = (struct smb2_file_access_info *)rsp->Buffer;
4449 file_info->AccessFlags = fp->daccess;
4450 rsp->OutputBufferLength =
4451 cpu_to_le32(sizeof(struct smb2_file_access_info));
4454 static int get_file_basic_info(struct smb2_query_info_rsp *rsp,
4455 struct ksmbd_file *fp, void *rsp_org)
4457 struct smb2_file_basic_info *basic_info;
4461 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4462 pr_err("no right to read the attributes : 0x%x\n",
4467 basic_info = (struct smb2_file_basic_info *)rsp->Buffer;
4468 generic_fillattr(file_mnt_idmap(fp->filp), STATX_BASIC_STATS,
4469 file_inode(fp->filp), &stat);
4470 basic_info->CreationTime = cpu_to_le64(fp->create_time);
4471 time = ksmbd_UnixTimeToNT(stat.atime);
4472 basic_info->LastAccessTime = cpu_to_le64(time);
4473 time = ksmbd_UnixTimeToNT(stat.mtime);
4474 basic_info->LastWriteTime = cpu_to_le64(time);
4475 time = ksmbd_UnixTimeToNT(stat.ctime);
4476 basic_info->ChangeTime = cpu_to_le64(time);
4477 basic_info->Attributes = fp->f_ci->m_fattr;
4478 basic_info->Pad1 = 0;
4479 rsp->OutputBufferLength =
4480 cpu_to_le32(sizeof(struct smb2_file_basic_info));
4484 static void get_file_standard_info(struct smb2_query_info_rsp *rsp,
4485 struct ksmbd_file *fp, void *rsp_org)
4487 struct smb2_file_standard_info *sinfo;
4488 unsigned int delete_pending;
4489 struct inode *inode;
4492 inode = file_inode(fp->filp);
4493 generic_fillattr(file_mnt_idmap(fp->filp), STATX_BASIC_STATS, inode, &stat);
4495 sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
4496 delete_pending = ksmbd_inode_pending_delete(fp);
4498 sinfo->AllocationSize = cpu_to_le64(inode->i_blocks << 9);
4499 sinfo->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4500 sinfo->NumberOfLinks = cpu_to_le32(get_nlink(&stat) - delete_pending);
4501 sinfo->DeletePending = delete_pending;
4502 sinfo->Directory = S_ISDIR(stat.mode) ? 1 : 0;
4503 rsp->OutputBufferLength =
4504 cpu_to_le32(sizeof(struct smb2_file_standard_info));
4507 static void get_file_alignment_info(struct smb2_query_info_rsp *rsp,
4510 struct smb2_file_alignment_info *file_info;
4512 file_info = (struct smb2_file_alignment_info *)rsp->Buffer;
4513 file_info->AlignmentRequirement = 0;
4514 rsp->OutputBufferLength =
4515 cpu_to_le32(sizeof(struct smb2_file_alignment_info));
4518 static int get_file_all_info(struct ksmbd_work *work,
4519 struct smb2_query_info_rsp *rsp,
4520 struct ksmbd_file *fp,
4523 struct ksmbd_conn *conn = work->conn;
4524 struct smb2_file_all_info *file_info;
4525 unsigned int delete_pending;
4526 struct inode *inode;
4532 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4533 ksmbd_debug(SMB, "no right to read the attributes : 0x%x\n",
4538 filename = convert_to_nt_pathname(work->tcon->share_conf, &fp->filp->f_path);
4539 if (IS_ERR(filename))
4540 return PTR_ERR(filename);
4542 inode = file_inode(fp->filp);
4543 generic_fillattr(file_mnt_idmap(fp->filp), STATX_BASIC_STATS, inode, &stat);
4545 ksmbd_debug(SMB, "filename = %s\n", filename);
4546 delete_pending = ksmbd_inode_pending_delete(fp);
4547 file_info = (struct smb2_file_all_info *)rsp->Buffer;
4549 file_info->CreationTime = cpu_to_le64(fp->create_time);
4550 time = ksmbd_UnixTimeToNT(stat.atime);
4551 file_info->LastAccessTime = cpu_to_le64(time);
4552 time = ksmbd_UnixTimeToNT(stat.mtime);
4553 file_info->LastWriteTime = cpu_to_le64(time);
4554 time = ksmbd_UnixTimeToNT(stat.ctime);
4555 file_info->ChangeTime = cpu_to_le64(time);
4556 file_info->Attributes = fp->f_ci->m_fattr;
4557 file_info->Pad1 = 0;
4558 file_info->AllocationSize =
4559 cpu_to_le64(inode->i_blocks << 9);
4560 file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4561 file_info->NumberOfLinks =
4562 cpu_to_le32(get_nlink(&stat) - delete_pending);
4563 file_info->DeletePending = delete_pending;
4564 file_info->Directory = S_ISDIR(stat.mode) ? 1 : 0;
4565 file_info->Pad2 = 0;
4566 file_info->IndexNumber = cpu_to_le64(stat.ino);
4567 file_info->EASize = 0;
4568 file_info->AccessFlags = fp->daccess;
4569 file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
4570 file_info->Mode = fp->coption;
4571 file_info->AlignmentRequirement = 0;
4572 conv_len = smbConvertToUTF16((__le16 *)file_info->FileName, filename,
4573 PATH_MAX, conn->local_nls, 0);
4575 file_info->FileNameLength = cpu_to_le32(conv_len);
4576 rsp->OutputBufferLength =
4577 cpu_to_le32(sizeof(struct smb2_file_all_info) + conv_len - 1);
4582 static void get_file_alternate_info(struct ksmbd_work *work,
4583 struct smb2_query_info_rsp *rsp,
4584 struct ksmbd_file *fp,
4587 struct ksmbd_conn *conn = work->conn;
4588 struct smb2_file_alt_name_info *file_info;
4589 struct dentry *dentry = fp->filp->f_path.dentry;
4592 spin_lock(&dentry->d_lock);
4593 file_info = (struct smb2_file_alt_name_info *)rsp->Buffer;
4594 conv_len = ksmbd_extract_shortname(conn,
4595 dentry->d_name.name,
4596 file_info->FileName);
4597 spin_unlock(&dentry->d_lock);
4598 file_info->FileNameLength = cpu_to_le32(conv_len);
4599 rsp->OutputBufferLength =
4600 cpu_to_le32(sizeof(struct smb2_file_alt_name_info) + conv_len);
4603 static void get_file_stream_info(struct ksmbd_work *work,
4604 struct smb2_query_info_rsp *rsp,
4605 struct ksmbd_file *fp,
4608 struct ksmbd_conn *conn = work->conn;
4609 struct smb2_file_stream_info *file_info;
4610 char *stream_name, *xattr_list = NULL, *stream_buf;
4612 const struct path *path = &fp->filp->f_path;
4613 ssize_t xattr_list_len;
4614 int nbytes = 0, streamlen, stream_name_len, next, idx = 0;
4616 struct smb2_query_info_req *req = ksmbd_req_buf_next(work);
4618 generic_fillattr(file_mnt_idmap(fp->filp), STATX_BASIC_STATS,
4619 file_inode(fp->filp), &stat);
4620 file_info = (struct smb2_file_stream_info *)rsp->Buffer;
4623 smb2_calc_max_out_buf_len(work, 8,
4624 le32_to_cpu(req->OutputBufferLength));
4625 if (buf_free_len < 0)
4628 xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
4629 if (xattr_list_len < 0) {
4631 } else if (!xattr_list_len) {
4632 ksmbd_debug(SMB, "empty xattr in the file\n");
4636 while (idx < xattr_list_len) {
4637 stream_name = xattr_list + idx;
4638 streamlen = strlen(stream_name);
4639 idx += streamlen + 1;
4641 ksmbd_debug(SMB, "%s, len %d\n", stream_name, streamlen);
4643 if (strncmp(&stream_name[XATTR_USER_PREFIX_LEN],
4644 STREAM_PREFIX, STREAM_PREFIX_LEN))
4647 stream_name_len = streamlen - (XATTR_USER_PREFIX_LEN +
4649 streamlen = stream_name_len;
4653 stream_buf = kmalloc(streamlen + 1, GFP_KERNEL);
4657 streamlen = snprintf(stream_buf, streamlen + 1,
4658 ":%s", &stream_name[XATTR_NAME_STREAM_LEN]);
4660 next = sizeof(struct smb2_file_stream_info) + streamlen * 2;
4661 if (next > buf_free_len) {
4666 file_info = (struct smb2_file_stream_info *)&rsp->Buffer[nbytes];
4667 streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
4668 stream_buf, streamlen,
4669 conn->local_nls, 0);
4672 file_info->StreamNameLength = cpu_to_le32(streamlen);
4673 file_info->StreamSize = cpu_to_le64(stream_name_len);
4674 file_info->StreamAllocationSize = cpu_to_le64(stream_name_len);
4677 buf_free_len -= next;
4678 file_info->NextEntryOffset = cpu_to_le32(next);
4682 if (!S_ISDIR(stat.mode) &&
4683 buf_free_len >= sizeof(struct smb2_file_stream_info) + 7 * 2) {
4684 file_info = (struct smb2_file_stream_info *)
4685 &rsp->Buffer[nbytes];
4686 streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
4687 "::$DATA", 7, conn->local_nls, 0);
4689 file_info->StreamNameLength = cpu_to_le32(streamlen);
4690 file_info->StreamSize = cpu_to_le64(stat.size);
4691 file_info->StreamAllocationSize = cpu_to_le64(stat.blocks << 9);
4692 nbytes += sizeof(struct smb2_file_stream_info) + streamlen;
4695 /* last entry offset should be 0 */
4696 file_info->NextEntryOffset = 0;
4699 rsp->OutputBufferLength = cpu_to_le32(nbytes);
4702 static void get_file_internal_info(struct smb2_query_info_rsp *rsp,
4703 struct ksmbd_file *fp, void *rsp_org)
4705 struct smb2_file_internal_info *file_info;
4708 generic_fillattr(file_mnt_idmap(fp->filp), STATX_BASIC_STATS,
4709 file_inode(fp->filp), &stat);
4710 file_info = (struct smb2_file_internal_info *)rsp->Buffer;
4711 file_info->IndexNumber = cpu_to_le64(stat.ino);
4712 rsp->OutputBufferLength =
4713 cpu_to_le32(sizeof(struct smb2_file_internal_info));
4716 static int get_file_network_open_info(struct smb2_query_info_rsp *rsp,
4717 struct ksmbd_file *fp, void *rsp_org)
4719 struct smb2_file_ntwrk_info *file_info;
4720 struct inode *inode;
4724 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4725 pr_err("no right to read the attributes : 0x%x\n",
4730 file_info = (struct smb2_file_ntwrk_info *)rsp->Buffer;
4732 inode = file_inode(fp->filp);
4733 generic_fillattr(file_mnt_idmap(fp->filp), STATX_BASIC_STATS, inode, &stat);
4735 file_info->CreationTime = cpu_to_le64(fp->create_time);
4736 time = ksmbd_UnixTimeToNT(stat.atime);
4737 file_info->LastAccessTime = cpu_to_le64(time);
4738 time = ksmbd_UnixTimeToNT(stat.mtime);
4739 file_info->LastWriteTime = cpu_to_le64(time);
4740 time = ksmbd_UnixTimeToNT(stat.ctime);
4741 file_info->ChangeTime = cpu_to_le64(time);
4742 file_info->Attributes = fp->f_ci->m_fattr;
4743 file_info->AllocationSize =
4744 cpu_to_le64(inode->i_blocks << 9);
4745 file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4746 file_info->Reserved = cpu_to_le32(0);
4747 rsp->OutputBufferLength =
4748 cpu_to_le32(sizeof(struct smb2_file_ntwrk_info));
4752 static void get_file_ea_info(struct smb2_query_info_rsp *rsp, void *rsp_org)
4754 struct smb2_file_ea_info *file_info;
4756 file_info = (struct smb2_file_ea_info *)rsp->Buffer;
4757 file_info->EASize = 0;
4758 rsp->OutputBufferLength =
4759 cpu_to_le32(sizeof(struct smb2_file_ea_info));
4762 static void get_file_position_info(struct smb2_query_info_rsp *rsp,
4763 struct ksmbd_file *fp, void *rsp_org)
4765 struct smb2_file_pos_info *file_info;
4767 file_info = (struct smb2_file_pos_info *)rsp->Buffer;
4768 file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
4769 rsp->OutputBufferLength =
4770 cpu_to_le32(sizeof(struct smb2_file_pos_info));
4773 static void get_file_mode_info(struct smb2_query_info_rsp *rsp,
4774 struct ksmbd_file *fp, void *rsp_org)
4776 struct smb2_file_mode_info *file_info;
4778 file_info = (struct smb2_file_mode_info *)rsp->Buffer;
4779 file_info->Mode = fp->coption & FILE_MODE_INFO_MASK;
4780 rsp->OutputBufferLength =
4781 cpu_to_le32(sizeof(struct smb2_file_mode_info));
4784 static void get_file_compression_info(struct smb2_query_info_rsp *rsp,
4785 struct ksmbd_file *fp, void *rsp_org)
4787 struct smb2_file_comp_info *file_info;
4790 generic_fillattr(file_mnt_idmap(fp->filp), STATX_BASIC_STATS,
4791 file_inode(fp->filp), &stat);
4793 file_info = (struct smb2_file_comp_info *)rsp->Buffer;
4794 file_info->CompressedFileSize = cpu_to_le64(stat.blocks << 9);
4795 file_info->CompressionFormat = COMPRESSION_FORMAT_NONE;
4796 file_info->CompressionUnitShift = 0;
4797 file_info->ChunkShift = 0;
4798 file_info->ClusterShift = 0;
4799 memset(&file_info->Reserved[0], 0, 3);
4801 rsp->OutputBufferLength =
4802 cpu_to_le32(sizeof(struct smb2_file_comp_info));
4805 static int get_file_attribute_tag_info(struct smb2_query_info_rsp *rsp,
4806 struct ksmbd_file *fp, void *rsp_org)
4808 struct smb2_file_attr_tag_info *file_info;
4810 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4811 pr_err("no right to read the attributes : 0x%x\n",
4816 file_info = (struct smb2_file_attr_tag_info *)rsp->Buffer;
4817 file_info->FileAttributes = fp->f_ci->m_fattr;
4818 file_info->ReparseTag = 0;
4819 rsp->OutputBufferLength =
4820 cpu_to_le32(sizeof(struct smb2_file_attr_tag_info));
4824 static void find_file_posix_info(struct smb2_query_info_rsp *rsp,
4825 struct ksmbd_file *fp, void *rsp_org)
4827 struct smb311_posix_qinfo *file_info;
4828 struct inode *inode = file_inode(fp->filp);
4829 struct mnt_idmap *idmap = file_mnt_idmap(fp->filp);
4830 vfsuid_t vfsuid = i_uid_into_vfsuid(idmap, inode);
4831 vfsgid_t vfsgid = i_gid_into_vfsgid(idmap, inode);
4833 int out_buf_len = sizeof(struct smb311_posix_qinfo) + 32;
4835 file_info = (struct smb311_posix_qinfo *)rsp->Buffer;
4836 file_info->CreationTime = cpu_to_le64(fp->create_time);
4837 time = ksmbd_UnixTimeToNT(inode->i_atime);
4838 file_info->LastAccessTime = cpu_to_le64(time);
4839 time = ksmbd_UnixTimeToNT(inode->i_mtime);
4840 file_info->LastWriteTime = cpu_to_le64(time);
4841 time = ksmbd_UnixTimeToNT(inode_get_ctime(inode));
4842 file_info->ChangeTime = cpu_to_le64(time);
4843 file_info->DosAttributes = fp->f_ci->m_fattr;
4844 file_info->Inode = cpu_to_le64(inode->i_ino);
4845 file_info->EndOfFile = cpu_to_le64(inode->i_size);
4846 file_info->AllocationSize = cpu_to_le64(inode->i_blocks << 9);
4847 file_info->HardLinks = cpu_to_le32(inode->i_nlink);
4848 file_info->Mode = cpu_to_le32(inode->i_mode & 0777);
4849 file_info->DeviceId = cpu_to_le32(inode->i_rdev);
4852 * Sids(32) contain two sids(Domain sid(16), UNIX group sid(16)).
4853 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) +
4854 * sub_auth(4 * 1(num_subauth)) + RID(4).
4856 id_to_sid(from_kuid_munged(&init_user_ns, vfsuid_into_kuid(vfsuid)),
4857 SIDUNIX_USER, (struct smb_sid *)&file_info->Sids[0]);
4858 id_to_sid(from_kgid_munged(&init_user_ns, vfsgid_into_kgid(vfsgid)),
4859 SIDUNIX_GROUP, (struct smb_sid *)&file_info->Sids[16]);
4861 rsp->OutputBufferLength = cpu_to_le32(out_buf_len);
4864 static int smb2_get_info_file(struct ksmbd_work *work,
4865 struct smb2_query_info_req *req,
4866 struct smb2_query_info_rsp *rsp)
4868 struct ksmbd_file *fp;
4869 int fileinfoclass = 0;
4871 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
4873 if (test_share_config_flag(work->tcon->share_conf,
4874 KSMBD_SHARE_FLAG_PIPE)) {
4875 /* smb2 info file called for pipe */
4876 return smb2_get_info_file_pipe(work->sess, req, rsp,
4877 work->response_buf);
4880 if (work->next_smb2_rcv_hdr_off) {
4881 if (!has_file_id(req->VolatileFileId)) {
4882 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
4883 work->compound_fid);
4884 id = work->compound_fid;
4885 pid = work->compound_pfid;
4889 if (!has_file_id(id)) {
4890 id = req->VolatileFileId;
4891 pid = req->PersistentFileId;
4894 fp = ksmbd_lookup_fd_slow(work, id, pid);
4898 fileinfoclass = req->FileInfoClass;
4900 switch (fileinfoclass) {
4901 case FILE_ACCESS_INFORMATION:
4902 get_file_access_info(rsp, fp, work->response_buf);
4905 case FILE_BASIC_INFORMATION:
4906 rc = get_file_basic_info(rsp, fp, work->response_buf);
4909 case FILE_STANDARD_INFORMATION:
4910 get_file_standard_info(rsp, fp, work->response_buf);
4913 case FILE_ALIGNMENT_INFORMATION:
4914 get_file_alignment_info(rsp, work->response_buf);
4917 case FILE_ALL_INFORMATION:
4918 rc = get_file_all_info(work, rsp, fp, work->response_buf);
4921 case FILE_ALTERNATE_NAME_INFORMATION:
4922 get_file_alternate_info(work, rsp, fp, work->response_buf);
4925 case FILE_STREAM_INFORMATION:
4926 get_file_stream_info(work, rsp, fp, work->response_buf);
4929 case FILE_INTERNAL_INFORMATION:
4930 get_file_internal_info(rsp, fp, work->response_buf);
4933 case FILE_NETWORK_OPEN_INFORMATION:
4934 rc = get_file_network_open_info(rsp, fp, work->response_buf);
4937 case FILE_EA_INFORMATION:
4938 get_file_ea_info(rsp, work->response_buf);
4941 case FILE_FULL_EA_INFORMATION:
4942 rc = smb2_get_ea(work, fp, req, rsp, work->response_buf);
4945 case FILE_POSITION_INFORMATION:
4946 get_file_position_info(rsp, fp, work->response_buf);
4949 case FILE_MODE_INFORMATION:
4950 get_file_mode_info(rsp, fp, work->response_buf);
4953 case FILE_COMPRESSION_INFORMATION:
4954 get_file_compression_info(rsp, fp, work->response_buf);
4957 case FILE_ATTRIBUTE_TAG_INFORMATION:
4958 rc = get_file_attribute_tag_info(rsp, fp, work->response_buf);
4960 case SMB_FIND_FILE_POSIX_INFO:
4961 if (!work->tcon->posix_extensions) {
4962 pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
4965 find_file_posix_info(rsp, fp, work->response_buf);
4969 ksmbd_debug(SMB, "fileinfoclass %d not supported yet\n",
4974 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4975 rsp, work->response_buf);
4976 ksmbd_fd_put(work, fp);
4980 static int smb2_get_info_filesystem(struct ksmbd_work *work,
4981 struct smb2_query_info_req *req,
4982 struct smb2_query_info_rsp *rsp)
4984 struct ksmbd_session *sess = work->sess;
4985 struct ksmbd_conn *conn = work->conn;
4986 struct ksmbd_share_config *share = work->tcon->share_conf;
4987 int fsinfoclass = 0;
4988 struct kstatfs stfs;
4995 rc = kern_path(share->path, LOOKUP_NO_SYMLINKS, &path);
4997 pr_err("cannot create vfs path\n");
5001 rc = vfs_statfs(&path, &stfs);
5003 pr_err("cannot do stat of path %s\n", share->path);
5008 fsinfoclass = req->FileInfoClass;
5010 switch (fsinfoclass) {
5011 case FS_DEVICE_INFORMATION:
5013 struct filesystem_device_info *info;
5015 info = (struct filesystem_device_info *)rsp->Buffer;
5017 info->DeviceType = cpu_to_le32(stfs.f_type);
5018 info->DeviceCharacteristics = cpu_to_le32(0x00000020);
5019 rsp->OutputBufferLength = cpu_to_le32(8);
5022 case FS_ATTRIBUTE_INFORMATION:
5024 struct filesystem_attribute_info *info;
5027 info = (struct filesystem_attribute_info *)rsp->Buffer;
5028 info->Attributes = cpu_to_le32(FILE_SUPPORTS_OBJECT_IDS |
5029 FILE_PERSISTENT_ACLS |
5030 FILE_UNICODE_ON_DISK |
5031 FILE_CASE_PRESERVED_NAMES |
5032 FILE_CASE_SENSITIVE_SEARCH |
5033 FILE_SUPPORTS_BLOCK_REFCOUNTING);
5035 info->Attributes |= cpu_to_le32(server_conf.share_fake_fscaps);
5037 if (test_share_config_flag(work->tcon->share_conf,
5038 KSMBD_SHARE_FLAG_STREAMS))
5039 info->Attributes |= cpu_to_le32(FILE_NAMED_STREAMS);
5041 info->MaxPathNameComponentLength = cpu_to_le32(stfs.f_namelen);
5042 len = smbConvertToUTF16((__le16 *)info->FileSystemName,
5043 "NTFS", PATH_MAX, conn->local_nls, 0);
5045 info->FileSystemNameLen = cpu_to_le32(len);
5046 sz = sizeof(struct filesystem_attribute_info) - 2 + len;
5047 rsp->OutputBufferLength = cpu_to_le32(sz);
5050 case FS_VOLUME_INFORMATION:
5052 struct filesystem_vol_info *info;
5054 unsigned int serial_crc = 0;
5056 info = (struct filesystem_vol_info *)(rsp->Buffer);
5057 info->VolumeCreationTime = 0;
5058 serial_crc = crc32_le(serial_crc, share->name,
5059 strlen(share->name));
5060 serial_crc = crc32_le(serial_crc, share->path,
5061 strlen(share->path));
5062 serial_crc = crc32_le(serial_crc, ksmbd_netbios_name(),
5063 strlen(ksmbd_netbios_name()));
5064 /* Taking dummy value of serial number*/
5065 info->SerialNumber = cpu_to_le32(serial_crc);
5066 len = smbConvertToUTF16((__le16 *)info->VolumeLabel,
5067 share->name, PATH_MAX,
5068 conn->local_nls, 0);
5070 info->VolumeLabelSize = cpu_to_le32(len);
5072 sz = sizeof(struct filesystem_vol_info) - 2 + len;
5073 rsp->OutputBufferLength = cpu_to_le32(sz);
5076 case FS_SIZE_INFORMATION:
5078 struct filesystem_info *info;
5080 info = (struct filesystem_info *)(rsp->Buffer);
5081 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
5082 info->FreeAllocationUnits = cpu_to_le64(stfs.f_bfree);
5083 info->SectorsPerAllocationUnit = cpu_to_le32(1);
5084 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
5085 rsp->OutputBufferLength = cpu_to_le32(24);
5088 case FS_FULL_SIZE_INFORMATION:
5090 struct smb2_fs_full_size_info *info;
5092 info = (struct smb2_fs_full_size_info *)(rsp->Buffer);
5093 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
5094 info->CallerAvailableAllocationUnits =
5095 cpu_to_le64(stfs.f_bavail);
5096 info->ActualAvailableAllocationUnits =
5097 cpu_to_le64(stfs.f_bfree);
5098 info->SectorsPerAllocationUnit = cpu_to_le32(1);
5099 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
5100 rsp->OutputBufferLength = cpu_to_le32(32);
5103 case FS_OBJECT_ID_INFORMATION:
5105 struct object_id_info *info;
5107 info = (struct object_id_info *)(rsp->Buffer);
5109 if (!user_guest(sess->user))
5110 memcpy(info->objid, user_passkey(sess->user), 16);
5112 memset(info->objid, 0, 16);
5114 info->extended_info.magic = cpu_to_le32(EXTENDED_INFO_MAGIC);
5115 info->extended_info.version = cpu_to_le32(1);
5116 info->extended_info.release = cpu_to_le32(1);
5117 info->extended_info.rel_date = 0;
5118 memcpy(info->extended_info.version_string, "1.1.0", strlen("1.1.0"));
5119 rsp->OutputBufferLength = cpu_to_le32(64);
5122 case FS_SECTOR_SIZE_INFORMATION:
5124 struct smb3_fs_ss_info *info;
5125 unsigned int sector_size =
5126 min_t(unsigned int, path.mnt->mnt_sb->s_blocksize, 4096);
5128 info = (struct smb3_fs_ss_info *)(rsp->Buffer);
5130 info->LogicalBytesPerSector = cpu_to_le32(sector_size);
5131 info->PhysicalBytesPerSectorForAtomicity =
5132 cpu_to_le32(sector_size);
5133 info->PhysicalBytesPerSectorForPerf = cpu_to_le32(sector_size);
5134 info->FSEffPhysicalBytesPerSectorForAtomicity =
5135 cpu_to_le32(sector_size);
5136 info->Flags = cpu_to_le32(SSINFO_FLAGS_ALIGNED_DEVICE |
5137 SSINFO_FLAGS_PARTITION_ALIGNED_ON_DEVICE);
5138 info->ByteOffsetForSectorAlignment = 0;
5139 info->ByteOffsetForPartitionAlignment = 0;
5140 rsp->OutputBufferLength = cpu_to_le32(28);
5143 case FS_CONTROL_INFORMATION:
5146 * TODO : The current implementation is based on
5147 * test result with win7(NTFS) server. It's need to
5148 * modify this to get valid Quota values
5151 struct smb2_fs_control_info *info;
5153 info = (struct smb2_fs_control_info *)(rsp->Buffer);
5154 info->FreeSpaceStartFiltering = 0;
5155 info->FreeSpaceThreshold = 0;
5156 info->FreeSpaceStopFiltering = 0;
5157 info->DefaultQuotaThreshold = cpu_to_le64(SMB2_NO_FID);
5158 info->DefaultQuotaLimit = cpu_to_le64(SMB2_NO_FID);
5160 rsp->OutputBufferLength = cpu_to_le32(48);
5163 case FS_POSIX_INFORMATION:
5165 struct filesystem_posix_info *info;
5167 if (!work->tcon->posix_extensions) {
5168 pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
5171 info = (struct filesystem_posix_info *)(rsp->Buffer);
5172 info->OptimalTransferSize = cpu_to_le32(stfs.f_bsize);
5173 info->BlockSize = cpu_to_le32(stfs.f_bsize);
5174 info->TotalBlocks = cpu_to_le64(stfs.f_blocks);
5175 info->BlocksAvail = cpu_to_le64(stfs.f_bfree);
5176 info->UserBlocksAvail = cpu_to_le64(stfs.f_bavail);
5177 info->TotalFileNodes = cpu_to_le64(stfs.f_files);
5178 info->FreeFileNodes = cpu_to_le64(stfs.f_ffree);
5179 rsp->OutputBufferLength = cpu_to_le32(56);
5187 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
5188 rsp, work->response_buf);
5193 static int smb2_get_info_sec(struct ksmbd_work *work,
5194 struct smb2_query_info_req *req,
5195 struct smb2_query_info_rsp *rsp)
5197 struct ksmbd_file *fp;
5198 struct mnt_idmap *idmap;
5199 struct smb_ntsd *pntsd = (struct smb_ntsd *)rsp->Buffer, *ppntsd = NULL;
5200 struct smb_fattr fattr = {{0}};
5201 struct inode *inode;
5202 __u32 secdesclen = 0;
5203 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
5204 int addition_info = le32_to_cpu(req->AdditionalInformation);
5205 int rc = 0, ppntsd_size = 0;
5207 if (addition_info & ~(OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO |
5208 PROTECTED_DACL_SECINFO |
5209 UNPROTECTED_DACL_SECINFO)) {
5210 ksmbd_debug(SMB, "Unsupported addition info: 0x%x)\n",
5213 pntsd->revision = cpu_to_le16(1);
5214 pntsd->type = cpu_to_le16(SELF_RELATIVE | DACL_PROTECTED);
5215 pntsd->osidoffset = 0;
5216 pntsd->gsidoffset = 0;
5217 pntsd->sacloffset = 0;
5218 pntsd->dacloffset = 0;
5220 secdesclen = sizeof(struct smb_ntsd);
5221 rsp->OutputBufferLength = cpu_to_le32(secdesclen);
5226 if (work->next_smb2_rcv_hdr_off) {
5227 if (!has_file_id(req->VolatileFileId)) {
5228 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
5229 work->compound_fid);
5230 id = work->compound_fid;
5231 pid = work->compound_pfid;
5235 if (!has_file_id(id)) {
5236 id = req->VolatileFileId;
5237 pid = req->PersistentFileId;
5240 fp = ksmbd_lookup_fd_slow(work, id, pid);
5244 idmap = file_mnt_idmap(fp->filp);
5245 inode = file_inode(fp->filp);
5246 ksmbd_acls_fattr(&fattr, idmap, inode);
5248 if (test_share_config_flag(work->tcon->share_conf,
5249 KSMBD_SHARE_FLAG_ACL_XATTR))
5250 ppntsd_size = ksmbd_vfs_get_sd_xattr(work->conn, idmap,
5251 fp->filp->f_path.dentry,
5254 /* Check if sd buffer size exceeds response buffer size */
5255 if (smb2_resp_buf_len(work, 8) > ppntsd_size)
5256 rc = build_sec_desc(idmap, pntsd, ppntsd, ppntsd_size,
5257 addition_info, &secdesclen, &fattr);
5258 posix_acl_release(fattr.cf_acls);
5259 posix_acl_release(fattr.cf_dacls);
5261 ksmbd_fd_put(work, fp);
5265 rsp->OutputBufferLength = cpu_to_le32(secdesclen);
5270 * smb2_query_info() - handler for smb2 query info command
5271 * @work: smb work containing query info request buffer
5273 * Return: 0 on success, otherwise error
5275 int smb2_query_info(struct ksmbd_work *work)
5277 struct smb2_query_info_req *req;
5278 struct smb2_query_info_rsp *rsp;
5281 WORK_BUFFERS(work, req, rsp);
5283 ksmbd_debug(SMB, "GOT query info request\n");
5285 switch (req->InfoType) {
5286 case SMB2_O_INFO_FILE:
5287 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
5288 rc = smb2_get_info_file(work, req, rsp);
5290 case SMB2_O_INFO_FILESYSTEM:
5291 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILESYSTEM\n");
5292 rc = smb2_get_info_filesystem(work, req, rsp);
5294 case SMB2_O_INFO_SECURITY:
5295 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
5296 rc = smb2_get_info_sec(work, req, rsp);
5299 ksmbd_debug(SMB, "InfoType %d not supported yet\n",
5305 rsp->StructureSize = cpu_to_le16(9);
5306 rsp->OutputBufferOffset = cpu_to_le16(72);
5307 rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
5308 offsetof(struct smb2_query_info_rsp, Buffer) +
5309 le32_to_cpu(rsp->OutputBufferLength));
5314 rsp->hdr.Status = STATUS_ACCESS_DENIED;
5315 else if (rc == -ENOENT)
5316 rsp->hdr.Status = STATUS_FILE_CLOSED;
5317 else if (rc == -EIO)
5318 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
5319 else if (rc == -ENOMEM)
5320 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
5321 else if (rc == -EOPNOTSUPP || rsp->hdr.Status == 0)
5322 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
5323 smb2_set_err_rsp(work);
5325 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n",
5333 * smb2_close_pipe() - handler for closing IPC pipe
5334 * @work: smb work containing close request buffer
5338 static noinline int smb2_close_pipe(struct ksmbd_work *work)
5341 struct smb2_close_req *req;
5342 struct smb2_close_rsp *rsp;
5344 WORK_BUFFERS(work, req, rsp);
5346 id = req->VolatileFileId;
5347 ksmbd_session_rpc_close(work->sess, id);
5349 rsp->StructureSize = cpu_to_le16(60);
5352 rsp->CreationTime = 0;
5353 rsp->LastAccessTime = 0;
5354 rsp->LastWriteTime = 0;
5355 rsp->ChangeTime = 0;
5356 rsp->AllocationSize = 0;
5358 rsp->Attributes = 0;
5360 return ksmbd_iov_pin_rsp(work, (void *)rsp,
5361 sizeof(struct smb2_close_rsp));
5365 * smb2_close() - handler for smb2 close file command
5366 * @work: smb work containing close request buffer
5370 int smb2_close(struct ksmbd_work *work)
5372 u64 volatile_id = KSMBD_NO_FID;
5374 struct smb2_close_req *req;
5375 struct smb2_close_rsp *rsp;
5376 struct ksmbd_conn *conn = work->conn;
5377 struct ksmbd_file *fp;
5378 struct inode *inode;
5382 WORK_BUFFERS(work, req, rsp);
5384 if (test_share_config_flag(work->tcon->share_conf,
5385 KSMBD_SHARE_FLAG_PIPE)) {
5386 ksmbd_debug(SMB, "IPC pipe close request\n");
5387 return smb2_close_pipe(work);
5390 sess_id = le64_to_cpu(req->hdr.SessionId);
5391 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5392 sess_id = work->compound_sid;
5394 work->compound_sid = 0;
5395 if (check_session_id(conn, sess_id)) {
5396 work->compound_sid = sess_id;
5398 rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
5399 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5400 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
5405 if (work->next_smb2_rcv_hdr_off &&
5406 !has_file_id(req->VolatileFileId)) {
5407 if (!has_file_id(work->compound_fid)) {
5408 /* file already closed, return FILE_CLOSED */
5409 ksmbd_debug(SMB, "file already closed\n");
5410 rsp->hdr.Status = STATUS_FILE_CLOSED;
5415 "Compound request set FID = %llu:%llu\n",
5417 work->compound_pfid);
5418 volatile_id = work->compound_fid;
5420 /* file closed, stored id is not valid anymore */
5421 work->compound_fid = KSMBD_NO_FID;
5422 work->compound_pfid = KSMBD_NO_FID;
5425 volatile_id = req->VolatileFileId;
5427 ksmbd_debug(SMB, "volatile_id = %llu\n", volatile_id);
5429 rsp->StructureSize = cpu_to_le16(60);
5432 if (req->Flags == SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB) {
5433 fp = ksmbd_lookup_fd_fast(work, volatile_id);
5439 inode = file_inode(fp->filp);
5440 rsp->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB;
5441 rsp->AllocationSize = S_ISDIR(inode->i_mode) ? 0 :
5442 cpu_to_le64(inode->i_blocks << 9);
5443 rsp->EndOfFile = cpu_to_le64(inode->i_size);
5444 rsp->Attributes = fp->f_ci->m_fattr;
5445 rsp->CreationTime = cpu_to_le64(fp->create_time);
5446 time = ksmbd_UnixTimeToNT(inode->i_atime);
5447 rsp->LastAccessTime = cpu_to_le64(time);
5448 time = ksmbd_UnixTimeToNT(inode->i_mtime);
5449 rsp->LastWriteTime = cpu_to_le64(time);
5450 time = ksmbd_UnixTimeToNT(inode_get_ctime(inode));
5451 rsp->ChangeTime = cpu_to_le64(time);
5452 ksmbd_fd_put(work, fp);
5455 rsp->AllocationSize = 0;
5457 rsp->Attributes = 0;
5458 rsp->CreationTime = 0;
5459 rsp->LastAccessTime = 0;
5460 rsp->LastWriteTime = 0;
5461 rsp->ChangeTime = 0;
5464 err = ksmbd_close_fd(work, volatile_id);
5467 err = ksmbd_iov_pin_rsp(work, (void *)rsp,
5468 sizeof(struct smb2_close_rsp));
5471 if (rsp->hdr.Status == 0)
5472 rsp->hdr.Status = STATUS_FILE_CLOSED;
5473 smb2_set_err_rsp(work);
5480 * smb2_echo() - handler for smb2 echo(ping) command
5481 * @work: smb work containing echo request buffer
5485 int smb2_echo(struct ksmbd_work *work)
5487 struct smb2_echo_rsp *rsp = smb2_get_msg(work->response_buf);
5489 if (work->next_smb2_rcv_hdr_off)
5490 rsp = ksmbd_resp_buf_next(work);
5492 rsp->StructureSize = cpu_to_le16(4);
5494 return ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_echo_rsp));
5497 static int smb2_rename(struct ksmbd_work *work,
5498 struct ksmbd_file *fp,
5499 struct smb2_file_rename_info *file_info,
5500 struct nls_table *local_nls)
5502 struct ksmbd_share_config *share = fp->tcon->share_conf;
5503 char *new_name = NULL;
5506 ksmbd_debug(SMB, "setting FILE_RENAME_INFO\n");
5507 new_name = smb2_get_name(file_info->FileName,
5508 le32_to_cpu(file_info->FileNameLength),
5510 if (IS_ERR(new_name))
5511 return PTR_ERR(new_name);
5513 if (strchr(new_name, ':')) {
5515 char *xattr_stream_name, *stream_name = NULL;
5516 size_t xattr_stream_size;
5519 rc = parse_stream_name(new_name, &stream_name, &s_type);
5523 len = strlen(new_name);
5524 if (len > 0 && new_name[len - 1] != '/') {
5525 pr_err("not allow base filename in rename\n");
5530 rc = ksmbd_vfs_xattr_stream_name(stream_name,
5537 rc = ksmbd_vfs_setxattr(file_mnt_idmap(fp->filp),
5542 pr_err("failed to store stream name in xattr: %d\n",
5551 ksmbd_debug(SMB, "new name %s\n", new_name);
5552 if (ksmbd_share_veto_filename(share, new_name)) {
5554 ksmbd_debug(SMB, "Can't rename vetoed file: %s\n", new_name);
5558 if (!file_info->ReplaceIfExists)
5559 flags = RENAME_NOREPLACE;
5561 rc = ksmbd_vfs_rename(work, &fp->filp->f_path, new_name, flags);
5567 static int smb2_create_link(struct ksmbd_work *work,
5568 struct ksmbd_share_config *share,
5569 struct smb2_file_link_info *file_info,
5570 unsigned int buf_len, struct file *filp,
5571 struct nls_table *local_nls)
5573 char *link_name = NULL, *target_name = NULL, *pathname = NULL;
5574 struct path path, parent_path;
5575 bool file_present = false;
5578 if (buf_len < (u64)sizeof(struct smb2_file_link_info) +
5579 le32_to_cpu(file_info->FileNameLength))
5582 ksmbd_debug(SMB, "setting FILE_LINK_INFORMATION\n");
5583 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
5587 link_name = smb2_get_name(file_info->FileName,
5588 le32_to_cpu(file_info->FileNameLength),
5590 if (IS_ERR(link_name) || S_ISDIR(file_inode(filp)->i_mode)) {
5595 ksmbd_debug(SMB, "link name is %s\n", link_name);
5596 target_name = file_path(filp, pathname, PATH_MAX);
5597 if (IS_ERR(target_name)) {
5602 ksmbd_debug(SMB, "target name is %s\n", target_name);
5603 rc = ksmbd_vfs_kern_path_locked(work, link_name, LOOKUP_NO_SYMLINKS,
5604 &parent_path, &path, 0);
5609 file_present = true;
5611 if (file_info->ReplaceIfExists) {
5613 rc = ksmbd_vfs_remove_file(work, &path);
5616 ksmbd_debug(SMB, "cannot delete %s\n",
5624 ksmbd_debug(SMB, "link already exists\n");
5629 rc = ksmbd_vfs_link(work, target_name, link_name);
5634 inode_unlock(d_inode(parent_path.dentry));
5636 path_put(&parent_path);
5638 if (!IS_ERR(link_name))
5644 static int set_file_basic_info(struct ksmbd_file *fp,
5645 struct smb2_file_basic_info *file_info,
5646 struct ksmbd_share_config *share)
5650 struct inode *inode;
5651 struct mnt_idmap *idmap;
5654 if (!(fp->daccess & FILE_WRITE_ATTRIBUTES_LE))
5659 inode = file_inode(filp);
5660 idmap = file_mnt_idmap(filp);
5662 if (file_info->CreationTime)
5663 fp->create_time = le64_to_cpu(file_info->CreationTime);
5665 if (file_info->LastAccessTime) {
5666 attrs.ia_atime = ksmbd_NTtimeToUnix(file_info->LastAccessTime);
5667 attrs.ia_valid |= (ATTR_ATIME | ATTR_ATIME_SET);
5670 attrs.ia_valid |= ATTR_CTIME;
5671 if (file_info->ChangeTime)
5672 attrs.ia_ctime = ksmbd_NTtimeToUnix(file_info->ChangeTime);
5674 attrs.ia_ctime = inode_get_ctime(inode);
5676 if (file_info->LastWriteTime) {
5677 attrs.ia_mtime = ksmbd_NTtimeToUnix(file_info->LastWriteTime);
5678 attrs.ia_valid |= (ATTR_MTIME | ATTR_MTIME_SET);
5681 if (file_info->Attributes) {
5682 if (!S_ISDIR(inode->i_mode) &&
5683 file_info->Attributes & FILE_ATTRIBUTE_DIRECTORY_LE) {
5684 pr_err("can't change a file to a directory\n");
5688 if (!(S_ISDIR(inode->i_mode) && file_info->Attributes == FILE_ATTRIBUTE_NORMAL_LE))
5689 fp->f_ci->m_fattr = file_info->Attributes |
5690 (fp->f_ci->m_fattr & FILE_ATTRIBUTE_DIRECTORY_LE);
5693 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_STORE_DOS_ATTRS) &&
5694 (file_info->CreationTime || file_info->Attributes)) {
5695 struct xattr_dos_attrib da = {0};
5698 da.itime = fp->itime;
5699 da.create_time = fp->create_time;
5700 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
5701 da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
5702 XATTR_DOSINFO_ITIME;
5704 rc = ksmbd_vfs_set_dos_attrib_xattr(idmap, &filp->f_path, &da);
5707 "failed to restore file attribute in EA\n");
5711 if (attrs.ia_valid) {
5712 struct dentry *dentry = filp->f_path.dentry;
5713 struct inode *inode = d_inode(dentry);
5715 if (IS_IMMUTABLE(inode) || IS_APPEND(inode))
5719 inode_set_ctime_to_ts(inode, attrs.ia_ctime);
5720 attrs.ia_valid &= ~ATTR_CTIME;
5721 rc = notify_change(idmap, dentry, &attrs, NULL);
5722 inode_unlock(inode);
5727 static int set_file_allocation_info(struct ksmbd_work *work,
5728 struct ksmbd_file *fp,
5729 struct smb2_file_alloc_info *file_alloc_info)
5732 * TODO : It's working fine only when store dos attributes
5733 * is not yes. need to implement a logic which works
5734 * properly with any smb.conf option
5738 struct inode *inode;
5741 if (!(fp->daccess & FILE_WRITE_DATA_LE))
5744 alloc_blks = (le64_to_cpu(file_alloc_info->AllocationSize) + 511) >> 9;
5745 inode = file_inode(fp->filp);
5747 if (alloc_blks > inode->i_blocks) {
5748 smb_break_all_levII_oplock(work, fp, 1);
5749 rc = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
5751 if (rc && rc != -EOPNOTSUPP) {
5752 pr_err("vfs_fallocate is failed : %d\n", rc);
5755 } else if (alloc_blks < inode->i_blocks) {
5759 * Allocation size could be smaller than original one
5760 * which means allocated blocks in file should be
5761 * deallocated. use truncate to cut out it, but inode
5762 * size is also updated with truncate offset.
5763 * inode size is retained by backup inode size.
5765 size = i_size_read(inode);
5766 rc = ksmbd_vfs_truncate(work, fp, alloc_blks * 512);
5768 pr_err("truncate failed!, err %d\n", rc);
5771 if (size < alloc_blks * 512)
5772 i_size_write(inode, size);
5777 static int set_end_of_file_info(struct ksmbd_work *work, struct ksmbd_file *fp,
5778 struct smb2_file_eof_info *file_eof_info)
5781 struct inode *inode;
5784 if (!(fp->daccess & FILE_WRITE_DATA_LE))
5787 newsize = le64_to_cpu(file_eof_info->EndOfFile);
5788 inode = file_inode(fp->filp);
5791 * If FILE_END_OF_FILE_INFORMATION of set_info_file is called
5792 * on FAT32 shared device, truncate execution time is too long
5793 * and network error could cause from windows client. because
5794 * truncate of some filesystem like FAT32 fill zero data in
5797 if (inode->i_sb->s_magic != MSDOS_SUPER_MAGIC) {
5798 ksmbd_debug(SMB, "truncated to newsize %lld\n", newsize);
5799 rc = ksmbd_vfs_truncate(work, fp, newsize);
5801 ksmbd_debug(SMB, "truncate failed!, err %d\n", rc);
5810 static int set_rename_info(struct ksmbd_work *work, struct ksmbd_file *fp,
5811 struct smb2_file_rename_info *rename_info,
5812 unsigned int buf_len)
5814 if (!(fp->daccess & FILE_DELETE_LE)) {
5815 pr_err("no right to delete : 0x%x\n", fp->daccess);
5819 if (buf_len < (u64)sizeof(struct smb2_file_rename_info) +
5820 le32_to_cpu(rename_info->FileNameLength))
5823 if (!le32_to_cpu(rename_info->FileNameLength))
5826 return smb2_rename(work, fp, rename_info, work->conn->local_nls);
5829 static int set_file_disposition_info(struct ksmbd_file *fp,
5830 struct smb2_file_disposition_info *file_info)
5832 struct inode *inode;
5834 if (!(fp->daccess & FILE_DELETE_LE)) {
5835 pr_err("no right to delete : 0x%x\n", fp->daccess);
5839 inode = file_inode(fp->filp);
5840 if (file_info->DeletePending) {
5841 if (S_ISDIR(inode->i_mode) &&
5842 ksmbd_vfs_empty_dir(fp) == -ENOTEMPTY)
5844 ksmbd_set_inode_pending_delete(fp);
5846 ksmbd_clear_inode_pending_delete(fp);
5851 static int set_file_position_info(struct ksmbd_file *fp,
5852 struct smb2_file_pos_info *file_info)
5854 loff_t current_byte_offset;
5855 unsigned long sector_size;
5856 struct inode *inode;
5858 inode = file_inode(fp->filp);
5859 current_byte_offset = le64_to_cpu(file_info->CurrentByteOffset);
5860 sector_size = inode->i_sb->s_blocksize;
5862 if (current_byte_offset < 0 ||
5863 (fp->coption == FILE_NO_INTERMEDIATE_BUFFERING_LE &&
5864 current_byte_offset & (sector_size - 1))) {
5865 pr_err("CurrentByteOffset is not valid : %llu\n",
5866 current_byte_offset);
5870 fp->filp->f_pos = current_byte_offset;
5874 static int set_file_mode_info(struct ksmbd_file *fp,
5875 struct smb2_file_mode_info *file_info)
5879 mode = file_info->Mode;
5881 if ((mode & ~FILE_MODE_INFO_MASK)) {
5882 pr_err("Mode is not valid : 0x%x\n", le32_to_cpu(mode));
5887 * TODO : need to implement consideration for
5888 * FILE_SYNCHRONOUS_IO_ALERT and FILE_SYNCHRONOUS_IO_NONALERT
5890 ksmbd_vfs_set_fadvise(fp->filp, mode);
5896 * smb2_set_info_file() - handler for smb2 set info command
5897 * @work: smb work containing set info command buffer
5898 * @fp: ksmbd_file pointer
5899 * @req: request buffer pointer
5900 * @share: ksmbd_share_config pointer
5902 * Return: 0 on success, otherwise error
5903 * TODO: need to implement an error handling for STATUS_INFO_LENGTH_MISMATCH
5905 static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp,
5906 struct smb2_set_info_req *req,
5907 struct ksmbd_share_config *share)
5909 unsigned int buf_len = le32_to_cpu(req->BufferLength);
5911 switch (req->FileInfoClass) {
5912 case FILE_BASIC_INFORMATION:
5914 if (buf_len < sizeof(struct smb2_file_basic_info))
5917 return set_file_basic_info(fp, (struct smb2_file_basic_info *)req->Buffer, share);
5919 case FILE_ALLOCATION_INFORMATION:
5921 if (buf_len < sizeof(struct smb2_file_alloc_info))
5924 return set_file_allocation_info(work, fp,
5925 (struct smb2_file_alloc_info *)req->Buffer);
5927 case FILE_END_OF_FILE_INFORMATION:
5929 if (buf_len < sizeof(struct smb2_file_eof_info))
5932 return set_end_of_file_info(work, fp,
5933 (struct smb2_file_eof_info *)req->Buffer);
5935 case FILE_RENAME_INFORMATION:
5937 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
5939 "User does not have write permission\n");
5943 if (buf_len < sizeof(struct smb2_file_rename_info))
5946 return set_rename_info(work, fp,
5947 (struct smb2_file_rename_info *)req->Buffer,
5950 case FILE_LINK_INFORMATION:
5952 if (buf_len < sizeof(struct smb2_file_link_info))
5955 return smb2_create_link(work, work->tcon->share_conf,
5956 (struct smb2_file_link_info *)req->Buffer,
5958 work->conn->local_nls);
5960 case FILE_DISPOSITION_INFORMATION:
5962 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
5964 "User does not have write permission\n");
5968 if (buf_len < sizeof(struct smb2_file_disposition_info))
5971 return set_file_disposition_info(fp,
5972 (struct smb2_file_disposition_info *)req->Buffer);
5974 case FILE_FULL_EA_INFORMATION:
5976 if (!(fp->daccess & FILE_WRITE_EA_LE)) {
5977 pr_err("Not permitted to write ext attr: 0x%x\n",
5982 if (buf_len < sizeof(struct smb2_ea_info))
5985 return smb2_set_ea((struct smb2_ea_info *)req->Buffer,
5986 buf_len, &fp->filp->f_path);
5988 case FILE_POSITION_INFORMATION:
5990 if (buf_len < sizeof(struct smb2_file_pos_info))
5993 return set_file_position_info(fp, (struct smb2_file_pos_info *)req->Buffer);
5995 case FILE_MODE_INFORMATION:
5997 if (buf_len < sizeof(struct smb2_file_mode_info))
6000 return set_file_mode_info(fp, (struct smb2_file_mode_info *)req->Buffer);
6004 pr_err("Unimplemented Fileinfoclass :%d\n", req->FileInfoClass);
6008 static int smb2_set_info_sec(struct ksmbd_file *fp, int addition_info,
6009 char *buffer, int buf_len)
6011 struct smb_ntsd *pntsd = (struct smb_ntsd *)buffer;
6013 fp->saccess |= FILE_SHARE_DELETE_LE;
6015 return set_info_sec(fp->conn, fp->tcon, &fp->filp->f_path, pntsd,
6020 * smb2_set_info() - handler for smb2 set info command handler
6021 * @work: smb work containing set info request buffer
6023 * Return: 0 on success, otherwise error
6025 int smb2_set_info(struct ksmbd_work *work)
6027 struct smb2_set_info_req *req;
6028 struct smb2_set_info_rsp *rsp;
6029 struct ksmbd_file *fp;
6031 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
6033 ksmbd_debug(SMB, "Received set info request\n");
6035 if (work->next_smb2_rcv_hdr_off) {
6036 req = ksmbd_req_buf_next(work);
6037 rsp = ksmbd_resp_buf_next(work);
6038 if (!has_file_id(req->VolatileFileId)) {
6039 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
6040 work->compound_fid);
6041 id = work->compound_fid;
6042 pid = work->compound_pfid;
6045 req = smb2_get_msg(work->request_buf);
6046 rsp = smb2_get_msg(work->response_buf);
6049 if (!has_file_id(id)) {
6050 id = req->VolatileFileId;
6051 pid = req->PersistentFileId;
6054 fp = ksmbd_lookup_fd_slow(work, id, pid);
6056 ksmbd_debug(SMB, "Invalid id for close: %u\n", id);
6061 switch (req->InfoType) {
6062 case SMB2_O_INFO_FILE:
6063 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
6064 rc = smb2_set_info_file(work, fp, req, work->tcon->share_conf);
6066 case SMB2_O_INFO_SECURITY:
6067 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
6068 if (ksmbd_override_fsids(work)) {
6072 rc = smb2_set_info_sec(fp,
6073 le32_to_cpu(req->AdditionalInformation),
6075 le32_to_cpu(req->BufferLength));
6076 ksmbd_revert_fsids(work);
6085 rsp->StructureSize = cpu_to_le16(2);
6086 rc = ksmbd_iov_pin_rsp(work, (void *)rsp,
6087 sizeof(struct smb2_set_info_rsp));
6090 ksmbd_fd_put(work, fp);
6094 if (rc == -EACCES || rc == -EPERM || rc == -EXDEV)
6095 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6096 else if (rc == -EINVAL)
6097 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6098 else if (rc == -ESHARE)
6099 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6100 else if (rc == -ENOENT)
6101 rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
6102 else if (rc == -EBUSY || rc == -ENOTEMPTY)
6103 rsp->hdr.Status = STATUS_DIRECTORY_NOT_EMPTY;
6104 else if (rc == -EAGAIN)
6105 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6106 else if (rc == -EBADF || rc == -ESTALE)
6107 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6108 else if (rc == -EEXIST)
6109 rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
6110 else if (rsp->hdr.Status == 0 || rc == -EOPNOTSUPP)
6111 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
6112 smb2_set_err_rsp(work);
6113 ksmbd_fd_put(work, fp);
6114 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n", rc);
6119 * smb2_read_pipe() - handler for smb2 read from IPC pipe
6120 * @work: smb work containing read IPC pipe command buffer
6122 * Return: 0 on success, otherwise error
6124 static noinline int smb2_read_pipe(struct ksmbd_work *work)
6126 int nbytes = 0, err;
6128 struct ksmbd_rpc_command *rpc_resp;
6129 struct smb2_read_req *req;
6130 struct smb2_read_rsp *rsp;
6132 WORK_BUFFERS(work, req, rsp);
6134 id = req->VolatileFileId;
6136 rpc_resp = ksmbd_rpc_read(work->sess, id);
6138 void *aux_payload_buf;
6140 if (rpc_resp->flags != KSMBD_RPC_OK) {
6146 kvmalloc(rpc_resp->payload_sz, GFP_KERNEL);
6147 if (!aux_payload_buf) {
6152 memcpy(aux_payload_buf, rpc_resp->payload, rpc_resp->payload_sz);
6154 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);
6162 err = ksmbd_iov_pin_rsp(work, (void *)rsp,
6163 offsetof(struct smb2_read_rsp, Buffer));
6168 rsp->StructureSize = cpu_to_le16(17);
6169 rsp->DataOffset = 80;
6171 rsp->DataLength = cpu_to_le32(nbytes);
6172 rsp->DataRemaining = 0;
6177 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
6178 smb2_set_err_rsp(work);
6183 static int smb2_set_remote_key_for_rdma(struct ksmbd_work *work,
6184 struct smb2_buffer_desc_v1 *desc,
6186 __le16 ChannelInfoLength)
6188 unsigned int i, ch_count;
6190 if (work->conn->dialect == SMB30_PROT_ID &&
6191 Channel != SMB2_CHANNEL_RDMA_V1)
6194 ch_count = le16_to_cpu(ChannelInfoLength) / sizeof(*desc);
6195 if (ksmbd_debug_types & KSMBD_DEBUG_RDMA) {
6196 for (i = 0; i < ch_count; i++) {
6197 pr_info("RDMA r/w request %#x: token %#x, length %#x\n",
6199 le32_to_cpu(desc[i].token),
6200 le32_to_cpu(desc[i].length));
6206 work->need_invalidate_rkey =
6207 (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE);
6208 if (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE)
6209 work->remote_key = le32_to_cpu(desc->token);
6213 static ssize_t smb2_read_rdma_channel(struct ksmbd_work *work,
6214 struct smb2_read_req *req, void *data_buf,
6219 err = ksmbd_conn_rdma_write(work->conn, data_buf, length,
6220 (struct smb2_buffer_desc_v1 *)
6221 ((char *)req + le16_to_cpu(req->ReadChannelInfoOffset)),
6222 le16_to_cpu(req->ReadChannelInfoLength));
6230 * smb2_read() - handler for smb2 read from file
6231 * @work: smb work containing read command buffer
6233 * Return: 0 on success, otherwise error
6235 int smb2_read(struct ksmbd_work *work)
6237 struct ksmbd_conn *conn = work->conn;
6238 struct smb2_read_req *req;
6239 struct smb2_read_rsp *rsp;
6240 struct ksmbd_file *fp = NULL;
6242 size_t length, mincount;
6243 ssize_t nbytes = 0, remain_bytes = 0;
6245 bool is_rdma_channel = false;
6246 unsigned int max_read_size = conn->vals->max_read_size;
6247 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
6248 void *aux_payload_buf;
6250 if (test_share_config_flag(work->tcon->share_conf,
6251 KSMBD_SHARE_FLAG_PIPE)) {
6252 ksmbd_debug(SMB, "IPC pipe read request\n");
6253 return smb2_read_pipe(work);
6256 if (work->next_smb2_rcv_hdr_off) {
6257 req = ksmbd_req_buf_next(work);
6258 rsp = ksmbd_resp_buf_next(work);
6259 if (!has_file_id(req->VolatileFileId)) {
6260 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
6261 work->compound_fid);
6262 id = work->compound_fid;
6263 pid = work->compound_pfid;
6266 req = smb2_get_msg(work->request_buf);
6267 rsp = smb2_get_msg(work->response_buf);
6270 if (!has_file_id(id)) {
6271 id = req->VolatileFileId;
6272 pid = req->PersistentFileId;
6275 if (req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE ||
6276 req->Channel == SMB2_CHANNEL_RDMA_V1) {
6277 is_rdma_channel = true;
6278 max_read_size = get_smbd_max_read_write_size();
6281 if (is_rdma_channel == true) {
6282 unsigned int ch_offset = le16_to_cpu(req->ReadChannelInfoOffset);
6284 if (ch_offset < offsetof(struct smb2_read_req, Buffer)) {
6288 err = smb2_set_remote_key_for_rdma(work,
6289 (struct smb2_buffer_desc_v1 *)
6290 ((char *)req + ch_offset),
6292 req->ReadChannelInfoLength);
6297 fp = ksmbd_lookup_fd_slow(work, id, pid);
6303 if (!(fp->daccess & (FILE_READ_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
6304 pr_err("Not permitted to read : 0x%x\n", fp->daccess);
6309 offset = le64_to_cpu(req->Offset);
6310 length = le32_to_cpu(req->Length);
6311 mincount = le32_to_cpu(req->MinimumCount);
6313 if (length > max_read_size) {
6314 ksmbd_debug(SMB, "limiting read size to max size(%u)\n",
6320 ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
6321 fp->filp, offset, length);
6323 aux_payload_buf = kvzalloc(length, GFP_KERNEL);
6324 if (!aux_payload_buf) {
6329 nbytes = ksmbd_vfs_read(work, fp, length, &offset, aux_payload_buf);
6335 if ((nbytes == 0 && length != 0) || nbytes < mincount) {
6336 kvfree(aux_payload_buf);
6337 rsp->hdr.Status = STATUS_END_OF_FILE;
6338 smb2_set_err_rsp(work);
6339 ksmbd_fd_put(work, fp);
6343 ksmbd_debug(SMB, "nbytes %zu, offset %lld mincount %zu\n",
6344 nbytes, offset, mincount);
6346 if (is_rdma_channel == true) {
6347 /* write data to the client using rdma channel */
6348 remain_bytes = smb2_read_rdma_channel(work, req,
6351 kvfree(aux_payload_buf);
6352 aux_payload_buf = NULL;
6354 if (remain_bytes < 0) {
6355 err = (int)remain_bytes;
6360 rsp->StructureSize = cpu_to_le16(17);
6361 rsp->DataOffset = 80;
6363 rsp->DataLength = cpu_to_le32(nbytes);
6364 rsp->DataRemaining = cpu_to_le32(remain_bytes);
6366 err = ksmbd_iov_pin_rsp_read(work, (void *)rsp,
6367 offsetof(struct smb2_read_rsp, Buffer),
6368 aux_payload_buf, nbytes);
6371 ksmbd_fd_put(work, fp);
6377 rsp->hdr.Status = STATUS_INVALID_DEVICE_REQUEST;
6378 else if (err == -EAGAIN)
6379 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6380 else if (err == -ENOENT)
6381 rsp->hdr.Status = STATUS_FILE_CLOSED;
6382 else if (err == -EACCES)
6383 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6384 else if (err == -ESHARE)
6385 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6386 else if (err == -EINVAL)
6387 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6389 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6391 smb2_set_err_rsp(work);
6393 ksmbd_fd_put(work, fp);
6398 * smb2_write_pipe() - handler for smb2 write on IPC pipe
6399 * @work: smb work containing write IPC pipe command buffer
6401 * Return: 0 on success, otherwise error
6403 static noinline int smb2_write_pipe(struct ksmbd_work *work)
6405 struct smb2_write_req *req;
6406 struct smb2_write_rsp *rsp;
6407 struct ksmbd_rpc_command *rpc_resp;
6409 int err = 0, ret = 0;
6413 WORK_BUFFERS(work, req, rsp);
6415 length = le32_to_cpu(req->Length);
6416 id = req->VolatileFileId;
6418 if ((u64)le16_to_cpu(req->DataOffset) + length >
6419 get_rfc1002_len(work->request_buf)) {
6420 pr_err("invalid write data offset %u, smb_len %u\n",
6421 le16_to_cpu(req->DataOffset),
6422 get_rfc1002_len(work->request_buf));
6427 data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
6428 le16_to_cpu(req->DataOffset));
6430 rpc_resp = ksmbd_rpc_write(work->sess, id, data_buf, length);
6432 if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
6433 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
6435 smb2_set_err_rsp(work);
6438 if (rpc_resp->flags != KSMBD_RPC_OK) {
6439 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6440 smb2_set_err_rsp(work);
6447 rsp->StructureSize = cpu_to_le16(17);
6448 rsp->DataOffset = 0;
6450 rsp->DataLength = cpu_to_le32(length);
6451 rsp->DataRemaining = 0;
6453 err = ksmbd_iov_pin_rsp(work, (void *)rsp,
6454 offsetof(struct smb2_write_rsp, Buffer));
6457 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6458 smb2_set_err_rsp(work);
6464 static ssize_t smb2_write_rdma_channel(struct ksmbd_work *work,
6465 struct smb2_write_req *req,
6466 struct ksmbd_file *fp,
6467 loff_t offset, size_t length, bool sync)
6473 data_buf = kvzalloc(length, GFP_KERNEL);
6477 ret = ksmbd_conn_rdma_read(work->conn, data_buf, length,
6478 (struct smb2_buffer_desc_v1 *)
6479 ((char *)req + le16_to_cpu(req->WriteChannelInfoOffset)),
6480 le16_to_cpu(req->WriteChannelInfoLength));
6486 ret = ksmbd_vfs_write(work, fp, data_buf, length, &offset, sync, &nbytes);
6495 * smb2_write() - handler for smb2 write from file
6496 * @work: smb work containing write command buffer
6498 * Return: 0 on success, otherwise error
6500 int smb2_write(struct ksmbd_work *work)
6502 struct smb2_write_req *req;
6503 struct smb2_write_rsp *rsp;
6504 struct ksmbd_file *fp = NULL;
6509 bool writethrough = false, is_rdma_channel = false;
6511 unsigned int max_write_size = work->conn->vals->max_write_size;
6513 WORK_BUFFERS(work, req, rsp);
6515 if (test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_PIPE)) {
6516 ksmbd_debug(SMB, "IPC pipe write request\n");
6517 return smb2_write_pipe(work);
6520 offset = le64_to_cpu(req->Offset);
6521 length = le32_to_cpu(req->Length);
6523 if (req->Channel == SMB2_CHANNEL_RDMA_V1 ||
6524 req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE) {
6525 is_rdma_channel = true;
6526 max_write_size = get_smbd_max_read_write_size();
6527 length = le32_to_cpu(req->RemainingBytes);
6530 if (is_rdma_channel == true) {
6531 unsigned int ch_offset = le16_to_cpu(req->WriteChannelInfoOffset);
6533 if (req->Length != 0 || req->DataOffset != 0 ||
6534 ch_offset < offsetof(struct smb2_write_req, Buffer)) {
6538 err = smb2_set_remote_key_for_rdma(work,
6539 (struct smb2_buffer_desc_v1 *)
6540 ((char *)req + ch_offset),
6542 req->WriteChannelInfoLength);
6547 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
6548 ksmbd_debug(SMB, "User does not have write permission\n");
6553 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
6559 if (!(fp->daccess & (FILE_WRITE_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
6560 pr_err("Not permitted to write : 0x%x\n", fp->daccess);
6565 if (length > max_write_size) {
6566 ksmbd_debug(SMB, "limiting write size to max size(%u)\n",
6572 ksmbd_debug(SMB, "flags %u\n", le32_to_cpu(req->Flags));
6573 if (le32_to_cpu(req->Flags) & SMB2_WRITEFLAG_WRITE_THROUGH)
6574 writethrough = true;
6576 if (is_rdma_channel == false) {
6577 if (le16_to_cpu(req->DataOffset) <
6578 offsetof(struct smb2_write_req, Buffer)) {
6583 data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
6584 le16_to_cpu(req->DataOffset));
6586 ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
6587 fp->filp, offset, length);
6588 err = ksmbd_vfs_write(work, fp, data_buf, length, &offset,
6589 writethrough, &nbytes);
6593 /* read data from the client using rdma channel, and
6596 nbytes = smb2_write_rdma_channel(work, req, fp, offset, length,
6604 rsp->StructureSize = cpu_to_le16(17);
6605 rsp->DataOffset = 0;
6607 rsp->DataLength = cpu_to_le32(nbytes);
6608 rsp->DataRemaining = 0;
6610 err = ksmbd_iov_pin_rsp(work, rsp, offsetof(struct smb2_write_rsp, Buffer));
6613 ksmbd_fd_put(work, fp);
6618 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6619 else if (err == -ENOSPC || err == -EFBIG)
6620 rsp->hdr.Status = STATUS_DISK_FULL;
6621 else if (err == -ENOENT)
6622 rsp->hdr.Status = STATUS_FILE_CLOSED;
6623 else if (err == -EACCES)
6624 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6625 else if (err == -ESHARE)
6626 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6627 else if (err == -EINVAL)
6628 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6630 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6632 smb2_set_err_rsp(work);
6633 ksmbd_fd_put(work, fp);
6638 * smb2_flush() - handler for smb2 flush file - fsync
6639 * @work: smb work containing flush command buffer
6641 * Return: 0 on success, otherwise error
6643 int smb2_flush(struct ksmbd_work *work)
6645 struct smb2_flush_req *req;
6646 struct smb2_flush_rsp *rsp;
6649 WORK_BUFFERS(work, req, rsp);
6651 ksmbd_debug(SMB, "SMB2_FLUSH called for fid %llu\n", req->VolatileFileId);
6653 err = ksmbd_vfs_fsync(work, req->VolatileFileId, req->PersistentFileId);
6657 rsp->StructureSize = cpu_to_le16(4);
6659 return ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_flush_rsp));
6662 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6663 smb2_set_err_rsp(work);
6668 * smb2_cancel() - handler for smb2 cancel command
6669 * @work: smb work containing cancel command buffer
6671 * Return: 0 on success, otherwise error
6673 int smb2_cancel(struct ksmbd_work *work)
6675 struct ksmbd_conn *conn = work->conn;
6676 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
6677 struct smb2_hdr *chdr;
6678 struct ksmbd_work *iter;
6679 struct list_head *command_list;
6681 if (work->next_smb2_rcv_hdr_off)
6682 hdr = ksmbd_resp_buf_next(work);
6684 ksmbd_debug(SMB, "smb2 cancel called on mid %llu, async flags 0x%x\n",
6685 hdr->MessageId, hdr->Flags);
6687 if (hdr->Flags & SMB2_FLAGS_ASYNC_COMMAND) {
6688 command_list = &conn->async_requests;
6690 spin_lock(&conn->request_lock);
6691 list_for_each_entry(iter, command_list,
6692 async_request_entry) {
6693 chdr = smb2_get_msg(iter->request_buf);
6695 if (iter->async_id !=
6696 le64_to_cpu(hdr->Id.AsyncId))
6700 "smb2 with AsyncId %llu cancelled command = 0x%x\n",
6701 le64_to_cpu(hdr->Id.AsyncId),
6702 le16_to_cpu(chdr->Command));
6703 iter->state = KSMBD_WORK_CANCELLED;
6704 if (iter->cancel_fn)
6705 iter->cancel_fn(iter->cancel_argv);
6708 spin_unlock(&conn->request_lock);
6710 command_list = &conn->requests;
6712 spin_lock(&conn->request_lock);
6713 list_for_each_entry(iter, command_list, request_entry) {
6714 chdr = smb2_get_msg(iter->request_buf);
6716 if (chdr->MessageId != hdr->MessageId ||
6721 "smb2 with mid %llu cancelled command = 0x%x\n",
6722 le64_to_cpu(hdr->MessageId),
6723 le16_to_cpu(chdr->Command));
6724 iter->state = KSMBD_WORK_CANCELLED;
6727 spin_unlock(&conn->request_lock);
6730 /* For SMB2_CANCEL command itself send no response*/
6731 work->send_no_response = 1;
6735 struct file_lock *smb_flock_init(struct file *f)
6737 struct file_lock *fl;
6739 fl = locks_alloc_lock();
6743 locks_init_lock(fl);
6746 fl->fl_pid = current->tgid;
6748 fl->fl_flags = FL_POSIX;
6750 fl->fl_lmops = NULL;
6756 static int smb2_set_flock_flags(struct file_lock *flock, int flags)
6760 /* Checking for wrong flag combination during lock request*/
6762 case SMB2_LOCKFLAG_SHARED:
6763 ksmbd_debug(SMB, "received shared request\n");
6765 flock->fl_type = F_RDLCK;
6766 flock->fl_flags |= FL_SLEEP;
6768 case SMB2_LOCKFLAG_EXCLUSIVE:
6769 ksmbd_debug(SMB, "received exclusive request\n");
6771 flock->fl_type = F_WRLCK;
6772 flock->fl_flags |= FL_SLEEP;
6774 case SMB2_LOCKFLAG_SHARED | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
6776 "received shared & fail immediately request\n");
6778 flock->fl_type = F_RDLCK;
6780 case SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
6782 "received exclusive & fail immediately request\n");
6784 flock->fl_type = F_WRLCK;
6786 case SMB2_LOCKFLAG_UNLOCK:
6787 ksmbd_debug(SMB, "received unlock request\n");
6788 flock->fl_type = F_UNLCK;
6796 static struct ksmbd_lock *smb2_lock_init(struct file_lock *flock,
6797 unsigned int cmd, int flags,
6798 struct list_head *lock_list)
6800 struct ksmbd_lock *lock;
6802 lock = kzalloc(sizeof(struct ksmbd_lock), GFP_KERNEL);
6808 lock->start = flock->fl_start;
6809 lock->end = flock->fl_end;
6810 lock->flags = flags;
6811 if (lock->start == lock->end)
6813 INIT_LIST_HEAD(&lock->clist);
6814 INIT_LIST_HEAD(&lock->flist);
6815 INIT_LIST_HEAD(&lock->llist);
6816 list_add_tail(&lock->llist, lock_list);
6821 static void smb2_remove_blocked_lock(void **argv)
6823 struct file_lock *flock = (struct file_lock *)argv[0];
6825 ksmbd_vfs_posix_lock_unblock(flock);
6826 wake_up(&flock->fl_wait);
6829 static inline bool lock_defer_pending(struct file_lock *fl)
6831 /* check pending lock waiters */
6832 return waitqueue_active(&fl->fl_wait);
6836 * smb2_lock() - handler for smb2 file lock command
6837 * @work: smb work containing lock command buffer
6839 * Return: 0 on success, otherwise error
6841 int smb2_lock(struct ksmbd_work *work)
6843 struct smb2_lock_req *req;
6844 struct smb2_lock_rsp *rsp;
6845 struct smb2_lock_element *lock_ele;
6846 struct ksmbd_file *fp = NULL;
6847 struct file_lock *flock = NULL;
6848 struct file *filp = NULL;
6852 int err = -EIO, i, rc = 0;
6853 u64 lock_start, lock_length;
6854 struct ksmbd_lock *smb_lock = NULL, *cmp_lock, *tmp, *tmp2;
6855 struct ksmbd_conn *conn;
6857 LIST_HEAD(lock_list);
6858 LIST_HEAD(rollback_list);
6861 WORK_BUFFERS(work, req, rsp);
6863 ksmbd_debug(SMB, "Received lock request\n");
6864 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
6866 ksmbd_debug(SMB, "Invalid file id for lock : %llu\n", req->VolatileFileId);
6872 lock_count = le16_to_cpu(req->LockCount);
6873 lock_ele = req->locks;
6875 ksmbd_debug(SMB, "lock count is %d\n", lock_count);
6881 for (i = 0; i < lock_count; i++) {
6882 flags = le32_to_cpu(lock_ele[i].Flags);
6884 flock = smb_flock_init(filp);
6888 cmd = smb2_set_flock_flags(flock, flags);
6890 lock_start = le64_to_cpu(lock_ele[i].Offset);
6891 lock_length = le64_to_cpu(lock_ele[i].Length);
6892 if (lock_start > U64_MAX - lock_length) {
6893 pr_err("Invalid lock range requested\n");
6894 rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
6895 locks_free_lock(flock);
6899 if (lock_start > OFFSET_MAX)
6900 flock->fl_start = OFFSET_MAX;
6902 flock->fl_start = lock_start;
6904 lock_length = le64_to_cpu(lock_ele[i].Length);
6905 if (lock_length > OFFSET_MAX - flock->fl_start)
6906 lock_length = OFFSET_MAX - flock->fl_start;
6908 flock->fl_end = flock->fl_start + lock_length;
6910 if (flock->fl_end < flock->fl_start) {
6912 "the end offset(%llx) is smaller than the start offset(%llx)\n",
6913 flock->fl_end, flock->fl_start);
6914 rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
6915 locks_free_lock(flock);
6919 /* Check conflict locks in one request */
6920 list_for_each_entry(cmp_lock, &lock_list, llist) {
6921 if (cmp_lock->fl->fl_start <= flock->fl_start &&
6922 cmp_lock->fl->fl_end >= flock->fl_end) {
6923 if (cmp_lock->fl->fl_type != F_UNLCK &&
6924 flock->fl_type != F_UNLCK) {
6925 pr_err("conflict two locks in one request\n");
6927 locks_free_lock(flock);
6933 smb_lock = smb2_lock_init(flock, cmd, flags, &lock_list);
6936 locks_free_lock(flock);
6941 list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
6942 if (smb_lock->cmd < 0) {
6947 if (!(smb_lock->flags & SMB2_LOCKFLAG_MASK)) {
6952 if ((prior_lock & (SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_SHARED) &&
6953 smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) ||
6954 (prior_lock == SMB2_LOCKFLAG_UNLOCK &&
6955 !(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK))) {
6960 prior_lock = smb_lock->flags;
6962 if (!(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) &&
6963 !(smb_lock->flags & SMB2_LOCKFLAG_FAIL_IMMEDIATELY))
6967 /* check locks in connection list */
6968 down_read(&conn_list_lock);
6969 list_for_each_entry(conn, &conn_list, conns_list) {
6970 spin_lock(&conn->llist_lock);
6971 list_for_each_entry_safe(cmp_lock, tmp2, &conn->lock_list, clist) {
6972 if (file_inode(cmp_lock->fl->fl_file) !=
6973 file_inode(smb_lock->fl->fl_file))
6976 if (smb_lock->fl->fl_type == F_UNLCK) {
6977 if (cmp_lock->fl->fl_file == smb_lock->fl->fl_file &&
6978 cmp_lock->start == smb_lock->start &&
6979 cmp_lock->end == smb_lock->end &&
6980 !lock_defer_pending(cmp_lock->fl)) {
6982 list_del(&cmp_lock->flist);
6983 list_del(&cmp_lock->clist);
6984 spin_unlock(&conn->llist_lock);
6985 up_read(&conn_list_lock);
6987 locks_free_lock(cmp_lock->fl);
6994 if (cmp_lock->fl->fl_file == smb_lock->fl->fl_file) {
6995 if (smb_lock->flags & SMB2_LOCKFLAG_SHARED)
6998 if (cmp_lock->flags & SMB2_LOCKFLAG_SHARED)
7002 /* check zero byte lock range */
7003 if (cmp_lock->zero_len && !smb_lock->zero_len &&
7004 cmp_lock->start > smb_lock->start &&
7005 cmp_lock->start < smb_lock->end) {
7006 spin_unlock(&conn->llist_lock);
7007 up_read(&conn_list_lock);
7008 pr_err("previous lock conflict with zero byte lock range\n");
7012 if (smb_lock->zero_len && !cmp_lock->zero_len &&
7013 smb_lock->start > cmp_lock->start &&
7014 smb_lock->start < cmp_lock->end) {
7015 spin_unlock(&conn->llist_lock);
7016 up_read(&conn_list_lock);
7017 pr_err("current lock conflict with zero byte lock range\n");
7021 if (((cmp_lock->start <= smb_lock->start &&
7022 cmp_lock->end > smb_lock->start) ||
7023 (cmp_lock->start < smb_lock->end &&
7024 cmp_lock->end >= smb_lock->end)) &&
7025 !cmp_lock->zero_len && !smb_lock->zero_len) {
7026 spin_unlock(&conn->llist_lock);
7027 up_read(&conn_list_lock);
7028 pr_err("Not allow lock operation on exclusive lock range\n");
7032 spin_unlock(&conn->llist_lock);
7034 up_read(&conn_list_lock);
7036 if (smb_lock->fl->fl_type == F_UNLCK && nolock) {
7037 pr_err("Try to unlock nolocked range\n");
7038 rsp->hdr.Status = STATUS_RANGE_NOT_LOCKED;
7043 if (smb_lock->zero_len) {
7048 flock = smb_lock->fl;
7049 list_del(&smb_lock->llist);
7051 rc = vfs_lock_file(filp, smb_lock->cmd, flock, NULL);
7053 if (flags & SMB2_LOCKFLAG_UNLOCK) {
7055 ksmbd_debug(SMB, "File unlocked\n");
7056 } else if (rc == -ENOENT) {
7057 rsp->hdr.Status = STATUS_NOT_LOCKED;
7060 locks_free_lock(flock);
7063 if (rc == FILE_LOCK_DEFERRED) {
7067 "would have to wait for getting lock\n");
7068 list_add(&smb_lock->llist, &rollback_list);
7070 argv = kmalloc(sizeof(void *), GFP_KERNEL);
7077 rc = setup_async_work(work,
7078 smb2_remove_blocked_lock,
7084 spin_lock(&fp->f_lock);
7085 list_add(&work->fp_entry, &fp->blocked_works);
7086 spin_unlock(&fp->f_lock);
7088 smb2_send_interim_resp(work, STATUS_PENDING);
7090 ksmbd_vfs_posix_lock_wait(flock);
7092 spin_lock(&fp->f_lock);
7093 list_del(&work->fp_entry);
7094 spin_unlock(&fp->f_lock);
7096 if (work->state != KSMBD_WORK_ACTIVE) {
7097 list_del(&smb_lock->llist);
7098 locks_free_lock(flock);
7100 if (work->state == KSMBD_WORK_CANCELLED) {
7104 smb2_send_interim_resp(work,
7106 work->send_no_response = 1;
7111 STATUS_RANGE_NOT_LOCKED;
7116 list_del(&smb_lock->llist);
7117 release_async_work(work);
7120 list_add(&smb_lock->llist, &rollback_list);
7121 spin_lock(&work->conn->llist_lock);
7122 list_add_tail(&smb_lock->clist,
7123 &work->conn->lock_list);
7124 list_add_tail(&smb_lock->flist,
7126 spin_unlock(&work->conn->llist_lock);
7127 ksmbd_debug(SMB, "successful in taking lock\n");
7134 if (atomic_read(&fp->f_ci->op_count) > 1)
7135 smb_break_all_oplock(work, fp);
7137 rsp->StructureSize = cpu_to_le16(4);
7138 ksmbd_debug(SMB, "successful in taking lock\n");
7139 rsp->hdr.Status = STATUS_SUCCESS;
7141 err = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_lock_rsp));
7145 ksmbd_fd_put(work, fp);
7149 list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
7150 locks_free_lock(smb_lock->fl);
7151 list_del(&smb_lock->llist);
7155 list_for_each_entry_safe(smb_lock, tmp, &rollback_list, llist) {
7156 struct file_lock *rlock = NULL;
7158 rlock = smb_flock_init(filp);
7159 rlock->fl_type = F_UNLCK;
7160 rlock->fl_start = smb_lock->start;
7161 rlock->fl_end = smb_lock->end;
7163 rc = vfs_lock_file(filp, F_SETLK, rlock, NULL);
7165 pr_err("rollback unlock fail : %d\n", rc);
7167 list_del(&smb_lock->llist);
7168 spin_lock(&work->conn->llist_lock);
7169 if (!list_empty(&smb_lock->flist))
7170 list_del(&smb_lock->flist);
7171 list_del(&smb_lock->clist);
7172 spin_unlock(&work->conn->llist_lock);
7174 locks_free_lock(smb_lock->fl);
7175 locks_free_lock(rlock);
7179 ksmbd_debug(SMB, "failed in taking lock(flags : %x), err : %d\n", flags, err);
7181 if (!rsp->hdr.Status) {
7183 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7184 else if (err == -ENOMEM)
7185 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
7186 else if (err == -ENOENT)
7187 rsp->hdr.Status = STATUS_FILE_CLOSED;
7189 rsp->hdr.Status = STATUS_LOCK_NOT_GRANTED;
7192 smb2_set_err_rsp(work);
7193 ksmbd_fd_put(work, fp);
7197 static int fsctl_copychunk(struct ksmbd_work *work,
7198 struct copychunk_ioctl_req *ci_req,
7199 unsigned int cnt_code,
7200 unsigned int input_count,
7201 unsigned long long volatile_id,
7202 unsigned long long persistent_id,
7203 struct smb2_ioctl_rsp *rsp)
7205 struct copychunk_ioctl_rsp *ci_rsp;
7206 struct ksmbd_file *src_fp = NULL, *dst_fp = NULL;
7207 struct srv_copychunk *chunks;
7208 unsigned int i, chunk_count, chunk_count_written = 0;
7209 unsigned int chunk_size_written = 0;
7210 loff_t total_size_written = 0;
7213 ci_rsp = (struct copychunk_ioctl_rsp *)&rsp->Buffer[0];
7215 rsp->VolatileFileId = volatile_id;
7216 rsp->PersistentFileId = persistent_id;
7217 ci_rsp->ChunksWritten =
7218 cpu_to_le32(ksmbd_server_side_copy_max_chunk_count());
7219 ci_rsp->ChunkBytesWritten =
7220 cpu_to_le32(ksmbd_server_side_copy_max_chunk_size());
7221 ci_rsp->TotalBytesWritten =
7222 cpu_to_le32(ksmbd_server_side_copy_max_total_size());
7224 chunks = (struct srv_copychunk *)&ci_req->Chunks[0];
7225 chunk_count = le32_to_cpu(ci_req->ChunkCount);
7226 if (chunk_count == 0)
7228 total_size_written = 0;
7230 /* verify the SRV_COPYCHUNK_COPY packet */
7231 if (chunk_count > ksmbd_server_side_copy_max_chunk_count() ||
7232 input_count < offsetof(struct copychunk_ioctl_req, Chunks) +
7233 chunk_count * sizeof(struct srv_copychunk)) {
7234 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7238 for (i = 0; i < chunk_count; i++) {
7239 if (le32_to_cpu(chunks[i].Length) == 0 ||
7240 le32_to_cpu(chunks[i].Length) > ksmbd_server_side_copy_max_chunk_size())
7242 total_size_written += le32_to_cpu(chunks[i].Length);
7245 if (i < chunk_count ||
7246 total_size_written > ksmbd_server_side_copy_max_total_size()) {
7247 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7251 src_fp = ksmbd_lookup_foreign_fd(work,
7252 le64_to_cpu(ci_req->ResumeKey[0]));
7253 dst_fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
7256 src_fp->persistent_id != le64_to_cpu(ci_req->ResumeKey[1])) {
7257 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
7262 rsp->hdr.Status = STATUS_FILE_CLOSED;
7267 * FILE_READ_DATA should only be included in
7268 * the FSCTL_COPYCHUNK case
7270 if (cnt_code == FSCTL_COPYCHUNK &&
7271 !(dst_fp->daccess & (FILE_READ_DATA_LE | FILE_GENERIC_READ_LE))) {
7272 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7276 ret = ksmbd_vfs_copy_file_ranges(work, src_fp, dst_fp,
7277 chunks, chunk_count,
7278 &chunk_count_written,
7279 &chunk_size_written,
7280 &total_size_written);
7283 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7285 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
7286 else if (ret == -EBADF)
7287 rsp->hdr.Status = STATUS_INVALID_HANDLE;
7288 else if (ret == -EFBIG || ret == -ENOSPC)
7289 rsp->hdr.Status = STATUS_DISK_FULL;
7290 else if (ret == -EINVAL)
7291 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7292 else if (ret == -EISDIR)
7293 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
7294 else if (ret == -E2BIG)
7295 rsp->hdr.Status = STATUS_INVALID_VIEW_SIZE;
7297 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
7300 ci_rsp->ChunksWritten = cpu_to_le32(chunk_count_written);
7301 ci_rsp->ChunkBytesWritten = cpu_to_le32(chunk_size_written);
7302 ci_rsp->TotalBytesWritten = cpu_to_le32(total_size_written);
7304 ksmbd_fd_put(work, src_fp);
7305 ksmbd_fd_put(work, dst_fp);
7309 static __be32 idev_ipv4_address(struct in_device *idev)
7313 struct in_ifaddr *ifa;
7316 in_dev_for_each_ifa_rcu(ifa, idev) {
7317 if (ifa->ifa_flags & IFA_F_SECONDARY)
7320 addr = ifa->ifa_address;
7327 static int fsctl_query_iface_info_ioctl(struct ksmbd_conn *conn,
7328 struct smb2_ioctl_rsp *rsp,
7329 unsigned int out_buf_len)
7331 struct network_interface_info_ioctl_rsp *nii_rsp = NULL;
7333 struct net_device *netdev;
7334 struct sockaddr_storage_rsp *sockaddr_storage;
7336 unsigned long long speed;
7339 for_each_netdev(&init_net, netdev) {
7340 bool ipv4_set = false;
7342 if (netdev->type == ARPHRD_LOOPBACK)
7345 flags = dev_get_flags(netdev);
7346 if (!(flags & IFF_RUNNING))
7350 nbytes + sizeof(struct network_interface_info_ioctl_rsp)) {
7355 nii_rsp = (struct network_interface_info_ioctl_rsp *)
7356 &rsp->Buffer[nbytes];
7357 nii_rsp->IfIndex = cpu_to_le32(netdev->ifindex);
7359 nii_rsp->Capability = 0;
7360 if (netdev->real_num_tx_queues > 1)
7361 nii_rsp->Capability |= cpu_to_le32(RSS_CAPABLE);
7362 if (ksmbd_rdma_capable_netdev(netdev))
7363 nii_rsp->Capability |= cpu_to_le32(RDMA_CAPABLE);
7365 nii_rsp->Next = cpu_to_le32(152);
7366 nii_rsp->Reserved = 0;
7368 if (netdev->ethtool_ops->get_link_ksettings) {
7369 struct ethtool_link_ksettings cmd;
7371 netdev->ethtool_ops->get_link_ksettings(netdev, &cmd);
7372 speed = cmd.base.speed;
7374 ksmbd_debug(SMB, "%s %s\n", netdev->name,
7375 "speed is unknown, defaulting to 1Gb/sec");
7380 nii_rsp->LinkSpeed = cpu_to_le64(speed);
7382 sockaddr_storage = (struct sockaddr_storage_rsp *)
7383 nii_rsp->SockAddr_Storage;
7384 memset(sockaddr_storage, 0, 128);
7387 struct in_device *idev;
7389 sockaddr_storage->Family = cpu_to_le16(INTERNETWORK);
7390 sockaddr_storage->addr4.Port = 0;
7392 idev = __in_dev_get_rtnl(netdev);
7395 sockaddr_storage->addr4.IPv4address =
7396 idev_ipv4_address(idev);
7397 nbytes += sizeof(struct network_interface_info_ioctl_rsp);
7401 struct inet6_dev *idev6;
7402 struct inet6_ifaddr *ifa;
7403 __u8 *ipv6_addr = sockaddr_storage->addr6.IPv6address;
7405 sockaddr_storage->Family = cpu_to_le16(INTERNETWORKV6);
7406 sockaddr_storage->addr6.Port = 0;
7407 sockaddr_storage->addr6.FlowInfo = 0;
7409 idev6 = __in6_dev_get(netdev);
7413 list_for_each_entry(ifa, &idev6->addr_list, if_list) {
7414 if (ifa->flags & (IFA_F_TENTATIVE |
7417 memcpy(ipv6_addr, ifa->addr.s6_addr, 16);
7420 sockaddr_storage->addr6.ScopeId = 0;
7421 nbytes += sizeof(struct network_interface_info_ioctl_rsp);
7426 /* zero if this is last one */
7430 rsp->PersistentFileId = SMB2_NO_FID;
7431 rsp->VolatileFileId = SMB2_NO_FID;
7435 static int fsctl_validate_negotiate_info(struct ksmbd_conn *conn,
7436 struct validate_negotiate_info_req *neg_req,
7437 struct validate_negotiate_info_rsp *neg_rsp,
7438 unsigned int in_buf_len)
7443 if (in_buf_len < offsetof(struct validate_negotiate_info_req, Dialects) +
7444 le16_to_cpu(neg_req->DialectCount) * sizeof(__le16))
7447 dialect = ksmbd_lookup_dialect_by_id(neg_req->Dialects,
7448 neg_req->DialectCount);
7449 if (dialect == BAD_PROT_ID || dialect != conn->dialect) {
7454 if (strncmp(neg_req->Guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE)) {
7459 if (le16_to_cpu(neg_req->SecurityMode) != conn->cli_sec_mode) {
7464 if (le32_to_cpu(neg_req->Capabilities) != conn->cli_cap) {
7469 neg_rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
7470 memset(neg_rsp->Guid, 0, SMB2_CLIENT_GUID_SIZE);
7471 neg_rsp->SecurityMode = cpu_to_le16(conn->srv_sec_mode);
7472 neg_rsp->Dialect = cpu_to_le16(conn->dialect);
7477 static int fsctl_query_allocated_ranges(struct ksmbd_work *work, u64 id,
7478 struct file_allocated_range_buffer *qar_req,
7479 struct file_allocated_range_buffer *qar_rsp,
7480 unsigned int in_count, unsigned int *out_count)
7482 struct ksmbd_file *fp;
7483 loff_t start, length;
7490 start = le64_to_cpu(qar_req->file_offset);
7491 length = le64_to_cpu(qar_req->length);
7493 if (start < 0 || length < 0)
7496 fp = ksmbd_lookup_fd_fast(work, id);
7500 ret = ksmbd_vfs_fqar_lseek(fp, start, length,
7501 qar_rsp, in_count, out_count);
7502 if (ret && ret != -E2BIG)
7505 ksmbd_fd_put(work, fp);
7509 static int fsctl_pipe_transceive(struct ksmbd_work *work, u64 id,
7510 unsigned int out_buf_len,
7511 struct smb2_ioctl_req *req,
7512 struct smb2_ioctl_rsp *rsp)
7514 struct ksmbd_rpc_command *rpc_resp;
7515 char *data_buf = (char *)&req->Buffer[0];
7518 rpc_resp = ksmbd_rpc_ioctl(work->sess, id, data_buf,
7519 le32_to_cpu(req->InputCount));
7521 if (rpc_resp->flags == KSMBD_RPC_SOME_NOT_MAPPED) {
7523 * set STATUS_SOME_NOT_MAPPED response
7524 * for unknown domain sid.
7526 rsp->hdr.Status = STATUS_SOME_NOT_MAPPED;
7527 } else if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
7528 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7530 } else if (rpc_resp->flags != KSMBD_RPC_OK) {
7531 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7535 nbytes = rpc_resp->payload_sz;
7536 if (rpc_resp->payload_sz > out_buf_len) {
7537 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
7538 nbytes = out_buf_len;
7541 if (!rpc_resp->payload_sz) {
7543 STATUS_UNEXPECTED_IO_ERROR;
7547 memcpy((char *)rsp->Buffer, rpc_resp->payload, nbytes);
7554 static inline int fsctl_set_sparse(struct ksmbd_work *work, u64 id,
7555 struct file_sparse *sparse)
7557 struct ksmbd_file *fp;
7558 struct mnt_idmap *idmap;
7562 fp = ksmbd_lookup_fd_fast(work, id);
7565 idmap = file_mnt_idmap(fp->filp);
7567 old_fattr = fp->f_ci->m_fattr;
7568 if (sparse->SetSparse)
7569 fp->f_ci->m_fattr |= FILE_ATTRIBUTE_SPARSE_FILE_LE;
7571 fp->f_ci->m_fattr &= ~FILE_ATTRIBUTE_SPARSE_FILE_LE;
7573 if (fp->f_ci->m_fattr != old_fattr &&
7574 test_share_config_flag(work->tcon->share_conf,
7575 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS)) {
7576 struct xattr_dos_attrib da;
7578 ret = ksmbd_vfs_get_dos_attrib_xattr(idmap,
7579 fp->filp->f_path.dentry, &da);
7583 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
7584 ret = ksmbd_vfs_set_dos_attrib_xattr(idmap,
7585 &fp->filp->f_path, &da);
7587 fp->f_ci->m_fattr = old_fattr;
7591 ksmbd_fd_put(work, fp);
7595 static int fsctl_request_resume_key(struct ksmbd_work *work,
7596 struct smb2_ioctl_req *req,
7597 struct resume_key_ioctl_rsp *key_rsp)
7599 struct ksmbd_file *fp;
7601 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
7605 memset(key_rsp, 0, sizeof(*key_rsp));
7606 key_rsp->ResumeKey[0] = req->VolatileFileId;
7607 key_rsp->ResumeKey[1] = req->PersistentFileId;
7608 ksmbd_fd_put(work, fp);
7614 * smb2_ioctl() - handler for smb2 ioctl command
7615 * @work: smb work containing ioctl command buffer
7617 * Return: 0 on success, otherwise error
7619 int smb2_ioctl(struct ksmbd_work *work)
7621 struct smb2_ioctl_req *req;
7622 struct smb2_ioctl_rsp *rsp;
7623 unsigned int cnt_code, nbytes = 0, out_buf_len, in_buf_len;
7624 u64 id = KSMBD_NO_FID;
7625 struct ksmbd_conn *conn = work->conn;
7628 if (work->next_smb2_rcv_hdr_off) {
7629 req = ksmbd_req_buf_next(work);
7630 rsp = ksmbd_resp_buf_next(work);
7631 if (!has_file_id(req->VolatileFileId)) {
7632 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
7633 work->compound_fid);
7634 id = work->compound_fid;
7637 req = smb2_get_msg(work->request_buf);
7638 rsp = smb2_get_msg(work->response_buf);
7641 if (!has_file_id(id))
7642 id = req->VolatileFileId;
7644 if (req->Flags != cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL)) {
7645 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7649 cnt_code = le32_to_cpu(req->CtlCode);
7650 ret = smb2_calc_max_out_buf_len(work, 48,
7651 le32_to_cpu(req->MaxOutputResponse));
7653 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7656 out_buf_len = (unsigned int)ret;
7657 in_buf_len = le32_to_cpu(req->InputCount);
7660 case FSCTL_DFS_GET_REFERRALS:
7661 case FSCTL_DFS_GET_REFERRALS_EX:
7662 /* Not support DFS yet */
7663 rsp->hdr.Status = STATUS_FS_DRIVER_REQUIRED;
7665 case FSCTL_CREATE_OR_GET_OBJECT_ID:
7667 struct file_object_buf_type1_ioctl_rsp *obj_buf;
7669 nbytes = sizeof(struct file_object_buf_type1_ioctl_rsp);
7670 obj_buf = (struct file_object_buf_type1_ioctl_rsp *)
7674 * TODO: This is dummy implementation to pass smbtorture
7675 * Need to check correct response later
7677 memset(obj_buf->ObjectId, 0x0, 16);
7678 memset(obj_buf->BirthVolumeId, 0x0, 16);
7679 memset(obj_buf->BirthObjectId, 0x0, 16);
7680 memset(obj_buf->DomainId, 0x0, 16);
7684 case FSCTL_PIPE_TRANSCEIVE:
7685 out_buf_len = min_t(u32, KSMBD_IPC_MAX_PAYLOAD, out_buf_len);
7686 nbytes = fsctl_pipe_transceive(work, id, out_buf_len, req, rsp);
7688 case FSCTL_VALIDATE_NEGOTIATE_INFO:
7689 if (conn->dialect < SMB30_PROT_ID) {
7694 if (in_buf_len < offsetof(struct validate_negotiate_info_req,
7700 if (out_buf_len < sizeof(struct validate_negotiate_info_rsp)) {
7705 ret = fsctl_validate_negotiate_info(conn,
7706 (struct validate_negotiate_info_req *)&req->Buffer[0],
7707 (struct validate_negotiate_info_rsp *)&rsp->Buffer[0],
7712 nbytes = sizeof(struct validate_negotiate_info_rsp);
7713 rsp->PersistentFileId = SMB2_NO_FID;
7714 rsp->VolatileFileId = SMB2_NO_FID;
7716 case FSCTL_QUERY_NETWORK_INTERFACE_INFO:
7717 ret = fsctl_query_iface_info_ioctl(conn, rsp, out_buf_len);
7722 case FSCTL_REQUEST_RESUME_KEY:
7723 if (out_buf_len < sizeof(struct resume_key_ioctl_rsp)) {
7728 ret = fsctl_request_resume_key(work, req,
7729 (struct resume_key_ioctl_rsp *)&rsp->Buffer[0]);
7732 rsp->PersistentFileId = req->PersistentFileId;
7733 rsp->VolatileFileId = req->VolatileFileId;
7734 nbytes = sizeof(struct resume_key_ioctl_rsp);
7736 case FSCTL_COPYCHUNK:
7737 case FSCTL_COPYCHUNK_WRITE:
7738 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7740 "User does not have write permission\n");
7745 if (in_buf_len < sizeof(struct copychunk_ioctl_req)) {
7750 if (out_buf_len < sizeof(struct copychunk_ioctl_rsp)) {
7755 nbytes = sizeof(struct copychunk_ioctl_rsp);
7756 rsp->VolatileFileId = req->VolatileFileId;
7757 rsp->PersistentFileId = req->PersistentFileId;
7758 fsctl_copychunk(work,
7759 (struct copychunk_ioctl_req *)&req->Buffer[0],
7760 le32_to_cpu(req->CtlCode),
7761 le32_to_cpu(req->InputCount),
7762 req->VolatileFileId,
7763 req->PersistentFileId,
7766 case FSCTL_SET_SPARSE:
7767 if (in_buf_len < sizeof(struct file_sparse)) {
7772 ret = fsctl_set_sparse(work, id,
7773 (struct file_sparse *)&req->Buffer[0]);
7777 case FSCTL_SET_ZERO_DATA:
7779 struct file_zero_data_information *zero_data;
7780 struct ksmbd_file *fp;
7781 loff_t off, len, bfz;
7783 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7785 "User does not have write permission\n");
7790 if (in_buf_len < sizeof(struct file_zero_data_information)) {
7796 (struct file_zero_data_information *)&req->Buffer[0];
7798 off = le64_to_cpu(zero_data->FileOffset);
7799 bfz = le64_to_cpu(zero_data->BeyondFinalZero);
7800 if (off < 0 || bfz < 0 || off > bfz) {
7807 fp = ksmbd_lookup_fd_fast(work, id);
7813 ret = ksmbd_vfs_zero_data(work, fp, off, len);
7814 ksmbd_fd_put(work, fp);
7820 case FSCTL_QUERY_ALLOCATED_RANGES:
7821 if (in_buf_len < sizeof(struct file_allocated_range_buffer)) {
7826 ret = fsctl_query_allocated_ranges(work, id,
7827 (struct file_allocated_range_buffer *)&req->Buffer[0],
7828 (struct file_allocated_range_buffer *)&rsp->Buffer[0],
7830 sizeof(struct file_allocated_range_buffer), &nbytes);
7831 if (ret == -E2BIG) {
7832 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
7833 } else if (ret < 0) {
7838 nbytes *= sizeof(struct file_allocated_range_buffer);
7840 case FSCTL_GET_REPARSE_POINT:
7842 struct reparse_data_buffer *reparse_ptr;
7843 struct ksmbd_file *fp;
7845 reparse_ptr = (struct reparse_data_buffer *)&rsp->Buffer[0];
7846 fp = ksmbd_lookup_fd_fast(work, id);
7848 pr_err("not found fp!!\n");
7853 reparse_ptr->ReparseTag =
7854 smb2_get_reparse_tag_special_file(file_inode(fp->filp)->i_mode);
7855 reparse_ptr->ReparseDataLength = 0;
7856 ksmbd_fd_put(work, fp);
7857 nbytes = sizeof(struct reparse_data_buffer);
7860 case FSCTL_DUPLICATE_EXTENTS_TO_FILE:
7862 struct ksmbd_file *fp_in, *fp_out = NULL;
7863 struct duplicate_extents_to_file *dup_ext;
7864 loff_t src_off, dst_off, length, cloned;
7866 if (in_buf_len < sizeof(struct duplicate_extents_to_file)) {
7871 dup_ext = (struct duplicate_extents_to_file *)&req->Buffer[0];
7873 fp_in = ksmbd_lookup_fd_slow(work, dup_ext->VolatileFileHandle,
7874 dup_ext->PersistentFileHandle);
7876 pr_err("not found file handle in duplicate extent to file\n");
7881 fp_out = ksmbd_lookup_fd_fast(work, id);
7883 pr_err("not found fp\n");
7888 src_off = le64_to_cpu(dup_ext->SourceFileOffset);
7889 dst_off = le64_to_cpu(dup_ext->TargetFileOffset);
7890 length = le64_to_cpu(dup_ext->ByteCount);
7892 * XXX: It is not clear if FSCTL_DUPLICATE_EXTENTS_TO_FILE
7893 * should fall back to vfs_copy_file_range(). This could be
7894 * beneficial when re-exporting nfs/smb mount, but note that
7895 * this can result in partial copy that returns an error status.
7896 * If/when FSCTL_DUPLICATE_EXTENTS_TO_FILE_EX is implemented,
7897 * fall back to vfs_copy_file_range(), should be avoided when
7898 * the flag DUPLICATE_EXTENTS_DATA_EX_SOURCE_ATOMIC is set.
7900 cloned = vfs_clone_file_range(fp_in->filp, src_off,
7901 fp_out->filp, dst_off, length, 0);
7902 if (cloned == -EXDEV || cloned == -EOPNOTSUPP) {
7905 } else if (cloned != length) {
7906 cloned = vfs_copy_file_range(fp_in->filp, src_off,
7907 fp_out->filp, dst_off,
7909 if (cloned != length) {
7918 ksmbd_fd_put(work, fp_in);
7919 ksmbd_fd_put(work, fp_out);
7925 ksmbd_debug(SMB, "not implemented yet ioctl command 0x%x\n",
7931 rsp->CtlCode = cpu_to_le32(cnt_code);
7932 rsp->InputCount = cpu_to_le32(0);
7933 rsp->InputOffset = cpu_to_le32(112);
7934 rsp->OutputOffset = cpu_to_le32(112);
7935 rsp->OutputCount = cpu_to_le32(nbytes);
7936 rsp->StructureSize = cpu_to_le16(49);
7937 rsp->Reserved = cpu_to_le16(0);
7938 rsp->Flags = cpu_to_le32(0);
7939 rsp->Reserved2 = cpu_to_le32(0);
7940 ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_ioctl_rsp) + nbytes);
7946 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7947 else if (ret == -ENOENT)
7948 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
7949 else if (ret == -EOPNOTSUPP)
7950 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7951 else if (ret == -ENOSPC)
7952 rsp->hdr.Status = STATUS_BUFFER_TOO_SMALL;
7953 else if (ret < 0 || rsp->hdr.Status == 0)
7954 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7955 smb2_set_err_rsp(work);
7960 * smb20_oplock_break_ack() - handler for smb2.0 oplock break command
7961 * @work: smb work containing oplock break command buffer
7965 static void smb20_oplock_break_ack(struct ksmbd_work *work)
7967 struct smb2_oplock_break *req;
7968 struct smb2_oplock_break *rsp;
7969 struct ksmbd_file *fp;
7970 struct oplock_info *opinfo = NULL;
7973 u64 volatile_id, persistent_id;
7974 char req_oplevel = 0, rsp_oplevel = 0;
7975 unsigned int oplock_change_type;
7977 WORK_BUFFERS(work, req, rsp);
7979 volatile_id = req->VolatileFid;
7980 persistent_id = req->PersistentFid;
7981 req_oplevel = req->OplockLevel;
7982 ksmbd_debug(OPLOCK, "v_id %llu, p_id %llu request oplock level %d\n",
7983 volatile_id, persistent_id, req_oplevel);
7985 fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
7987 rsp->hdr.Status = STATUS_FILE_CLOSED;
7988 smb2_set_err_rsp(work);
7992 opinfo = opinfo_get(fp);
7994 pr_err("unexpected null oplock_info\n");
7995 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
7996 smb2_set_err_rsp(work);
7997 ksmbd_fd_put(work, fp);
8001 if (opinfo->level == SMB2_OPLOCK_LEVEL_NONE) {
8002 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
8006 if (opinfo->op_state == OPLOCK_STATE_NONE) {
8007 ksmbd_debug(SMB, "unexpected oplock state 0x%x\n", opinfo->op_state);
8008 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8012 if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
8013 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
8014 (req_oplevel != SMB2_OPLOCK_LEVEL_II &&
8015 req_oplevel != SMB2_OPLOCK_LEVEL_NONE)) {
8016 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8017 oplock_change_type = OPLOCK_WRITE_TO_NONE;
8018 } else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
8019 req_oplevel != SMB2_OPLOCK_LEVEL_NONE) {
8020 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8021 oplock_change_type = OPLOCK_READ_TO_NONE;
8022 } else if (req_oplevel == SMB2_OPLOCK_LEVEL_II ||
8023 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
8024 err = STATUS_INVALID_DEVICE_STATE;
8025 if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
8026 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
8027 req_oplevel == SMB2_OPLOCK_LEVEL_II) {
8028 oplock_change_type = OPLOCK_WRITE_TO_READ;
8029 } else if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
8030 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
8031 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
8032 oplock_change_type = OPLOCK_WRITE_TO_NONE;
8033 } else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
8034 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
8035 oplock_change_type = OPLOCK_READ_TO_NONE;
8037 oplock_change_type = 0;
8040 oplock_change_type = 0;
8043 switch (oplock_change_type) {
8044 case OPLOCK_WRITE_TO_READ:
8045 ret = opinfo_write_to_read(opinfo);
8046 rsp_oplevel = SMB2_OPLOCK_LEVEL_II;
8048 case OPLOCK_WRITE_TO_NONE:
8049 ret = opinfo_write_to_none(opinfo);
8050 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
8052 case OPLOCK_READ_TO_NONE:
8053 ret = opinfo_read_to_none(opinfo);
8054 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
8057 pr_err("unknown oplock change 0x%x -> 0x%x\n",
8058 opinfo->level, rsp_oplevel);
8062 rsp->hdr.Status = err;
8066 opinfo->op_state = OPLOCK_STATE_NONE;
8067 wake_up_interruptible_all(&opinfo->oplock_q);
8069 ksmbd_fd_put(work, fp);
8071 rsp->StructureSize = cpu_to_le16(24);
8072 rsp->OplockLevel = rsp_oplevel;
8075 rsp->VolatileFid = volatile_id;
8076 rsp->PersistentFid = persistent_id;
8077 ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_oplock_break));
8082 opinfo->op_state = OPLOCK_STATE_NONE;
8083 wake_up_interruptible_all(&opinfo->oplock_q);
8086 ksmbd_fd_put(work, fp);
8087 smb2_set_err_rsp(work);
8090 static int check_lease_state(struct lease *lease, __le32 req_state)
8092 if ((lease->new_state ==
8093 (SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE)) &&
8094 !(req_state & SMB2_LEASE_WRITE_CACHING_LE)) {
8095 lease->new_state = req_state;
8099 if (lease->new_state == req_state)
8106 * smb21_lease_break_ack() - handler for smb2.1 lease break command
8107 * @work: smb work containing lease break command buffer
8111 static void smb21_lease_break_ack(struct ksmbd_work *work)
8113 struct ksmbd_conn *conn = work->conn;
8114 struct smb2_lease_ack *req;
8115 struct smb2_lease_ack *rsp;
8116 struct oplock_info *opinfo;
8119 unsigned int lease_change_type;
8121 struct lease *lease;
8123 WORK_BUFFERS(work, req, rsp);
8125 ksmbd_debug(OPLOCK, "smb21 lease break, lease state(0x%x)\n",
8126 le32_to_cpu(req->LeaseState));
8127 opinfo = lookup_lease_in_table(conn, req->LeaseKey);
8129 ksmbd_debug(OPLOCK, "file not opened\n");
8130 smb2_set_err_rsp(work);
8131 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8134 lease = opinfo->o_lease;
8136 if (opinfo->op_state == OPLOCK_STATE_NONE) {
8137 pr_err("unexpected lease break state 0x%x\n",
8139 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8143 if (check_lease_state(lease, req->LeaseState)) {
8144 rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
8146 "req lease state: 0x%x, expected state: 0x%x\n",
8147 req->LeaseState, lease->new_state);
8151 if (!atomic_read(&opinfo->breaking_cnt)) {
8152 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8156 /* check for bad lease state */
8157 if (req->LeaseState &
8158 (~(SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE))) {
8159 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8160 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8161 lease_change_type = OPLOCK_WRITE_TO_NONE;
8163 lease_change_type = OPLOCK_READ_TO_NONE;
8164 ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8165 le32_to_cpu(lease->state),
8166 le32_to_cpu(req->LeaseState));
8167 } else if (lease->state == SMB2_LEASE_READ_CACHING_LE &&
8168 req->LeaseState != SMB2_LEASE_NONE_LE) {
8169 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8170 lease_change_type = OPLOCK_READ_TO_NONE;
8171 ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8172 le32_to_cpu(lease->state),
8173 le32_to_cpu(req->LeaseState));
8175 /* valid lease state changes */
8176 err = STATUS_INVALID_DEVICE_STATE;
8177 if (req->LeaseState == SMB2_LEASE_NONE_LE) {
8178 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8179 lease_change_type = OPLOCK_WRITE_TO_NONE;
8181 lease_change_type = OPLOCK_READ_TO_NONE;
8182 } else if (req->LeaseState & SMB2_LEASE_READ_CACHING_LE) {
8183 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8184 lease_change_type = OPLOCK_WRITE_TO_READ;
8186 lease_change_type = OPLOCK_READ_HANDLE_TO_READ;
8188 lease_change_type = 0;
8192 switch (lease_change_type) {
8193 case OPLOCK_WRITE_TO_READ:
8194 ret = opinfo_write_to_read(opinfo);
8196 case OPLOCK_READ_HANDLE_TO_READ:
8197 ret = opinfo_read_handle_to_read(opinfo);
8199 case OPLOCK_WRITE_TO_NONE:
8200 ret = opinfo_write_to_none(opinfo);
8202 case OPLOCK_READ_TO_NONE:
8203 ret = opinfo_read_to_none(opinfo);
8206 ksmbd_debug(OPLOCK, "unknown lease change 0x%x -> 0x%x\n",
8207 le32_to_cpu(lease->state),
8208 le32_to_cpu(req->LeaseState));
8211 lease_state = lease->state;
8212 opinfo->op_state = OPLOCK_STATE_NONE;
8213 wake_up_interruptible_all(&opinfo->oplock_q);
8214 atomic_dec(&opinfo->breaking_cnt);
8215 wake_up_interruptible_all(&opinfo->oplock_brk);
8219 rsp->hdr.Status = err;
8223 rsp->StructureSize = cpu_to_le16(36);
8226 memcpy(rsp->LeaseKey, req->LeaseKey, 16);
8227 rsp->LeaseState = lease_state;
8228 rsp->LeaseDuration = 0;
8229 ret = ksmbd_iov_pin_rsp(work, rsp, sizeof(struct smb2_lease_ack));
8234 opinfo->op_state = OPLOCK_STATE_NONE;
8235 wake_up_interruptible_all(&opinfo->oplock_q);
8236 atomic_dec(&opinfo->breaking_cnt);
8237 wake_up_interruptible_all(&opinfo->oplock_brk);
8240 smb2_set_err_rsp(work);
8244 * smb2_oplock_break() - dispatcher for smb2.0 and 2.1 oplock/lease break
8245 * @work: smb work containing oplock/lease break command buffer
8249 int smb2_oplock_break(struct ksmbd_work *work)
8251 struct smb2_oplock_break *req;
8252 struct smb2_oplock_break *rsp;
8254 WORK_BUFFERS(work, req, rsp);
8256 switch (le16_to_cpu(req->StructureSize)) {
8257 case OP_BREAK_STRUCT_SIZE_20:
8258 smb20_oplock_break_ack(work);
8260 case OP_BREAK_STRUCT_SIZE_21:
8261 smb21_lease_break_ack(work);
8264 ksmbd_debug(OPLOCK, "invalid break cmd %d\n",
8265 le16_to_cpu(req->StructureSize));
8266 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8267 smb2_set_err_rsp(work);
8274 * smb2_notify() - handler for smb2 notify request
8275 * @work: smb work containing notify command buffer
8279 int smb2_notify(struct ksmbd_work *work)
8281 struct smb2_change_notify_req *req;
8282 struct smb2_change_notify_rsp *rsp;
8284 WORK_BUFFERS(work, req, rsp);
8286 if (work->next_smb2_rcv_hdr_off && req->hdr.NextCommand) {
8287 rsp->hdr.Status = STATUS_INTERNAL_ERROR;
8288 smb2_set_err_rsp(work);
8292 smb2_set_err_rsp(work);
8293 rsp->hdr.Status = STATUS_NOT_IMPLEMENTED;
8298 * smb2_is_sign_req() - handler for checking packet signing status
8299 * @work: smb work containing notify command buffer
8300 * @command: SMB2 command id
8302 * Return: true if packed is signed, false otherwise
8304 bool smb2_is_sign_req(struct ksmbd_work *work, unsigned int command)
8306 struct smb2_hdr *rcv_hdr2 = smb2_get_msg(work->request_buf);
8308 if ((rcv_hdr2->Flags & SMB2_FLAGS_SIGNED) &&
8309 command != SMB2_NEGOTIATE_HE &&
8310 command != SMB2_SESSION_SETUP_HE &&
8311 command != SMB2_OPLOCK_BREAK_HE)
8318 * smb2_check_sign_req() - handler for req packet sign processing
8319 * @work: smb work containing notify command buffer
8321 * Return: 1 on success, 0 otherwise
8323 int smb2_check_sign_req(struct ksmbd_work *work)
8325 struct smb2_hdr *hdr;
8326 char signature_req[SMB2_SIGNATURE_SIZE];
8327 char signature[SMB2_HMACSHA256_SIZE];
8331 hdr = smb2_get_msg(work->request_buf);
8332 if (work->next_smb2_rcv_hdr_off)
8333 hdr = ksmbd_req_buf_next(work);
8335 if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8336 len = get_rfc1002_len(work->request_buf);
8337 else if (hdr->NextCommand)
8338 len = le32_to_cpu(hdr->NextCommand);
8340 len = get_rfc1002_len(work->request_buf) -
8341 work->next_smb2_rcv_hdr_off;
8343 memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8344 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8346 iov[0].iov_base = (char *)&hdr->ProtocolId;
8347 iov[0].iov_len = len;
8349 if (ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, 1,
8353 if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8354 pr_err("bad smb2 signature\n");
8362 * smb2_set_sign_rsp() - handler for rsp packet sign processing
8363 * @work: smb work containing notify command buffer
8366 void smb2_set_sign_rsp(struct ksmbd_work *work)
8368 struct smb2_hdr *hdr;
8369 char signature[SMB2_HMACSHA256_SIZE];
8373 hdr = ksmbd_resp_buf_curr(work);
8374 hdr->Flags |= SMB2_FLAGS_SIGNED;
8375 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8377 if (hdr->Command == SMB2_READ) {
8378 iov = &work->iov[work->iov_idx - 1];
8381 iov = &work->iov[work->iov_idx];
8384 if (!ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, n_vec,
8386 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
8390 * smb3_check_sign_req() - handler for req packet sign processing
8391 * @work: smb work containing notify command buffer
8393 * Return: 1 on success, 0 otherwise
8395 int smb3_check_sign_req(struct ksmbd_work *work)
8397 struct ksmbd_conn *conn = work->conn;
8399 struct smb2_hdr *hdr;
8400 struct channel *chann;
8401 char signature_req[SMB2_SIGNATURE_SIZE];
8402 char signature[SMB2_CMACAES_SIZE];
8406 hdr = smb2_get_msg(work->request_buf);
8407 if (work->next_smb2_rcv_hdr_off)
8408 hdr = ksmbd_req_buf_next(work);
8410 if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8411 len = get_rfc1002_len(work->request_buf);
8412 else if (hdr->NextCommand)
8413 len = le32_to_cpu(hdr->NextCommand);
8415 len = get_rfc1002_len(work->request_buf) -
8416 work->next_smb2_rcv_hdr_off;
8418 if (le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8419 signing_key = work->sess->smb3signingkey;
8421 chann = lookup_chann_list(work->sess, conn);
8425 signing_key = chann->smb3signingkey;
8429 pr_err("SMB3 signing key is not generated\n");
8433 memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8434 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8435 iov[0].iov_base = (char *)&hdr->ProtocolId;
8436 iov[0].iov_len = len;
8438 if (ksmbd_sign_smb3_pdu(conn, signing_key, iov, 1, signature))
8441 if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8442 pr_err("bad smb2 signature\n");
8450 * smb3_set_sign_rsp() - handler for rsp packet sign processing
8451 * @work: smb work containing notify command buffer
8454 void smb3_set_sign_rsp(struct ksmbd_work *work)
8456 struct ksmbd_conn *conn = work->conn;
8457 struct smb2_hdr *hdr;
8458 struct channel *chann;
8459 char signature[SMB2_CMACAES_SIZE];
8464 hdr = ksmbd_resp_buf_curr(work);
8466 if (conn->binding == false &&
8467 le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8468 signing_key = work->sess->smb3signingkey;
8470 chann = lookup_chann_list(work->sess, work->conn);
8474 signing_key = chann->smb3signingkey;
8480 hdr->Flags |= SMB2_FLAGS_SIGNED;
8481 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8483 if (hdr->Command == SMB2_READ) {
8484 iov = &work->iov[work->iov_idx - 1];
8487 iov = &work->iov[work->iov_idx];
8490 if (!ksmbd_sign_smb3_pdu(conn, signing_key, iov, n_vec,
8492 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
8496 * smb3_preauth_hash_rsp() - handler for computing preauth hash on response
8497 * @work: smb work containing response buffer
8500 void smb3_preauth_hash_rsp(struct ksmbd_work *work)
8502 struct ksmbd_conn *conn = work->conn;
8503 struct ksmbd_session *sess = work->sess;
8504 struct smb2_hdr *req, *rsp;
8506 if (conn->dialect != SMB311_PROT_ID)
8509 WORK_BUFFERS(work, req, rsp);
8511 if (le16_to_cpu(req->Command) == SMB2_NEGOTIATE_HE &&
8513 ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
8514 conn->preauth_info->Preauth_HashValue);
8516 if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE && sess) {
8519 if (conn->binding) {
8520 struct preauth_session *preauth_sess;
8522 preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
8525 hash_value = preauth_sess->Preauth_HashValue;
8527 hash_value = sess->Preauth_HashValue;
8531 ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
8536 static void fill_transform_hdr(void *tr_buf, char *old_buf, __le16 cipher_type)
8538 struct smb2_transform_hdr *tr_hdr = tr_buf + 4;
8539 struct smb2_hdr *hdr = smb2_get_msg(old_buf);
8540 unsigned int orig_len = get_rfc1002_len(old_buf);
8542 /* tr_buf must be cleared by the caller */
8543 tr_hdr->ProtocolId = SMB2_TRANSFORM_PROTO_NUM;
8544 tr_hdr->OriginalMessageSize = cpu_to_le32(orig_len);
8545 tr_hdr->Flags = cpu_to_le16(TRANSFORM_FLAG_ENCRYPTED);
8546 if (cipher_type == SMB2_ENCRYPTION_AES128_GCM ||
8547 cipher_type == SMB2_ENCRYPTION_AES256_GCM)
8548 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_GCM_NONCE);
8550 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_CCM_NONCE);
8551 memcpy(&tr_hdr->SessionId, &hdr->SessionId, 8);
8552 inc_rfc1001_len(tr_buf, sizeof(struct smb2_transform_hdr));
8553 inc_rfc1001_len(tr_buf, orig_len);
8556 int smb3_encrypt_resp(struct ksmbd_work *work)
8558 struct kvec *iov = work->iov;
8562 tr_buf = kzalloc(sizeof(struct smb2_transform_hdr) + 4, GFP_KERNEL);
8566 /* fill transform header */
8567 fill_transform_hdr(tr_buf, work->response_buf, work->conn->cipher_type);
8569 iov[0].iov_base = tr_buf;
8570 iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
8571 work->tr_buf = tr_buf;
8573 return ksmbd_crypt_message(work, iov, work->iov_idx + 1, 1);
8576 bool smb3_is_transform_hdr(void *buf)
8578 struct smb2_transform_hdr *trhdr = smb2_get_msg(buf);
8580 return trhdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM;
8583 int smb3_decrypt_req(struct ksmbd_work *work)
8585 struct ksmbd_session *sess;
8586 char *buf = work->request_buf;
8587 unsigned int pdu_length = get_rfc1002_len(buf);
8589 int buf_data_size = pdu_length - sizeof(struct smb2_transform_hdr);
8590 struct smb2_transform_hdr *tr_hdr = smb2_get_msg(buf);
8593 if (pdu_length < sizeof(struct smb2_transform_hdr) ||
8594 buf_data_size < sizeof(struct smb2_hdr)) {
8595 pr_err("Transform message is too small (%u)\n",
8597 return -ECONNABORTED;
8600 if (buf_data_size < le32_to_cpu(tr_hdr->OriginalMessageSize)) {
8601 pr_err("Transform message is broken\n");
8602 return -ECONNABORTED;
8605 sess = ksmbd_session_lookup_all(work->conn, le64_to_cpu(tr_hdr->SessionId));
8607 pr_err("invalid session id(%llx) in transform header\n",
8608 le64_to_cpu(tr_hdr->SessionId));
8609 return -ECONNABORTED;
8612 iov[0].iov_base = buf;
8613 iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
8614 iov[1].iov_base = buf + sizeof(struct smb2_transform_hdr) + 4;
8615 iov[1].iov_len = buf_data_size;
8616 rc = ksmbd_crypt_message(work, iov, 2, 0);
8620 memmove(buf + 4, iov[1].iov_base, buf_data_size);
8621 *(__be32 *)buf = cpu_to_be32(buf_data_size);
8626 bool smb3_11_final_sess_setup_resp(struct ksmbd_work *work)
8628 struct ksmbd_conn *conn = work->conn;
8629 struct ksmbd_session *sess = work->sess;
8630 struct smb2_hdr *rsp = smb2_get_msg(work->response_buf);
8632 if (conn->dialect < SMB30_PROT_ID)
8635 if (work->next_smb2_rcv_hdr_off)
8636 rsp = ksmbd_resp_buf_next(work);
8638 if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE &&
8639 sess->user && !user_guest(sess->user) &&
8640 rsp->Status == STATUS_SUCCESS)