1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * Copyright (C) 2016 Namjae Jeon <linkinjeon@kernel.org>
4 * Copyright (C) 2018 Samsung Electronics Co., Ltd.
7 #include <linux/inetdevice.h>
8 #include <net/addrconf.h>
9 #include <linux/syscalls.h>
10 #include <linux/namei.h>
11 #include <linux/statfs.h>
12 #include <linux/ethtool.h>
13 #include <linux/falloc.h>
14 #include <linux/mount.h>
23 #include "connection.h"
24 #include "transport_ipc.h"
25 #include "transport_rdma.h"
27 #include "vfs_cache.h"
31 #include "smb_common.h"
32 #include "smbstatus.h"
33 #include "ksmbd_work.h"
34 #include "mgmt/user_config.h"
35 #include "mgmt/share_config.h"
36 #include "mgmt/tree_connect.h"
37 #include "mgmt/user_session.h"
38 #include "mgmt/ksmbd_ida.h"
41 static void __wbuf(struct ksmbd_work *work, void **req, void **rsp)
43 if (work->next_smb2_rcv_hdr_off) {
44 *req = ksmbd_req_buf_next(work);
45 *rsp = ksmbd_resp_buf_next(work);
47 *req = smb2_get_msg(work->request_buf);
48 *rsp = smb2_get_msg(work->response_buf);
52 #define WORK_BUFFERS(w, rq, rs) __wbuf((w), (void **)&(rq), (void **)&(rs))
55 * check_session_id() - check for valid session id in smb header
56 * @conn: connection instance
57 * @id: session id from smb header
59 * Return: 1 if valid session id, otherwise 0
61 static inline bool check_session_id(struct ksmbd_conn *conn, u64 id)
63 struct ksmbd_session *sess;
65 if (id == 0 || id == -1)
68 sess = ksmbd_session_lookup_all(conn, id);
71 pr_err("Invalid user session id: %llu\n", id);
75 struct channel *lookup_chann_list(struct ksmbd_session *sess, struct ksmbd_conn *conn)
77 return xa_load(&sess->ksmbd_chann_list, (long)conn);
81 * smb2_get_ksmbd_tcon() - get tree connection information using a tree id.
84 * Return: 0 if there is a tree connection matched or these are
85 * skipable commands, otherwise error
87 int smb2_get_ksmbd_tcon(struct ksmbd_work *work)
89 struct smb2_hdr *req_hdr = smb2_get_msg(work->request_buf);
90 unsigned int cmd = le16_to_cpu(req_hdr->Command);
93 if (cmd == SMB2_TREE_CONNECT_HE ||
94 cmd == SMB2_CANCEL_HE ||
95 cmd == SMB2_LOGOFF_HE) {
96 ksmbd_debug(SMB, "skip to check tree connect request\n");
100 if (xa_empty(&work->sess->tree_conns)) {
101 ksmbd_debug(SMB, "NO tree connected\n");
105 tree_id = le32_to_cpu(req_hdr->Id.SyncId.TreeId);
108 * If request is not the first in Compound request,
109 * Just validate tree id in header with work->tcon->id.
111 if (work->next_smb2_rcv_hdr_off) {
113 pr_err("The first operation in the compound does not have tcon\n");
116 if (work->tcon->id != tree_id) {
117 pr_err("tree id(%u) is different with id(%u) in first operation\n",
118 tree_id, work->tcon->id);
124 work->tcon = ksmbd_tree_conn_lookup(work->sess, tree_id);
126 pr_err("Invalid tid %d\n", tree_id);
134 * smb2_set_err_rsp() - set error response code on smb response
135 * @work: smb work containing response buffer
137 void smb2_set_err_rsp(struct ksmbd_work *work)
139 struct smb2_err_rsp *err_rsp;
141 if (work->next_smb2_rcv_hdr_off)
142 err_rsp = ksmbd_resp_buf_next(work);
144 err_rsp = smb2_get_msg(work->response_buf);
146 if (err_rsp->hdr.Status != STATUS_STOPPED_ON_SYMLINK) {
147 err_rsp->StructureSize = SMB2_ERROR_STRUCTURE_SIZE2_LE;
148 err_rsp->ErrorContextCount = 0;
149 err_rsp->Reserved = 0;
150 err_rsp->ByteCount = 0;
151 err_rsp->ErrorData[0] = 0;
152 inc_rfc1001_len(work->response_buf, SMB2_ERROR_STRUCTURE_SIZE2);
157 * is_smb2_neg_cmd() - is it smb2 negotiation command
158 * @work: smb work containing smb header
160 * Return: true if smb2 negotiation command, otherwise false
162 bool is_smb2_neg_cmd(struct ksmbd_work *work)
164 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
166 /* is it SMB2 header ? */
167 if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
170 /* make sure it is request not response message */
171 if (hdr->Flags & SMB2_FLAGS_SERVER_TO_REDIR)
174 if (hdr->Command != SMB2_NEGOTIATE)
181 * is_smb2_rsp() - is it smb2 response
182 * @work: smb work containing smb response buffer
184 * Return: true if smb2 response, otherwise false
186 bool is_smb2_rsp(struct ksmbd_work *work)
188 struct smb2_hdr *hdr = smb2_get_msg(work->response_buf);
190 /* is it SMB2 header ? */
191 if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
194 /* make sure it is response not request message */
195 if (!(hdr->Flags & SMB2_FLAGS_SERVER_TO_REDIR))
202 * get_smb2_cmd_val() - get smb command code from smb header
203 * @work: smb work containing smb request buffer
205 * Return: smb2 request command value
207 u16 get_smb2_cmd_val(struct ksmbd_work *work)
209 struct smb2_hdr *rcv_hdr;
211 if (work->next_smb2_rcv_hdr_off)
212 rcv_hdr = ksmbd_req_buf_next(work);
214 rcv_hdr = smb2_get_msg(work->request_buf);
215 return le16_to_cpu(rcv_hdr->Command);
219 * set_smb2_rsp_status() - set error response code on smb2 header
220 * @work: smb work containing response buffer
221 * @err: error response code
223 void set_smb2_rsp_status(struct ksmbd_work *work, __le32 err)
225 struct smb2_hdr *rsp_hdr;
227 if (work->next_smb2_rcv_hdr_off)
228 rsp_hdr = ksmbd_resp_buf_next(work);
230 rsp_hdr = smb2_get_msg(work->response_buf);
231 rsp_hdr->Status = err;
232 smb2_set_err_rsp(work);
236 * init_smb2_neg_rsp() - initialize smb2 response for negotiate command
237 * @work: smb work containing smb request buffer
239 * smb2 negotiate response is sent in reply of smb1 negotiate command for
240 * dialect auto-negotiation.
242 int init_smb2_neg_rsp(struct ksmbd_work *work)
244 struct smb2_hdr *rsp_hdr;
245 struct smb2_negotiate_rsp *rsp;
246 struct ksmbd_conn *conn = work->conn;
248 *(__be32 *)work->response_buf =
249 cpu_to_be32(conn->vals->header_size);
251 rsp_hdr = smb2_get_msg(work->response_buf);
252 memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
253 rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
254 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
255 rsp_hdr->CreditRequest = cpu_to_le16(2);
256 rsp_hdr->Command = SMB2_NEGOTIATE;
257 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
258 rsp_hdr->NextCommand = 0;
259 rsp_hdr->MessageId = 0;
260 rsp_hdr->Id.SyncId.ProcessId = 0;
261 rsp_hdr->Id.SyncId.TreeId = 0;
262 rsp_hdr->SessionId = 0;
263 memset(rsp_hdr->Signature, 0, 16);
265 rsp = smb2_get_msg(work->response_buf);
267 WARN_ON(ksmbd_conn_good(conn));
269 rsp->StructureSize = cpu_to_le16(65);
270 ksmbd_debug(SMB, "conn->dialect 0x%x\n", conn->dialect);
271 rsp->DialectRevision = cpu_to_le16(conn->dialect);
272 /* Not setting conn guid rsp->ServerGUID, as it
273 * not used by client for identifying connection
275 rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
276 /* Default Max Message Size till SMB2.0, 64K*/
277 rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
278 rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
279 rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);
281 rsp->SystemTime = cpu_to_le64(ksmbd_systime());
282 rsp->ServerStartTime = 0;
284 rsp->SecurityBufferOffset = cpu_to_le16(128);
285 rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
286 ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) +
287 le16_to_cpu(rsp->SecurityBufferOffset));
288 inc_rfc1001_len(work->response_buf,
289 sizeof(struct smb2_negotiate_rsp) -
290 sizeof(struct smb2_hdr) - sizeof(rsp->Buffer) +
292 rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
293 if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY)
294 rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
295 conn->use_spnego = true;
297 ksmbd_conn_set_need_negotiate(conn);
302 * smb2_set_rsp_credits() - set number of credits in response buffer
303 * @work: smb work containing smb response buffer
305 int smb2_set_rsp_credits(struct ksmbd_work *work)
307 struct smb2_hdr *req_hdr = ksmbd_req_buf_next(work);
308 struct smb2_hdr *hdr = ksmbd_resp_buf_next(work);
309 struct ksmbd_conn *conn = work->conn;
310 unsigned short credits_requested, aux_max;
311 unsigned short credit_charge, credits_granted = 0;
313 if (work->send_no_response)
316 hdr->CreditCharge = req_hdr->CreditCharge;
318 if (conn->total_credits > conn->vals->max_credits) {
319 hdr->CreditRequest = 0;
320 pr_err("Total credits overflow: %d\n", conn->total_credits);
324 credit_charge = max_t(unsigned short,
325 le16_to_cpu(req_hdr->CreditCharge), 1);
326 if (credit_charge > conn->total_credits) {
327 ksmbd_debug(SMB, "Insufficient credits granted, given: %u, granted: %u\n",
328 credit_charge, conn->total_credits);
332 conn->total_credits -= credit_charge;
333 conn->outstanding_credits -= credit_charge;
334 credits_requested = max_t(unsigned short,
335 le16_to_cpu(req_hdr->CreditRequest), 1);
337 /* according to smb2.credits smbtorture, Windows server
338 * 2016 or later grant up to 8192 credits at once.
340 * TODO: Need to adjuct CreditRequest value according to
343 if (hdr->Command == SMB2_NEGOTIATE)
346 aux_max = conn->vals->max_credits - conn->total_credits;
347 credits_granted = min_t(unsigned short, credits_requested, aux_max);
349 conn->total_credits += credits_granted;
350 work->credits_granted += credits_granted;
352 if (!req_hdr->NextCommand) {
353 /* Update CreditRequest in last request */
354 hdr->CreditRequest = cpu_to_le16(work->credits_granted);
357 "credits: requested[%d] granted[%d] total_granted[%d]\n",
358 credits_requested, credits_granted,
359 conn->total_credits);
364 * init_chained_smb2_rsp() - initialize smb2 chained response
365 * @work: smb work containing smb response buffer
367 static void init_chained_smb2_rsp(struct ksmbd_work *work)
369 struct smb2_hdr *req = ksmbd_req_buf_next(work);
370 struct smb2_hdr *rsp = ksmbd_resp_buf_next(work);
371 struct smb2_hdr *rsp_hdr;
372 struct smb2_hdr *rcv_hdr;
373 int next_hdr_offset = 0;
376 /* Len of this response = updated RFC len - offset of previous cmd
377 * in the compound rsp
380 /* Storing the current local FID which may be needed by subsequent
381 * command in the compound request
383 if (req->Command == SMB2_CREATE && rsp->Status == STATUS_SUCCESS) {
384 work->compound_fid = ((struct smb2_create_rsp *)rsp)->VolatileFileId;
385 work->compound_pfid = ((struct smb2_create_rsp *)rsp)->PersistentFileId;
386 work->compound_sid = le64_to_cpu(rsp->SessionId);
389 len = get_rfc1002_len(work->response_buf) - work->next_smb2_rsp_hdr_off;
390 next_hdr_offset = le32_to_cpu(req->NextCommand);
392 new_len = ALIGN(len, 8);
393 inc_rfc1001_len(work->response_buf,
394 sizeof(struct smb2_hdr) + new_len - len);
395 rsp->NextCommand = cpu_to_le32(new_len);
397 work->next_smb2_rcv_hdr_off += next_hdr_offset;
398 work->next_smb2_rsp_hdr_off += new_len;
400 "Compound req new_len = %d rcv off = %d rsp off = %d\n",
401 new_len, work->next_smb2_rcv_hdr_off,
402 work->next_smb2_rsp_hdr_off);
404 rsp_hdr = ksmbd_resp_buf_next(work);
405 rcv_hdr = ksmbd_req_buf_next(work);
407 if (!(rcv_hdr->Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
408 ksmbd_debug(SMB, "related flag should be set\n");
409 work->compound_fid = KSMBD_NO_FID;
410 work->compound_pfid = KSMBD_NO_FID;
412 memset((char *)rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
413 rsp_hdr->ProtocolId = SMB2_PROTO_NUMBER;
414 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
415 rsp_hdr->Command = rcv_hdr->Command;
418 * Message is response. We don't grant oplock yet.
420 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR |
421 SMB2_FLAGS_RELATED_OPERATIONS);
422 rsp_hdr->NextCommand = 0;
423 rsp_hdr->MessageId = rcv_hdr->MessageId;
424 rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
425 rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
426 rsp_hdr->SessionId = rcv_hdr->SessionId;
427 memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);
431 * is_chained_smb2_message() - check for chained command
432 * @work: smb work containing smb request buffer
434 * Return: true if chained request, otherwise false
436 bool is_chained_smb2_message(struct ksmbd_work *work)
438 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
439 unsigned int len, next_cmd;
441 if (hdr->ProtocolId != SMB2_PROTO_NUMBER)
444 hdr = ksmbd_req_buf_next(work);
445 next_cmd = le32_to_cpu(hdr->NextCommand);
447 if ((u64)work->next_smb2_rcv_hdr_off + next_cmd +
448 __SMB2_HEADER_STRUCTURE_SIZE >
449 get_rfc1002_len(work->request_buf)) {
450 pr_err("next command(%u) offset exceeds smb msg size\n",
455 if ((u64)get_rfc1002_len(work->response_buf) + MAX_CIFS_SMALL_BUFFER_SIZE >
457 pr_err("next response offset exceeds response buffer size\n");
461 ksmbd_debug(SMB, "got SMB2 chained command\n");
462 init_chained_smb2_rsp(work);
464 } else if (work->next_smb2_rcv_hdr_off) {
466 * This is last request in chained command,
467 * align response to 8 byte
469 len = ALIGN(get_rfc1002_len(work->response_buf), 8);
470 len = len - get_rfc1002_len(work->response_buf);
472 ksmbd_debug(SMB, "padding len %u\n", len);
473 inc_rfc1001_len(work->response_buf, len);
474 if (work->aux_payload_sz)
475 work->aux_payload_sz += len;
482 * init_smb2_rsp_hdr() - initialize smb2 response
483 * @work: smb work containing smb request buffer
487 int init_smb2_rsp_hdr(struct ksmbd_work *work)
489 struct smb2_hdr *rsp_hdr = smb2_get_msg(work->response_buf);
490 struct smb2_hdr *rcv_hdr = smb2_get_msg(work->request_buf);
491 struct ksmbd_conn *conn = work->conn;
493 memset(rsp_hdr, 0, sizeof(struct smb2_hdr) + 2);
494 *(__be32 *)work->response_buf =
495 cpu_to_be32(conn->vals->header_size);
496 rsp_hdr->ProtocolId = rcv_hdr->ProtocolId;
497 rsp_hdr->StructureSize = SMB2_HEADER_STRUCTURE_SIZE;
498 rsp_hdr->Command = rcv_hdr->Command;
501 * Message is response. We don't grant oplock yet.
503 rsp_hdr->Flags = (SMB2_FLAGS_SERVER_TO_REDIR);
504 rsp_hdr->NextCommand = 0;
505 rsp_hdr->MessageId = rcv_hdr->MessageId;
506 rsp_hdr->Id.SyncId.ProcessId = rcv_hdr->Id.SyncId.ProcessId;
507 rsp_hdr->Id.SyncId.TreeId = rcv_hdr->Id.SyncId.TreeId;
508 rsp_hdr->SessionId = rcv_hdr->SessionId;
509 memcpy(rsp_hdr->Signature, rcv_hdr->Signature, 16);
511 work->syncronous = true;
512 if (work->async_id) {
513 ksmbd_release_id(&conn->async_ida, work->async_id);
521 * smb2_allocate_rsp_buf() - allocate smb2 response buffer
522 * @work: smb work containing smb request buffer
524 * Return: 0 on success, otherwise -ENOMEM
526 int smb2_allocate_rsp_buf(struct ksmbd_work *work)
528 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
529 size_t small_sz = MAX_CIFS_SMALL_BUFFER_SIZE;
530 size_t large_sz = small_sz + work->conn->vals->max_trans_size;
531 size_t sz = small_sz;
532 int cmd = le16_to_cpu(hdr->Command);
534 if (cmd == SMB2_IOCTL_HE || cmd == SMB2_QUERY_DIRECTORY_HE)
537 if (cmd == SMB2_QUERY_INFO_HE) {
538 struct smb2_query_info_req *req;
540 req = smb2_get_msg(work->request_buf);
541 if ((req->InfoType == SMB2_O_INFO_FILE &&
542 (req->FileInfoClass == FILE_FULL_EA_INFORMATION ||
543 req->FileInfoClass == FILE_ALL_INFORMATION)) ||
544 req->InfoType == SMB2_O_INFO_SECURITY)
548 /* allocate large response buf for chained commands */
549 if (le32_to_cpu(hdr->NextCommand) > 0)
552 work->response_buf = kvmalloc(sz, GFP_KERNEL | __GFP_ZERO);
553 if (!work->response_buf)
556 work->response_sz = sz;
561 * smb2_check_user_session() - check for valid session for a user
562 * @work: smb work containing smb request buffer
564 * Return: 0 on success, otherwise error
566 int smb2_check_user_session(struct ksmbd_work *work)
568 struct smb2_hdr *req_hdr = smb2_get_msg(work->request_buf);
569 struct ksmbd_conn *conn = work->conn;
570 unsigned int cmd = conn->ops->get_cmd_val(work);
571 unsigned long long sess_id;
574 * SMB2_ECHO, SMB2_NEGOTIATE, SMB2_SESSION_SETUP command do not
575 * require a session id, so no need to validate user session's for
578 if (cmd == SMB2_ECHO_HE || cmd == SMB2_NEGOTIATE_HE ||
579 cmd == SMB2_SESSION_SETUP_HE)
582 if (!ksmbd_conn_good(conn))
585 sess_id = le64_to_cpu(req_hdr->SessionId);
588 * If request is not the first in Compound request,
589 * Just validate session id in header with work->sess->id.
591 if (work->next_smb2_rcv_hdr_off) {
593 pr_err("The first operation in the compound does not have sess\n");
596 if (work->sess->id != sess_id) {
597 pr_err("session id(%llu) is different with the first operation(%lld)\n",
598 sess_id, work->sess->id);
604 /* Check for validity of user session */
605 work->sess = ksmbd_session_lookup_all(conn, sess_id);
608 ksmbd_debug(SMB, "Invalid user session, Uid %llu\n", sess_id);
612 static void destroy_previous_session(struct ksmbd_conn *conn,
613 struct ksmbd_user *user, u64 id)
615 struct ksmbd_session *prev_sess = ksmbd_session_lookup_slowpath(id);
616 struct ksmbd_user *prev_user;
617 struct channel *chann;
623 prev_user = prev_sess->user;
626 strcmp(user->name, prev_user->name) ||
627 user->passkey_sz != prev_user->passkey_sz ||
628 memcmp(user->passkey, prev_user->passkey, user->passkey_sz))
631 prev_sess->state = SMB2_SESSION_EXPIRED;
632 xa_for_each(&prev_sess->ksmbd_chann_list, index, chann)
633 ksmbd_conn_set_exiting(chann->conn);
637 * smb2_get_name() - get filename string from on the wire smb format
638 * @src: source buffer
639 * @maxlen: maxlen of source string
640 * @local_nls: nls_table pointer
642 * Return: matching converted filename on success, otherwise error ptr
645 smb2_get_name(const char *src, const int maxlen, struct nls_table *local_nls)
649 name = smb_strndup_from_utf16(src, maxlen, 1, local_nls);
651 pr_err("failed to get name %ld\n", PTR_ERR(name));
655 ksmbd_conv_path_to_unix(name);
656 ksmbd_strip_last_slash(name);
660 int setup_async_work(struct ksmbd_work *work, void (*fn)(void **), void **arg)
662 struct smb2_hdr *rsp_hdr;
663 struct ksmbd_conn *conn = work->conn;
666 rsp_hdr = smb2_get_msg(work->response_buf);
667 rsp_hdr->Flags |= SMB2_FLAGS_ASYNC_COMMAND;
669 id = ksmbd_acquire_async_msg_id(&conn->async_ida);
671 pr_err("Failed to alloc async message id\n");
674 work->syncronous = false;
676 rsp_hdr->Id.AsyncId = cpu_to_le64(id);
679 "Send interim Response to inform async request id : %d\n",
682 work->cancel_fn = fn;
683 work->cancel_argv = arg;
685 if (list_empty(&work->async_request_entry)) {
686 spin_lock(&conn->request_lock);
687 list_add_tail(&work->async_request_entry, &conn->async_requests);
688 spin_unlock(&conn->request_lock);
694 void smb2_send_interim_resp(struct ksmbd_work *work, __le32 status)
696 struct smb2_hdr *rsp_hdr;
698 rsp_hdr = smb2_get_msg(work->response_buf);
699 smb2_set_err_rsp(work);
700 rsp_hdr->Status = status;
703 ksmbd_conn_write(work);
708 static __le32 smb2_get_reparse_tag_special_file(umode_t mode)
710 if (S_ISDIR(mode) || S_ISREG(mode))
714 return IO_REPARSE_TAG_LX_SYMLINK_LE;
715 else if (S_ISFIFO(mode))
716 return IO_REPARSE_TAG_LX_FIFO_LE;
717 else if (S_ISSOCK(mode))
718 return IO_REPARSE_TAG_AF_UNIX_LE;
719 else if (S_ISCHR(mode))
720 return IO_REPARSE_TAG_LX_CHR_LE;
721 else if (S_ISBLK(mode))
722 return IO_REPARSE_TAG_LX_BLK_LE;
728 * smb2_get_dos_mode() - get file mode in dos format from unix mode
729 * @stat: kstat containing file mode
730 * @attribute: attribute flags
732 * Return: converted dos mode
734 static int smb2_get_dos_mode(struct kstat *stat, int attribute)
738 if (S_ISDIR(stat->mode)) {
739 attr = FILE_ATTRIBUTE_DIRECTORY |
740 (attribute & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM));
742 attr = (attribute & 0x00005137) | FILE_ATTRIBUTE_ARCHIVE;
743 attr &= ~(FILE_ATTRIBUTE_DIRECTORY);
744 if (S_ISREG(stat->mode) && (server_conf.share_fake_fscaps &
745 FILE_SUPPORTS_SPARSE_FILES))
746 attr |= FILE_ATTRIBUTE_SPARSE_FILE;
748 if (smb2_get_reparse_tag_special_file(stat->mode))
749 attr |= FILE_ATTRIBUTE_REPARSE_POINT;
755 static void build_preauth_ctxt(struct smb2_preauth_neg_context *pneg_ctxt,
758 pneg_ctxt->ContextType = SMB2_PREAUTH_INTEGRITY_CAPABILITIES;
759 pneg_ctxt->DataLength = cpu_to_le16(38);
760 pneg_ctxt->HashAlgorithmCount = cpu_to_le16(1);
761 pneg_ctxt->Reserved = cpu_to_le32(0);
762 pneg_ctxt->SaltLength = cpu_to_le16(SMB311_SALT_SIZE);
763 get_random_bytes(pneg_ctxt->Salt, SMB311_SALT_SIZE);
764 pneg_ctxt->HashAlgorithms = hash_id;
767 static void build_encrypt_ctxt(struct smb2_encryption_neg_context *pneg_ctxt,
770 pneg_ctxt->ContextType = SMB2_ENCRYPTION_CAPABILITIES;
771 pneg_ctxt->DataLength = cpu_to_le16(4);
772 pneg_ctxt->Reserved = cpu_to_le32(0);
773 pneg_ctxt->CipherCount = cpu_to_le16(1);
774 pneg_ctxt->Ciphers[0] = cipher_type;
777 static void build_compression_ctxt(struct smb2_compression_capabilities_context *pneg_ctxt,
780 pneg_ctxt->ContextType = SMB2_COMPRESSION_CAPABILITIES;
781 pneg_ctxt->DataLength =
782 cpu_to_le16(sizeof(struct smb2_compression_capabilities_context)
783 - sizeof(struct smb2_neg_context));
784 pneg_ctxt->Reserved = cpu_to_le32(0);
785 pneg_ctxt->CompressionAlgorithmCount = cpu_to_le16(1);
786 pneg_ctxt->Flags = cpu_to_le32(0);
787 pneg_ctxt->CompressionAlgorithms[0] = comp_algo;
790 static void build_sign_cap_ctxt(struct smb2_signing_capabilities *pneg_ctxt,
793 pneg_ctxt->ContextType = SMB2_SIGNING_CAPABILITIES;
794 pneg_ctxt->DataLength =
795 cpu_to_le16((sizeof(struct smb2_signing_capabilities) + 2)
796 - sizeof(struct smb2_neg_context));
797 pneg_ctxt->Reserved = cpu_to_le32(0);
798 pneg_ctxt->SigningAlgorithmCount = cpu_to_le16(1);
799 pneg_ctxt->SigningAlgorithms[0] = sign_algo;
802 static void build_posix_ctxt(struct smb2_posix_neg_context *pneg_ctxt)
804 pneg_ctxt->ContextType = SMB2_POSIX_EXTENSIONS_AVAILABLE;
805 pneg_ctxt->DataLength = cpu_to_le16(POSIX_CTXT_DATA_LEN);
806 /* SMB2_CREATE_TAG_POSIX is "0x93AD25509CB411E7B42383DE968BCD7C" */
807 pneg_ctxt->Name[0] = 0x93;
808 pneg_ctxt->Name[1] = 0xAD;
809 pneg_ctxt->Name[2] = 0x25;
810 pneg_ctxt->Name[3] = 0x50;
811 pneg_ctxt->Name[4] = 0x9C;
812 pneg_ctxt->Name[5] = 0xB4;
813 pneg_ctxt->Name[6] = 0x11;
814 pneg_ctxt->Name[7] = 0xE7;
815 pneg_ctxt->Name[8] = 0xB4;
816 pneg_ctxt->Name[9] = 0x23;
817 pneg_ctxt->Name[10] = 0x83;
818 pneg_ctxt->Name[11] = 0xDE;
819 pneg_ctxt->Name[12] = 0x96;
820 pneg_ctxt->Name[13] = 0x8B;
821 pneg_ctxt->Name[14] = 0xCD;
822 pneg_ctxt->Name[15] = 0x7C;
825 static void assemble_neg_contexts(struct ksmbd_conn *conn,
826 struct smb2_negotiate_rsp *rsp,
829 char *pneg_ctxt = (char *)rsp +
830 le32_to_cpu(rsp->NegotiateContextOffset);
831 int neg_ctxt_cnt = 1;
835 "assemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
836 build_preauth_ctxt((struct smb2_preauth_neg_context *)pneg_ctxt,
837 conn->preauth_info->Preauth_HashId);
838 rsp->NegotiateContextCount = cpu_to_le16(neg_ctxt_cnt);
839 inc_rfc1001_len(smb2_buf_len, AUTH_GSS_PADDING);
840 ctxt_size = sizeof(struct smb2_preauth_neg_context);
841 /* Round to 8 byte boundary */
842 pneg_ctxt += round_up(sizeof(struct smb2_preauth_neg_context), 8);
844 if (conn->cipher_type) {
845 ctxt_size = round_up(ctxt_size, 8);
847 "assemble SMB2_ENCRYPTION_CAPABILITIES context\n");
848 build_encrypt_ctxt((struct smb2_encryption_neg_context *)pneg_ctxt,
850 rsp->NegotiateContextCount = cpu_to_le16(++neg_ctxt_cnt);
851 ctxt_size += sizeof(struct smb2_encryption_neg_context) + 2;
852 /* Round to 8 byte boundary */
854 round_up(sizeof(struct smb2_encryption_neg_context) + 2,
858 if (conn->compress_algorithm) {
859 ctxt_size = round_up(ctxt_size, 8);
861 "assemble SMB2_COMPRESSION_CAPABILITIES context\n");
862 /* Temporarily set to SMB3_COMPRESS_NONE */
863 build_compression_ctxt((struct smb2_compression_capabilities_context *)pneg_ctxt,
864 conn->compress_algorithm);
865 rsp->NegotiateContextCount = cpu_to_le16(++neg_ctxt_cnt);
866 ctxt_size += sizeof(struct smb2_compression_capabilities_context) + 2;
867 /* Round to 8 byte boundary */
868 pneg_ctxt += round_up(sizeof(struct smb2_compression_capabilities_context) + 2,
872 if (conn->posix_ext_supported) {
873 ctxt_size = round_up(ctxt_size, 8);
875 "assemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
876 build_posix_ctxt((struct smb2_posix_neg_context *)pneg_ctxt);
877 rsp->NegotiateContextCount = cpu_to_le16(++neg_ctxt_cnt);
878 ctxt_size += sizeof(struct smb2_posix_neg_context);
879 /* Round to 8 byte boundary */
880 pneg_ctxt += round_up(sizeof(struct smb2_posix_neg_context), 8);
883 if (conn->signing_negotiated) {
884 ctxt_size = round_up(ctxt_size, 8);
886 "assemble SMB2_SIGNING_CAPABILITIES context\n");
887 build_sign_cap_ctxt((struct smb2_signing_capabilities *)pneg_ctxt,
888 conn->signing_algorithm);
889 rsp->NegotiateContextCount = cpu_to_le16(++neg_ctxt_cnt);
890 ctxt_size += sizeof(struct smb2_signing_capabilities) + 2;
893 inc_rfc1001_len(smb2_buf_len, ctxt_size);
896 static __le32 decode_preauth_ctxt(struct ksmbd_conn *conn,
897 struct smb2_preauth_neg_context *pneg_ctxt,
901 * sizeof(smb2_preauth_neg_context) assumes SMB311_SALT_SIZE Salt,
902 * which may not be present. Only check for used HashAlgorithms[1].
905 sizeof(struct smb2_neg_context) + MIN_PREAUTH_CTXT_DATA_LEN)
906 return STATUS_INVALID_PARAMETER;
908 if (pneg_ctxt->HashAlgorithms != SMB2_PREAUTH_INTEGRITY_SHA512)
909 return STATUS_NO_PREAUTH_INTEGRITY_HASH_OVERLAP;
911 conn->preauth_info->Preauth_HashId = SMB2_PREAUTH_INTEGRITY_SHA512;
912 return STATUS_SUCCESS;
915 static void decode_encrypt_ctxt(struct ksmbd_conn *conn,
916 struct smb2_encryption_neg_context *pneg_ctxt,
922 if (sizeof(struct smb2_encryption_neg_context) > ctxt_len) {
923 pr_err("Invalid SMB2_ENCRYPTION_CAPABILITIES context size\n");
927 conn->cipher_type = 0;
929 cph_cnt = le16_to_cpu(pneg_ctxt->CipherCount);
930 cphs_size = cph_cnt * sizeof(__le16);
932 if (sizeof(struct smb2_encryption_neg_context) + cphs_size >
934 pr_err("Invalid cipher count(%d)\n", cph_cnt);
938 if (!(server_conf.flags & KSMBD_GLOBAL_FLAG_SMB2_ENCRYPTION))
941 for (i = 0; i < cph_cnt; i++) {
942 if (pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_GCM ||
943 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES128_CCM ||
944 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_CCM ||
945 pneg_ctxt->Ciphers[i] == SMB2_ENCRYPTION_AES256_GCM) {
946 ksmbd_debug(SMB, "Cipher ID = 0x%x\n",
947 pneg_ctxt->Ciphers[i]);
948 conn->cipher_type = pneg_ctxt->Ciphers[i];
955 * smb3_encryption_negotiated() - checks if server and client agreed on enabling encryption
956 * @conn: smb connection
958 * Return: true if connection should be encrypted, else false
960 bool smb3_encryption_negotiated(struct ksmbd_conn *conn)
962 if (!conn->ops->generate_encryptionkey)
966 * SMB 3.0 and 3.0.2 dialects use the SMB2_GLOBAL_CAP_ENCRYPTION flag.
967 * SMB 3.1.1 uses the cipher_type field.
969 return (conn->vals->capabilities & SMB2_GLOBAL_CAP_ENCRYPTION) ||
973 static void decode_compress_ctxt(struct ksmbd_conn *conn,
974 struct smb2_compression_capabilities_context *pneg_ctxt)
976 conn->compress_algorithm = SMB3_COMPRESS_NONE;
979 static void decode_sign_cap_ctxt(struct ksmbd_conn *conn,
980 struct smb2_signing_capabilities *pneg_ctxt,
984 int i, sign_alos_size;
986 if (sizeof(struct smb2_signing_capabilities) > ctxt_len) {
987 pr_err("Invalid SMB2_SIGNING_CAPABILITIES context length\n");
991 conn->signing_negotiated = false;
992 sign_algo_cnt = le16_to_cpu(pneg_ctxt->SigningAlgorithmCount);
993 sign_alos_size = sign_algo_cnt * sizeof(__le16);
995 if (sizeof(struct smb2_signing_capabilities) + sign_alos_size >
997 pr_err("Invalid signing algorithm count(%d)\n", sign_algo_cnt);
1001 for (i = 0; i < sign_algo_cnt; i++) {
1002 if (pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_HMAC_SHA256_LE ||
1003 pneg_ctxt->SigningAlgorithms[i] == SIGNING_ALG_AES_CMAC_LE) {
1004 ksmbd_debug(SMB, "Signing Algorithm ID = 0x%x\n",
1005 pneg_ctxt->SigningAlgorithms[i]);
1006 conn->signing_negotiated = true;
1007 conn->signing_algorithm =
1008 pneg_ctxt->SigningAlgorithms[i];
1014 static __le32 deassemble_neg_contexts(struct ksmbd_conn *conn,
1015 struct smb2_negotiate_req *req,
1016 unsigned int len_of_smb)
1018 /* +4 is to account for the RFC1001 len field */
1019 struct smb2_neg_context *pctx = (struct smb2_neg_context *)req;
1020 int i = 0, len_of_ctxts;
1021 unsigned int offset = le32_to_cpu(req->NegotiateContextOffset);
1022 unsigned int neg_ctxt_cnt = le16_to_cpu(req->NegotiateContextCount);
1023 __le32 status = STATUS_INVALID_PARAMETER;
1025 ksmbd_debug(SMB, "decoding %d negotiate contexts\n", neg_ctxt_cnt);
1026 if (len_of_smb <= offset) {
1027 ksmbd_debug(SMB, "Invalid response: negotiate context offset\n");
1031 len_of_ctxts = len_of_smb - offset;
1033 while (i++ < neg_ctxt_cnt) {
1036 if (len_of_ctxts < (int)sizeof(struct smb2_neg_context))
1039 pctx = (struct smb2_neg_context *)((char *)pctx + offset);
1040 clen = le16_to_cpu(pctx->DataLength);
1041 ctxt_len = clen + sizeof(struct smb2_neg_context);
1043 if (ctxt_len > len_of_ctxts)
1046 if (pctx->ContextType == SMB2_PREAUTH_INTEGRITY_CAPABILITIES) {
1048 "deassemble SMB2_PREAUTH_INTEGRITY_CAPABILITIES context\n");
1049 if (conn->preauth_info->Preauth_HashId)
1052 status = decode_preauth_ctxt(conn,
1053 (struct smb2_preauth_neg_context *)pctx,
1055 if (status != STATUS_SUCCESS)
1057 } else if (pctx->ContextType == SMB2_ENCRYPTION_CAPABILITIES) {
1059 "deassemble SMB2_ENCRYPTION_CAPABILITIES context\n");
1060 if (conn->cipher_type)
1063 decode_encrypt_ctxt(conn,
1064 (struct smb2_encryption_neg_context *)pctx,
1066 } else if (pctx->ContextType == SMB2_COMPRESSION_CAPABILITIES) {
1068 "deassemble SMB2_COMPRESSION_CAPABILITIES context\n");
1069 if (conn->compress_algorithm)
1072 decode_compress_ctxt(conn,
1073 (struct smb2_compression_capabilities_context *)pctx);
1074 } else if (pctx->ContextType == SMB2_NETNAME_NEGOTIATE_CONTEXT_ID) {
1076 "deassemble SMB2_NETNAME_NEGOTIATE_CONTEXT_ID context\n");
1077 } else if (pctx->ContextType == SMB2_POSIX_EXTENSIONS_AVAILABLE) {
1079 "deassemble SMB2_POSIX_EXTENSIONS_AVAILABLE context\n");
1080 conn->posix_ext_supported = true;
1081 } else if (pctx->ContextType == SMB2_SIGNING_CAPABILITIES) {
1083 "deassemble SMB2_SIGNING_CAPABILITIES context\n");
1085 decode_sign_cap_ctxt(conn,
1086 (struct smb2_signing_capabilities *)pctx,
1090 /* offsets must be 8 byte aligned */
1091 offset = (ctxt_len + 7) & ~0x7;
1092 len_of_ctxts -= offset;
1098 * smb2_handle_negotiate() - handler for smb2 negotiate command
1099 * @work: smb work containing smb request buffer
1103 int smb2_handle_negotiate(struct ksmbd_work *work)
1105 struct ksmbd_conn *conn = work->conn;
1106 struct smb2_negotiate_req *req = smb2_get_msg(work->request_buf);
1107 struct smb2_negotiate_rsp *rsp = smb2_get_msg(work->response_buf);
1109 unsigned int smb2_buf_len, smb2_neg_size;
1112 ksmbd_debug(SMB, "Received negotiate request\n");
1113 conn->need_neg = false;
1114 if (ksmbd_conn_good(conn)) {
1115 pr_err("conn->tcp_status is already in CifsGood State\n");
1116 work->send_no_response = 1;
1120 smb2_buf_len = get_rfc1002_len(work->request_buf);
1121 smb2_neg_size = offsetof(struct smb2_negotiate_req, Dialects);
1122 if (smb2_neg_size > smb2_buf_len) {
1123 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1128 if (req->DialectCount == 0) {
1129 pr_err("malformed packet\n");
1130 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1135 if (conn->dialect == SMB311_PROT_ID) {
1136 unsigned int nego_ctxt_off = le32_to_cpu(req->NegotiateContextOffset);
1138 if (smb2_buf_len < nego_ctxt_off) {
1139 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1144 if (smb2_neg_size > nego_ctxt_off) {
1145 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1150 if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
1152 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1157 if (smb2_neg_size + le16_to_cpu(req->DialectCount) * sizeof(__le16) >
1159 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1165 conn->cli_cap = le32_to_cpu(req->Capabilities);
1166 switch (conn->dialect) {
1167 case SMB311_PROT_ID:
1168 conn->preauth_info =
1169 kzalloc(sizeof(struct preauth_integrity_info),
1171 if (!conn->preauth_info) {
1173 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1177 status = deassemble_neg_contexts(conn, req,
1178 get_rfc1002_len(work->request_buf));
1179 if (status != STATUS_SUCCESS) {
1180 pr_err("deassemble_neg_contexts error(0x%x)\n",
1182 rsp->hdr.Status = status;
1184 kfree(conn->preauth_info);
1185 conn->preauth_info = NULL;
1189 rc = init_smb3_11_server(conn);
1191 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1192 kfree(conn->preauth_info);
1193 conn->preauth_info = NULL;
1197 ksmbd_gen_preauth_integrity_hash(conn,
1199 conn->preauth_info->Preauth_HashValue);
1200 rsp->NegotiateContextOffset =
1201 cpu_to_le32(OFFSET_OF_NEG_CONTEXT);
1202 assemble_neg_contexts(conn, rsp, work->response_buf);
1204 case SMB302_PROT_ID:
1205 init_smb3_02_server(conn);
1208 init_smb3_0_server(conn);
1211 init_smb2_1_server(conn);
1216 ksmbd_debug(SMB, "Server dialect :0x%x not supported\n",
1218 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
1222 rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
1225 conn->connection_type = conn->dialect;
1227 rsp->MaxTransactSize = cpu_to_le32(conn->vals->max_trans_size);
1228 rsp->MaxReadSize = cpu_to_le32(conn->vals->max_read_size);
1229 rsp->MaxWriteSize = cpu_to_le32(conn->vals->max_write_size);
1231 memcpy(conn->ClientGUID, req->ClientGUID,
1232 SMB2_CLIENT_GUID_SIZE);
1233 conn->cli_sec_mode = le16_to_cpu(req->SecurityMode);
1235 rsp->StructureSize = cpu_to_le16(65);
1236 rsp->DialectRevision = cpu_to_le16(conn->dialect);
1237 /* Not setting conn guid rsp->ServerGUID, as it
1238 * not used by client for identifying server
1240 memset(rsp->ServerGUID, 0, SMB2_CLIENT_GUID_SIZE);
1242 rsp->SystemTime = cpu_to_le64(ksmbd_systime());
1243 rsp->ServerStartTime = 0;
1244 ksmbd_debug(SMB, "negotiate context offset %d, count %d\n",
1245 le32_to_cpu(rsp->NegotiateContextOffset),
1246 le16_to_cpu(rsp->NegotiateContextCount));
1248 rsp->SecurityBufferOffset = cpu_to_le16(128);
1249 rsp->SecurityBufferLength = cpu_to_le16(AUTH_GSS_LENGTH);
1250 ksmbd_copy_gss_neg_header((char *)(&rsp->hdr) +
1251 le16_to_cpu(rsp->SecurityBufferOffset));
1252 inc_rfc1001_len(work->response_buf, sizeof(struct smb2_negotiate_rsp) -
1253 sizeof(struct smb2_hdr) - sizeof(rsp->Buffer) +
1255 rsp->SecurityMode = SMB2_NEGOTIATE_SIGNING_ENABLED_LE;
1256 conn->use_spnego = true;
1258 if ((server_conf.signing == KSMBD_CONFIG_OPT_AUTO ||
1259 server_conf.signing == KSMBD_CONFIG_OPT_DISABLED) &&
1260 req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED_LE)
1262 else if (server_conf.signing == KSMBD_CONFIG_OPT_MANDATORY) {
1263 server_conf.enforced_signing = true;
1264 rsp->SecurityMode |= SMB2_NEGOTIATE_SIGNING_REQUIRED_LE;
1268 conn->srv_sec_mode = le16_to_cpu(rsp->SecurityMode);
1269 ksmbd_conn_set_need_negotiate(conn);
1273 smb2_set_err_rsp(work);
1278 static int alloc_preauth_hash(struct ksmbd_session *sess,
1279 struct ksmbd_conn *conn)
1281 if (sess->Preauth_HashValue)
1284 sess->Preauth_HashValue = kmemdup(conn->preauth_info->Preauth_HashValue,
1285 PREAUTH_HASHVALUE_SIZE, GFP_KERNEL);
1286 if (!sess->Preauth_HashValue)
1292 static int generate_preauth_hash(struct ksmbd_work *work)
1294 struct ksmbd_conn *conn = work->conn;
1295 struct ksmbd_session *sess = work->sess;
1298 if (conn->dialect != SMB311_PROT_ID)
1301 if (conn->binding) {
1302 struct preauth_session *preauth_sess;
1304 preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
1305 if (!preauth_sess) {
1306 preauth_sess = ksmbd_preauth_session_alloc(conn, sess->id);
1311 preauth_hash = preauth_sess->Preauth_HashValue;
1313 if (!sess->Preauth_HashValue)
1314 if (alloc_preauth_hash(sess, conn))
1316 preauth_hash = sess->Preauth_HashValue;
1319 ksmbd_gen_preauth_integrity_hash(conn, work->request_buf, preauth_hash);
1323 static int decode_negotiation_token(struct ksmbd_conn *conn,
1324 struct negotiate_message *negblob,
1327 if (!conn->use_spnego)
1330 if (ksmbd_decode_negTokenInit((char *)negblob, sz, conn)) {
1331 if (ksmbd_decode_negTokenTarg((char *)negblob, sz, conn)) {
1332 conn->auth_mechs |= KSMBD_AUTH_NTLMSSP;
1333 conn->preferred_auth_mech = KSMBD_AUTH_NTLMSSP;
1334 conn->use_spnego = false;
1340 static int ntlm_negotiate(struct ksmbd_work *work,
1341 struct negotiate_message *negblob,
1344 struct smb2_sess_setup_rsp *rsp = smb2_get_msg(work->response_buf);
1345 struct challenge_message *chgblob;
1346 unsigned char *spnego_blob = NULL;
1347 u16 spnego_blob_len;
1351 ksmbd_debug(SMB, "negotiate phase\n");
1352 rc = ksmbd_decode_ntlmssp_neg_blob(negblob, negblob_len, work->conn);
1356 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1358 (struct challenge_message *)((char *)&rsp->hdr.ProtocolId + sz);
1359 memset(chgblob, 0, sizeof(struct challenge_message));
1361 if (!work->conn->use_spnego) {
1362 sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
1366 rsp->SecurityBufferLength = cpu_to_le16(sz);
1370 sz = sizeof(struct challenge_message);
1371 sz += (strlen(ksmbd_netbios_name()) * 2 + 1 + 4) * 6;
1373 neg_blob = kzalloc(sz, GFP_KERNEL);
1377 chgblob = (struct challenge_message *)neg_blob;
1378 sz = ksmbd_build_ntlmssp_challenge_blob(chgblob, work->conn);
1384 rc = build_spnego_ntlmssp_neg_blob(&spnego_blob, &spnego_blob_len,
1391 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1392 memcpy((char *)&rsp->hdr.ProtocolId + sz, spnego_blob, spnego_blob_len);
1393 rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
1401 static struct authenticate_message *user_authblob(struct ksmbd_conn *conn,
1402 struct smb2_sess_setup_req *req)
1406 if (conn->use_spnego && conn->mechToken)
1407 return (struct authenticate_message *)conn->mechToken;
1409 sz = le16_to_cpu(req->SecurityBufferOffset);
1410 return (struct authenticate_message *)((char *)&req->hdr.ProtocolId
1414 static struct ksmbd_user *session_user(struct ksmbd_conn *conn,
1415 struct smb2_sess_setup_req *req)
1417 struct authenticate_message *authblob;
1418 struct ksmbd_user *user;
1420 unsigned int name_off, name_len, secbuf_len;
1422 secbuf_len = le16_to_cpu(req->SecurityBufferLength);
1423 if (secbuf_len < sizeof(struct authenticate_message)) {
1424 ksmbd_debug(SMB, "blob len %d too small\n", secbuf_len);
1427 authblob = user_authblob(conn, req);
1428 name_off = le32_to_cpu(authblob->UserName.BufferOffset);
1429 name_len = le16_to_cpu(authblob->UserName.Length);
1431 if (secbuf_len < (u64)name_off + name_len)
1434 name = smb_strndup_from_utf16((const char *)authblob + name_off,
1439 pr_err("cannot allocate memory\n");
1443 ksmbd_debug(SMB, "session setup request for user %s\n", name);
1444 user = ksmbd_login_user(name);
1449 static int ntlm_authenticate(struct ksmbd_work *work)
1451 struct smb2_sess_setup_req *req = smb2_get_msg(work->request_buf);
1452 struct smb2_sess_setup_rsp *rsp = smb2_get_msg(work->response_buf);
1453 struct ksmbd_conn *conn = work->conn;
1454 struct ksmbd_session *sess = work->sess;
1455 struct channel *chann = NULL;
1456 struct ksmbd_user *user;
1460 ksmbd_debug(SMB, "authenticate phase\n");
1461 if (conn->use_spnego) {
1462 unsigned char *spnego_blob;
1463 u16 spnego_blob_len;
1465 rc = build_spnego_ntlmssp_auth_blob(&spnego_blob,
1471 sz = le16_to_cpu(rsp->SecurityBufferOffset);
1472 memcpy((char *)&rsp->hdr.ProtocolId + sz, spnego_blob, spnego_blob_len);
1473 rsp->SecurityBufferLength = cpu_to_le16(spnego_blob_len);
1475 inc_rfc1001_len(work->response_buf, spnego_blob_len - 1);
1478 user = session_user(conn, req);
1480 ksmbd_debug(SMB, "Unknown user name or an error\n");
1484 /* Check for previous session */
1485 prev_id = le64_to_cpu(req->PreviousSessionId);
1486 if (prev_id && prev_id != sess->id)
1487 destroy_previous_session(conn, user, prev_id);
1489 if (sess->state == SMB2_SESSION_VALID) {
1491 * Reuse session if anonymous try to connect
1492 * on reauthetication.
1494 if (conn->binding == false && ksmbd_anonymous_user(user)) {
1495 ksmbd_free_user(user);
1499 if (!ksmbd_compare_user(sess->user, user)) {
1500 ksmbd_free_user(user);
1503 ksmbd_free_user(user);
1508 if (conn->binding == false && user_guest(sess->user)) {
1509 rsp->SessionFlags = SMB2_SESSION_FLAG_IS_GUEST_LE;
1511 struct authenticate_message *authblob;
1513 authblob = user_authblob(conn, req);
1514 sz = le16_to_cpu(req->SecurityBufferLength);
1515 rc = ksmbd_decode_ntlmssp_auth_blob(authblob, sz, conn, sess);
1517 set_user_flag(sess->user, KSMBD_USER_FLAG_BAD_PASSWORD);
1518 ksmbd_debug(SMB, "authentication failed\n");
1524 * If session state is SMB2_SESSION_VALID, We can assume
1525 * that it is reauthentication. And the user/password
1526 * has been verified, so return it here.
1528 if (sess->state == SMB2_SESSION_VALID) {
1530 goto binding_session;
1534 if ((rsp->SessionFlags != SMB2_SESSION_FLAG_IS_GUEST_LE &&
1535 (conn->sign || server_conf.enforced_signing)) ||
1536 (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
1539 if (smb3_encryption_negotiated(conn) &&
1540 !(req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1541 rc = conn->ops->generate_encryptionkey(conn, sess);
1544 "SMB3 encryption key generation failed\n");
1548 rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
1550 * signing is disable if encryption is enable
1557 if (conn->dialect >= SMB30_PROT_ID) {
1558 chann = lookup_chann_list(sess, conn);
1560 chann = kmalloc(sizeof(struct channel), GFP_KERNEL);
1565 xa_store(&sess->ksmbd_chann_list, (long)conn, chann, GFP_KERNEL);
1569 if (conn->ops->generate_signingkey) {
1570 rc = conn->ops->generate_signingkey(sess, conn);
1572 ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
1577 if (!ksmbd_conn_lookup_dialect(conn)) {
1578 pr_err("fail to verify the dialect\n");
1584 #ifdef CONFIG_SMB_SERVER_KERBEROS5
1585 static int krb5_authenticate(struct ksmbd_work *work)
1587 struct smb2_sess_setup_req *req = smb2_get_msg(work->request_buf);
1588 struct smb2_sess_setup_rsp *rsp = smb2_get_msg(work->response_buf);
1589 struct ksmbd_conn *conn = work->conn;
1590 struct ksmbd_session *sess = work->sess;
1591 char *in_blob, *out_blob;
1592 struct channel *chann = NULL;
1594 int in_len, out_len;
1597 in_blob = (char *)&req->hdr.ProtocolId +
1598 le16_to_cpu(req->SecurityBufferOffset);
1599 in_len = le16_to_cpu(req->SecurityBufferLength);
1600 out_blob = (char *)&rsp->hdr.ProtocolId +
1601 le16_to_cpu(rsp->SecurityBufferOffset);
1602 out_len = work->response_sz -
1603 (le16_to_cpu(rsp->SecurityBufferOffset) + 4);
1605 /* Check previous session */
1606 prev_sess_id = le64_to_cpu(req->PreviousSessionId);
1607 if (prev_sess_id && prev_sess_id != sess->id)
1608 destroy_previous_session(conn, sess->user, prev_sess_id);
1610 if (sess->state == SMB2_SESSION_VALID)
1611 ksmbd_free_user(sess->user);
1613 retval = ksmbd_krb5_authenticate(sess, in_blob, in_len,
1614 out_blob, &out_len);
1616 ksmbd_debug(SMB, "krb5 authentication failed\n");
1619 rsp->SecurityBufferLength = cpu_to_le16(out_len);
1620 inc_rfc1001_len(work->response_buf, out_len - 1);
1622 if ((conn->sign || server_conf.enforced_signing) ||
1623 (req->SecurityMode & SMB2_NEGOTIATE_SIGNING_REQUIRED))
1626 if (smb3_encryption_negotiated(conn)) {
1627 retval = conn->ops->generate_encryptionkey(conn, sess);
1630 "SMB3 encryption key generation failed\n");
1634 rsp->SessionFlags = SMB2_SESSION_FLAG_ENCRYPT_DATA_LE;
1638 if (conn->dialect >= SMB30_PROT_ID) {
1639 chann = lookup_chann_list(sess, conn);
1641 chann = kmalloc(sizeof(struct channel), GFP_KERNEL);
1646 xa_store(&sess->ksmbd_chann_list, (long)conn, chann, GFP_KERNEL);
1650 if (conn->ops->generate_signingkey) {
1651 retval = conn->ops->generate_signingkey(sess, conn);
1653 ksmbd_debug(SMB, "SMB3 signing key generation failed\n");
1658 if (!ksmbd_conn_lookup_dialect(conn)) {
1659 pr_err("fail to verify the dialect\n");
1665 static int krb5_authenticate(struct ksmbd_work *work)
1671 int smb2_sess_setup(struct ksmbd_work *work)
1673 struct ksmbd_conn *conn = work->conn;
1674 struct smb2_sess_setup_req *req = smb2_get_msg(work->request_buf);
1675 struct smb2_sess_setup_rsp *rsp = smb2_get_msg(work->response_buf);
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 rsp->StructureSize = cpu_to_le16(9);
1684 rsp->SessionFlags = 0;
1685 rsp->SecurityBufferOffset = cpu_to_le16(72);
1686 rsp->SecurityBufferLength = 0;
1687 inc_rfc1001_len(work->response_buf, 9);
1689 ksmbd_conn_lock(conn);
1690 if (!req->hdr.SessionId) {
1691 sess = ksmbd_smb2_session_create();
1696 rsp->hdr.SessionId = cpu_to_le64(sess->id);
1697 rc = ksmbd_session_register(conn, sess);
1700 } else if (conn->dialect >= SMB30_PROT_ID &&
1701 (server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
1702 req->Flags & SMB2_SESSION_REQ_FLAG_BINDING) {
1703 u64 sess_id = le64_to_cpu(req->hdr.SessionId);
1705 sess = ksmbd_session_lookup_slowpath(sess_id);
1711 if (conn->dialect != sess->dialect) {
1716 if (!(req->hdr.Flags & SMB2_FLAGS_SIGNED)) {
1721 if (strncmp(conn->ClientGUID, sess->ClientGUID,
1722 SMB2_CLIENT_GUID_SIZE)) {
1727 if (sess->state == SMB2_SESSION_IN_PROGRESS) {
1732 if (sess->state == SMB2_SESSION_EXPIRED) {
1737 if (ksmbd_conn_need_reconnect(conn)) {
1743 if (ksmbd_session_lookup(conn, sess_id)) {
1748 if (user_guest(sess->user)) {
1753 conn->binding = true;
1754 } else if ((conn->dialect < SMB30_PROT_ID ||
1755 server_conf.flags & KSMBD_GLOBAL_FLAG_SMB3_MULTICHANNEL) &&
1756 (req->Flags & SMB2_SESSION_REQ_FLAG_BINDING)) {
1761 sess = ksmbd_session_lookup(conn,
1762 le64_to_cpu(req->hdr.SessionId));
1768 if (sess->state == SMB2_SESSION_EXPIRED) {
1773 if (ksmbd_conn_need_reconnect(conn)) {
1781 negblob_off = le16_to_cpu(req->SecurityBufferOffset);
1782 negblob_len = le16_to_cpu(req->SecurityBufferLength);
1783 if (negblob_off < offsetof(struct smb2_sess_setup_req, Buffer) ||
1784 negblob_len < offsetof(struct negotiate_message, NegotiateFlags)) {
1789 negblob = (struct negotiate_message *)((char *)&req->hdr.ProtocolId +
1792 if (decode_negotiation_token(conn, negblob, negblob_len) == 0) {
1793 if (conn->mechToken)
1794 negblob = (struct negotiate_message *)conn->mechToken;
1797 if (server_conf.auth_mechs & conn->auth_mechs) {
1798 rc = generate_preauth_hash(work);
1802 if (conn->preferred_auth_mech &
1803 (KSMBD_AUTH_KRB5 | KSMBD_AUTH_MSKRB5)) {
1804 rc = krb5_authenticate(work);
1810 if (!ksmbd_conn_need_reconnect(conn)) {
1811 ksmbd_conn_set_good(conn);
1812 sess->state = SMB2_SESSION_VALID;
1814 kfree(sess->Preauth_HashValue);
1815 sess->Preauth_HashValue = NULL;
1816 } else if (conn->preferred_auth_mech == KSMBD_AUTH_NTLMSSP) {
1817 if (negblob->MessageType == NtLmNegotiate) {
1818 rc = ntlm_negotiate(work, negblob, negblob_len);
1822 STATUS_MORE_PROCESSING_REQUIRED;
1824 * Note: here total size -1 is done as an
1825 * adjustment for 0 size blob
1827 inc_rfc1001_len(work->response_buf,
1828 le16_to_cpu(rsp->SecurityBufferLength) - 1);
1830 } else if (negblob->MessageType == NtLmAuthenticate) {
1831 rc = ntlm_authenticate(work);
1835 if (!ksmbd_conn_need_reconnect(conn)) {
1836 ksmbd_conn_set_good(conn);
1837 sess->state = SMB2_SESSION_VALID;
1839 if (conn->binding) {
1840 struct preauth_session *preauth_sess;
1843 ksmbd_preauth_session_lookup(conn, sess->id);
1845 list_del(&preauth_sess->preauth_entry);
1846 kfree(preauth_sess);
1849 kfree(sess->Preauth_HashValue);
1850 sess->Preauth_HashValue = NULL;
1852 pr_info_ratelimited("Unknown NTLMSSP message type : 0x%x\n",
1853 le32_to_cpu(negblob->MessageType));
1857 /* TODO: need one more negotiation */
1858 pr_err("Not support the preferred authentication\n");
1862 pr_err("Not support authentication\n");
1868 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
1869 else if (rc == -ENOENT)
1870 rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
1871 else if (rc == -EACCES)
1872 rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
1873 else if (rc == -EFAULT)
1874 rsp->hdr.Status = STATUS_NETWORK_SESSION_EXPIRED;
1875 else if (rc == -ENOMEM)
1876 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
1877 else if (rc == -EOPNOTSUPP)
1878 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
1880 rsp->hdr.Status = STATUS_LOGON_FAILURE;
1882 if (conn->use_spnego && conn->mechToken) {
1883 kfree(conn->mechToken);
1884 conn->mechToken = NULL;
1889 * SecurityBufferOffset should be set to zero
1890 * in session setup error response.
1892 rsp->SecurityBufferOffset = 0;
1895 bool try_delay = false;
1898 * To avoid dictionary attacks (repeated session setups rapidly sent) to
1899 * connect to server, ksmbd make a delay of a 5 seconds on session setup
1900 * failure to make it harder to send enough random connection requests
1901 * to break into a server.
1903 if (sess->user && sess->user->flags & KSMBD_USER_FLAG_DELAY_SESSION)
1906 sess->last_active = jiffies;
1907 sess->state = SMB2_SESSION_EXPIRED;
1909 ksmbd_conn_set_need_reconnect(conn);
1911 ksmbd_conn_set_need_negotiate(conn);
1916 ksmbd_conn_unlock(conn);
1921 * smb2_tree_connect() - handler for smb2 tree connect command
1922 * @work: smb work containing smb request buffer
1924 * Return: 0 on success, otherwise error
1926 int smb2_tree_connect(struct ksmbd_work *work)
1928 struct ksmbd_conn *conn = work->conn;
1929 struct smb2_tree_connect_req *req = smb2_get_msg(work->request_buf);
1930 struct smb2_tree_connect_rsp *rsp = smb2_get_msg(work->response_buf);
1931 struct ksmbd_session *sess = work->sess;
1932 char *treename = NULL, *name = NULL;
1933 struct ksmbd_tree_conn_status status;
1934 struct ksmbd_share_config *share;
1937 treename = smb_strndup_from_utf16(req->Buffer,
1938 le16_to_cpu(req->PathLength), true,
1940 if (IS_ERR(treename)) {
1941 pr_err("treename is NULL\n");
1942 status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
1946 name = ksmbd_extract_sharename(conn->um, treename);
1948 status.ret = KSMBD_TREE_CONN_STATUS_ERROR;
1952 ksmbd_debug(SMB, "tree connect request for tree %s treename %s\n",
1955 status = ksmbd_tree_conn_connect(conn, sess, name);
1956 if (status.ret == KSMBD_TREE_CONN_STATUS_OK)
1957 rsp->hdr.Id.SyncId.TreeId = cpu_to_le32(status.tree_conn->id);
1961 share = status.tree_conn->share_conf;
1962 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
1963 ksmbd_debug(SMB, "IPC share path request\n");
1964 rsp->ShareType = SMB2_SHARE_TYPE_PIPE;
1965 rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
1966 FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE |
1967 FILE_DELETE_LE | FILE_READ_CONTROL_LE |
1968 FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
1969 FILE_SYNCHRONIZE_LE;
1971 rsp->ShareType = SMB2_SHARE_TYPE_DISK;
1972 rsp->MaximalAccess = FILE_READ_DATA_LE | FILE_READ_EA_LE |
1973 FILE_EXECUTE_LE | FILE_READ_ATTRIBUTES_LE;
1974 if (test_tree_conn_flag(status.tree_conn,
1975 KSMBD_TREE_CONN_FLAG_WRITABLE)) {
1976 rsp->MaximalAccess |= FILE_WRITE_DATA_LE |
1977 FILE_APPEND_DATA_LE | FILE_WRITE_EA_LE |
1978 FILE_DELETE_LE | FILE_WRITE_ATTRIBUTES_LE |
1979 FILE_DELETE_CHILD_LE | FILE_READ_CONTROL_LE |
1980 FILE_WRITE_DAC_LE | FILE_WRITE_OWNER_LE |
1981 FILE_SYNCHRONIZE_LE;
1985 status.tree_conn->maximal_access = le32_to_cpu(rsp->MaximalAccess);
1986 if (conn->posix_ext_supported)
1987 status.tree_conn->posix_extensions = true;
1989 rsp->StructureSize = cpu_to_le16(16);
1990 inc_rfc1001_len(work->response_buf, 16);
1992 rsp->Capabilities = 0;
1994 /* default manual caching */
1995 rsp->ShareFlags = SMB2_SHAREFLAG_MANUAL_CACHING;
1997 if (!IS_ERR(treename))
2002 switch (status.ret) {
2003 case KSMBD_TREE_CONN_STATUS_OK:
2004 rsp->hdr.Status = STATUS_SUCCESS;
2009 case KSMBD_TREE_CONN_STATUS_NO_SHARE:
2010 rsp->hdr.Status = STATUS_BAD_NETWORK_NAME;
2013 case KSMBD_TREE_CONN_STATUS_NOMEM:
2014 rsp->hdr.Status = STATUS_NO_MEMORY;
2016 case KSMBD_TREE_CONN_STATUS_ERROR:
2017 case KSMBD_TREE_CONN_STATUS_TOO_MANY_CONNS:
2018 case KSMBD_TREE_CONN_STATUS_TOO_MANY_SESSIONS:
2019 rsp->hdr.Status = STATUS_ACCESS_DENIED;
2022 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2025 rsp->hdr.Status = STATUS_ACCESS_DENIED;
2028 if (status.ret != KSMBD_TREE_CONN_STATUS_OK)
2029 smb2_set_err_rsp(work);
2035 * smb2_create_open_flags() - convert smb open flags to unix open flags
2036 * @file_present: is file already present
2037 * @access: file access flags
2038 * @disposition: file disposition flags
2039 * @may_flags: set with MAY_ flags
2041 * Return: file open flags
2043 static int smb2_create_open_flags(bool file_present, __le32 access,
2047 int oflags = O_NONBLOCK | O_LARGEFILE;
2049 if (access & FILE_READ_DESIRED_ACCESS_LE &&
2050 access & FILE_WRITE_DESIRE_ACCESS_LE) {
2052 *may_flags = MAY_OPEN | MAY_READ | MAY_WRITE;
2053 } else if (access & FILE_WRITE_DESIRE_ACCESS_LE) {
2055 *may_flags = MAY_OPEN | MAY_WRITE;
2058 *may_flags = MAY_OPEN | MAY_READ;
2061 if (access == FILE_READ_ATTRIBUTES_LE)
2065 switch (disposition & FILE_CREATE_MASK_LE) {
2067 case FILE_CREATE_LE:
2069 case FILE_SUPERSEDE_LE:
2070 case FILE_OVERWRITE_LE:
2071 case FILE_OVERWRITE_IF_LE:
2078 switch (disposition & FILE_CREATE_MASK_LE) {
2079 case FILE_SUPERSEDE_LE:
2080 case FILE_CREATE_LE:
2081 case FILE_OPEN_IF_LE:
2082 case FILE_OVERWRITE_IF_LE:
2086 case FILE_OVERWRITE_LE:
2098 * smb2_tree_disconnect() - handler for smb tree connect request
2099 * @work: smb work containing request buffer
2103 int smb2_tree_disconnect(struct ksmbd_work *work)
2105 struct smb2_tree_disconnect_rsp *rsp = smb2_get_msg(work->response_buf);
2106 struct ksmbd_session *sess = work->sess;
2107 struct ksmbd_tree_connect *tcon = work->tcon;
2109 rsp->StructureSize = cpu_to_le16(4);
2110 inc_rfc1001_len(work->response_buf, 4);
2112 ksmbd_debug(SMB, "request\n");
2114 if (!tcon || test_and_set_bit(TREE_CONN_EXPIRE, &tcon->status)) {
2115 struct smb2_tree_disconnect_req *req =
2116 smb2_get_msg(work->request_buf);
2118 ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
2120 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2121 smb2_set_err_rsp(work);
2125 ksmbd_close_tree_conn_fds(work);
2126 ksmbd_tree_conn_disconnect(sess, tcon);
2132 * smb2_session_logoff() - handler for session log off request
2133 * @work: smb work containing request buffer
2137 int smb2_session_logoff(struct ksmbd_work *work)
2139 struct ksmbd_conn *conn = work->conn;
2140 struct smb2_logoff_rsp *rsp = smb2_get_msg(work->response_buf);
2141 struct ksmbd_session *sess;
2142 struct smb2_logoff_req *req = smb2_get_msg(work->request_buf);
2143 u64 sess_id = le64_to_cpu(req->hdr.SessionId);
2145 rsp->StructureSize = cpu_to_le16(4);
2146 inc_rfc1001_len(work->response_buf, 4);
2148 ksmbd_debug(SMB, "request\n");
2150 ksmbd_all_conn_set_status(sess_id, KSMBD_SESS_NEED_RECONNECT);
2151 ksmbd_close_session_fds(work);
2152 ksmbd_conn_wait_idle(conn, sess_id);
2155 * Re-lookup session to validate if session is deleted
2156 * while waiting request complete
2158 sess = ksmbd_session_lookup_all(conn, sess_id);
2159 if (ksmbd_tree_conn_session_logoff(sess)) {
2160 ksmbd_debug(SMB, "Invalid tid %d\n", req->hdr.Id.SyncId.TreeId);
2161 rsp->hdr.Status = STATUS_NETWORK_NAME_DELETED;
2162 smb2_set_err_rsp(work);
2166 ksmbd_destroy_file_table(&sess->file_table);
2167 sess->state = SMB2_SESSION_EXPIRED;
2169 ksmbd_free_user(sess->user);
2171 ksmbd_all_conn_set_status(sess_id, KSMBD_SESS_NEED_NEGOTIATE);
2176 * create_smb2_pipe() - create IPC pipe
2177 * @work: smb work containing request buffer
2179 * Return: 0 on success, otherwise error
2181 static noinline int create_smb2_pipe(struct ksmbd_work *work)
2183 struct smb2_create_rsp *rsp = smb2_get_msg(work->response_buf);
2184 struct smb2_create_req *req = smb2_get_msg(work->request_buf);
2189 name = smb_strndup_from_utf16(req->Buffer, le16_to_cpu(req->NameLength),
2190 1, work->conn->local_nls);
2192 rsp->hdr.Status = STATUS_NO_MEMORY;
2193 err = PTR_ERR(name);
2197 id = ksmbd_session_rpc_open(work->sess, name);
2199 pr_err("Unable to open RPC pipe: %d\n", id);
2204 rsp->hdr.Status = STATUS_SUCCESS;
2205 rsp->StructureSize = cpu_to_le16(89);
2206 rsp->OplockLevel = SMB2_OPLOCK_LEVEL_NONE;
2208 rsp->CreateAction = cpu_to_le32(FILE_OPENED);
2210 rsp->CreationTime = cpu_to_le64(0);
2211 rsp->LastAccessTime = cpu_to_le64(0);
2212 rsp->ChangeTime = cpu_to_le64(0);
2213 rsp->AllocationSize = cpu_to_le64(0);
2214 rsp->EndofFile = cpu_to_le64(0);
2215 rsp->FileAttributes = FILE_ATTRIBUTE_NORMAL_LE;
2217 rsp->VolatileFileId = id;
2218 rsp->PersistentFileId = 0;
2219 rsp->CreateContextsOffset = 0;
2220 rsp->CreateContextsLength = 0;
2222 inc_rfc1001_len(work->response_buf, 88); /* StructureSize - 1*/
2229 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2233 rsp->hdr.Status = STATUS_NO_MEMORY;
2240 smb2_set_err_rsp(work);
2245 * smb2_set_ea() - handler for setting extended attributes using set
2247 * @eabuf: set info command buffer
2248 * @buf_len: set info command buffer length
2249 * @path: dentry path for get ea
2251 * Return: 0 on success, otherwise error
2253 static int smb2_set_ea(struct smb2_ea_info *eabuf, unsigned int buf_len,
2254 const struct path *path)
2256 struct user_namespace *user_ns = mnt_user_ns(path->mnt);
2257 char *attr_name = NULL, *value;
2259 unsigned int next = 0;
2261 if (buf_len < sizeof(struct smb2_ea_info) + eabuf->EaNameLength +
2262 le16_to_cpu(eabuf->EaValueLength))
2265 attr_name = kmalloc(XATTR_NAME_MAX + 1, GFP_KERNEL);
2270 if (!eabuf->EaNameLength)
2274 "name : <%s>, name_len : %u, value_len : %u, next : %u\n",
2275 eabuf->name, eabuf->EaNameLength,
2276 le16_to_cpu(eabuf->EaValueLength),
2277 le32_to_cpu(eabuf->NextEntryOffset));
2279 if (eabuf->EaNameLength >
2280 (XATTR_NAME_MAX - XATTR_USER_PREFIX_LEN)) {
2285 memcpy(attr_name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN);
2286 memcpy(&attr_name[XATTR_USER_PREFIX_LEN], eabuf->name,
2287 eabuf->EaNameLength);
2288 attr_name[XATTR_USER_PREFIX_LEN + eabuf->EaNameLength] = '\0';
2289 value = (char *)&eabuf->name + eabuf->EaNameLength + 1;
2291 if (!eabuf->EaValueLength) {
2292 rc = ksmbd_vfs_casexattr_len(user_ns,
2295 XATTR_USER_PREFIX_LEN +
2296 eabuf->EaNameLength);
2298 /* delete the EA only when it exits */
2300 rc = ksmbd_vfs_remove_xattr(user_ns,
2306 "remove xattr failed(%d)\n",
2312 /* if the EA doesn't exist, just do nothing. */
2315 rc = ksmbd_vfs_setxattr(user_ns,
2316 path->dentry, attr_name, value,
2317 le16_to_cpu(eabuf->EaValueLength), 0);
2320 "ksmbd_vfs_setxattr is failed(%d)\n",
2327 next = le32_to_cpu(eabuf->NextEntryOffset);
2328 if (next == 0 || buf_len < next)
2331 eabuf = (struct smb2_ea_info *)((char *)eabuf + next);
2332 if (next < (u32)eabuf->EaNameLength + le16_to_cpu(eabuf->EaValueLength))
2335 } while (next != 0);
2341 static noinline int smb2_set_stream_name_xattr(const struct path *path,
2342 struct ksmbd_file *fp,
2343 char *stream_name, int s_type)
2345 struct user_namespace *user_ns = mnt_user_ns(path->mnt);
2346 size_t xattr_stream_size;
2347 char *xattr_stream_name;
2350 rc = ksmbd_vfs_xattr_stream_name(stream_name,
2357 fp->stream.name = xattr_stream_name;
2358 fp->stream.size = xattr_stream_size;
2360 /* Check if there is stream prefix in xattr space */
2361 rc = ksmbd_vfs_casexattr_len(user_ns,
2368 if (fp->cdoption == FILE_OPEN_LE) {
2369 ksmbd_debug(SMB, "XATTR stream name lookup failed: %d\n", rc);
2373 rc = ksmbd_vfs_setxattr(user_ns, path->dentry,
2374 xattr_stream_name, NULL, 0, 0);
2376 pr_err("Failed to store XATTR stream name :%d\n", rc);
2380 static int smb2_remove_smb_xattrs(const struct path *path)
2382 struct user_namespace *user_ns = mnt_user_ns(path->mnt);
2383 char *name, *xattr_list = NULL;
2384 ssize_t xattr_list_len;
2387 xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
2388 if (xattr_list_len < 0) {
2390 } else if (!xattr_list_len) {
2391 ksmbd_debug(SMB, "empty xattr in the file\n");
2395 for (name = xattr_list; name - xattr_list < xattr_list_len;
2396 name += strlen(name) + 1) {
2397 ksmbd_debug(SMB, "%s, len %zd\n", name, strlen(name));
2399 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN) &&
2400 !strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
2401 STREAM_PREFIX_LEN)) {
2402 err = ksmbd_vfs_remove_xattr(user_ns, path->dentry,
2405 ksmbd_debug(SMB, "remove xattr failed : %s\n",
2414 static int smb2_create_truncate(const struct path *path)
2416 int rc = vfs_truncate(path, 0);
2419 pr_err("vfs_truncate failed, rc %d\n", rc);
2423 rc = smb2_remove_smb_xattrs(path);
2424 if (rc == -EOPNOTSUPP)
2428 "ksmbd_truncate_stream_name_xattr failed, rc %d\n",
2433 static void smb2_new_xattrs(struct ksmbd_tree_connect *tcon, const struct path *path,
2434 struct ksmbd_file *fp)
2436 struct xattr_dos_attrib da = {0};
2439 if (!test_share_config_flag(tcon->share_conf,
2440 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2444 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
2445 da.itime = da.create_time = fp->create_time;
2446 da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
2447 XATTR_DOSINFO_ITIME;
2449 rc = ksmbd_vfs_set_dos_attrib_xattr(mnt_user_ns(path->mnt),
2452 ksmbd_debug(SMB, "failed to store file attribute into xattr\n");
2455 static void smb2_update_xattrs(struct ksmbd_tree_connect *tcon,
2456 const struct path *path, struct ksmbd_file *fp)
2458 struct xattr_dos_attrib da;
2461 fp->f_ci->m_fattr &= ~(FILE_ATTRIBUTE_HIDDEN_LE | FILE_ATTRIBUTE_SYSTEM_LE);
2463 /* get FileAttributes from XATTR_NAME_DOS_ATTRIBUTE */
2464 if (!test_share_config_flag(tcon->share_conf,
2465 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS))
2468 rc = ksmbd_vfs_get_dos_attrib_xattr(mnt_user_ns(path->mnt),
2471 fp->f_ci->m_fattr = cpu_to_le32(da.attr);
2472 fp->create_time = da.create_time;
2473 fp->itime = da.itime;
2477 static int smb2_creat(struct ksmbd_work *work, struct path *path, char *name,
2478 int open_flags, umode_t posix_mode, bool is_dir)
2480 struct ksmbd_tree_connect *tcon = work->tcon;
2481 struct ksmbd_share_config *share = tcon->share_conf;
2485 if (!(open_flags & O_CREAT))
2488 ksmbd_debug(SMB, "file does not exist, so creating\n");
2489 if (is_dir == true) {
2490 ksmbd_debug(SMB, "creating directory\n");
2492 mode = share_config_directory_mode(share, posix_mode);
2493 rc = ksmbd_vfs_mkdir(work, name, mode);
2497 ksmbd_debug(SMB, "creating regular file\n");
2499 mode = share_config_create_mode(share, posix_mode);
2500 rc = ksmbd_vfs_create(work, name, mode);
2505 rc = ksmbd_vfs_kern_path(work, name, 0, path, 0);
2507 pr_err("cannot get linux path (%s), err = %d\n",
2514 static int smb2_create_sd_buffer(struct ksmbd_work *work,
2515 struct smb2_create_req *req,
2516 const struct path *path)
2518 struct create_context *context;
2519 struct create_sd_buf_req *sd_buf;
2521 if (!req->CreateContextsOffset)
2524 /* Parse SD BUFFER create contexts */
2525 context = smb2_find_context_vals(req, SMB2_CREATE_SD_BUFFER, 4);
2528 else if (IS_ERR(context))
2529 return PTR_ERR(context);
2532 "Set ACLs using SMB2_CREATE_SD_BUFFER context\n");
2533 sd_buf = (struct create_sd_buf_req *)context;
2534 if (le16_to_cpu(context->DataOffset) +
2535 le32_to_cpu(context->DataLength) <
2536 sizeof(struct create_sd_buf_req))
2538 return set_info_sec(work->conn, work->tcon, path, &sd_buf->ntsd,
2539 le32_to_cpu(sd_buf->ccontext.DataLength), true);
2542 static void ksmbd_acls_fattr(struct smb_fattr *fattr,
2543 struct user_namespace *mnt_userns,
2544 struct inode *inode)
2546 vfsuid_t vfsuid = i_uid_into_vfsuid(mnt_userns, inode);
2547 vfsgid_t vfsgid = i_gid_into_vfsgid(mnt_userns, inode);
2549 fattr->cf_uid = vfsuid_into_kuid(vfsuid);
2550 fattr->cf_gid = vfsgid_into_kgid(vfsgid);
2551 fattr->cf_mode = inode->i_mode;
2552 fattr->cf_acls = NULL;
2553 fattr->cf_dacls = NULL;
2555 if (IS_ENABLED(CONFIG_FS_POSIX_ACL)) {
2556 fattr->cf_acls = get_acl(inode, ACL_TYPE_ACCESS);
2557 if (S_ISDIR(inode->i_mode))
2558 fattr->cf_dacls = get_acl(inode, ACL_TYPE_DEFAULT);
2563 * smb2_open() - handler for smb file open request
2564 * @work: smb work containing request buffer
2566 * Return: 0 on success, otherwise error
2568 int smb2_open(struct ksmbd_work *work)
2570 struct ksmbd_conn *conn = work->conn;
2571 struct ksmbd_session *sess = work->sess;
2572 struct ksmbd_tree_connect *tcon = work->tcon;
2573 struct smb2_create_req *req;
2574 struct smb2_create_rsp *rsp;
2576 struct ksmbd_share_config *share = tcon->share_conf;
2577 struct ksmbd_file *fp = NULL;
2578 struct file *filp = NULL;
2579 struct user_namespace *user_ns = NULL;
2581 struct create_context *context;
2582 struct lease_ctx_info *lc = NULL;
2583 struct create_ea_buf_req *ea_buf = NULL;
2584 struct oplock_info *opinfo;
2585 __le32 *next_ptr = NULL;
2586 int req_op_level = 0, open_flags = 0, may_flags = 0, file_info = 0;
2588 int contxt_cnt = 0, query_disk_id = 0;
2589 int maximal_access_ctxt = 0, posix_ctxt = 0;
2593 char *stream_name = NULL;
2594 bool file_present = false, created = false, already_permitted = false;
2595 int share_ret, need_truncate = 0;
2597 umode_t posix_mode = 0;
2598 __le32 daccess, maximal_access = 0;
2600 WORK_BUFFERS(work, req, rsp);
2602 if (req->hdr.NextCommand && !work->next_smb2_rcv_hdr_off &&
2603 (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)) {
2604 ksmbd_debug(SMB, "invalid flag in chained command\n");
2605 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
2606 smb2_set_err_rsp(work);
2610 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_PIPE)) {
2611 ksmbd_debug(SMB, "IPC pipe create request\n");
2612 return create_smb2_pipe(work);
2615 if (req->NameLength) {
2616 if ((req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
2617 *(char *)req->Buffer == '\\') {
2618 pr_err("not allow directory name included leading slash\n");
2623 name = smb2_get_name(req->Buffer,
2624 le16_to_cpu(req->NameLength),
2625 work->conn->local_nls);
2634 ksmbd_debug(SMB, "converted name = %s\n", name);
2635 if (strchr(name, ':')) {
2636 if (!test_share_config_flag(work->tcon->share_conf,
2637 KSMBD_SHARE_FLAG_STREAMS)) {
2641 rc = parse_stream_name(name, &stream_name, &s_type);
2646 rc = ksmbd_validate_filename(name);
2650 if (ksmbd_share_veto_filename(share, name)) {
2652 ksmbd_debug(SMB, "Reject open(), vetoed file: %s\n",
2657 name = kstrdup("", GFP_KERNEL);
2664 req_op_level = req->RequestedOplockLevel;
2665 if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE)
2666 lc = parse_lease_state(req);
2668 if (le32_to_cpu(req->ImpersonationLevel) > le32_to_cpu(IL_DELEGATE)) {
2669 pr_err("Invalid impersonationlevel : 0x%x\n",
2670 le32_to_cpu(req->ImpersonationLevel));
2672 rsp->hdr.Status = STATUS_BAD_IMPERSONATION_LEVEL;
2676 if (req->CreateOptions && !(req->CreateOptions & CREATE_OPTIONS_MASK_LE)) {
2677 pr_err("Invalid create options : 0x%x\n",
2678 le32_to_cpu(req->CreateOptions));
2682 if (req->CreateOptions & FILE_SEQUENTIAL_ONLY_LE &&
2683 req->CreateOptions & FILE_RANDOM_ACCESS_LE)
2684 req->CreateOptions = ~(FILE_SEQUENTIAL_ONLY_LE);
2686 if (req->CreateOptions &
2687 (FILE_OPEN_BY_FILE_ID_LE | CREATE_TREE_CONNECTION |
2688 FILE_RESERVE_OPFILTER_LE)) {
2693 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
2694 if (req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE) {
2697 } else if (req->CreateOptions & FILE_NO_COMPRESSION_LE) {
2698 req->CreateOptions = ~(FILE_NO_COMPRESSION_LE);
2703 if (le32_to_cpu(req->CreateDisposition) >
2704 le32_to_cpu(FILE_OVERWRITE_IF_LE)) {
2705 pr_err("Invalid create disposition : 0x%x\n",
2706 le32_to_cpu(req->CreateDisposition));
2711 if (!(req->DesiredAccess & DESIRED_ACCESS_MASK)) {
2712 pr_err("Invalid desired access : 0x%x\n",
2713 le32_to_cpu(req->DesiredAccess));
2718 if (req->FileAttributes && !(req->FileAttributes & FILE_ATTRIBUTE_MASK_LE)) {
2719 pr_err("Invalid file attribute : 0x%x\n",
2720 le32_to_cpu(req->FileAttributes));
2725 if (req->CreateContextsOffset) {
2726 /* Parse non-durable handle create contexts */
2727 context = smb2_find_context_vals(req, SMB2_CREATE_EA_BUFFER, 4);
2728 if (IS_ERR(context)) {
2729 rc = PTR_ERR(context);
2731 } else if (context) {
2732 ea_buf = (struct create_ea_buf_req *)context;
2733 if (le16_to_cpu(context->DataOffset) +
2734 le32_to_cpu(context->DataLength) <
2735 sizeof(struct create_ea_buf_req)) {
2739 if (req->CreateOptions & FILE_NO_EA_KNOWLEDGE_LE) {
2740 rsp->hdr.Status = STATUS_ACCESS_DENIED;
2746 context = smb2_find_context_vals(req,
2747 SMB2_CREATE_QUERY_MAXIMAL_ACCESS_REQUEST, 4);
2748 if (IS_ERR(context)) {
2749 rc = PTR_ERR(context);
2751 } else if (context) {
2753 "get query maximal access context\n");
2754 maximal_access_ctxt = 1;
2757 context = smb2_find_context_vals(req,
2758 SMB2_CREATE_TIMEWARP_REQUEST, 4);
2759 if (IS_ERR(context)) {
2760 rc = PTR_ERR(context);
2762 } else if (context) {
2763 ksmbd_debug(SMB, "get timewarp context\n");
2768 if (tcon->posix_extensions) {
2769 context = smb2_find_context_vals(req,
2770 SMB2_CREATE_TAG_POSIX, 16);
2771 if (IS_ERR(context)) {
2772 rc = PTR_ERR(context);
2774 } else if (context) {
2775 struct create_posix *posix =
2776 (struct create_posix *)context;
2777 if (le16_to_cpu(context->DataOffset) +
2778 le32_to_cpu(context->DataLength) <
2779 sizeof(struct create_posix) - 4) {
2783 ksmbd_debug(SMB, "get posix context\n");
2785 posix_mode = le32_to_cpu(posix->Mode);
2791 if (ksmbd_override_fsids(work)) {
2796 rc = ksmbd_vfs_kern_path(work, name, LOOKUP_NO_SYMLINKS, &path, 1);
2798 if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE) {
2800 * If file exists with under flags, return access
2803 if (req->CreateDisposition == FILE_OVERWRITE_IF_LE ||
2804 req->CreateDisposition == FILE_OPEN_IF_LE) {
2810 if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
2812 "User does not have write permission\n");
2817 } else if (d_is_symlink(path.dentry)) {
2827 ksmbd_debug(SMB, "can not get linux path for %s, rc = %d\n",
2831 file_present = true;
2832 user_ns = mnt_user_ns(path.mnt);
2835 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE) {
2836 if (s_type == DATA_STREAM) {
2838 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2841 if (file_present && S_ISDIR(d_inode(path.dentry)->i_mode) &&
2842 s_type == DATA_STREAM) {
2844 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
2848 if (req->CreateOptions & FILE_DIRECTORY_FILE_LE &&
2849 req->FileAttributes & FILE_ATTRIBUTE_NORMAL_LE) {
2850 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2858 if (file_present && req->CreateOptions & FILE_NON_DIRECTORY_FILE_LE &&
2859 S_ISDIR(d_inode(path.dentry)->i_mode) &&
2860 !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2861 ksmbd_debug(SMB, "open() argument is a directory: %s, %x\n",
2862 name, req->CreateOptions);
2863 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
2868 if (file_present && (req->CreateOptions & FILE_DIRECTORY_FILE_LE) &&
2869 !(req->CreateDisposition == FILE_CREATE_LE) &&
2870 !S_ISDIR(d_inode(path.dentry)->i_mode)) {
2871 rsp->hdr.Status = STATUS_NOT_A_DIRECTORY;
2876 if (!stream_name && file_present &&
2877 req->CreateDisposition == FILE_CREATE_LE) {
2882 daccess = smb_map_generic_desired_access(req->DesiredAccess);
2884 if (file_present && !(req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2885 rc = smb_check_perm_dacl(conn, &path, &daccess,
2891 if (daccess & FILE_MAXIMAL_ACCESS_LE) {
2892 if (!file_present) {
2893 daccess = cpu_to_le32(GENERIC_ALL_FLAGS);
2895 rc = ksmbd_vfs_query_maximal_access(user_ns,
2900 already_permitted = true;
2902 maximal_access = daccess;
2905 open_flags = smb2_create_open_flags(file_present, daccess,
2906 req->CreateDisposition,
2909 if (!test_tree_conn_flag(tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
2910 if (open_flags & O_CREAT) {
2912 "User does not have write permission\n");
2918 /*create file if not present */
2919 if (!file_present) {
2920 rc = smb2_creat(work, &path, name, open_flags, posix_mode,
2921 req->CreateOptions & FILE_DIRECTORY_FILE_LE);
2923 if (rc == -ENOENT) {
2925 rsp->hdr.Status = STATUS_OBJECT_PATH_NOT_FOUND;
2931 user_ns = mnt_user_ns(path.mnt);
2933 if (le32_to_cpu(ea_buf->ccontext.DataLength) <
2934 sizeof(struct smb2_ea_info)) {
2939 rc = smb2_set_ea(&ea_buf->ea,
2940 le32_to_cpu(ea_buf->ccontext.DataLength),
2942 if (rc == -EOPNOTSUPP)
2947 } else if (!already_permitted) {
2948 /* FILE_READ_ATTRIBUTE is allowed without inode_permission,
2949 * because execute(search) permission on a parent directory,
2950 * is already granted.
2952 if (daccess & ~(FILE_READ_ATTRIBUTES_LE | FILE_READ_CONTROL_LE)) {
2953 rc = inode_permission(user_ns,
2954 d_inode(path.dentry),
2959 if ((daccess & FILE_DELETE_LE) ||
2960 (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)) {
2961 rc = ksmbd_vfs_may_delete(user_ns,
2969 rc = ksmbd_query_inode_status(d_inode(path.dentry->d_parent));
2970 if (rc == KSMBD_INODE_STATUS_PENDING_DELETE) {
2976 filp = dentry_open(&path, open_flags, current_cred());
2979 pr_err("dentry open for dir failed, rc %d\n", rc);
2984 if (!(open_flags & O_TRUNC))
2985 file_info = FILE_OPENED;
2987 file_info = FILE_OVERWRITTEN;
2989 if ((req->CreateDisposition & FILE_CREATE_MASK_LE) ==
2991 file_info = FILE_SUPERSEDED;
2992 } else if (open_flags & O_CREAT) {
2993 file_info = FILE_CREATED;
2996 ksmbd_vfs_set_fadvise(filp, req->CreateOptions);
2998 /* Obtain Volatile-ID */
2999 fp = ksmbd_open_fd(work, filp);
3007 /* Get Persistent-ID */
3008 ksmbd_open_durable_fd(fp);
3009 if (!has_file_id(fp->persistent_id)) {
3014 fp->cdoption = req->CreateDisposition;
3015 fp->daccess = daccess;
3016 fp->saccess = req->ShareAccess;
3017 fp->coption = req->CreateOptions;
3019 /* Set default windows and posix acls if creating new file */
3022 struct inode *inode = d_inode(path.dentry);
3024 posix_acl_rc = ksmbd_vfs_inherit_posix_acl(user_ns,
3026 d_inode(path.dentry->d_parent));
3028 ksmbd_debug(SMB, "inherit posix acl failed : %d\n", posix_acl_rc);
3030 if (test_share_config_flag(work->tcon->share_conf,
3031 KSMBD_SHARE_FLAG_ACL_XATTR)) {
3032 rc = smb_inherit_dacl(conn, &path, sess->user->uid,
3037 rc = smb2_create_sd_buffer(work, req, &path);
3040 ksmbd_vfs_set_init_posix_acl(user_ns,
3043 if (test_share_config_flag(work->tcon->share_conf,
3044 KSMBD_SHARE_FLAG_ACL_XATTR)) {
3045 struct smb_fattr fattr;
3046 struct smb_ntsd *pntsd;
3047 int pntsd_size, ace_num = 0;
3049 ksmbd_acls_fattr(&fattr, user_ns, inode);
3051 ace_num = fattr.cf_acls->a_count;
3053 ace_num += fattr.cf_dacls->a_count;
3055 pntsd = kmalloc(sizeof(struct smb_ntsd) +
3056 sizeof(struct smb_sid) * 3 +
3057 sizeof(struct smb_acl) +
3058 sizeof(struct smb_ace) * ace_num * 2,
3061 posix_acl_release(fattr.cf_acls);
3062 posix_acl_release(fattr.cf_dacls);
3066 rc = build_sec_desc(user_ns,
3071 &pntsd_size, &fattr);
3072 posix_acl_release(fattr.cf_acls);
3073 posix_acl_release(fattr.cf_dacls);
3079 rc = ksmbd_vfs_set_sd_xattr(conn,
3086 pr_err("failed to store ntacl in xattr : %d\n",
3095 rc = smb2_set_stream_name_xattr(&path,
3101 file_info = FILE_CREATED;
3104 fp->attrib_only = !(req->DesiredAccess & ~(FILE_READ_ATTRIBUTES_LE |
3105 FILE_WRITE_ATTRIBUTES_LE | FILE_SYNCHRONIZE_LE));
3106 if (!S_ISDIR(file_inode(filp)->i_mode) && open_flags & O_TRUNC &&
3107 !fp->attrib_only && !stream_name) {
3108 smb_break_all_oplock(work, fp);
3112 /* fp should be searchable through ksmbd_inode.m_fp_list
3113 * after daccess, saccess, attrib_only, and stream are
3116 write_lock(&fp->f_ci->m_lock);
3117 list_add(&fp->node, &fp->f_ci->m_fp_list);
3118 write_unlock(&fp->f_ci->m_lock);
3120 /* Check delete pending among previous fp before oplock break */
3121 if (ksmbd_inode_pending_delete(fp)) {
3126 share_ret = ksmbd_smb_check_shared_mode(fp->filp, fp);
3127 if (!test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_OPLOCKS) ||
3128 (req_op_level == SMB2_OPLOCK_LEVEL_LEASE &&
3129 !(conn->vals->capabilities & SMB2_GLOBAL_CAP_LEASING))) {
3130 if (share_ret < 0 && !S_ISDIR(file_inode(fp->filp)->i_mode)) {
3135 if (req_op_level == SMB2_OPLOCK_LEVEL_LEASE) {
3136 req_op_level = smb2_map_lease_to_oplock(lc->req_state);
3138 "lease req for(%s) req oplock state 0x%x, lease state 0x%x\n",
3139 name, req_op_level, lc->req_state);
3140 rc = find_same_lease_key(sess, fp->f_ci, lc);
3143 } else if (open_flags == O_RDONLY &&
3144 (req_op_level == SMB2_OPLOCK_LEVEL_BATCH ||
3145 req_op_level == SMB2_OPLOCK_LEVEL_EXCLUSIVE))
3146 req_op_level = SMB2_OPLOCK_LEVEL_II;
3148 rc = smb_grant_oplock(work, req_op_level,
3149 fp->persistent_id, fp,
3150 le32_to_cpu(req->hdr.Id.SyncId.TreeId),
3156 if (req->CreateOptions & FILE_DELETE_ON_CLOSE_LE)
3157 ksmbd_fd_set_delete_on_close(fp, file_info);
3159 if (need_truncate) {
3160 rc = smb2_create_truncate(&path);
3165 if (req->CreateContextsOffset) {
3166 struct create_alloc_size_req *az_req;
3168 az_req = (struct create_alloc_size_req *)smb2_find_context_vals(req,
3169 SMB2_CREATE_ALLOCATION_SIZE, 4);
3170 if (IS_ERR(az_req)) {
3171 rc = PTR_ERR(az_req);
3173 } else if (az_req) {
3177 if (le16_to_cpu(az_req->ccontext.DataOffset) +
3178 le32_to_cpu(az_req->ccontext.DataLength) <
3179 sizeof(struct create_alloc_size_req)) {
3183 alloc_size = le64_to_cpu(az_req->AllocationSize);
3185 "request smb2 create allocate size : %llu\n",
3187 smb_break_all_levII_oplock(work, fp, 1);
3188 err = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
3192 "vfs_fallocate is failed : %d\n",
3196 context = smb2_find_context_vals(req, SMB2_CREATE_QUERY_ON_DISK_ID, 4);
3197 if (IS_ERR(context)) {
3198 rc = PTR_ERR(context);
3200 } else if (context) {
3201 ksmbd_debug(SMB, "get query on disk id context\n");
3206 rc = ksmbd_vfs_getattr(&path, &stat);
3210 if (stat.result_mask & STATX_BTIME)
3211 fp->create_time = ksmbd_UnixTimeToNT(stat.btime);
3213 fp->create_time = ksmbd_UnixTimeToNT(stat.ctime);
3214 if (req->FileAttributes || fp->f_ci->m_fattr == 0)
3216 cpu_to_le32(smb2_get_dos_mode(&stat, le32_to_cpu(req->FileAttributes)));
3219 smb2_update_xattrs(tcon, &path, fp);
3221 smb2_new_xattrs(tcon, &path, fp);
3223 memcpy(fp->client_guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE);
3225 rsp->StructureSize = cpu_to_le16(89);
3227 opinfo = rcu_dereference(fp->f_opinfo);
3228 rsp->OplockLevel = opinfo != NULL ? opinfo->level : 0;
3231 rsp->CreateAction = cpu_to_le32(file_info);
3232 rsp->CreationTime = cpu_to_le64(fp->create_time);
3233 time = ksmbd_UnixTimeToNT(stat.atime);
3234 rsp->LastAccessTime = cpu_to_le64(time);
3235 time = ksmbd_UnixTimeToNT(stat.mtime);
3236 rsp->LastWriteTime = cpu_to_le64(time);
3237 time = ksmbd_UnixTimeToNT(stat.ctime);
3238 rsp->ChangeTime = cpu_to_le64(time);
3239 rsp->AllocationSize = S_ISDIR(stat.mode) ? 0 :
3240 cpu_to_le64(stat.blocks << 9);
3241 rsp->EndofFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
3242 rsp->FileAttributes = fp->f_ci->m_fattr;
3246 rsp->PersistentFileId = fp->persistent_id;
3247 rsp->VolatileFileId = fp->volatile_id;
3249 rsp->CreateContextsOffset = 0;
3250 rsp->CreateContextsLength = 0;
3251 inc_rfc1001_len(work->response_buf, 88); /* StructureSize - 1*/
3253 /* If lease is request send lease context response */
3254 if (opinfo && opinfo->is_lease) {
3255 struct create_context *lease_ccontext;
3257 ksmbd_debug(SMB, "lease granted on(%s) lease state 0x%x\n",
3258 name, opinfo->o_lease->state);
3259 rsp->OplockLevel = SMB2_OPLOCK_LEVEL_LEASE;
3261 lease_ccontext = (struct create_context *)rsp->Buffer;
3263 create_lease_buf(rsp->Buffer, opinfo->o_lease);
3264 le32_add_cpu(&rsp->CreateContextsLength,
3265 conn->vals->create_lease_size);
3266 inc_rfc1001_len(work->response_buf,
3267 conn->vals->create_lease_size);
3268 next_ptr = &lease_ccontext->Next;
3269 next_off = conn->vals->create_lease_size;
3272 if (maximal_access_ctxt) {
3273 struct create_context *mxac_ccontext;
3275 if (maximal_access == 0)
3276 ksmbd_vfs_query_maximal_access(user_ns,
3279 mxac_ccontext = (struct create_context *)(rsp->Buffer +
3280 le32_to_cpu(rsp->CreateContextsLength));
3282 create_mxac_rsp_buf(rsp->Buffer +
3283 le32_to_cpu(rsp->CreateContextsLength),
3284 le32_to_cpu(maximal_access));
3285 le32_add_cpu(&rsp->CreateContextsLength,
3286 conn->vals->create_mxac_size);
3287 inc_rfc1001_len(work->response_buf,
3288 conn->vals->create_mxac_size);
3290 *next_ptr = cpu_to_le32(next_off);
3291 next_ptr = &mxac_ccontext->Next;
3292 next_off = conn->vals->create_mxac_size;
3295 if (query_disk_id) {
3296 struct create_context *disk_id_ccontext;
3298 disk_id_ccontext = (struct create_context *)(rsp->Buffer +
3299 le32_to_cpu(rsp->CreateContextsLength));
3301 create_disk_id_rsp_buf(rsp->Buffer +
3302 le32_to_cpu(rsp->CreateContextsLength),
3303 stat.ino, tcon->id);
3304 le32_add_cpu(&rsp->CreateContextsLength,
3305 conn->vals->create_disk_id_size);
3306 inc_rfc1001_len(work->response_buf,
3307 conn->vals->create_disk_id_size);
3309 *next_ptr = cpu_to_le32(next_off);
3310 next_ptr = &disk_id_ccontext->Next;
3311 next_off = conn->vals->create_disk_id_size;
3316 create_posix_rsp_buf(rsp->Buffer +
3317 le32_to_cpu(rsp->CreateContextsLength),
3319 le32_add_cpu(&rsp->CreateContextsLength,
3320 conn->vals->create_posix_size);
3321 inc_rfc1001_len(work->response_buf,
3322 conn->vals->create_posix_size);
3324 *next_ptr = cpu_to_le32(next_off);
3327 if (contxt_cnt > 0) {
3328 rsp->CreateContextsOffset =
3329 cpu_to_le32(offsetof(struct smb2_create_rsp, Buffer));
3333 if (file_present || created)
3335 ksmbd_revert_fsids(work);
3339 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
3340 else if (rc == -EOPNOTSUPP)
3341 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
3342 else if (rc == -EACCES || rc == -ESTALE || rc == -EXDEV)
3343 rsp->hdr.Status = STATUS_ACCESS_DENIED;
3344 else if (rc == -ENOENT)
3345 rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
3346 else if (rc == -EPERM)
3347 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
3348 else if (rc == -EBUSY)
3349 rsp->hdr.Status = STATUS_DELETE_PENDING;
3350 else if (rc == -EBADF)
3351 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
3352 else if (rc == -ENOEXEC)
3353 rsp->hdr.Status = STATUS_DUPLICATE_OBJECTID;
3354 else if (rc == -ENXIO)
3355 rsp->hdr.Status = STATUS_NO_SUCH_DEVICE;
3356 else if (rc == -EEXIST)
3357 rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
3358 else if (rc == -EMFILE)
3359 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
3360 if (!rsp->hdr.Status)
3361 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
3364 ksmbd_fd_put(work, fp);
3365 smb2_set_err_rsp(work);
3366 ksmbd_debug(SMB, "Error response: %x\n", rsp->hdr.Status);
3375 static int readdir_info_level_struct_sz(int info_level)
3377 switch (info_level) {
3378 case FILE_FULL_DIRECTORY_INFORMATION:
3379 return sizeof(struct file_full_directory_info);
3380 case FILE_BOTH_DIRECTORY_INFORMATION:
3381 return sizeof(struct file_both_directory_info);
3382 case FILE_DIRECTORY_INFORMATION:
3383 return sizeof(struct file_directory_info);
3384 case FILE_NAMES_INFORMATION:
3385 return sizeof(struct file_names_info);
3386 case FILEID_FULL_DIRECTORY_INFORMATION:
3387 return sizeof(struct file_id_full_dir_info);
3388 case FILEID_BOTH_DIRECTORY_INFORMATION:
3389 return sizeof(struct file_id_both_directory_info);
3390 case SMB_FIND_FILE_POSIX_INFO:
3391 return sizeof(struct smb2_posix_info);
3397 static int dentry_name(struct ksmbd_dir_info *d_info, int info_level)
3399 switch (info_level) {
3400 case FILE_FULL_DIRECTORY_INFORMATION:
3402 struct file_full_directory_info *ffdinfo;
3404 ffdinfo = (struct file_full_directory_info *)d_info->rptr;
3405 d_info->rptr += le32_to_cpu(ffdinfo->NextEntryOffset);
3406 d_info->name = ffdinfo->FileName;
3407 d_info->name_len = le32_to_cpu(ffdinfo->FileNameLength);
3410 case FILE_BOTH_DIRECTORY_INFORMATION:
3412 struct file_both_directory_info *fbdinfo;
3414 fbdinfo = (struct file_both_directory_info *)d_info->rptr;
3415 d_info->rptr += le32_to_cpu(fbdinfo->NextEntryOffset);
3416 d_info->name = fbdinfo->FileName;
3417 d_info->name_len = le32_to_cpu(fbdinfo->FileNameLength);
3420 case FILE_DIRECTORY_INFORMATION:
3422 struct file_directory_info *fdinfo;
3424 fdinfo = (struct file_directory_info *)d_info->rptr;
3425 d_info->rptr += le32_to_cpu(fdinfo->NextEntryOffset);
3426 d_info->name = fdinfo->FileName;
3427 d_info->name_len = le32_to_cpu(fdinfo->FileNameLength);
3430 case FILE_NAMES_INFORMATION:
3432 struct file_names_info *fninfo;
3434 fninfo = (struct file_names_info *)d_info->rptr;
3435 d_info->rptr += le32_to_cpu(fninfo->NextEntryOffset);
3436 d_info->name = fninfo->FileName;
3437 d_info->name_len = le32_to_cpu(fninfo->FileNameLength);
3440 case FILEID_FULL_DIRECTORY_INFORMATION:
3442 struct file_id_full_dir_info *dinfo;
3444 dinfo = (struct file_id_full_dir_info *)d_info->rptr;
3445 d_info->rptr += le32_to_cpu(dinfo->NextEntryOffset);
3446 d_info->name = dinfo->FileName;
3447 d_info->name_len = le32_to_cpu(dinfo->FileNameLength);
3450 case FILEID_BOTH_DIRECTORY_INFORMATION:
3452 struct file_id_both_directory_info *fibdinfo;
3454 fibdinfo = (struct file_id_both_directory_info *)d_info->rptr;
3455 d_info->rptr += le32_to_cpu(fibdinfo->NextEntryOffset);
3456 d_info->name = fibdinfo->FileName;
3457 d_info->name_len = le32_to_cpu(fibdinfo->FileNameLength);
3460 case SMB_FIND_FILE_POSIX_INFO:
3462 struct smb2_posix_info *posix_info;
3464 posix_info = (struct smb2_posix_info *)d_info->rptr;
3465 d_info->rptr += le32_to_cpu(posix_info->NextEntryOffset);
3466 d_info->name = posix_info->name;
3467 d_info->name_len = le32_to_cpu(posix_info->name_len);
3476 * smb2_populate_readdir_entry() - encode directory entry in smb2 response
3478 * @conn: connection instance
3479 * @info_level: smb information level
3480 * @d_info: structure included variables for query dir
3481 * @ksmbd_kstat: ksmbd wrapper of dirent stat information
3483 * if directory has many entries, find first can't read it fully.
3484 * find next might be called multiple times to read remaining dir entries
3486 * Return: 0 on success, otherwise error
3488 static int smb2_populate_readdir_entry(struct ksmbd_conn *conn, int info_level,
3489 struct ksmbd_dir_info *d_info,
3490 struct ksmbd_kstat *ksmbd_kstat)
3492 int next_entry_offset = 0;
3496 int struct_sz, rc = 0;
3498 conv_name = ksmbd_convert_dir_info_name(d_info,
3504 /* Somehow the name has only terminating NULL bytes */
3507 goto free_conv_name;
3510 struct_sz = readdir_info_level_struct_sz(info_level) - 1 + conv_len;
3511 next_entry_offset = ALIGN(struct_sz, KSMBD_DIR_INFO_ALIGNMENT);
3512 d_info->last_entry_off_align = next_entry_offset - struct_sz;
3514 if (next_entry_offset > d_info->out_buf_len) {
3515 d_info->out_buf_len = 0;
3517 goto free_conv_name;
3520 kstat = d_info->wptr;
3521 if (info_level != FILE_NAMES_INFORMATION)
3522 kstat = ksmbd_vfs_init_kstat(&d_info->wptr, ksmbd_kstat);
3524 switch (info_level) {
3525 case FILE_FULL_DIRECTORY_INFORMATION:
3527 struct file_full_directory_info *ffdinfo;
3529 ffdinfo = (struct file_full_directory_info *)kstat;
3530 ffdinfo->FileNameLength = cpu_to_le32(conv_len);
3532 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3533 if (ffdinfo->EaSize)
3534 ffdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3535 if (d_info->hide_dot_file && d_info->name[0] == '.')
3536 ffdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3537 memcpy(ffdinfo->FileName, conv_name, conv_len);
3538 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3541 case FILE_BOTH_DIRECTORY_INFORMATION:
3543 struct file_both_directory_info *fbdinfo;
3545 fbdinfo = (struct file_both_directory_info *)kstat;
3546 fbdinfo->FileNameLength = cpu_to_le32(conv_len);
3548 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3549 if (fbdinfo->EaSize)
3550 fbdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3551 fbdinfo->ShortNameLength = 0;
3552 fbdinfo->Reserved = 0;
3553 if (d_info->hide_dot_file && d_info->name[0] == '.')
3554 fbdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3555 memcpy(fbdinfo->FileName, conv_name, conv_len);
3556 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3559 case FILE_DIRECTORY_INFORMATION:
3561 struct file_directory_info *fdinfo;
3563 fdinfo = (struct file_directory_info *)kstat;
3564 fdinfo->FileNameLength = cpu_to_le32(conv_len);
3565 if (d_info->hide_dot_file && d_info->name[0] == '.')
3566 fdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3567 memcpy(fdinfo->FileName, conv_name, conv_len);
3568 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3571 case FILE_NAMES_INFORMATION:
3573 struct file_names_info *fninfo;
3575 fninfo = (struct file_names_info *)kstat;
3576 fninfo->FileNameLength = cpu_to_le32(conv_len);
3577 memcpy(fninfo->FileName, conv_name, conv_len);
3578 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3581 case FILEID_FULL_DIRECTORY_INFORMATION:
3583 struct file_id_full_dir_info *dinfo;
3585 dinfo = (struct file_id_full_dir_info *)kstat;
3586 dinfo->FileNameLength = cpu_to_le32(conv_len);
3588 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3590 dinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3591 dinfo->Reserved = 0;
3592 dinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
3593 if (d_info->hide_dot_file && d_info->name[0] == '.')
3594 dinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3595 memcpy(dinfo->FileName, conv_name, conv_len);
3596 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3599 case FILEID_BOTH_DIRECTORY_INFORMATION:
3601 struct file_id_both_directory_info *fibdinfo;
3603 fibdinfo = (struct file_id_both_directory_info *)kstat;
3604 fibdinfo->FileNameLength = cpu_to_le32(conv_len);
3606 smb2_get_reparse_tag_special_file(ksmbd_kstat->kstat->mode);
3607 if (fibdinfo->EaSize)
3608 fibdinfo->ExtFileAttributes = FILE_ATTRIBUTE_REPARSE_POINT_LE;
3609 fibdinfo->UniqueId = cpu_to_le64(ksmbd_kstat->kstat->ino);
3610 fibdinfo->ShortNameLength = 0;
3611 fibdinfo->Reserved = 0;
3612 fibdinfo->Reserved2 = cpu_to_le16(0);
3613 if (d_info->hide_dot_file && d_info->name[0] == '.')
3614 fibdinfo->ExtFileAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3615 memcpy(fibdinfo->FileName, conv_name, conv_len);
3616 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3619 case SMB_FIND_FILE_POSIX_INFO:
3621 struct smb2_posix_info *posix_info;
3624 posix_info = (struct smb2_posix_info *)kstat;
3625 posix_info->Ignored = 0;
3626 posix_info->CreationTime = cpu_to_le64(ksmbd_kstat->create_time);
3627 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->ctime);
3628 posix_info->ChangeTime = cpu_to_le64(time);
3629 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->atime);
3630 posix_info->LastAccessTime = cpu_to_le64(time);
3631 time = ksmbd_UnixTimeToNT(ksmbd_kstat->kstat->mtime);
3632 posix_info->LastWriteTime = cpu_to_le64(time);
3633 posix_info->EndOfFile = cpu_to_le64(ksmbd_kstat->kstat->size);
3634 posix_info->AllocationSize = cpu_to_le64(ksmbd_kstat->kstat->blocks << 9);
3635 posix_info->DeviceId = cpu_to_le32(ksmbd_kstat->kstat->rdev);
3636 posix_info->HardLinks = cpu_to_le32(ksmbd_kstat->kstat->nlink);
3637 posix_info->Mode = cpu_to_le32(ksmbd_kstat->kstat->mode & 0777);
3638 posix_info->Inode = cpu_to_le64(ksmbd_kstat->kstat->ino);
3639 posix_info->DosAttributes =
3640 S_ISDIR(ksmbd_kstat->kstat->mode) ?
3641 FILE_ATTRIBUTE_DIRECTORY_LE : FILE_ATTRIBUTE_ARCHIVE_LE;
3642 if (d_info->hide_dot_file && d_info->name[0] == '.')
3643 posix_info->DosAttributes |= FILE_ATTRIBUTE_HIDDEN_LE;
3645 * SidBuffer(32) contain two sids(Domain sid(16), UNIX group sid(16)).
3646 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) +
3647 * sub_auth(4 * 1(num_subauth)) + RID(4).
3649 id_to_sid(from_kuid_munged(&init_user_ns, ksmbd_kstat->kstat->uid),
3650 SIDUNIX_USER, (struct smb_sid *)&posix_info->SidBuffer[0]);
3651 id_to_sid(from_kgid_munged(&init_user_ns, ksmbd_kstat->kstat->gid),
3652 SIDUNIX_GROUP, (struct smb_sid *)&posix_info->SidBuffer[16]);
3653 memcpy(posix_info->name, conv_name, conv_len);
3654 posix_info->name_len = cpu_to_le32(conv_len);
3655 posix_info->NextEntryOffset = cpu_to_le32(next_entry_offset);
3659 } /* switch (info_level) */
3661 d_info->last_entry_offset = d_info->data_count;
3662 d_info->data_count += next_entry_offset;
3663 d_info->out_buf_len -= next_entry_offset;
3664 d_info->wptr += next_entry_offset;
3667 "info_level : %d, buf_len :%d, next_offset : %d, data_count : %d\n",
3668 info_level, d_info->out_buf_len,
3669 next_entry_offset, d_info->data_count);
3676 struct smb2_query_dir_private {
3677 struct ksmbd_work *work;
3678 char *search_pattern;
3679 struct ksmbd_file *dir_fp;
3681 struct ksmbd_dir_info *d_info;
3685 static void lock_dir(struct ksmbd_file *dir_fp)
3687 struct dentry *dir = dir_fp->filp->f_path.dentry;
3689 inode_lock_nested(d_inode(dir), I_MUTEX_PARENT);
3692 static void unlock_dir(struct ksmbd_file *dir_fp)
3694 struct dentry *dir = dir_fp->filp->f_path.dentry;
3696 inode_unlock(d_inode(dir));
3699 static int process_query_dir_entries(struct smb2_query_dir_private *priv)
3701 struct user_namespace *user_ns = file_mnt_user_ns(priv->dir_fp->filp);
3703 struct ksmbd_kstat ksmbd_kstat;
3707 for (i = 0; i < priv->d_info->num_entry; i++) {
3708 struct dentry *dent;
3710 if (dentry_name(priv->d_info, priv->info_level))
3713 lock_dir(priv->dir_fp);
3714 dent = lookup_one(user_ns, priv->d_info->name,
3715 priv->dir_fp->filp->f_path.dentry,
3716 priv->d_info->name_len);
3717 unlock_dir(priv->dir_fp);
3720 ksmbd_debug(SMB, "Cannot lookup `%s' [%ld]\n",
3725 if (unlikely(d_is_negative(dent))) {
3727 ksmbd_debug(SMB, "Negative dentry `%s'\n",
3728 priv->d_info->name);
3732 ksmbd_kstat.kstat = &kstat;
3733 if (priv->info_level != FILE_NAMES_INFORMATION)
3734 ksmbd_vfs_fill_dentry_attrs(priv->work,
3739 rc = smb2_populate_readdir_entry(priv->work->conn,
3750 static int reserve_populate_dentry(struct ksmbd_dir_info *d_info,
3755 int next_entry_offset;
3757 struct_sz = readdir_info_level_struct_sz(info_level);
3758 if (struct_sz == -EOPNOTSUPP)
3761 conv_len = (d_info->name_len + 1) * 2;
3762 next_entry_offset = ALIGN(struct_sz - 1 + conv_len,
3763 KSMBD_DIR_INFO_ALIGNMENT);
3765 if (next_entry_offset > d_info->out_buf_len) {
3766 d_info->out_buf_len = 0;
3770 switch (info_level) {
3771 case FILE_FULL_DIRECTORY_INFORMATION:
3773 struct file_full_directory_info *ffdinfo;
3775 ffdinfo = (struct file_full_directory_info *)d_info->wptr;
3776 memcpy(ffdinfo->FileName, d_info->name, d_info->name_len);
3777 ffdinfo->FileName[d_info->name_len] = 0x00;
3778 ffdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3779 ffdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3782 case FILE_BOTH_DIRECTORY_INFORMATION:
3784 struct file_both_directory_info *fbdinfo;
3786 fbdinfo = (struct file_both_directory_info *)d_info->wptr;
3787 memcpy(fbdinfo->FileName, d_info->name, d_info->name_len);
3788 fbdinfo->FileName[d_info->name_len] = 0x00;
3789 fbdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3790 fbdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3793 case FILE_DIRECTORY_INFORMATION:
3795 struct file_directory_info *fdinfo;
3797 fdinfo = (struct file_directory_info *)d_info->wptr;
3798 memcpy(fdinfo->FileName, d_info->name, d_info->name_len);
3799 fdinfo->FileName[d_info->name_len] = 0x00;
3800 fdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3801 fdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3804 case FILE_NAMES_INFORMATION:
3806 struct file_names_info *fninfo;
3808 fninfo = (struct file_names_info *)d_info->wptr;
3809 memcpy(fninfo->FileName, d_info->name, d_info->name_len);
3810 fninfo->FileName[d_info->name_len] = 0x00;
3811 fninfo->FileNameLength = cpu_to_le32(d_info->name_len);
3812 fninfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3815 case FILEID_FULL_DIRECTORY_INFORMATION:
3817 struct file_id_full_dir_info *dinfo;
3819 dinfo = (struct file_id_full_dir_info *)d_info->wptr;
3820 memcpy(dinfo->FileName, d_info->name, d_info->name_len);
3821 dinfo->FileName[d_info->name_len] = 0x00;
3822 dinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3823 dinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3826 case FILEID_BOTH_DIRECTORY_INFORMATION:
3828 struct file_id_both_directory_info *fibdinfo;
3830 fibdinfo = (struct file_id_both_directory_info *)d_info->wptr;
3831 memcpy(fibdinfo->FileName, d_info->name, d_info->name_len);
3832 fibdinfo->FileName[d_info->name_len] = 0x00;
3833 fibdinfo->FileNameLength = cpu_to_le32(d_info->name_len);
3834 fibdinfo->NextEntryOffset = cpu_to_le32(next_entry_offset);
3837 case SMB_FIND_FILE_POSIX_INFO:
3839 struct smb2_posix_info *posix_info;
3841 posix_info = (struct smb2_posix_info *)d_info->wptr;
3842 memcpy(posix_info->name, d_info->name, d_info->name_len);
3843 posix_info->name[d_info->name_len] = 0x00;
3844 posix_info->name_len = cpu_to_le32(d_info->name_len);
3845 posix_info->NextEntryOffset =
3846 cpu_to_le32(next_entry_offset);
3849 } /* switch (info_level) */
3851 d_info->num_entry++;
3852 d_info->out_buf_len -= next_entry_offset;
3853 d_info->wptr += next_entry_offset;
3857 static bool __query_dir(struct dir_context *ctx, const char *name, int namlen,
3858 loff_t offset, u64 ino, unsigned int d_type)
3860 struct ksmbd_readdir_data *buf;
3861 struct smb2_query_dir_private *priv;
3862 struct ksmbd_dir_info *d_info;
3865 buf = container_of(ctx, struct ksmbd_readdir_data, ctx);
3866 priv = buf->private;
3867 d_info = priv->d_info;
3869 /* dot and dotdot entries are already reserved */
3870 if (!strcmp(".", name) || !strcmp("..", name))
3872 if (ksmbd_share_veto_filename(priv->work->tcon->share_conf, name))
3874 if (!match_pattern(name, namlen, priv->search_pattern))
3877 d_info->name = name;
3878 d_info->name_len = namlen;
3879 rc = reserve_populate_dentry(d_info, priv->info_level);
3882 if (d_info->flags & SMB2_RETURN_SINGLE_ENTRY)
3883 d_info->out_buf_len = 0;
3887 static int verify_info_level(int info_level)
3889 switch (info_level) {
3890 case FILE_FULL_DIRECTORY_INFORMATION:
3891 case FILE_BOTH_DIRECTORY_INFORMATION:
3892 case FILE_DIRECTORY_INFORMATION:
3893 case FILE_NAMES_INFORMATION:
3894 case FILEID_FULL_DIRECTORY_INFORMATION:
3895 case FILEID_BOTH_DIRECTORY_INFORMATION:
3896 case SMB_FIND_FILE_POSIX_INFO:
3905 static int smb2_resp_buf_len(struct ksmbd_work *work, unsigned short hdr2_len)
3909 free_len = (int)(work->response_sz -
3910 (get_rfc1002_len(work->response_buf) + 4)) - hdr2_len;
3914 static int smb2_calc_max_out_buf_len(struct ksmbd_work *work,
3915 unsigned short hdr2_len,
3916 unsigned int out_buf_len)
3920 if (out_buf_len > work->conn->vals->max_trans_size)
3923 free_len = smb2_resp_buf_len(work, hdr2_len);
3927 return min_t(int, out_buf_len, free_len);
3930 int smb2_query_dir(struct ksmbd_work *work)
3932 struct ksmbd_conn *conn = work->conn;
3933 struct smb2_query_directory_req *req;
3934 struct smb2_query_directory_rsp *rsp;
3935 struct ksmbd_share_config *share = work->tcon->share_conf;
3936 struct ksmbd_file *dir_fp = NULL;
3937 struct ksmbd_dir_info d_info;
3939 char *srch_ptr = NULL;
3940 unsigned char srch_flag;
3942 struct smb2_query_dir_private query_dir_private = {NULL, };
3944 WORK_BUFFERS(work, req, rsp);
3946 if (ksmbd_override_fsids(work)) {
3947 rsp->hdr.Status = STATUS_NO_MEMORY;
3948 smb2_set_err_rsp(work);
3952 rc = verify_info_level(req->FileInformationClass);
3958 dir_fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
3964 if (!(dir_fp->daccess & FILE_LIST_DIRECTORY_LE) ||
3965 inode_permission(file_mnt_user_ns(dir_fp->filp),
3966 file_inode(dir_fp->filp),
3967 MAY_READ | MAY_EXEC)) {
3968 pr_err("no right to enumerate directory (%pD)\n", dir_fp->filp);
3973 if (!S_ISDIR(file_inode(dir_fp->filp)->i_mode)) {
3974 pr_err("can't do query dir for a file\n");
3979 srch_flag = req->Flags;
3980 srch_ptr = smb_strndup_from_utf16(req->Buffer,
3981 le16_to_cpu(req->FileNameLength), 1,
3983 if (IS_ERR(srch_ptr)) {
3984 ksmbd_debug(SMB, "Search Pattern not found\n");
3988 ksmbd_debug(SMB, "Search pattern is %s\n", srch_ptr);
3991 if (srch_flag & SMB2_REOPEN || srch_flag & SMB2_RESTART_SCANS) {
3992 ksmbd_debug(SMB, "Restart directory scan\n");
3993 generic_file_llseek(dir_fp->filp, 0, SEEK_SET);
3996 memset(&d_info, 0, sizeof(struct ksmbd_dir_info));
3997 d_info.wptr = (char *)rsp->Buffer;
3998 d_info.rptr = (char *)rsp->Buffer;
3999 d_info.out_buf_len =
4000 smb2_calc_max_out_buf_len(work, 8,
4001 le32_to_cpu(req->OutputBufferLength));
4002 if (d_info.out_buf_len < 0) {
4006 d_info.flags = srch_flag;
4009 * reserve dot and dotdot entries in head of buffer
4012 rc = ksmbd_populate_dot_dotdot_entries(work, req->FileInformationClass,
4013 dir_fp, &d_info, srch_ptr,
4014 smb2_populate_readdir_entry);
4020 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_HIDE_DOT_FILES))
4021 d_info.hide_dot_file = true;
4023 buffer_sz = d_info.out_buf_len;
4024 d_info.rptr = d_info.wptr;
4025 query_dir_private.work = work;
4026 query_dir_private.search_pattern = srch_ptr;
4027 query_dir_private.dir_fp = dir_fp;
4028 query_dir_private.d_info = &d_info;
4029 query_dir_private.info_level = req->FileInformationClass;
4030 dir_fp->readdir_data.private = &query_dir_private;
4031 set_ctx_actor(&dir_fp->readdir_data.ctx, __query_dir);
4033 rc = iterate_dir(dir_fp->filp, &dir_fp->readdir_data.ctx);
4035 * req->OutputBufferLength is too small to contain even one entry.
4036 * In this case, it immediately returns OutputBufferLength 0 to client.
4038 if (!d_info.out_buf_len && !d_info.num_entry)
4040 if (rc > 0 || rc == -ENOSPC)
4045 d_info.wptr = d_info.rptr;
4046 d_info.out_buf_len = buffer_sz;
4047 rc = process_query_dir_entries(&query_dir_private);
4051 if (!d_info.data_count && d_info.out_buf_len >= 0) {
4052 if (srch_flag & SMB2_RETURN_SINGLE_ENTRY && !is_asterisk(srch_ptr)) {
4053 rsp->hdr.Status = STATUS_NO_SUCH_FILE;
4055 dir_fp->dot_dotdot[0] = dir_fp->dot_dotdot[1] = 0;
4056 rsp->hdr.Status = STATUS_NO_MORE_FILES;
4058 rsp->StructureSize = cpu_to_le16(9);
4059 rsp->OutputBufferOffset = cpu_to_le16(0);
4060 rsp->OutputBufferLength = cpu_to_le32(0);
4062 inc_rfc1001_len(work->response_buf, 9);
4065 ((struct file_directory_info *)
4066 ((char *)rsp->Buffer + d_info.last_entry_offset))
4067 ->NextEntryOffset = 0;
4068 if (d_info.data_count >= d_info.last_entry_off_align)
4069 d_info.data_count -= d_info.last_entry_off_align;
4071 rsp->StructureSize = cpu_to_le16(9);
4072 rsp->OutputBufferOffset = cpu_to_le16(72);
4073 rsp->OutputBufferLength = cpu_to_le32(d_info.data_count);
4074 inc_rfc1001_len(work->response_buf, 8 + d_info.data_count);
4078 ksmbd_fd_put(work, dir_fp);
4079 ksmbd_revert_fsids(work);
4083 pr_err("error while processing smb2 query dir rc = %d\n", rc);
4088 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
4089 else if (rc == -EACCES)
4090 rsp->hdr.Status = STATUS_ACCESS_DENIED;
4091 else if (rc == -ENOENT)
4092 rsp->hdr.Status = STATUS_NO_SUCH_FILE;
4093 else if (rc == -EBADF)
4094 rsp->hdr.Status = STATUS_FILE_CLOSED;
4095 else if (rc == -ENOMEM)
4096 rsp->hdr.Status = STATUS_NO_MEMORY;
4097 else if (rc == -EFAULT)
4098 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
4099 else if (rc == -EIO)
4100 rsp->hdr.Status = STATUS_FILE_CORRUPT_ERROR;
4101 if (!rsp->hdr.Status)
4102 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
4104 smb2_set_err_rsp(work);
4105 ksmbd_fd_put(work, dir_fp);
4106 ksmbd_revert_fsids(work);
4111 * buffer_check_err() - helper function to check buffer errors
4112 * @reqOutputBufferLength: max buffer length expected in command response
4113 * @rsp: query info response buffer contains output buffer length
4114 * @rsp_org: base response buffer pointer in case of chained response
4115 * @infoclass_size: query info class response buffer size
4117 * Return: 0 on success, otherwise error
4119 static int buffer_check_err(int reqOutputBufferLength,
4120 struct smb2_query_info_rsp *rsp,
4121 void *rsp_org, int infoclass_size)
4123 if (reqOutputBufferLength < le32_to_cpu(rsp->OutputBufferLength)) {
4124 if (reqOutputBufferLength < infoclass_size) {
4125 pr_err("Invalid Buffer Size Requested\n");
4126 rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
4127 *(__be32 *)rsp_org = cpu_to_be32(sizeof(struct smb2_hdr));
4131 ksmbd_debug(SMB, "Buffer Overflow\n");
4132 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
4133 *(__be32 *)rsp_org = cpu_to_be32(sizeof(struct smb2_hdr) +
4134 reqOutputBufferLength);
4135 rsp->OutputBufferLength = cpu_to_le32(reqOutputBufferLength);
4140 static void get_standard_info_pipe(struct smb2_query_info_rsp *rsp,
4143 struct smb2_file_standard_info *sinfo;
4145 sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
4147 sinfo->AllocationSize = cpu_to_le64(4096);
4148 sinfo->EndOfFile = cpu_to_le64(0);
4149 sinfo->NumberOfLinks = cpu_to_le32(1);
4150 sinfo->DeletePending = 1;
4151 sinfo->Directory = 0;
4152 rsp->OutputBufferLength =
4153 cpu_to_le32(sizeof(struct smb2_file_standard_info));
4154 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_standard_info));
4157 static void get_internal_info_pipe(struct smb2_query_info_rsp *rsp, u64 num,
4160 struct smb2_file_internal_info *file_info;
4162 file_info = (struct smb2_file_internal_info *)rsp->Buffer;
4164 /* any unique number */
4165 file_info->IndexNumber = cpu_to_le64(num | (1ULL << 63));
4166 rsp->OutputBufferLength =
4167 cpu_to_le32(sizeof(struct smb2_file_internal_info));
4168 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_internal_info));
4171 static int smb2_get_info_file_pipe(struct ksmbd_session *sess,
4172 struct smb2_query_info_req *req,
4173 struct smb2_query_info_rsp *rsp,
4180 * Windows can sometime send query file info request on
4181 * pipe without opening it, checking error condition here
4183 id = req->VolatileFileId;
4184 if (!ksmbd_session_rpc_method(sess, id))
4187 ksmbd_debug(SMB, "FileInfoClass %u, FileId 0x%llx\n",
4188 req->FileInfoClass, req->VolatileFileId);
4190 switch (req->FileInfoClass) {
4191 case FILE_STANDARD_INFORMATION:
4192 get_standard_info_pipe(rsp, rsp_org);
4193 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4195 FILE_STANDARD_INFORMATION_SIZE);
4197 case FILE_INTERNAL_INFORMATION:
4198 get_internal_info_pipe(rsp, id, rsp_org);
4199 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4201 FILE_INTERNAL_INFORMATION_SIZE);
4204 ksmbd_debug(SMB, "smb2_info_file_pipe for %u not supported\n",
4205 req->FileInfoClass);
4212 * smb2_get_ea() - handler for smb2 get extended attribute command
4213 * @work: smb work containing query info command buffer
4214 * @fp: ksmbd_file pointer
4215 * @req: get extended attribute request
4216 * @rsp: response buffer pointer
4217 * @rsp_org: base response buffer pointer in case of chained response
4219 * Return: 0 on success, otherwise error
4221 static int smb2_get_ea(struct ksmbd_work *work, struct ksmbd_file *fp,
4222 struct smb2_query_info_req *req,
4223 struct smb2_query_info_rsp *rsp, void *rsp_org)
4225 struct smb2_ea_info *eainfo, *prev_eainfo;
4226 char *name, *ptr, *xattr_list = NULL, *buf;
4227 int rc, name_len, value_len, xattr_list_len, idx;
4228 ssize_t buf_free_len, alignment_bytes, next_offset, rsp_data_cnt = 0;
4229 struct smb2_ea_info_req *ea_req = NULL;
4230 const struct path *path;
4231 struct user_namespace *user_ns = file_mnt_user_ns(fp->filp);
4233 if (!(fp->daccess & FILE_READ_EA_LE)) {
4234 pr_err("Not permitted to read ext attr : 0x%x\n",
4239 path = &fp->filp->f_path;
4240 /* single EA entry is requested with given user.* name */
4241 if (req->InputBufferLength) {
4242 if (le32_to_cpu(req->InputBufferLength) <
4243 sizeof(struct smb2_ea_info_req))
4246 ea_req = (struct smb2_ea_info_req *)req->Buffer;
4248 /* need to send all EAs, if no specific EA is requested*/
4249 if (le32_to_cpu(req->Flags) & SL_RETURN_SINGLE_ENTRY)
4251 "All EAs are requested but need to send single EA entry in rsp flags 0x%x\n",
4252 le32_to_cpu(req->Flags));
4256 smb2_calc_max_out_buf_len(work, 8,
4257 le32_to_cpu(req->OutputBufferLength));
4258 if (buf_free_len < 0)
4261 rc = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
4263 rsp->hdr.Status = STATUS_INVALID_HANDLE;
4265 } else if (!rc) { /* there is no EA in the file */
4266 ksmbd_debug(SMB, "no ea data in the file\n");
4269 xattr_list_len = rc;
4271 ptr = (char *)rsp->Buffer;
4272 eainfo = (struct smb2_ea_info *)ptr;
4273 prev_eainfo = eainfo;
4276 while (idx < xattr_list_len) {
4277 name = xattr_list + idx;
4278 name_len = strlen(name);
4280 ksmbd_debug(SMB, "%s, len %d\n", name, name_len);
4281 idx += name_len + 1;
4284 * CIFS does not support EA other than user.* namespace,
4285 * still keep the framework generic, to list other attrs
4288 if (strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4291 if (!strncmp(&name[XATTR_USER_PREFIX_LEN], STREAM_PREFIX,
4295 if (req->InputBufferLength &&
4296 strncmp(&name[XATTR_USER_PREFIX_LEN], ea_req->name,
4297 ea_req->EaNameLength))
4300 if (!strncmp(&name[XATTR_USER_PREFIX_LEN],
4301 DOS_ATTRIBUTE_PREFIX, DOS_ATTRIBUTE_PREFIX_LEN))
4304 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4305 name_len -= XATTR_USER_PREFIX_LEN;
4307 ptr = (char *)(&eainfo->name + name_len + 1);
4308 buf_free_len -= (offsetof(struct smb2_ea_info, name) +
4310 /* bailout if xattr can't fit in buf_free_len */
4311 value_len = ksmbd_vfs_getxattr(user_ns, path->dentry,
4313 if (value_len <= 0) {
4315 rsp->hdr.Status = STATUS_INVALID_HANDLE;
4319 buf_free_len -= value_len;
4320 if (buf_free_len < 0) {
4325 memcpy(ptr, buf, value_len);
4330 eainfo->EaNameLength = name_len;
4332 if (!strncmp(name, XATTR_USER_PREFIX, XATTR_USER_PREFIX_LEN))
4333 memcpy(eainfo->name, &name[XATTR_USER_PREFIX_LEN],
4336 memcpy(eainfo->name, name, name_len);
4338 eainfo->name[name_len] = '\0';
4339 eainfo->EaValueLength = cpu_to_le16(value_len);
4340 next_offset = offsetof(struct smb2_ea_info, name) +
4341 name_len + 1 + value_len;
4343 /* align next xattr entry at 4 byte bundary */
4344 alignment_bytes = ((next_offset + 3) & ~3) - next_offset;
4345 if (alignment_bytes) {
4346 memset(ptr, '\0', alignment_bytes);
4347 ptr += alignment_bytes;
4348 next_offset += alignment_bytes;
4349 buf_free_len -= alignment_bytes;
4351 eainfo->NextEntryOffset = cpu_to_le32(next_offset);
4352 prev_eainfo = eainfo;
4353 eainfo = (struct smb2_ea_info *)ptr;
4354 rsp_data_cnt += next_offset;
4356 if (req->InputBufferLength) {
4357 ksmbd_debug(SMB, "single entry requested\n");
4362 /* no more ea entries */
4363 prev_eainfo->NextEntryOffset = 0;
4366 if (rsp_data_cnt == 0)
4367 rsp->hdr.Status = STATUS_NO_EAS_ON_FILE;
4368 rsp->OutputBufferLength = cpu_to_le32(rsp_data_cnt);
4369 inc_rfc1001_len(rsp_org, rsp_data_cnt);
4375 static void get_file_access_info(struct smb2_query_info_rsp *rsp,
4376 struct ksmbd_file *fp, void *rsp_org)
4378 struct smb2_file_access_info *file_info;
4380 file_info = (struct smb2_file_access_info *)rsp->Buffer;
4381 file_info->AccessFlags = fp->daccess;
4382 rsp->OutputBufferLength =
4383 cpu_to_le32(sizeof(struct smb2_file_access_info));
4384 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_access_info));
4387 static int get_file_basic_info(struct smb2_query_info_rsp *rsp,
4388 struct ksmbd_file *fp, void *rsp_org)
4390 struct smb2_file_basic_info *basic_info;
4394 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4395 pr_err("no right to read the attributes : 0x%x\n",
4400 basic_info = (struct smb2_file_basic_info *)rsp->Buffer;
4401 generic_fillattr(file_mnt_user_ns(fp->filp), file_inode(fp->filp),
4403 basic_info->CreationTime = cpu_to_le64(fp->create_time);
4404 time = ksmbd_UnixTimeToNT(stat.atime);
4405 basic_info->LastAccessTime = cpu_to_le64(time);
4406 time = ksmbd_UnixTimeToNT(stat.mtime);
4407 basic_info->LastWriteTime = cpu_to_le64(time);
4408 time = ksmbd_UnixTimeToNT(stat.ctime);
4409 basic_info->ChangeTime = cpu_to_le64(time);
4410 basic_info->Attributes = fp->f_ci->m_fattr;
4411 basic_info->Pad1 = 0;
4412 rsp->OutputBufferLength =
4413 cpu_to_le32(sizeof(struct smb2_file_basic_info));
4414 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_basic_info));
4418 static void get_file_standard_info(struct smb2_query_info_rsp *rsp,
4419 struct ksmbd_file *fp, void *rsp_org)
4421 struct smb2_file_standard_info *sinfo;
4422 unsigned int delete_pending;
4423 struct inode *inode;
4426 inode = file_inode(fp->filp);
4427 generic_fillattr(file_mnt_user_ns(fp->filp), inode, &stat);
4429 sinfo = (struct smb2_file_standard_info *)rsp->Buffer;
4430 delete_pending = ksmbd_inode_pending_delete(fp);
4432 sinfo->AllocationSize = cpu_to_le64(inode->i_blocks << 9);
4433 sinfo->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4434 sinfo->NumberOfLinks = cpu_to_le32(get_nlink(&stat) - delete_pending);
4435 sinfo->DeletePending = delete_pending;
4436 sinfo->Directory = S_ISDIR(stat.mode) ? 1 : 0;
4437 rsp->OutputBufferLength =
4438 cpu_to_le32(sizeof(struct smb2_file_standard_info));
4439 inc_rfc1001_len(rsp_org,
4440 sizeof(struct smb2_file_standard_info));
4443 static void get_file_alignment_info(struct smb2_query_info_rsp *rsp,
4446 struct smb2_file_alignment_info *file_info;
4448 file_info = (struct smb2_file_alignment_info *)rsp->Buffer;
4449 file_info->AlignmentRequirement = 0;
4450 rsp->OutputBufferLength =
4451 cpu_to_le32(sizeof(struct smb2_file_alignment_info));
4452 inc_rfc1001_len(rsp_org,
4453 sizeof(struct smb2_file_alignment_info));
4456 static int get_file_all_info(struct ksmbd_work *work,
4457 struct smb2_query_info_rsp *rsp,
4458 struct ksmbd_file *fp,
4461 struct ksmbd_conn *conn = work->conn;
4462 struct smb2_file_all_info *file_info;
4463 unsigned int delete_pending;
4464 struct inode *inode;
4470 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4471 ksmbd_debug(SMB, "no right to read the attributes : 0x%x\n",
4476 filename = convert_to_nt_pathname(work->tcon->share_conf, &fp->filp->f_path);
4477 if (IS_ERR(filename))
4478 return PTR_ERR(filename);
4480 inode = file_inode(fp->filp);
4481 generic_fillattr(file_mnt_user_ns(fp->filp), inode, &stat);
4483 ksmbd_debug(SMB, "filename = %s\n", filename);
4484 delete_pending = ksmbd_inode_pending_delete(fp);
4485 file_info = (struct smb2_file_all_info *)rsp->Buffer;
4487 file_info->CreationTime = cpu_to_le64(fp->create_time);
4488 time = ksmbd_UnixTimeToNT(stat.atime);
4489 file_info->LastAccessTime = cpu_to_le64(time);
4490 time = ksmbd_UnixTimeToNT(stat.mtime);
4491 file_info->LastWriteTime = cpu_to_le64(time);
4492 time = ksmbd_UnixTimeToNT(stat.ctime);
4493 file_info->ChangeTime = cpu_to_le64(time);
4494 file_info->Attributes = fp->f_ci->m_fattr;
4495 file_info->Pad1 = 0;
4496 file_info->AllocationSize =
4497 cpu_to_le64(inode->i_blocks << 9);
4498 file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4499 file_info->NumberOfLinks =
4500 cpu_to_le32(get_nlink(&stat) - delete_pending);
4501 file_info->DeletePending = delete_pending;
4502 file_info->Directory = S_ISDIR(stat.mode) ? 1 : 0;
4503 file_info->Pad2 = 0;
4504 file_info->IndexNumber = cpu_to_le64(stat.ino);
4505 file_info->EASize = 0;
4506 file_info->AccessFlags = fp->daccess;
4507 file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
4508 file_info->Mode = fp->coption;
4509 file_info->AlignmentRequirement = 0;
4510 conv_len = smbConvertToUTF16((__le16 *)file_info->FileName, filename,
4511 PATH_MAX, conn->local_nls, 0);
4513 file_info->FileNameLength = cpu_to_le32(conv_len);
4514 rsp->OutputBufferLength =
4515 cpu_to_le32(sizeof(struct smb2_file_all_info) + conv_len - 1);
4517 inc_rfc1001_len(rsp_org, le32_to_cpu(rsp->OutputBufferLength));
4521 static void get_file_alternate_info(struct ksmbd_work *work,
4522 struct smb2_query_info_rsp *rsp,
4523 struct ksmbd_file *fp,
4526 struct ksmbd_conn *conn = work->conn;
4527 struct smb2_file_alt_name_info *file_info;
4528 struct dentry *dentry = fp->filp->f_path.dentry;
4531 spin_lock(&dentry->d_lock);
4532 file_info = (struct smb2_file_alt_name_info *)rsp->Buffer;
4533 conv_len = ksmbd_extract_shortname(conn,
4534 dentry->d_name.name,
4535 file_info->FileName);
4536 spin_unlock(&dentry->d_lock);
4537 file_info->FileNameLength = cpu_to_le32(conv_len);
4538 rsp->OutputBufferLength =
4539 cpu_to_le32(sizeof(struct smb2_file_alt_name_info) + conv_len);
4540 inc_rfc1001_len(rsp_org, le32_to_cpu(rsp->OutputBufferLength));
4543 static void get_file_stream_info(struct ksmbd_work *work,
4544 struct smb2_query_info_rsp *rsp,
4545 struct ksmbd_file *fp,
4548 struct ksmbd_conn *conn = work->conn;
4549 struct smb2_file_stream_info *file_info;
4550 char *stream_name, *xattr_list = NULL, *stream_buf;
4552 const struct path *path = &fp->filp->f_path;
4553 ssize_t xattr_list_len;
4554 int nbytes = 0, streamlen, stream_name_len, next, idx = 0;
4556 struct smb2_query_info_req *req = ksmbd_req_buf_next(work);
4558 generic_fillattr(file_mnt_user_ns(fp->filp), file_inode(fp->filp),
4560 file_info = (struct smb2_file_stream_info *)rsp->Buffer;
4563 smb2_calc_max_out_buf_len(work, 8,
4564 le32_to_cpu(req->OutputBufferLength));
4565 if (buf_free_len < 0)
4568 xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
4569 if (xattr_list_len < 0) {
4571 } else if (!xattr_list_len) {
4572 ksmbd_debug(SMB, "empty xattr in the file\n");
4576 while (idx < xattr_list_len) {
4577 stream_name = xattr_list + idx;
4578 streamlen = strlen(stream_name);
4579 idx += streamlen + 1;
4581 ksmbd_debug(SMB, "%s, len %d\n", stream_name, streamlen);
4583 if (strncmp(&stream_name[XATTR_USER_PREFIX_LEN],
4584 STREAM_PREFIX, STREAM_PREFIX_LEN))
4587 stream_name_len = streamlen - (XATTR_USER_PREFIX_LEN +
4589 streamlen = stream_name_len;
4593 stream_buf = kmalloc(streamlen + 1, GFP_KERNEL);
4597 streamlen = snprintf(stream_buf, streamlen + 1,
4598 ":%s", &stream_name[XATTR_NAME_STREAM_LEN]);
4600 next = sizeof(struct smb2_file_stream_info) + streamlen * 2;
4601 if (next > buf_free_len) {
4606 file_info = (struct smb2_file_stream_info *)&rsp->Buffer[nbytes];
4607 streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
4608 stream_buf, streamlen,
4609 conn->local_nls, 0);
4612 file_info->StreamNameLength = cpu_to_le32(streamlen);
4613 file_info->StreamSize = cpu_to_le64(stream_name_len);
4614 file_info->StreamAllocationSize = cpu_to_le64(stream_name_len);
4617 buf_free_len -= next;
4618 file_info->NextEntryOffset = cpu_to_le32(next);
4622 if (!S_ISDIR(stat.mode) &&
4623 buf_free_len >= sizeof(struct smb2_file_stream_info) + 7 * 2) {
4624 file_info = (struct smb2_file_stream_info *)
4625 &rsp->Buffer[nbytes];
4626 streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
4627 "::$DATA", 7, conn->local_nls, 0);
4629 file_info->StreamNameLength = cpu_to_le32(streamlen);
4630 file_info->StreamSize = cpu_to_le64(stat.size);
4631 file_info->StreamAllocationSize = cpu_to_le64(stat.blocks << 9);
4632 nbytes += sizeof(struct smb2_file_stream_info) + streamlen;
4635 /* last entry offset should be 0 */
4636 file_info->NextEntryOffset = 0;
4639 rsp->OutputBufferLength = cpu_to_le32(nbytes);
4640 inc_rfc1001_len(rsp_org, nbytes);
4643 static void get_file_internal_info(struct smb2_query_info_rsp *rsp,
4644 struct ksmbd_file *fp, void *rsp_org)
4646 struct smb2_file_internal_info *file_info;
4649 generic_fillattr(file_mnt_user_ns(fp->filp), file_inode(fp->filp),
4651 file_info = (struct smb2_file_internal_info *)rsp->Buffer;
4652 file_info->IndexNumber = cpu_to_le64(stat.ino);
4653 rsp->OutputBufferLength =
4654 cpu_to_le32(sizeof(struct smb2_file_internal_info));
4655 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_internal_info));
4658 static int get_file_network_open_info(struct smb2_query_info_rsp *rsp,
4659 struct ksmbd_file *fp, void *rsp_org)
4661 struct smb2_file_ntwrk_info *file_info;
4662 struct inode *inode;
4666 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4667 pr_err("no right to read the attributes : 0x%x\n",
4672 file_info = (struct smb2_file_ntwrk_info *)rsp->Buffer;
4674 inode = file_inode(fp->filp);
4675 generic_fillattr(file_mnt_user_ns(fp->filp), inode, &stat);
4677 file_info->CreationTime = cpu_to_le64(fp->create_time);
4678 time = ksmbd_UnixTimeToNT(stat.atime);
4679 file_info->LastAccessTime = cpu_to_le64(time);
4680 time = ksmbd_UnixTimeToNT(stat.mtime);
4681 file_info->LastWriteTime = cpu_to_le64(time);
4682 time = ksmbd_UnixTimeToNT(stat.ctime);
4683 file_info->ChangeTime = cpu_to_le64(time);
4684 file_info->Attributes = fp->f_ci->m_fattr;
4685 file_info->AllocationSize =
4686 cpu_to_le64(inode->i_blocks << 9);
4687 file_info->EndOfFile = S_ISDIR(stat.mode) ? 0 : cpu_to_le64(stat.size);
4688 file_info->Reserved = cpu_to_le32(0);
4689 rsp->OutputBufferLength =
4690 cpu_to_le32(sizeof(struct smb2_file_ntwrk_info));
4691 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_ntwrk_info));
4695 static void get_file_ea_info(struct smb2_query_info_rsp *rsp, void *rsp_org)
4697 struct smb2_file_ea_info *file_info;
4699 file_info = (struct smb2_file_ea_info *)rsp->Buffer;
4700 file_info->EASize = 0;
4701 rsp->OutputBufferLength =
4702 cpu_to_le32(sizeof(struct smb2_file_ea_info));
4703 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_ea_info));
4706 static void get_file_position_info(struct smb2_query_info_rsp *rsp,
4707 struct ksmbd_file *fp, void *rsp_org)
4709 struct smb2_file_pos_info *file_info;
4711 file_info = (struct smb2_file_pos_info *)rsp->Buffer;
4712 file_info->CurrentByteOffset = cpu_to_le64(fp->filp->f_pos);
4713 rsp->OutputBufferLength =
4714 cpu_to_le32(sizeof(struct smb2_file_pos_info));
4715 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_pos_info));
4718 static void get_file_mode_info(struct smb2_query_info_rsp *rsp,
4719 struct ksmbd_file *fp, void *rsp_org)
4721 struct smb2_file_mode_info *file_info;
4723 file_info = (struct smb2_file_mode_info *)rsp->Buffer;
4724 file_info->Mode = fp->coption & FILE_MODE_INFO_MASK;
4725 rsp->OutputBufferLength =
4726 cpu_to_le32(sizeof(struct smb2_file_mode_info));
4727 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_mode_info));
4730 static void get_file_compression_info(struct smb2_query_info_rsp *rsp,
4731 struct ksmbd_file *fp, void *rsp_org)
4733 struct smb2_file_comp_info *file_info;
4736 generic_fillattr(file_mnt_user_ns(fp->filp), file_inode(fp->filp),
4739 file_info = (struct smb2_file_comp_info *)rsp->Buffer;
4740 file_info->CompressedFileSize = cpu_to_le64(stat.blocks << 9);
4741 file_info->CompressionFormat = COMPRESSION_FORMAT_NONE;
4742 file_info->CompressionUnitShift = 0;
4743 file_info->ChunkShift = 0;
4744 file_info->ClusterShift = 0;
4745 memset(&file_info->Reserved[0], 0, 3);
4747 rsp->OutputBufferLength =
4748 cpu_to_le32(sizeof(struct smb2_file_comp_info));
4749 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_comp_info));
4752 static int get_file_attribute_tag_info(struct smb2_query_info_rsp *rsp,
4753 struct ksmbd_file *fp, void *rsp_org)
4755 struct smb2_file_attr_tag_info *file_info;
4757 if (!(fp->daccess & FILE_READ_ATTRIBUTES_LE)) {
4758 pr_err("no right to read the attributes : 0x%x\n",
4763 file_info = (struct smb2_file_attr_tag_info *)rsp->Buffer;
4764 file_info->FileAttributes = fp->f_ci->m_fattr;
4765 file_info->ReparseTag = 0;
4766 rsp->OutputBufferLength =
4767 cpu_to_le32(sizeof(struct smb2_file_attr_tag_info));
4768 inc_rfc1001_len(rsp_org, sizeof(struct smb2_file_attr_tag_info));
4772 static int find_file_posix_info(struct smb2_query_info_rsp *rsp,
4773 struct ksmbd_file *fp, void *rsp_org)
4775 struct smb311_posix_qinfo *file_info;
4776 struct inode *inode = file_inode(fp->filp);
4777 struct user_namespace *user_ns = file_mnt_user_ns(fp->filp);
4778 vfsuid_t vfsuid = i_uid_into_vfsuid(user_ns, inode);
4779 vfsgid_t vfsgid = i_gid_into_vfsgid(user_ns, inode);
4781 int out_buf_len = sizeof(struct smb311_posix_qinfo) + 32;
4783 file_info = (struct smb311_posix_qinfo *)rsp->Buffer;
4784 file_info->CreationTime = cpu_to_le64(fp->create_time);
4785 time = ksmbd_UnixTimeToNT(inode->i_atime);
4786 file_info->LastAccessTime = cpu_to_le64(time);
4787 time = ksmbd_UnixTimeToNT(inode->i_mtime);
4788 file_info->LastWriteTime = cpu_to_le64(time);
4789 time = ksmbd_UnixTimeToNT(inode->i_ctime);
4790 file_info->ChangeTime = cpu_to_le64(time);
4791 file_info->DosAttributes = fp->f_ci->m_fattr;
4792 file_info->Inode = cpu_to_le64(inode->i_ino);
4793 file_info->EndOfFile = cpu_to_le64(inode->i_size);
4794 file_info->AllocationSize = cpu_to_le64(inode->i_blocks << 9);
4795 file_info->HardLinks = cpu_to_le32(inode->i_nlink);
4796 file_info->Mode = cpu_to_le32(inode->i_mode & 0777);
4797 file_info->DeviceId = cpu_to_le32(inode->i_rdev);
4800 * Sids(32) contain two sids(Domain sid(16), UNIX group sid(16)).
4801 * UNIX sid(16) = revision(1) + num_subauth(1) + authority(6) +
4802 * sub_auth(4 * 1(num_subauth)) + RID(4).
4804 id_to_sid(from_kuid_munged(&init_user_ns, vfsuid_into_kuid(vfsuid)),
4805 SIDUNIX_USER, (struct smb_sid *)&file_info->Sids[0]);
4806 id_to_sid(from_kgid_munged(&init_user_ns, vfsgid_into_kgid(vfsgid)),
4807 SIDUNIX_GROUP, (struct smb_sid *)&file_info->Sids[16]);
4809 rsp->OutputBufferLength = cpu_to_le32(out_buf_len);
4810 inc_rfc1001_len(rsp_org, out_buf_len);
4814 static int smb2_get_info_file(struct ksmbd_work *work,
4815 struct smb2_query_info_req *req,
4816 struct smb2_query_info_rsp *rsp)
4818 struct ksmbd_file *fp;
4819 int fileinfoclass = 0;
4821 int file_infoclass_size;
4822 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
4824 if (test_share_config_flag(work->tcon->share_conf,
4825 KSMBD_SHARE_FLAG_PIPE)) {
4826 /* smb2 info file called for pipe */
4827 return smb2_get_info_file_pipe(work->sess, req, rsp,
4828 work->response_buf);
4831 if (work->next_smb2_rcv_hdr_off) {
4832 if (!has_file_id(req->VolatileFileId)) {
4833 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
4834 work->compound_fid);
4835 id = work->compound_fid;
4836 pid = work->compound_pfid;
4840 if (!has_file_id(id)) {
4841 id = req->VolatileFileId;
4842 pid = req->PersistentFileId;
4845 fp = ksmbd_lookup_fd_slow(work, id, pid);
4849 fileinfoclass = req->FileInfoClass;
4851 switch (fileinfoclass) {
4852 case FILE_ACCESS_INFORMATION:
4853 get_file_access_info(rsp, fp, work->response_buf);
4854 file_infoclass_size = FILE_ACCESS_INFORMATION_SIZE;
4857 case FILE_BASIC_INFORMATION:
4858 rc = get_file_basic_info(rsp, fp, work->response_buf);
4859 file_infoclass_size = FILE_BASIC_INFORMATION_SIZE;
4862 case FILE_STANDARD_INFORMATION:
4863 get_file_standard_info(rsp, fp, work->response_buf);
4864 file_infoclass_size = FILE_STANDARD_INFORMATION_SIZE;
4867 case FILE_ALIGNMENT_INFORMATION:
4868 get_file_alignment_info(rsp, work->response_buf);
4869 file_infoclass_size = FILE_ALIGNMENT_INFORMATION_SIZE;
4872 case FILE_ALL_INFORMATION:
4873 rc = get_file_all_info(work, rsp, fp, work->response_buf);
4874 file_infoclass_size = FILE_ALL_INFORMATION_SIZE;
4877 case FILE_ALTERNATE_NAME_INFORMATION:
4878 get_file_alternate_info(work, rsp, fp, work->response_buf);
4879 file_infoclass_size = FILE_ALTERNATE_NAME_INFORMATION_SIZE;
4882 case FILE_STREAM_INFORMATION:
4883 get_file_stream_info(work, rsp, fp, work->response_buf);
4884 file_infoclass_size = FILE_STREAM_INFORMATION_SIZE;
4887 case FILE_INTERNAL_INFORMATION:
4888 get_file_internal_info(rsp, fp, work->response_buf);
4889 file_infoclass_size = FILE_INTERNAL_INFORMATION_SIZE;
4892 case FILE_NETWORK_OPEN_INFORMATION:
4893 rc = get_file_network_open_info(rsp, fp, work->response_buf);
4894 file_infoclass_size = FILE_NETWORK_OPEN_INFORMATION_SIZE;
4897 case FILE_EA_INFORMATION:
4898 get_file_ea_info(rsp, work->response_buf);
4899 file_infoclass_size = FILE_EA_INFORMATION_SIZE;
4902 case FILE_FULL_EA_INFORMATION:
4903 rc = smb2_get_ea(work, fp, req, rsp, work->response_buf);
4904 file_infoclass_size = FILE_FULL_EA_INFORMATION_SIZE;
4907 case FILE_POSITION_INFORMATION:
4908 get_file_position_info(rsp, fp, work->response_buf);
4909 file_infoclass_size = FILE_POSITION_INFORMATION_SIZE;
4912 case FILE_MODE_INFORMATION:
4913 get_file_mode_info(rsp, fp, work->response_buf);
4914 file_infoclass_size = FILE_MODE_INFORMATION_SIZE;
4917 case FILE_COMPRESSION_INFORMATION:
4918 get_file_compression_info(rsp, fp, work->response_buf);
4919 file_infoclass_size = FILE_COMPRESSION_INFORMATION_SIZE;
4922 case FILE_ATTRIBUTE_TAG_INFORMATION:
4923 rc = get_file_attribute_tag_info(rsp, fp, work->response_buf);
4924 file_infoclass_size = FILE_ATTRIBUTE_TAG_INFORMATION_SIZE;
4926 case SMB_FIND_FILE_POSIX_INFO:
4927 if (!work->tcon->posix_extensions) {
4928 pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
4931 file_infoclass_size = find_file_posix_info(rsp, fp,
4932 work->response_buf);
4936 ksmbd_debug(SMB, "fileinfoclass %d not supported yet\n",
4941 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
4942 rsp, work->response_buf,
4943 file_infoclass_size);
4944 ksmbd_fd_put(work, fp);
4948 static int smb2_get_info_filesystem(struct ksmbd_work *work,
4949 struct smb2_query_info_req *req,
4950 struct smb2_query_info_rsp *rsp)
4952 struct ksmbd_session *sess = work->sess;
4953 struct ksmbd_conn *conn = work->conn;
4954 struct ksmbd_share_config *share = work->tcon->share_conf;
4955 int fsinfoclass = 0;
4956 struct kstatfs stfs;
4959 int fs_infoclass_size = 0;
4964 rc = kern_path(share->path, LOOKUP_NO_SYMLINKS, &path);
4966 pr_err("cannot create vfs path\n");
4970 rc = vfs_statfs(&path, &stfs);
4972 pr_err("cannot do stat of path %s\n", share->path);
4977 fsinfoclass = req->FileInfoClass;
4979 switch (fsinfoclass) {
4980 case FS_DEVICE_INFORMATION:
4982 struct filesystem_device_info *info;
4984 info = (struct filesystem_device_info *)rsp->Buffer;
4986 info->DeviceType = cpu_to_le32(stfs.f_type);
4987 info->DeviceCharacteristics = cpu_to_le32(0x00000020);
4988 rsp->OutputBufferLength = cpu_to_le32(8);
4989 inc_rfc1001_len(work->response_buf, 8);
4990 fs_infoclass_size = FS_DEVICE_INFORMATION_SIZE;
4993 case FS_ATTRIBUTE_INFORMATION:
4995 struct filesystem_attribute_info *info;
4998 info = (struct filesystem_attribute_info *)rsp->Buffer;
4999 info->Attributes = cpu_to_le32(FILE_SUPPORTS_OBJECT_IDS |
5000 FILE_PERSISTENT_ACLS |
5001 FILE_UNICODE_ON_DISK |
5002 FILE_CASE_PRESERVED_NAMES |
5003 FILE_CASE_SENSITIVE_SEARCH |
5004 FILE_SUPPORTS_BLOCK_REFCOUNTING);
5006 info->Attributes |= cpu_to_le32(server_conf.share_fake_fscaps);
5008 if (test_share_config_flag(work->tcon->share_conf,
5009 KSMBD_SHARE_FLAG_STREAMS))
5010 info->Attributes |= cpu_to_le32(FILE_NAMED_STREAMS);
5012 info->MaxPathNameComponentLength = cpu_to_le32(stfs.f_namelen);
5013 len = smbConvertToUTF16((__le16 *)info->FileSystemName,
5014 "NTFS", PATH_MAX, conn->local_nls, 0);
5016 info->FileSystemNameLen = cpu_to_le32(len);
5017 sz = sizeof(struct filesystem_attribute_info) - 2 + len;
5018 rsp->OutputBufferLength = cpu_to_le32(sz);
5019 inc_rfc1001_len(work->response_buf, sz);
5020 fs_infoclass_size = FS_ATTRIBUTE_INFORMATION_SIZE;
5023 case FS_VOLUME_INFORMATION:
5025 struct filesystem_vol_info *info;
5027 unsigned int serial_crc = 0;
5029 info = (struct filesystem_vol_info *)(rsp->Buffer);
5030 info->VolumeCreationTime = 0;
5031 serial_crc = crc32_le(serial_crc, share->name,
5032 strlen(share->name));
5033 serial_crc = crc32_le(serial_crc, share->path,
5034 strlen(share->path));
5035 serial_crc = crc32_le(serial_crc, ksmbd_netbios_name(),
5036 strlen(ksmbd_netbios_name()));
5037 /* Taking dummy value of serial number*/
5038 info->SerialNumber = cpu_to_le32(serial_crc);
5039 len = smbConvertToUTF16((__le16 *)info->VolumeLabel,
5040 share->name, PATH_MAX,
5041 conn->local_nls, 0);
5043 info->VolumeLabelSize = cpu_to_le32(len);
5045 sz = sizeof(struct filesystem_vol_info) - 2 + len;
5046 rsp->OutputBufferLength = cpu_to_le32(sz);
5047 inc_rfc1001_len(work->response_buf, sz);
5048 fs_infoclass_size = FS_VOLUME_INFORMATION_SIZE;
5051 case FS_SIZE_INFORMATION:
5053 struct filesystem_info *info;
5055 info = (struct filesystem_info *)(rsp->Buffer);
5056 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
5057 info->FreeAllocationUnits = cpu_to_le64(stfs.f_bfree);
5058 info->SectorsPerAllocationUnit = cpu_to_le32(1);
5059 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
5060 rsp->OutputBufferLength = cpu_to_le32(24);
5061 inc_rfc1001_len(work->response_buf, 24);
5062 fs_infoclass_size = FS_SIZE_INFORMATION_SIZE;
5065 case FS_FULL_SIZE_INFORMATION:
5067 struct smb2_fs_full_size_info *info;
5069 info = (struct smb2_fs_full_size_info *)(rsp->Buffer);
5070 info->TotalAllocationUnits = cpu_to_le64(stfs.f_blocks);
5071 info->CallerAvailableAllocationUnits =
5072 cpu_to_le64(stfs.f_bavail);
5073 info->ActualAvailableAllocationUnits =
5074 cpu_to_le64(stfs.f_bfree);
5075 info->SectorsPerAllocationUnit = cpu_to_le32(1);
5076 info->BytesPerSector = cpu_to_le32(stfs.f_bsize);
5077 rsp->OutputBufferLength = cpu_to_le32(32);
5078 inc_rfc1001_len(work->response_buf, 32);
5079 fs_infoclass_size = FS_FULL_SIZE_INFORMATION_SIZE;
5082 case FS_OBJECT_ID_INFORMATION:
5084 struct object_id_info *info;
5086 info = (struct object_id_info *)(rsp->Buffer);
5088 if (!user_guest(sess->user))
5089 memcpy(info->objid, user_passkey(sess->user), 16);
5091 memset(info->objid, 0, 16);
5093 info->extended_info.magic = cpu_to_le32(EXTENDED_INFO_MAGIC);
5094 info->extended_info.version = cpu_to_le32(1);
5095 info->extended_info.release = cpu_to_le32(1);
5096 info->extended_info.rel_date = 0;
5097 memcpy(info->extended_info.version_string, "1.1.0", strlen("1.1.0"));
5098 rsp->OutputBufferLength = cpu_to_le32(64);
5099 inc_rfc1001_len(work->response_buf, 64);
5100 fs_infoclass_size = FS_OBJECT_ID_INFORMATION_SIZE;
5103 case FS_SECTOR_SIZE_INFORMATION:
5105 struct smb3_fs_ss_info *info;
5106 unsigned int sector_size =
5107 min_t(unsigned int, path.mnt->mnt_sb->s_blocksize, 4096);
5109 info = (struct smb3_fs_ss_info *)(rsp->Buffer);
5111 info->LogicalBytesPerSector = cpu_to_le32(sector_size);
5112 info->PhysicalBytesPerSectorForAtomicity =
5113 cpu_to_le32(sector_size);
5114 info->PhysicalBytesPerSectorForPerf = cpu_to_le32(sector_size);
5115 info->FSEffPhysicalBytesPerSectorForAtomicity =
5116 cpu_to_le32(sector_size);
5117 info->Flags = cpu_to_le32(SSINFO_FLAGS_ALIGNED_DEVICE |
5118 SSINFO_FLAGS_PARTITION_ALIGNED_ON_DEVICE);
5119 info->ByteOffsetForSectorAlignment = 0;
5120 info->ByteOffsetForPartitionAlignment = 0;
5121 rsp->OutputBufferLength = cpu_to_le32(28);
5122 inc_rfc1001_len(work->response_buf, 28);
5123 fs_infoclass_size = FS_SECTOR_SIZE_INFORMATION_SIZE;
5126 case FS_CONTROL_INFORMATION:
5129 * TODO : The current implementation is based on
5130 * test result with win7(NTFS) server. It's need to
5131 * modify this to get valid Quota values
5134 struct smb2_fs_control_info *info;
5136 info = (struct smb2_fs_control_info *)(rsp->Buffer);
5137 info->FreeSpaceStartFiltering = 0;
5138 info->FreeSpaceThreshold = 0;
5139 info->FreeSpaceStopFiltering = 0;
5140 info->DefaultQuotaThreshold = cpu_to_le64(SMB2_NO_FID);
5141 info->DefaultQuotaLimit = cpu_to_le64(SMB2_NO_FID);
5143 rsp->OutputBufferLength = cpu_to_le32(48);
5144 inc_rfc1001_len(work->response_buf, 48);
5145 fs_infoclass_size = FS_CONTROL_INFORMATION_SIZE;
5148 case FS_POSIX_INFORMATION:
5150 struct filesystem_posix_info *info;
5152 if (!work->tcon->posix_extensions) {
5153 pr_err("client doesn't negotiate with SMB3.1.1 POSIX Extensions\n");
5156 info = (struct filesystem_posix_info *)(rsp->Buffer);
5157 info->OptimalTransferSize = cpu_to_le32(stfs.f_bsize);
5158 info->BlockSize = cpu_to_le32(stfs.f_bsize);
5159 info->TotalBlocks = cpu_to_le64(stfs.f_blocks);
5160 info->BlocksAvail = cpu_to_le64(stfs.f_bfree);
5161 info->UserBlocksAvail = cpu_to_le64(stfs.f_bavail);
5162 info->TotalFileNodes = cpu_to_le64(stfs.f_files);
5163 info->FreeFileNodes = cpu_to_le64(stfs.f_ffree);
5164 rsp->OutputBufferLength = cpu_to_le32(56);
5165 inc_rfc1001_len(work->response_buf, 56);
5166 fs_infoclass_size = FS_POSIX_INFORMATION_SIZE;
5174 rc = buffer_check_err(le32_to_cpu(req->OutputBufferLength),
5175 rsp, work->response_buf,
5181 static int smb2_get_info_sec(struct ksmbd_work *work,
5182 struct smb2_query_info_req *req,
5183 struct smb2_query_info_rsp *rsp)
5185 struct ksmbd_file *fp;
5186 struct user_namespace *user_ns;
5187 struct smb_ntsd *pntsd = (struct smb_ntsd *)rsp->Buffer, *ppntsd = NULL;
5188 struct smb_fattr fattr = {{0}};
5189 struct inode *inode;
5190 __u32 secdesclen = 0;
5191 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
5192 int addition_info = le32_to_cpu(req->AdditionalInformation);
5193 int rc = 0, ppntsd_size = 0;
5195 if (addition_info & ~(OWNER_SECINFO | GROUP_SECINFO | DACL_SECINFO |
5196 PROTECTED_DACL_SECINFO |
5197 UNPROTECTED_DACL_SECINFO)) {
5198 ksmbd_debug(SMB, "Unsupported addition info: 0x%x)\n",
5201 pntsd->revision = cpu_to_le16(1);
5202 pntsd->type = cpu_to_le16(SELF_RELATIVE | DACL_PROTECTED);
5203 pntsd->osidoffset = 0;
5204 pntsd->gsidoffset = 0;
5205 pntsd->sacloffset = 0;
5206 pntsd->dacloffset = 0;
5208 secdesclen = sizeof(struct smb_ntsd);
5209 rsp->OutputBufferLength = cpu_to_le32(secdesclen);
5210 inc_rfc1001_len(work->response_buf, secdesclen);
5215 if (work->next_smb2_rcv_hdr_off) {
5216 if (!has_file_id(req->VolatileFileId)) {
5217 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
5218 work->compound_fid);
5219 id = work->compound_fid;
5220 pid = work->compound_pfid;
5224 if (!has_file_id(id)) {
5225 id = req->VolatileFileId;
5226 pid = req->PersistentFileId;
5229 fp = ksmbd_lookup_fd_slow(work, id, pid);
5233 user_ns = file_mnt_user_ns(fp->filp);
5234 inode = file_inode(fp->filp);
5235 ksmbd_acls_fattr(&fattr, user_ns, inode);
5237 if (test_share_config_flag(work->tcon->share_conf,
5238 KSMBD_SHARE_FLAG_ACL_XATTR))
5239 ppntsd_size = ksmbd_vfs_get_sd_xattr(work->conn, user_ns,
5240 fp->filp->f_path.dentry,
5243 /* Check if sd buffer size exceeds response buffer size */
5244 if (smb2_resp_buf_len(work, 8) > ppntsd_size)
5245 rc = build_sec_desc(user_ns, pntsd, ppntsd, ppntsd_size,
5246 addition_info, &secdesclen, &fattr);
5247 posix_acl_release(fattr.cf_acls);
5248 posix_acl_release(fattr.cf_dacls);
5250 ksmbd_fd_put(work, fp);
5254 rsp->OutputBufferLength = cpu_to_le32(secdesclen);
5255 inc_rfc1001_len(work->response_buf, secdesclen);
5260 * smb2_query_info() - handler for smb2 query info command
5261 * @work: smb work containing query info request buffer
5263 * Return: 0 on success, otherwise error
5265 int smb2_query_info(struct ksmbd_work *work)
5267 struct smb2_query_info_req *req;
5268 struct smb2_query_info_rsp *rsp;
5271 WORK_BUFFERS(work, req, rsp);
5273 ksmbd_debug(SMB, "GOT query info request\n");
5275 switch (req->InfoType) {
5276 case SMB2_O_INFO_FILE:
5277 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
5278 rc = smb2_get_info_file(work, req, rsp);
5280 case SMB2_O_INFO_FILESYSTEM:
5281 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILESYSTEM\n");
5282 rc = smb2_get_info_filesystem(work, req, rsp);
5284 case SMB2_O_INFO_SECURITY:
5285 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
5286 rc = smb2_get_info_sec(work, req, rsp);
5289 ksmbd_debug(SMB, "InfoType %d not supported yet\n",
5296 rsp->hdr.Status = STATUS_ACCESS_DENIED;
5297 else if (rc == -ENOENT)
5298 rsp->hdr.Status = STATUS_FILE_CLOSED;
5299 else if (rc == -EIO)
5300 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
5301 else if (rc == -EOPNOTSUPP || rsp->hdr.Status == 0)
5302 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
5303 smb2_set_err_rsp(work);
5305 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n",
5309 rsp->StructureSize = cpu_to_le16(9);
5310 rsp->OutputBufferOffset = cpu_to_le16(72);
5311 inc_rfc1001_len(work->response_buf, 8);
5316 * smb2_close_pipe() - handler for closing IPC pipe
5317 * @work: smb work containing close request buffer
5321 static noinline int smb2_close_pipe(struct ksmbd_work *work)
5324 struct smb2_close_req *req = smb2_get_msg(work->request_buf);
5325 struct smb2_close_rsp *rsp = smb2_get_msg(work->response_buf);
5327 id = req->VolatileFileId;
5328 ksmbd_session_rpc_close(work->sess, id);
5330 rsp->StructureSize = cpu_to_le16(60);
5333 rsp->CreationTime = 0;
5334 rsp->LastAccessTime = 0;
5335 rsp->LastWriteTime = 0;
5336 rsp->ChangeTime = 0;
5337 rsp->AllocationSize = 0;
5339 rsp->Attributes = 0;
5340 inc_rfc1001_len(work->response_buf, 60);
5345 * smb2_close() - handler for smb2 close file command
5346 * @work: smb work containing close request buffer
5350 int smb2_close(struct ksmbd_work *work)
5352 u64 volatile_id = KSMBD_NO_FID;
5354 struct smb2_close_req *req;
5355 struct smb2_close_rsp *rsp;
5356 struct ksmbd_conn *conn = work->conn;
5357 struct ksmbd_file *fp;
5358 struct inode *inode;
5362 WORK_BUFFERS(work, req, rsp);
5364 if (test_share_config_flag(work->tcon->share_conf,
5365 KSMBD_SHARE_FLAG_PIPE)) {
5366 ksmbd_debug(SMB, "IPC pipe close request\n");
5367 return smb2_close_pipe(work);
5370 sess_id = le64_to_cpu(req->hdr.SessionId);
5371 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5372 sess_id = work->compound_sid;
5374 work->compound_sid = 0;
5375 if (check_session_id(conn, sess_id)) {
5376 work->compound_sid = sess_id;
5378 rsp->hdr.Status = STATUS_USER_SESSION_DELETED;
5379 if (req->hdr.Flags & SMB2_FLAGS_RELATED_OPERATIONS)
5380 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
5385 if (work->next_smb2_rcv_hdr_off &&
5386 !has_file_id(req->VolatileFileId)) {
5387 if (!has_file_id(work->compound_fid)) {
5388 /* file already closed, return FILE_CLOSED */
5389 ksmbd_debug(SMB, "file already closed\n");
5390 rsp->hdr.Status = STATUS_FILE_CLOSED;
5395 "Compound request set FID = %llu:%llu\n",
5397 work->compound_pfid);
5398 volatile_id = work->compound_fid;
5400 /* file closed, stored id is not valid anymore */
5401 work->compound_fid = KSMBD_NO_FID;
5402 work->compound_pfid = KSMBD_NO_FID;
5405 volatile_id = req->VolatileFileId;
5407 ksmbd_debug(SMB, "volatile_id = %llu\n", volatile_id);
5409 rsp->StructureSize = cpu_to_le16(60);
5412 if (req->Flags == SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB) {
5413 fp = ksmbd_lookup_fd_fast(work, volatile_id);
5419 inode = file_inode(fp->filp);
5420 rsp->Flags = SMB2_CLOSE_FLAG_POSTQUERY_ATTRIB;
5421 rsp->AllocationSize = S_ISDIR(inode->i_mode) ? 0 :
5422 cpu_to_le64(inode->i_blocks << 9);
5423 rsp->EndOfFile = cpu_to_le64(inode->i_size);
5424 rsp->Attributes = fp->f_ci->m_fattr;
5425 rsp->CreationTime = cpu_to_le64(fp->create_time);
5426 time = ksmbd_UnixTimeToNT(inode->i_atime);
5427 rsp->LastAccessTime = cpu_to_le64(time);
5428 time = ksmbd_UnixTimeToNT(inode->i_mtime);
5429 rsp->LastWriteTime = cpu_to_le64(time);
5430 time = ksmbd_UnixTimeToNT(inode->i_ctime);
5431 rsp->ChangeTime = cpu_to_le64(time);
5432 ksmbd_fd_put(work, fp);
5435 rsp->AllocationSize = 0;
5437 rsp->Attributes = 0;
5438 rsp->CreationTime = 0;
5439 rsp->LastAccessTime = 0;
5440 rsp->LastWriteTime = 0;
5441 rsp->ChangeTime = 0;
5444 err = ksmbd_close_fd(work, volatile_id);
5447 if (rsp->hdr.Status == 0)
5448 rsp->hdr.Status = STATUS_FILE_CLOSED;
5449 smb2_set_err_rsp(work);
5451 inc_rfc1001_len(work->response_buf, 60);
5458 * smb2_echo() - handler for smb2 echo(ping) command
5459 * @work: smb work containing echo request buffer
5463 int smb2_echo(struct ksmbd_work *work)
5465 struct smb2_echo_rsp *rsp = smb2_get_msg(work->response_buf);
5467 rsp->StructureSize = cpu_to_le16(4);
5469 inc_rfc1001_len(work->response_buf, 4);
5473 static int smb2_rename(struct ksmbd_work *work,
5474 struct ksmbd_file *fp,
5475 struct user_namespace *user_ns,
5476 struct smb2_file_rename_info *file_info,
5477 struct nls_table *local_nls)
5479 struct ksmbd_share_config *share = fp->tcon->share_conf;
5480 char *new_name = NULL, *abs_oldname = NULL, *old_name = NULL;
5481 char *pathname = NULL;
5483 bool file_present = true;
5486 ksmbd_debug(SMB, "setting FILE_RENAME_INFO\n");
5487 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
5491 abs_oldname = file_path(fp->filp, pathname, PATH_MAX);
5492 if (IS_ERR(abs_oldname)) {
5496 old_name = strrchr(abs_oldname, '/');
5497 if (old_name && old_name[1] != '\0') {
5500 ksmbd_debug(SMB, "can't get last component in path %s\n",
5506 new_name = smb2_get_name(file_info->FileName,
5507 le32_to_cpu(file_info->FileNameLength),
5509 if (IS_ERR(new_name)) {
5510 rc = PTR_ERR(new_name);
5514 if (strchr(new_name, ':')) {
5516 char *xattr_stream_name, *stream_name = NULL;
5517 size_t xattr_stream_size;
5520 rc = parse_stream_name(new_name, &stream_name, &s_type);
5524 len = strlen(new_name);
5525 if (len > 0 && new_name[len - 1] != '/') {
5526 pr_err("not allow base filename in rename\n");
5531 rc = ksmbd_vfs_xattr_stream_name(stream_name,
5538 rc = ksmbd_vfs_setxattr(user_ns,
5539 fp->filp->f_path.dentry,
5543 pr_err("failed to store stream name in xattr: %d\n",
5552 ksmbd_debug(SMB, "new name %s\n", new_name);
5553 rc = ksmbd_vfs_kern_path(work, new_name, LOOKUP_NO_SYMLINKS, &path, 1);
5557 file_present = false;
5562 if (ksmbd_share_veto_filename(share, new_name)) {
5564 ksmbd_debug(SMB, "Can't rename vetoed file: %s\n", new_name);
5568 if (file_info->ReplaceIfExists) {
5570 rc = ksmbd_vfs_remove_file(work, new_name);
5572 if (rc != -ENOTEMPTY)
5574 ksmbd_debug(SMB, "cannot delete %s, rc %d\n",
5581 strncmp(old_name, path.dentry->d_name.name, strlen(old_name))) {
5584 "cannot rename already existing file\n");
5589 rc = ksmbd_vfs_fp_rename(work, fp, new_name);
5592 if (!IS_ERR(new_name))
5597 static int smb2_create_link(struct ksmbd_work *work,
5598 struct ksmbd_share_config *share,
5599 struct smb2_file_link_info *file_info,
5600 unsigned int buf_len, struct file *filp,
5601 struct nls_table *local_nls)
5603 char *link_name = NULL, *target_name = NULL, *pathname = NULL;
5605 bool file_present = true;
5608 if (buf_len < (u64)sizeof(struct smb2_file_link_info) +
5609 le32_to_cpu(file_info->FileNameLength))
5612 ksmbd_debug(SMB, "setting FILE_LINK_INFORMATION\n");
5613 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
5617 link_name = smb2_get_name(file_info->FileName,
5618 le32_to_cpu(file_info->FileNameLength),
5620 if (IS_ERR(link_name) || S_ISDIR(file_inode(filp)->i_mode)) {
5625 ksmbd_debug(SMB, "link name is %s\n", link_name);
5626 target_name = file_path(filp, pathname, PATH_MAX);
5627 if (IS_ERR(target_name)) {
5632 ksmbd_debug(SMB, "target name is %s\n", target_name);
5633 rc = ksmbd_vfs_kern_path(work, link_name, LOOKUP_NO_SYMLINKS, &path, 0);
5637 file_present = false;
5642 if (file_info->ReplaceIfExists) {
5644 rc = ksmbd_vfs_remove_file(work, link_name);
5647 ksmbd_debug(SMB, "cannot delete %s\n",
5655 ksmbd_debug(SMB, "link already exists\n");
5660 rc = ksmbd_vfs_link(work, target_name, link_name);
5664 if (!IS_ERR(link_name))
5670 static int set_file_basic_info(struct ksmbd_file *fp,
5671 struct smb2_file_basic_info *file_info,
5672 struct ksmbd_share_config *share)
5676 struct inode *inode;
5677 struct user_namespace *user_ns;
5680 if (!(fp->daccess & FILE_WRITE_ATTRIBUTES_LE))
5685 inode = file_inode(filp);
5686 user_ns = file_mnt_user_ns(filp);
5688 if (file_info->CreationTime)
5689 fp->create_time = le64_to_cpu(file_info->CreationTime);
5691 if (file_info->LastAccessTime) {
5692 attrs.ia_atime = ksmbd_NTtimeToUnix(file_info->LastAccessTime);
5693 attrs.ia_valid |= (ATTR_ATIME | ATTR_ATIME_SET);
5696 attrs.ia_valid |= ATTR_CTIME;
5697 if (file_info->ChangeTime)
5698 attrs.ia_ctime = ksmbd_NTtimeToUnix(file_info->ChangeTime);
5700 attrs.ia_ctime = inode->i_ctime;
5702 if (file_info->LastWriteTime) {
5703 attrs.ia_mtime = ksmbd_NTtimeToUnix(file_info->LastWriteTime);
5704 attrs.ia_valid |= (ATTR_MTIME | ATTR_MTIME_SET);
5707 if (file_info->Attributes) {
5708 if (!S_ISDIR(inode->i_mode) &&
5709 file_info->Attributes & FILE_ATTRIBUTE_DIRECTORY_LE) {
5710 pr_err("can't change a file to a directory\n");
5714 if (!(S_ISDIR(inode->i_mode) && file_info->Attributes == FILE_ATTRIBUTE_NORMAL_LE))
5715 fp->f_ci->m_fattr = file_info->Attributes |
5716 (fp->f_ci->m_fattr & FILE_ATTRIBUTE_DIRECTORY_LE);
5719 if (test_share_config_flag(share, KSMBD_SHARE_FLAG_STORE_DOS_ATTRS) &&
5720 (file_info->CreationTime || file_info->Attributes)) {
5721 struct xattr_dos_attrib da = {0};
5724 da.itime = fp->itime;
5725 da.create_time = fp->create_time;
5726 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
5727 da.flags = XATTR_DOSINFO_ATTRIB | XATTR_DOSINFO_CREATE_TIME |
5728 XATTR_DOSINFO_ITIME;
5730 rc = ksmbd_vfs_set_dos_attrib_xattr(user_ns,
5731 filp->f_path.dentry, &da);
5734 "failed to restore file attribute in EA\n");
5738 if (attrs.ia_valid) {
5739 struct dentry *dentry = filp->f_path.dentry;
5740 struct inode *inode = d_inode(dentry);
5742 if (IS_IMMUTABLE(inode) || IS_APPEND(inode))
5746 inode->i_ctime = attrs.ia_ctime;
5747 attrs.ia_valid &= ~ATTR_CTIME;
5748 rc = notify_change(user_ns, dentry, &attrs, NULL);
5749 inode_unlock(inode);
5754 static int set_file_allocation_info(struct ksmbd_work *work,
5755 struct ksmbd_file *fp,
5756 struct smb2_file_alloc_info *file_alloc_info)
5759 * TODO : It's working fine only when store dos attributes
5760 * is not yes. need to implement a logic which works
5761 * properly with any smb.conf option
5765 struct inode *inode;
5768 if (!(fp->daccess & FILE_WRITE_DATA_LE))
5771 alloc_blks = (le64_to_cpu(file_alloc_info->AllocationSize) + 511) >> 9;
5772 inode = file_inode(fp->filp);
5774 if (alloc_blks > inode->i_blocks) {
5775 smb_break_all_levII_oplock(work, fp, 1);
5776 rc = vfs_fallocate(fp->filp, FALLOC_FL_KEEP_SIZE, 0,
5778 if (rc && rc != -EOPNOTSUPP) {
5779 pr_err("vfs_fallocate is failed : %d\n", rc);
5782 } else if (alloc_blks < inode->i_blocks) {
5786 * Allocation size could be smaller than original one
5787 * which means allocated blocks in file should be
5788 * deallocated. use truncate to cut out it, but inode
5789 * size is also updated with truncate offset.
5790 * inode size is retained by backup inode size.
5792 size = i_size_read(inode);
5793 rc = ksmbd_vfs_truncate(work, fp, alloc_blks * 512);
5795 pr_err("truncate failed!, err %d\n", rc);
5798 if (size < alloc_blks * 512)
5799 i_size_write(inode, size);
5804 static int set_end_of_file_info(struct ksmbd_work *work, struct ksmbd_file *fp,
5805 struct smb2_file_eof_info *file_eof_info)
5808 struct inode *inode;
5811 if (!(fp->daccess & FILE_WRITE_DATA_LE))
5814 newsize = le64_to_cpu(file_eof_info->EndOfFile);
5815 inode = file_inode(fp->filp);
5818 * If FILE_END_OF_FILE_INFORMATION of set_info_file is called
5819 * on FAT32 shared device, truncate execution time is too long
5820 * and network error could cause from windows client. because
5821 * truncate of some filesystem like FAT32 fill zero data in
5824 if (inode->i_sb->s_magic != MSDOS_SUPER_MAGIC) {
5825 ksmbd_debug(SMB, "truncated to newsize %lld\n", newsize);
5826 rc = ksmbd_vfs_truncate(work, fp, newsize);
5828 ksmbd_debug(SMB, "truncate failed!, err %d\n", rc);
5837 static int set_rename_info(struct ksmbd_work *work, struct ksmbd_file *fp,
5838 struct smb2_file_rename_info *rename_info,
5839 unsigned int buf_len)
5841 struct user_namespace *user_ns;
5842 struct ksmbd_file *parent_fp;
5843 struct dentry *parent;
5844 struct dentry *dentry = fp->filp->f_path.dentry;
5847 if (!(fp->daccess & FILE_DELETE_LE)) {
5848 pr_err("no right to delete : 0x%x\n", fp->daccess);
5852 if (buf_len < (u64)sizeof(struct smb2_file_rename_info) +
5853 le32_to_cpu(rename_info->FileNameLength))
5856 user_ns = file_mnt_user_ns(fp->filp);
5857 if (ksmbd_stream_fd(fp))
5860 parent = dget_parent(dentry);
5861 ret = ksmbd_vfs_lock_parent(user_ns, parent, dentry);
5867 parent_fp = ksmbd_lookup_fd_inode(d_inode(parent));
5868 inode_unlock(d_inode(parent));
5872 if (parent_fp->daccess & FILE_DELETE_LE) {
5873 pr_err("parent dir is opened with delete access\n");
5874 ksmbd_fd_put(work, parent_fp);
5877 ksmbd_fd_put(work, parent_fp);
5880 return smb2_rename(work, fp, user_ns, rename_info,
5881 work->conn->local_nls);
5884 static int set_file_disposition_info(struct ksmbd_file *fp,
5885 struct smb2_file_disposition_info *file_info)
5887 struct inode *inode;
5889 if (!(fp->daccess & FILE_DELETE_LE)) {
5890 pr_err("no right to delete : 0x%x\n", fp->daccess);
5894 inode = file_inode(fp->filp);
5895 if (file_info->DeletePending) {
5896 if (S_ISDIR(inode->i_mode) &&
5897 ksmbd_vfs_empty_dir(fp) == -ENOTEMPTY)
5899 ksmbd_set_inode_pending_delete(fp);
5901 ksmbd_clear_inode_pending_delete(fp);
5906 static int set_file_position_info(struct ksmbd_file *fp,
5907 struct smb2_file_pos_info *file_info)
5909 loff_t current_byte_offset;
5910 unsigned long sector_size;
5911 struct inode *inode;
5913 inode = file_inode(fp->filp);
5914 current_byte_offset = le64_to_cpu(file_info->CurrentByteOffset);
5915 sector_size = inode->i_sb->s_blocksize;
5917 if (current_byte_offset < 0 ||
5918 (fp->coption == FILE_NO_INTERMEDIATE_BUFFERING_LE &&
5919 current_byte_offset & (sector_size - 1))) {
5920 pr_err("CurrentByteOffset is not valid : %llu\n",
5921 current_byte_offset);
5925 fp->filp->f_pos = current_byte_offset;
5929 static int set_file_mode_info(struct ksmbd_file *fp,
5930 struct smb2_file_mode_info *file_info)
5934 mode = file_info->Mode;
5936 if ((mode & ~FILE_MODE_INFO_MASK)) {
5937 pr_err("Mode is not valid : 0x%x\n", le32_to_cpu(mode));
5942 * TODO : need to implement consideration for
5943 * FILE_SYNCHRONOUS_IO_ALERT and FILE_SYNCHRONOUS_IO_NONALERT
5945 ksmbd_vfs_set_fadvise(fp->filp, mode);
5951 * smb2_set_info_file() - handler for smb2 set info command
5952 * @work: smb work containing set info command buffer
5953 * @fp: ksmbd_file pointer
5954 * @req: request buffer pointer
5955 * @share: ksmbd_share_config pointer
5957 * Return: 0 on success, otherwise error
5958 * TODO: need to implement an error handling for STATUS_INFO_LENGTH_MISMATCH
5960 static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp,
5961 struct smb2_set_info_req *req,
5962 struct ksmbd_share_config *share)
5964 unsigned int buf_len = le32_to_cpu(req->BufferLength);
5966 switch (req->FileInfoClass) {
5967 case FILE_BASIC_INFORMATION:
5969 if (buf_len < sizeof(struct smb2_file_basic_info))
5972 return set_file_basic_info(fp, (struct smb2_file_basic_info *)req->Buffer, share);
5974 case FILE_ALLOCATION_INFORMATION:
5976 if (buf_len < sizeof(struct smb2_file_alloc_info))
5979 return set_file_allocation_info(work, fp,
5980 (struct smb2_file_alloc_info *)req->Buffer);
5982 case FILE_END_OF_FILE_INFORMATION:
5984 if (buf_len < sizeof(struct smb2_file_eof_info))
5987 return set_end_of_file_info(work, fp,
5988 (struct smb2_file_eof_info *)req->Buffer);
5990 case FILE_RENAME_INFORMATION:
5992 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
5994 "User does not have write permission\n");
5998 if (buf_len < sizeof(struct smb2_file_rename_info))
6001 return set_rename_info(work, fp,
6002 (struct smb2_file_rename_info *)req->Buffer,
6005 case FILE_LINK_INFORMATION:
6007 if (buf_len < sizeof(struct smb2_file_link_info))
6010 return smb2_create_link(work, work->tcon->share_conf,
6011 (struct smb2_file_link_info *)req->Buffer,
6013 work->conn->local_nls);
6015 case FILE_DISPOSITION_INFORMATION:
6017 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
6019 "User does not have write permission\n");
6023 if (buf_len < sizeof(struct smb2_file_disposition_info))
6026 return set_file_disposition_info(fp,
6027 (struct smb2_file_disposition_info *)req->Buffer);
6029 case FILE_FULL_EA_INFORMATION:
6031 if (!(fp->daccess & FILE_WRITE_EA_LE)) {
6032 pr_err("Not permitted to write ext attr: 0x%x\n",
6037 if (buf_len < sizeof(struct smb2_ea_info))
6040 return smb2_set_ea((struct smb2_ea_info *)req->Buffer,
6041 buf_len, &fp->filp->f_path);
6043 case FILE_POSITION_INFORMATION:
6045 if (buf_len < sizeof(struct smb2_file_pos_info))
6048 return set_file_position_info(fp, (struct smb2_file_pos_info *)req->Buffer);
6050 case FILE_MODE_INFORMATION:
6052 if (buf_len < sizeof(struct smb2_file_mode_info))
6055 return set_file_mode_info(fp, (struct smb2_file_mode_info *)req->Buffer);
6059 pr_err("Unimplemented Fileinfoclass :%d\n", req->FileInfoClass);
6063 static int smb2_set_info_sec(struct ksmbd_file *fp, int addition_info,
6064 char *buffer, int buf_len)
6066 struct smb_ntsd *pntsd = (struct smb_ntsd *)buffer;
6068 fp->saccess |= FILE_SHARE_DELETE_LE;
6070 return set_info_sec(fp->conn, fp->tcon, &fp->filp->f_path, pntsd,
6075 * smb2_set_info() - handler for smb2 set info command handler
6076 * @work: smb work containing set info request buffer
6078 * Return: 0 on success, otherwise error
6080 int smb2_set_info(struct ksmbd_work *work)
6082 struct smb2_set_info_req *req;
6083 struct smb2_set_info_rsp *rsp;
6084 struct ksmbd_file *fp;
6086 unsigned int id = KSMBD_NO_FID, pid = KSMBD_NO_FID;
6088 ksmbd_debug(SMB, "Received set info request\n");
6090 if (work->next_smb2_rcv_hdr_off) {
6091 req = ksmbd_req_buf_next(work);
6092 rsp = ksmbd_resp_buf_next(work);
6093 if (!has_file_id(req->VolatileFileId)) {
6094 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
6095 work->compound_fid);
6096 id = work->compound_fid;
6097 pid = work->compound_pfid;
6100 req = smb2_get_msg(work->request_buf);
6101 rsp = smb2_get_msg(work->response_buf);
6104 if (!has_file_id(id)) {
6105 id = req->VolatileFileId;
6106 pid = req->PersistentFileId;
6109 fp = ksmbd_lookup_fd_slow(work, id, pid);
6111 ksmbd_debug(SMB, "Invalid id for close: %u\n", id);
6116 switch (req->InfoType) {
6117 case SMB2_O_INFO_FILE:
6118 ksmbd_debug(SMB, "GOT SMB2_O_INFO_FILE\n");
6119 rc = smb2_set_info_file(work, fp, req, work->tcon->share_conf);
6121 case SMB2_O_INFO_SECURITY:
6122 ksmbd_debug(SMB, "GOT SMB2_O_INFO_SECURITY\n");
6123 if (ksmbd_override_fsids(work)) {
6127 rc = smb2_set_info_sec(fp,
6128 le32_to_cpu(req->AdditionalInformation),
6130 le32_to_cpu(req->BufferLength));
6131 ksmbd_revert_fsids(work);
6140 rsp->StructureSize = cpu_to_le16(2);
6141 inc_rfc1001_len(work->response_buf, 2);
6142 ksmbd_fd_put(work, fp);
6146 if (rc == -EACCES || rc == -EPERM || rc == -EXDEV)
6147 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6148 else if (rc == -EINVAL)
6149 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6150 else if (rc == -ESHARE)
6151 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6152 else if (rc == -ENOENT)
6153 rsp->hdr.Status = STATUS_OBJECT_NAME_INVALID;
6154 else if (rc == -EBUSY || rc == -ENOTEMPTY)
6155 rsp->hdr.Status = STATUS_DIRECTORY_NOT_EMPTY;
6156 else if (rc == -EAGAIN)
6157 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6158 else if (rc == -EBADF || rc == -ESTALE)
6159 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6160 else if (rc == -EEXIST)
6161 rsp->hdr.Status = STATUS_OBJECT_NAME_COLLISION;
6162 else if (rsp->hdr.Status == 0 || rc == -EOPNOTSUPP)
6163 rsp->hdr.Status = STATUS_INVALID_INFO_CLASS;
6164 smb2_set_err_rsp(work);
6165 ksmbd_fd_put(work, fp);
6166 ksmbd_debug(SMB, "error while processing smb2 query rc = %d\n", rc);
6171 * smb2_read_pipe() - handler for smb2 read from IPC pipe
6172 * @work: smb work containing read IPC pipe command buffer
6174 * Return: 0 on success, otherwise error
6176 static noinline int smb2_read_pipe(struct ksmbd_work *work)
6178 int nbytes = 0, err;
6180 struct ksmbd_rpc_command *rpc_resp;
6181 struct smb2_read_req *req = smb2_get_msg(work->request_buf);
6182 struct smb2_read_rsp *rsp = smb2_get_msg(work->response_buf);
6184 id = req->VolatileFileId;
6186 inc_rfc1001_len(work->response_buf, 16);
6187 rpc_resp = ksmbd_rpc_read(work->sess, id);
6189 if (rpc_resp->flags != KSMBD_RPC_OK) {
6194 work->aux_payload_buf =
6195 kvmalloc(rpc_resp->payload_sz, GFP_KERNEL | __GFP_ZERO);
6196 if (!work->aux_payload_buf) {
6201 memcpy(work->aux_payload_buf, rpc_resp->payload,
6202 rpc_resp->payload_sz);
6204 nbytes = rpc_resp->payload_sz;
6205 work->resp_hdr_sz = get_rfc1002_len(work->response_buf) + 4;
6206 work->aux_payload_sz = nbytes;
6210 rsp->StructureSize = cpu_to_le16(17);
6211 rsp->DataOffset = 80;
6213 rsp->DataLength = cpu_to_le32(nbytes);
6214 rsp->DataRemaining = 0;
6216 inc_rfc1001_len(work->response_buf, nbytes);
6220 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
6221 smb2_set_err_rsp(work);
6226 static int smb2_set_remote_key_for_rdma(struct ksmbd_work *work,
6227 struct smb2_buffer_desc_v1 *desc,
6229 __le16 ChannelInfoLength)
6231 unsigned int i, ch_count;
6233 if (work->conn->dialect == SMB30_PROT_ID &&
6234 Channel != SMB2_CHANNEL_RDMA_V1)
6237 ch_count = le16_to_cpu(ChannelInfoLength) / sizeof(*desc);
6238 if (ksmbd_debug_types & KSMBD_DEBUG_RDMA) {
6239 for (i = 0; i < ch_count; i++) {
6240 pr_info("RDMA r/w request %#x: token %#x, length %#x\n",
6242 le32_to_cpu(desc[i].token),
6243 le32_to_cpu(desc[i].length));
6249 work->need_invalidate_rkey =
6250 (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE);
6251 if (Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE)
6252 work->remote_key = le32_to_cpu(desc->token);
6256 static ssize_t smb2_read_rdma_channel(struct ksmbd_work *work,
6257 struct smb2_read_req *req, void *data_buf,
6262 err = ksmbd_conn_rdma_write(work->conn, data_buf, length,
6263 (struct smb2_buffer_desc_v1 *)
6264 ((char *)req + le16_to_cpu(req->ReadChannelInfoOffset)),
6265 le16_to_cpu(req->ReadChannelInfoLength));
6273 * smb2_read() - handler for smb2 read from file
6274 * @work: smb work containing read command buffer
6276 * Return: 0 on success, otherwise error
6278 int smb2_read(struct ksmbd_work *work)
6280 struct ksmbd_conn *conn = work->conn;
6281 struct smb2_read_req *req;
6282 struct smb2_read_rsp *rsp;
6283 struct ksmbd_file *fp = NULL;
6285 size_t length, mincount;
6286 ssize_t nbytes = 0, remain_bytes = 0;
6288 bool is_rdma_channel = false;
6289 unsigned int max_read_size = conn->vals->max_read_size;
6291 WORK_BUFFERS(work, req, rsp);
6293 if (test_share_config_flag(work->tcon->share_conf,
6294 KSMBD_SHARE_FLAG_PIPE)) {
6295 ksmbd_debug(SMB, "IPC pipe read request\n");
6296 return smb2_read_pipe(work);
6299 if (req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE ||
6300 req->Channel == SMB2_CHANNEL_RDMA_V1) {
6301 is_rdma_channel = true;
6302 max_read_size = get_smbd_max_read_write_size();
6305 if (is_rdma_channel == true) {
6306 unsigned int ch_offset = le16_to_cpu(req->ReadChannelInfoOffset);
6308 if (ch_offset < offsetof(struct smb2_read_req, Buffer)) {
6312 err = smb2_set_remote_key_for_rdma(work,
6313 (struct smb2_buffer_desc_v1 *)
6314 ((char *)req + ch_offset),
6316 req->ReadChannelInfoLength);
6321 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
6327 if (!(fp->daccess & (FILE_READ_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
6328 pr_err("Not permitted to read : 0x%x\n", fp->daccess);
6333 offset = le64_to_cpu(req->Offset);
6334 length = le32_to_cpu(req->Length);
6335 mincount = le32_to_cpu(req->MinimumCount);
6337 if (length > max_read_size) {
6338 ksmbd_debug(SMB, "limiting read size to max size(%u)\n",
6344 ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
6345 fp->filp, offset, length);
6347 work->aux_payload_buf = kvmalloc(length, GFP_KERNEL | __GFP_ZERO);
6348 if (!work->aux_payload_buf) {
6353 nbytes = ksmbd_vfs_read(work, fp, length, &offset);
6359 if ((nbytes == 0 && length != 0) || nbytes < mincount) {
6360 kvfree(work->aux_payload_buf);
6361 work->aux_payload_buf = NULL;
6362 rsp->hdr.Status = STATUS_END_OF_FILE;
6363 smb2_set_err_rsp(work);
6364 ksmbd_fd_put(work, fp);
6368 ksmbd_debug(SMB, "nbytes %zu, offset %lld mincount %zu\n",
6369 nbytes, offset, mincount);
6371 if (is_rdma_channel == true) {
6372 /* write data to the client using rdma channel */
6373 remain_bytes = smb2_read_rdma_channel(work, req,
6374 work->aux_payload_buf,
6376 kvfree(work->aux_payload_buf);
6377 work->aux_payload_buf = NULL;
6380 if (remain_bytes < 0) {
6381 err = (int)remain_bytes;
6386 rsp->StructureSize = cpu_to_le16(17);
6387 rsp->DataOffset = 80;
6389 rsp->DataLength = cpu_to_le32(nbytes);
6390 rsp->DataRemaining = cpu_to_le32(remain_bytes);
6392 inc_rfc1001_len(work->response_buf, 16);
6393 work->resp_hdr_sz = get_rfc1002_len(work->response_buf) + 4;
6394 work->aux_payload_sz = nbytes;
6395 inc_rfc1001_len(work->response_buf, nbytes);
6396 ksmbd_fd_put(work, fp);
6402 rsp->hdr.Status = STATUS_INVALID_DEVICE_REQUEST;
6403 else if (err == -EAGAIN)
6404 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6405 else if (err == -ENOENT)
6406 rsp->hdr.Status = STATUS_FILE_CLOSED;
6407 else if (err == -EACCES)
6408 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6409 else if (err == -ESHARE)
6410 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6411 else if (err == -EINVAL)
6412 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6414 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6416 smb2_set_err_rsp(work);
6418 ksmbd_fd_put(work, fp);
6423 * smb2_write_pipe() - handler for smb2 write on IPC pipe
6424 * @work: smb work containing write IPC pipe command buffer
6426 * Return: 0 on success, otherwise error
6428 static noinline int smb2_write_pipe(struct ksmbd_work *work)
6430 struct smb2_write_req *req = smb2_get_msg(work->request_buf);
6431 struct smb2_write_rsp *rsp = smb2_get_msg(work->response_buf);
6432 struct ksmbd_rpc_command *rpc_resp;
6434 int err = 0, ret = 0;
6438 length = le32_to_cpu(req->Length);
6439 id = req->VolatileFileId;
6441 if ((u64)le16_to_cpu(req->DataOffset) + length >
6442 get_rfc1002_len(work->request_buf)) {
6443 pr_err("invalid write data offset %u, smb_len %u\n",
6444 le16_to_cpu(req->DataOffset),
6445 get_rfc1002_len(work->request_buf));
6450 data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
6451 le16_to_cpu(req->DataOffset));
6453 rpc_resp = ksmbd_rpc_write(work->sess, id, data_buf, length);
6455 if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
6456 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
6458 smb2_set_err_rsp(work);
6461 if (rpc_resp->flags != KSMBD_RPC_OK) {
6462 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6463 smb2_set_err_rsp(work);
6470 rsp->StructureSize = cpu_to_le16(17);
6471 rsp->DataOffset = 0;
6473 rsp->DataLength = cpu_to_le32(length);
6474 rsp->DataRemaining = 0;
6476 inc_rfc1001_len(work->response_buf, 16);
6480 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6481 smb2_set_err_rsp(work);
6487 static ssize_t smb2_write_rdma_channel(struct ksmbd_work *work,
6488 struct smb2_write_req *req,
6489 struct ksmbd_file *fp,
6490 loff_t offset, size_t length, bool sync)
6496 data_buf = kvmalloc(length, GFP_KERNEL | __GFP_ZERO);
6500 ret = ksmbd_conn_rdma_read(work->conn, data_buf, length,
6501 (struct smb2_buffer_desc_v1 *)
6502 ((char *)req + le16_to_cpu(req->WriteChannelInfoOffset)),
6503 le16_to_cpu(req->WriteChannelInfoLength));
6509 ret = ksmbd_vfs_write(work, fp, data_buf, length, &offset, sync, &nbytes);
6518 * smb2_write() - handler for smb2 write from file
6519 * @work: smb work containing write command buffer
6521 * Return: 0 on success, otherwise error
6523 int smb2_write(struct ksmbd_work *work)
6525 struct smb2_write_req *req;
6526 struct smb2_write_rsp *rsp;
6527 struct ksmbd_file *fp = NULL;
6532 bool writethrough = false, is_rdma_channel = false;
6534 unsigned int max_write_size = work->conn->vals->max_write_size;
6536 WORK_BUFFERS(work, req, rsp);
6538 if (test_share_config_flag(work->tcon->share_conf, KSMBD_SHARE_FLAG_PIPE)) {
6539 ksmbd_debug(SMB, "IPC pipe write request\n");
6540 return smb2_write_pipe(work);
6543 offset = le64_to_cpu(req->Offset);
6544 length = le32_to_cpu(req->Length);
6546 if (req->Channel == SMB2_CHANNEL_RDMA_V1 ||
6547 req->Channel == SMB2_CHANNEL_RDMA_V1_INVALIDATE) {
6548 is_rdma_channel = true;
6549 max_write_size = get_smbd_max_read_write_size();
6550 length = le32_to_cpu(req->RemainingBytes);
6553 if (is_rdma_channel == true) {
6554 unsigned int ch_offset = le16_to_cpu(req->WriteChannelInfoOffset);
6556 if (req->Length != 0 || req->DataOffset != 0 ||
6557 ch_offset < offsetof(struct smb2_write_req, Buffer)) {
6561 err = smb2_set_remote_key_for_rdma(work,
6562 (struct smb2_buffer_desc_v1 *)
6563 ((char *)req + ch_offset),
6565 req->WriteChannelInfoLength);
6570 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
6571 ksmbd_debug(SMB, "User does not have write permission\n");
6576 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
6582 if (!(fp->daccess & (FILE_WRITE_DATA_LE | FILE_READ_ATTRIBUTES_LE))) {
6583 pr_err("Not permitted to write : 0x%x\n", fp->daccess);
6588 if (length > max_write_size) {
6589 ksmbd_debug(SMB, "limiting write size to max size(%u)\n",
6595 ksmbd_debug(SMB, "flags %u\n", le32_to_cpu(req->Flags));
6596 if (le32_to_cpu(req->Flags) & SMB2_WRITEFLAG_WRITE_THROUGH)
6597 writethrough = true;
6599 if (is_rdma_channel == false) {
6600 if (le16_to_cpu(req->DataOffset) <
6601 offsetof(struct smb2_write_req, Buffer)) {
6606 data_buf = (char *)(((char *)&req->hdr.ProtocolId) +
6607 le16_to_cpu(req->DataOffset));
6609 ksmbd_debug(SMB, "filename %pD, offset %lld, len %zu\n",
6610 fp->filp, offset, length);
6611 err = ksmbd_vfs_write(work, fp, data_buf, length, &offset,
6612 writethrough, &nbytes);
6616 /* read data from the client using rdma channel, and
6619 nbytes = smb2_write_rdma_channel(work, req, fp, offset, length,
6627 rsp->StructureSize = cpu_to_le16(17);
6628 rsp->DataOffset = 0;
6630 rsp->DataLength = cpu_to_le32(nbytes);
6631 rsp->DataRemaining = 0;
6633 inc_rfc1001_len(work->response_buf, 16);
6634 ksmbd_fd_put(work, fp);
6639 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
6640 else if (err == -ENOSPC || err == -EFBIG)
6641 rsp->hdr.Status = STATUS_DISK_FULL;
6642 else if (err == -ENOENT)
6643 rsp->hdr.Status = STATUS_FILE_CLOSED;
6644 else if (err == -EACCES)
6645 rsp->hdr.Status = STATUS_ACCESS_DENIED;
6646 else if (err == -ESHARE)
6647 rsp->hdr.Status = STATUS_SHARING_VIOLATION;
6648 else if (err == -EINVAL)
6649 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
6651 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6653 smb2_set_err_rsp(work);
6654 ksmbd_fd_put(work, fp);
6659 * smb2_flush() - handler for smb2 flush file - fsync
6660 * @work: smb work containing flush command buffer
6662 * Return: 0 on success, otherwise error
6664 int smb2_flush(struct ksmbd_work *work)
6666 struct smb2_flush_req *req;
6667 struct smb2_flush_rsp *rsp;
6670 WORK_BUFFERS(work, req, rsp);
6672 ksmbd_debug(SMB, "SMB2_FLUSH called for fid %llu\n", req->VolatileFileId);
6674 err = ksmbd_vfs_fsync(work, req->VolatileFileId, req->PersistentFileId);
6678 rsp->StructureSize = cpu_to_le16(4);
6680 inc_rfc1001_len(work->response_buf, 4);
6685 rsp->hdr.Status = STATUS_INVALID_HANDLE;
6686 smb2_set_err_rsp(work);
6693 * smb2_cancel() - handler for smb2 cancel command
6694 * @work: smb work containing cancel command buffer
6696 * Return: 0 on success, otherwise error
6698 int smb2_cancel(struct ksmbd_work *work)
6700 struct ksmbd_conn *conn = work->conn;
6701 struct smb2_hdr *hdr = smb2_get_msg(work->request_buf);
6702 struct smb2_hdr *chdr;
6703 struct ksmbd_work *iter;
6704 struct list_head *command_list;
6706 ksmbd_debug(SMB, "smb2 cancel called on mid %llu, async flags 0x%x\n",
6707 hdr->MessageId, hdr->Flags);
6709 if (hdr->Flags & SMB2_FLAGS_ASYNC_COMMAND) {
6710 command_list = &conn->async_requests;
6712 spin_lock(&conn->request_lock);
6713 list_for_each_entry(iter, command_list,
6714 async_request_entry) {
6715 chdr = smb2_get_msg(iter->request_buf);
6717 if (iter->async_id !=
6718 le64_to_cpu(hdr->Id.AsyncId))
6722 "smb2 with AsyncId %llu cancelled command = 0x%x\n",
6723 le64_to_cpu(hdr->Id.AsyncId),
6724 le16_to_cpu(chdr->Command));
6725 iter->state = KSMBD_WORK_CANCELLED;
6726 if (iter->cancel_fn)
6727 iter->cancel_fn(iter->cancel_argv);
6730 spin_unlock(&conn->request_lock);
6732 command_list = &conn->requests;
6734 spin_lock(&conn->request_lock);
6735 list_for_each_entry(iter, command_list, request_entry) {
6736 chdr = smb2_get_msg(iter->request_buf);
6738 if (chdr->MessageId != hdr->MessageId ||
6743 "smb2 with mid %llu cancelled command = 0x%x\n",
6744 le64_to_cpu(hdr->MessageId),
6745 le16_to_cpu(chdr->Command));
6746 iter->state = KSMBD_WORK_CANCELLED;
6749 spin_unlock(&conn->request_lock);
6752 /* For SMB2_CANCEL command itself send no response*/
6753 work->send_no_response = 1;
6757 struct file_lock *smb_flock_init(struct file *f)
6759 struct file_lock *fl;
6761 fl = locks_alloc_lock();
6765 locks_init_lock(fl);
6768 fl->fl_pid = current->tgid;
6770 fl->fl_flags = FL_POSIX;
6772 fl->fl_lmops = NULL;
6778 static int smb2_set_flock_flags(struct file_lock *flock, int flags)
6782 /* Checking for wrong flag combination during lock request*/
6784 case SMB2_LOCKFLAG_SHARED:
6785 ksmbd_debug(SMB, "received shared request\n");
6787 flock->fl_type = F_RDLCK;
6788 flock->fl_flags |= FL_SLEEP;
6790 case SMB2_LOCKFLAG_EXCLUSIVE:
6791 ksmbd_debug(SMB, "received exclusive request\n");
6793 flock->fl_type = F_WRLCK;
6794 flock->fl_flags |= FL_SLEEP;
6796 case SMB2_LOCKFLAG_SHARED | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
6798 "received shared & fail immediately request\n");
6800 flock->fl_type = F_RDLCK;
6802 case SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_FAIL_IMMEDIATELY:
6804 "received exclusive & fail immediately request\n");
6806 flock->fl_type = F_WRLCK;
6808 case SMB2_LOCKFLAG_UNLOCK:
6809 ksmbd_debug(SMB, "received unlock request\n");
6810 flock->fl_type = F_UNLCK;
6818 static struct ksmbd_lock *smb2_lock_init(struct file_lock *flock,
6819 unsigned int cmd, int flags,
6820 struct list_head *lock_list)
6822 struct ksmbd_lock *lock;
6824 lock = kzalloc(sizeof(struct ksmbd_lock), GFP_KERNEL);
6830 lock->start = flock->fl_start;
6831 lock->end = flock->fl_end;
6832 lock->flags = flags;
6833 if (lock->start == lock->end)
6835 INIT_LIST_HEAD(&lock->clist);
6836 INIT_LIST_HEAD(&lock->flist);
6837 INIT_LIST_HEAD(&lock->llist);
6838 list_add_tail(&lock->llist, lock_list);
6843 static void smb2_remove_blocked_lock(void **argv)
6845 struct file_lock *flock = (struct file_lock *)argv[0];
6847 ksmbd_vfs_posix_lock_unblock(flock);
6848 wake_up(&flock->fl_wait);
6851 static inline bool lock_defer_pending(struct file_lock *fl)
6853 /* check pending lock waiters */
6854 return waitqueue_active(&fl->fl_wait);
6858 * smb2_lock() - handler for smb2 file lock command
6859 * @work: smb work containing lock command buffer
6861 * Return: 0 on success, otherwise error
6863 int smb2_lock(struct ksmbd_work *work)
6865 struct smb2_lock_req *req = smb2_get_msg(work->request_buf);
6866 struct smb2_lock_rsp *rsp = smb2_get_msg(work->response_buf);
6867 struct smb2_lock_element *lock_ele;
6868 struct ksmbd_file *fp = NULL;
6869 struct file_lock *flock = NULL;
6870 struct file *filp = NULL;
6874 int err = -EIO, i, rc = 0;
6875 u64 lock_start, lock_length;
6876 struct ksmbd_lock *smb_lock = NULL, *cmp_lock, *tmp, *tmp2;
6877 struct ksmbd_conn *conn;
6879 LIST_HEAD(lock_list);
6880 LIST_HEAD(rollback_list);
6883 ksmbd_debug(SMB, "Received lock request\n");
6884 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
6886 ksmbd_debug(SMB, "Invalid file id for lock : %llu\n", req->VolatileFileId);
6892 lock_count = le16_to_cpu(req->LockCount);
6893 lock_ele = req->locks;
6895 ksmbd_debug(SMB, "lock count is %d\n", lock_count);
6901 for (i = 0; i < lock_count; i++) {
6902 flags = le32_to_cpu(lock_ele[i].Flags);
6904 flock = smb_flock_init(filp);
6908 cmd = smb2_set_flock_flags(flock, flags);
6910 lock_start = le64_to_cpu(lock_ele[i].Offset);
6911 lock_length = le64_to_cpu(lock_ele[i].Length);
6912 if (lock_start > U64_MAX - lock_length) {
6913 pr_err("Invalid lock range requested\n");
6914 rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
6918 if (lock_start > OFFSET_MAX)
6919 flock->fl_start = OFFSET_MAX;
6921 flock->fl_start = lock_start;
6923 lock_length = le64_to_cpu(lock_ele[i].Length);
6924 if (lock_length > OFFSET_MAX - flock->fl_start)
6925 lock_length = OFFSET_MAX - flock->fl_start;
6927 flock->fl_end = flock->fl_start + lock_length;
6929 if (flock->fl_end < flock->fl_start) {
6931 "the end offset(%llx) is smaller than the start offset(%llx)\n",
6932 flock->fl_end, flock->fl_start);
6933 rsp->hdr.Status = STATUS_INVALID_LOCK_RANGE;
6937 /* Check conflict locks in one request */
6938 list_for_each_entry(cmp_lock, &lock_list, llist) {
6939 if (cmp_lock->fl->fl_start <= flock->fl_start &&
6940 cmp_lock->fl->fl_end >= flock->fl_end) {
6941 if (cmp_lock->fl->fl_type != F_UNLCK &&
6942 flock->fl_type != F_UNLCK) {
6943 pr_err("conflict two locks in one request\n");
6950 smb_lock = smb2_lock_init(flock, cmd, flags, &lock_list);
6957 list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
6958 if (smb_lock->cmd < 0) {
6963 if (!(smb_lock->flags & SMB2_LOCKFLAG_MASK)) {
6968 if ((prior_lock & (SMB2_LOCKFLAG_EXCLUSIVE | SMB2_LOCKFLAG_SHARED) &&
6969 smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) ||
6970 (prior_lock == SMB2_LOCKFLAG_UNLOCK &&
6971 !(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK))) {
6976 prior_lock = smb_lock->flags;
6978 if (!(smb_lock->flags & SMB2_LOCKFLAG_UNLOCK) &&
6979 !(smb_lock->flags & SMB2_LOCKFLAG_FAIL_IMMEDIATELY))
6983 /* check locks in connection list */
6984 down_read(&conn_list_lock);
6985 list_for_each_entry(conn, &conn_list, conns_list) {
6986 spin_lock(&conn->llist_lock);
6987 list_for_each_entry_safe(cmp_lock, tmp2, &conn->lock_list, clist) {
6988 if (file_inode(cmp_lock->fl->fl_file) !=
6989 file_inode(smb_lock->fl->fl_file))
6992 if (smb_lock->fl->fl_type == F_UNLCK) {
6993 if (cmp_lock->fl->fl_file == smb_lock->fl->fl_file &&
6994 cmp_lock->start == smb_lock->start &&
6995 cmp_lock->end == smb_lock->end &&
6996 !lock_defer_pending(cmp_lock->fl)) {
6998 list_del(&cmp_lock->flist);
6999 list_del(&cmp_lock->clist);
7000 spin_unlock(&conn->llist_lock);
7001 up_read(&conn_list_lock);
7003 locks_free_lock(cmp_lock->fl);
7010 if (cmp_lock->fl->fl_file == smb_lock->fl->fl_file) {
7011 if (smb_lock->flags & SMB2_LOCKFLAG_SHARED)
7014 if (cmp_lock->flags & SMB2_LOCKFLAG_SHARED)
7018 /* check zero byte lock range */
7019 if (cmp_lock->zero_len && !smb_lock->zero_len &&
7020 cmp_lock->start > smb_lock->start &&
7021 cmp_lock->start < smb_lock->end) {
7022 spin_unlock(&conn->llist_lock);
7023 up_read(&conn_list_lock);
7024 pr_err("previous lock conflict with zero byte lock range\n");
7028 if (smb_lock->zero_len && !cmp_lock->zero_len &&
7029 smb_lock->start > cmp_lock->start &&
7030 smb_lock->start < cmp_lock->end) {
7031 spin_unlock(&conn->llist_lock);
7032 up_read(&conn_list_lock);
7033 pr_err("current lock conflict with zero byte lock range\n");
7037 if (((cmp_lock->start <= smb_lock->start &&
7038 cmp_lock->end > smb_lock->start) ||
7039 (cmp_lock->start < smb_lock->end &&
7040 cmp_lock->end >= smb_lock->end)) &&
7041 !cmp_lock->zero_len && !smb_lock->zero_len) {
7042 spin_unlock(&conn->llist_lock);
7043 up_read(&conn_list_lock);
7044 pr_err("Not allow lock operation on exclusive lock range\n");
7048 spin_unlock(&conn->llist_lock);
7050 up_read(&conn_list_lock);
7052 if (smb_lock->fl->fl_type == F_UNLCK && nolock) {
7053 pr_err("Try to unlock nolocked range\n");
7054 rsp->hdr.Status = STATUS_RANGE_NOT_LOCKED;
7059 if (smb_lock->zero_len) {
7064 flock = smb_lock->fl;
7065 list_del(&smb_lock->llist);
7067 rc = vfs_lock_file(filp, smb_lock->cmd, flock, NULL);
7069 if (flags & SMB2_LOCKFLAG_UNLOCK) {
7071 ksmbd_debug(SMB, "File unlocked\n");
7072 } else if (rc == -ENOENT) {
7073 rsp->hdr.Status = STATUS_NOT_LOCKED;
7076 locks_free_lock(flock);
7079 if (rc == FILE_LOCK_DEFERRED) {
7083 "would have to wait for getting lock\n");
7084 spin_lock(&work->conn->llist_lock);
7085 list_add_tail(&smb_lock->clist,
7086 &work->conn->lock_list);
7087 spin_unlock(&work->conn->llist_lock);
7088 list_add(&smb_lock->llist, &rollback_list);
7090 argv = kmalloc(sizeof(void *), GFP_KERNEL);
7097 rc = setup_async_work(work,
7098 smb2_remove_blocked_lock,
7104 spin_lock(&fp->f_lock);
7105 list_add(&work->fp_entry, &fp->blocked_works);
7106 spin_unlock(&fp->f_lock);
7108 smb2_send_interim_resp(work, STATUS_PENDING);
7110 ksmbd_vfs_posix_lock_wait(flock);
7112 spin_lock(&work->conn->request_lock);
7113 spin_lock(&fp->f_lock);
7114 list_del(&work->fp_entry);
7115 work->cancel_fn = NULL;
7117 spin_unlock(&fp->f_lock);
7118 spin_unlock(&work->conn->request_lock);
7120 if (work->state != KSMBD_WORK_ACTIVE) {
7121 list_del(&smb_lock->llist);
7122 spin_lock(&work->conn->llist_lock);
7123 list_del(&smb_lock->clist);
7124 spin_unlock(&work->conn->llist_lock);
7125 locks_free_lock(flock);
7127 if (work->state == KSMBD_WORK_CANCELLED) {
7131 smb2_send_interim_resp(work,
7133 work->send_no_response = 1;
7136 init_smb2_rsp_hdr(work);
7137 smb2_set_err_rsp(work);
7139 STATUS_RANGE_NOT_LOCKED;
7144 list_del(&smb_lock->llist);
7145 spin_lock(&work->conn->llist_lock);
7146 list_del(&smb_lock->clist);
7147 spin_unlock(&work->conn->llist_lock);
7151 spin_lock(&work->conn->llist_lock);
7152 list_add_tail(&smb_lock->clist,
7153 &work->conn->lock_list);
7154 list_add_tail(&smb_lock->flist,
7156 spin_unlock(&work->conn->llist_lock);
7157 list_add(&smb_lock->llist, &rollback_list);
7158 ksmbd_debug(SMB, "successful in taking lock\n");
7165 if (atomic_read(&fp->f_ci->op_count) > 1)
7166 smb_break_all_oplock(work, fp);
7168 rsp->StructureSize = cpu_to_le16(4);
7169 ksmbd_debug(SMB, "successful in taking lock\n");
7170 rsp->hdr.Status = STATUS_SUCCESS;
7172 inc_rfc1001_len(work->response_buf, 4);
7173 ksmbd_fd_put(work, fp);
7177 list_for_each_entry_safe(smb_lock, tmp, &lock_list, llist) {
7178 locks_free_lock(smb_lock->fl);
7179 list_del(&smb_lock->llist);
7183 list_for_each_entry_safe(smb_lock, tmp, &rollback_list, llist) {
7184 struct file_lock *rlock = NULL;
7186 rlock = smb_flock_init(filp);
7187 rlock->fl_type = F_UNLCK;
7188 rlock->fl_start = smb_lock->start;
7189 rlock->fl_end = smb_lock->end;
7191 rc = vfs_lock_file(filp, 0, rlock, NULL);
7193 pr_err("rollback unlock fail : %d\n", rc);
7195 list_del(&smb_lock->llist);
7196 spin_lock(&work->conn->llist_lock);
7197 if (!list_empty(&smb_lock->flist))
7198 list_del(&smb_lock->flist);
7199 list_del(&smb_lock->clist);
7200 spin_unlock(&work->conn->llist_lock);
7202 locks_free_lock(smb_lock->fl);
7203 locks_free_lock(rlock);
7207 ksmbd_debug(SMB, "failed in taking lock(flags : %x), err : %d\n", flags, err);
7209 if (!rsp->hdr.Status) {
7211 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7212 else if (err == -ENOMEM)
7213 rsp->hdr.Status = STATUS_INSUFFICIENT_RESOURCES;
7214 else if (err == -ENOENT)
7215 rsp->hdr.Status = STATUS_FILE_CLOSED;
7217 rsp->hdr.Status = STATUS_LOCK_NOT_GRANTED;
7220 smb2_set_err_rsp(work);
7221 ksmbd_fd_put(work, fp);
7225 static int fsctl_copychunk(struct ksmbd_work *work,
7226 struct copychunk_ioctl_req *ci_req,
7227 unsigned int cnt_code,
7228 unsigned int input_count,
7229 unsigned long long volatile_id,
7230 unsigned long long persistent_id,
7231 struct smb2_ioctl_rsp *rsp)
7233 struct copychunk_ioctl_rsp *ci_rsp;
7234 struct ksmbd_file *src_fp = NULL, *dst_fp = NULL;
7235 struct srv_copychunk *chunks;
7236 unsigned int i, chunk_count, chunk_count_written = 0;
7237 unsigned int chunk_size_written = 0;
7238 loff_t total_size_written = 0;
7241 ci_rsp = (struct copychunk_ioctl_rsp *)&rsp->Buffer[0];
7243 rsp->VolatileFileId = volatile_id;
7244 rsp->PersistentFileId = persistent_id;
7245 ci_rsp->ChunksWritten =
7246 cpu_to_le32(ksmbd_server_side_copy_max_chunk_count());
7247 ci_rsp->ChunkBytesWritten =
7248 cpu_to_le32(ksmbd_server_side_copy_max_chunk_size());
7249 ci_rsp->TotalBytesWritten =
7250 cpu_to_le32(ksmbd_server_side_copy_max_total_size());
7252 chunks = (struct srv_copychunk *)&ci_req->Chunks[0];
7253 chunk_count = le32_to_cpu(ci_req->ChunkCount);
7254 if (chunk_count == 0)
7256 total_size_written = 0;
7258 /* verify the SRV_COPYCHUNK_COPY packet */
7259 if (chunk_count > ksmbd_server_side_copy_max_chunk_count() ||
7260 input_count < offsetof(struct copychunk_ioctl_req, Chunks) +
7261 chunk_count * sizeof(struct srv_copychunk)) {
7262 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7266 for (i = 0; i < chunk_count; i++) {
7267 if (le32_to_cpu(chunks[i].Length) == 0 ||
7268 le32_to_cpu(chunks[i].Length) > ksmbd_server_side_copy_max_chunk_size())
7270 total_size_written += le32_to_cpu(chunks[i].Length);
7273 if (i < chunk_count ||
7274 total_size_written > ksmbd_server_side_copy_max_total_size()) {
7275 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7279 src_fp = ksmbd_lookup_foreign_fd(work,
7280 le64_to_cpu(ci_req->ResumeKey[0]));
7281 dst_fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
7284 src_fp->persistent_id != le64_to_cpu(ci_req->ResumeKey[1])) {
7285 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
7290 rsp->hdr.Status = STATUS_FILE_CLOSED;
7295 * FILE_READ_DATA should only be included in
7296 * the FSCTL_COPYCHUNK case
7298 if (cnt_code == FSCTL_COPYCHUNK &&
7299 !(dst_fp->daccess & (FILE_READ_DATA_LE | FILE_GENERIC_READ_LE))) {
7300 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7304 ret = ksmbd_vfs_copy_file_ranges(work, src_fp, dst_fp,
7305 chunks, chunk_count,
7306 &chunk_count_written,
7307 &chunk_size_written,
7308 &total_size_written);
7311 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7313 rsp->hdr.Status = STATUS_FILE_LOCK_CONFLICT;
7314 else if (ret == -EBADF)
7315 rsp->hdr.Status = STATUS_INVALID_HANDLE;
7316 else if (ret == -EFBIG || ret == -ENOSPC)
7317 rsp->hdr.Status = STATUS_DISK_FULL;
7318 else if (ret == -EINVAL)
7319 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7320 else if (ret == -EISDIR)
7321 rsp->hdr.Status = STATUS_FILE_IS_A_DIRECTORY;
7322 else if (ret == -E2BIG)
7323 rsp->hdr.Status = STATUS_INVALID_VIEW_SIZE;
7325 rsp->hdr.Status = STATUS_UNEXPECTED_IO_ERROR;
7328 ci_rsp->ChunksWritten = cpu_to_le32(chunk_count_written);
7329 ci_rsp->ChunkBytesWritten = cpu_to_le32(chunk_size_written);
7330 ci_rsp->TotalBytesWritten = cpu_to_le32(total_size_written);
7332 ksmbd_fd_put(work, src_fp);
7333 ksmbd_fd_put(work, dst_fp);
7337 static __be32 idev_ipv4_address(struct in_device *idev)
7341 struct in_ifaddr *ifa;
7344 in_dev_for_each_ifa_rcu(ifa, idev) {
7345 if (ifa->ifa_flags & IFA_F_SECONDARY)
7348 addr = ifa->ifa_address;
7355 static int fsctl_query_iface_info_ioctl(struct ksmbd_conn *conn,
7356 struct smb2_ioctl_rsp *rsp,
7357 unsigned int out_buf_len)
7359 struct network_interface_info_ioctl_rsp *nii_rsp = NULL;
7361 struct net_device *netdev;
7362 struct sockaddr_storage_rsp *sockaddr_storage;
7364 unsigned long long speed;
7367 for_each_netdev(&init_net, netdev) {
7368 bool ipv4_set = false;
7370 if (netdev->type == ARPHRD_LOOPBACK)
7373 flags = dev_get_flags(netdev);
7374 if (!(flags & IFF_RUNNING))
7378 nbytes + sizeof(struct network_interface_info_ioctl_rsp)) {
7383 nii_rsp = (struct network_interface_info_ioctl_rsp *)
7384 &rsp->Buffer[nbytes];
7385 nii_rsp->IfIndex = cpu_to_le32(netdev->ifindex);
7387 nii_rsp->Capability = 0;
7388 if (netdev->real_num_tx_queues > 1)
7389 nii_rsp->Capability |= cpu_to_le32(RSS_CAPABLE);
7390 if (ksmbd_rdma_capable_netdev(netdev))
7391 nii_rsp->Capability |= cpu_to_le32(RDMA_CAPABLE);
7393 nii_rsp->Next = cpu_to_le32(152);
7394 nii_rsp->Reserved = 0;
7396 if (netdev->ethtool_ops->get_link_ksettings) {
7397 struct ethtool_link_ksettings cmd;
7399 netdev->ethtool_ops->get_link_ksettings(netdev, &cmd);
7400 speed = cmd.base.speed;
7402 ksmbd_debug(SMB, "%s %s\n", netdev->name,
7403 "speed is unknown, defaulting to 1Gb/sec");
7408 nii_rsp->LinkSpeed = cpu_to_le64(speed);
7410 sockaddr_storage = (struct sockaddr_storage_rsp *)
7411 nii_rsp->SockAddr_Storage;
7412 memset(sockaddr_storage, 0, 128);
7415 struct in_device *idev;
7417 sockaddr_storage->Family = cpu_to_le16(INTERNETWORK);
7418 sockaddr_storage->addr4.Port = 0;
7420 idev = __in_dev_get_rtnl(netdev);
7423 sockaddr_storage->addr4.IPv4address =
7424 idev_ipv4_address(idev);
7425 nbytes += sizeof(struct network_interface_info_ioctl_rsp);
7429 struct inet6_dev *idev6;
7430 struct inet6_ifaddr *ifa;
7431 __u8 *ipv6_addr = sockaddr_storage->addr6.IPv6address;
7433 sockaddr_storage->Family = cpu_to_le16(INTERNETWORKV6);
7434 sockaddr_storage->addr6.Port = 0;
7435 sockaddr_storage->addr6.FlowInfo = 0;
7437 idev6 = __in6_dev_get(netdev);
7441 list_for_each_entry(ifa, &idev6->addr_list, if_list) {
7442 if (ifa->flags & (IFA_F_TENTATIVE |
7445 memcpy(ipv6_addr, ifa->addr.s6_addr, 16);
7448 sockaddr_storage->addr6.ScopeId = 0;
7449 nbytes += sizeof(struct network_interface_info_ioctl_rsp);
7454 /* zero if this is last one */
7458 rsp->PersistentFileId = SMB2_NO_FID;
7459 rsp->VolatileFileId = SMB2_NO_FID;
7463 static int fsctl_validate_negotiate_info(struct ksmbd_conn *conn,
7464 struct validate_negotiate_info_req *neg_req,
7465 struct validate_negotiate_info_rsp *neg_rsp,
7466 unsigned int in_buf_len)
7471 if (in_buf_len < offsetof(struct validate_negotiate_info_req, Dialects) +
7472 le16_to_cpu(neg_req->DialectCount) * sizeof(__le16))
7475 dialect = ksmbd_lookup_dialect_by_id(neg_req->Dialects,
7476 neg_req->DialectCount);
7477 if (dialect == BAD_PROT_ID || dialect != conn->dialect) {
7482 if (strncmp(neg_req->Guid, conn->ClientGUID, SMB2_CLIENT_GUID_SIZE)) {
7487 if (le16_to_cpu(neg_req->SecurityMode) != conn->cli_sec_mode) {
7492 if (le32_to_cpu(neg_req->Capabilities) != conn->cli_cap) {
7497 neg_rsp->Capabilities = cpu_to_le32(conn->vals->capabilities);
7498 memset(neg_rsp->Guid, 0, SMB2_CLIENT_GUID_SIZE);
7499 neg_rsp->SecurityMode = cpu_to_le16(conn->srv_sec_mode);
7500 neg_rsp->Dialect = cpu_to_le16(conn->dialect);
7505 static int fsctl_query_allocated_ranges(struct ksmbd_work *work, u64 id,
7506 struct file_allocated_range_buffer *qar_req,
7507 struct file_allocated_range_buffer *qar_rsp,
7508 unsigned int in_count, unsigned int *out_count)
7510 struct ksmbd_file *fp;
7511 loff_t start, length;
7518 start = le64_to_cpu(qar_req->file_offset);
7519 length = le64_to_cpu(qar_req->length);
7521 if (start < 0 || length < 0)
7524 fp = ksmbd_lookup_fd_fast(work, id);
7528 ret = ksmbd_vfs_fqar_lseek(fp, start, length,
7529 qar_rsp, in_count, out_count);
7530 if (ret && ret != -E2BIG)
7533 ksmbd_fd_put(work, fp);
7537 static int fsctl_pipe_transceive(struct ksmbd_work *work, u64 id,
7538 unsigned int out_buf_len,
7539 struct smb2_ioctl_req *req,
7540 struct smb2_ioctl_rsp *rsp)
7542 struct ksmbd_rpc_command *rpc_resp;
7543 char *data_buf = (char *)&req->Buffer[0];
7546 rpc_resp = ksmbd_rpc_ioctl(work->sess, id, data_buf,
7547 le32_to_cpu(req->InputCount));
7549 if (rpc_resp->flags == KSMBD_RPC_SOME_NOT_MAPPED) {
7551 * set STATUS_SOME_NOT_MAPPED response
7552 * for unknown domain sid.
7554 rsp->hdr.Status = STATUS_SOME_NOT_MAPPED;
7555 } else if (rpc_resp->flags == KSMBD_RPC_ENOTIMPLEMENTED) {
7556 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7558 } else if (rpc_resp->flags != KSMBD_RPC_OK) {
7559 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7563 nbytes = rpc_resp->payload_sz;
7564 if (rpc_resp->payload_sz > out_buf_len) {
7565 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
7566 nbytes = out_buf_len;
7569 if (!rpc_resp->payload_sz) {
7571 STATUS_UNEXPECTED_IO_ERROR;
7575 memcpy((char *)rsp->Buffer, rpc_resp->payload, nbytes);
7582 static inline int fsctl_set_sparse(struct ksmbd_work *work, u64 id,
7583 struct file_sparse *sparse)
7585 struct ksmbd_file *fp;
7586 struct user_namespace *user_ns;
7590 fp = ksmbd_lookup_fd_fast(work, id);
7593 user_ns = file_mnt_user_ns(fp->filp);
7595 old_fattr = fp->f_ci->m_fattr;
7596 if (sparse->SetSparse)
7597 fp->f_ci->m_fattr |= FILE_ATTRIBUTE_SPARSE_FILE_LE;
7599 fp->f_ci->m_fattr &= ~FILE_ATTRIBUTE_SPARSE_FILE_LE;
7601 if (fp->f_ci->m_fattr != old_fattr &&
7602 test_share_config_flag(work->tcon->share_conf,
7603 KSMBD_SHARE_FLAG_STORE_DOS_ATTRS)) {
7604 struct xattr_dos_attrib da;
7606 ret = ksmbd_vfs_get_dos_attrib_xattr(user_ns,
7607 fp->filp->f_path.dentry, &da);
7611 da.attr = le32_to_cpu(fp->f_ci->m_fattr);
7612 ret = ksmbd_vfs_set_dos_attrib_xattr(user_ns,
7613 fp->filp->f_path.dentry, &da);
7615 fp->f_ci->m_fattr = old_fattr;
7619 ksmbd_fd_put(work, fp);
7623 static int fsctl_request_resume_key(struct ksmbd_work *work,
7624 struct smb2_ioctl_req *req,
7625 struct resume_key_ioctl_rsp *key_rsp)
7627 struct ksmbd_file *fp;
7629 fp = ksmbd_lookup_fd_slow(work, req->VolatileFileId, req->PersistentFileId);
7633 memset(key_rsp, 0, sizeof(*key_rsp));
7634 key_rsp->ResumeKey[0] = req->VolatileFileId;
7635 key_rsp->ResumeKey[1] = req->PersistentFileId;
7636 ksmbd_fd_put(work, fp);
7642 * smb2_ioctl() - handler for smb2 ioctl command
7643 * @work: smb work containing ioctl command buffer
7645 * Return: 0 on success, otherwise error
7647 int smb2_ioctl(struct ksmbd_work *work)
7649 struct smb2_ioctl_req *req;
7650 struct smb2_ioctl_rsp *rsp;
7651 unsigned int cnt_code, nbytes = 0, out_buf_len, in_buf_len;
7652 u64 id = KSMBD_NO_FID;
7653 struct ksmbd_conn *conn = work->conn;
7656 if (work->next_smb2_rcv_hdr_off) {
7657 req = ksmbd_req_buf_next(work);
7658 rsp = ksmbd_resp_buf_next(work);
7659 if (!has_file_id(req->VolatileFileId)) {
7660 ksmbd_debug(SMB, "Compound request set FID = %llu\n",
7661 work->compound_fid);
7662 id = work->compound_fid;
7665 req = smb2_get_msg(work->request_buf);
7666 rsp = smb2_get_msg(work->response_buf);
7669 if (!has_file_id(id))
7670 id = req->VolatileFileId;
7672 if (req->Flags != cpu_to_le32(SMB2_0_IOCTL_IS_FSCTL)) {
7673 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7677 cnt_code = le32_to_cpu(req->CtlCode);
7678 ret = smb2_calc_max_out_buf_len(work, 48,
7679 le32_to_cpu(req->MaxOutputResponse));
7681 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7684 out_buf_len = (unsigned int)ret;
7685 in_buf_len = le32_to_cpu(req->InputCount);
7688 case FSCTL_DFS_GET_REFERRALS:
7689 case FSCTL_DFS_GET_REFERRALS_EX:
7690 /* Not support DFS yet */
7691 rsp->hdr.Status = STATUS_FS_DRIVER_REQUIRED;
7693 case FSCTL_CREATE_OR_GET_OBJECT_ID:
7695 struct file_object_buf_type1_ioctl_rsp *obj_buf;
7697 nbytes = sizeof(struct file_object_buf_type1_ioctl_rsp);
7698 obj_buf = (struct file_object_buf_type1_ioctl_rsp *)
7702 * TODO: This is dummy implementation to pass smbtorture
7703 * Need to check correct response later
7705 memset(obj_buf->ObjectId, 0x0, 16);
7706 memset(obj_buf->BirthVolumeId, 0x0, 16);
7707 memset(obj_buf->BirthObjectId, 0x0, 16);
7708 memset(obj_buf->DomainId, 0x0, 16);
7712 case FSCTL_PIPE_TRANSCEIVE:
7713 out_buf_len = min_t(u32, KSMBD_IPC_MAX_PAYLOAD, out_buf_len);
7714 nbytes = fsctl_pipe_transceive(work, id, out_buf_len, req, rsp);
7716 case FSCTL_VALIDATE_NEGOTIATE_INFO:
7717 if (conn->dialect < SMB30_PROT_ID) {
7722 if (in_buf_len < offsetof(struct validate_negotiate_info_req,
7728 if (out_buf_len < sizeof(struct validate_negotiate_info_rsp)) {
7733 ret = fsctl_validate_negotiate_info(conn,
7734 (struct validate_negotiate_info_req *)&req->Buffer[0],
7735 (struct validate_negotiate_info_rsp *)&rsp->Buffer[0],
7740 nbytes = sizeof(struct validate_negotiate_info_rsp);
7741 rsp->PersistentFileId = SMB2_NO_FID;
7742 rsp->VolatileFileId = SMB2_NO_FID;
7744 case FSCTL_QUERY_NETWORK_INTERFACE_INFO:
7745 ret = fsctl_query_iface_info_ioctl(conn, rsp, out_buf_len);
7750 case FSCTL_REQUEST_RESUME_KEY:
7751 if (out_buf_len < sizeof(struct resume_key_ioctl_rsp)) {
7756 ret = fsctl_request_resume_key(work, req,
7757 (struct resume_key_ioctl_rsp *)&rsp->Buffer[0]);
7760 rsp->PersistentFileId = req->PersistentFileId;
7761 rsp->VolatileFileId = req->VolatileFileId;
7762 nbytes = sizeof(struct resume_key_ioctl_rsp);
7764 case FSCTL_COPYCHUNK:
7765 case FSCTL_COPYCHUNK_WRITE:
7766 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7768 "User does not have write permission\n");
7773 if (in_buf_len < sizeof(struct copychunk_ioctl_req)) {
7778 if (out_buf_len < sizeof(struct copychunk_ioctl_rsp)) {
7783 nbytes = sizeof(struct copychunk_ioctl_rsp);
7784 rsp->VolatileFileId = req->VolatileFileId;
7785 rsp->PersistentFileId = req->PersistentFileId;
7786 fsctl_copychunk(work,
7787 (struct copychunk_ioctl_req *)&req->Buffer[0],
7788 le32_to_cpu(req->CtlCode),
7789 le32_to_cpu(req->InputCount),
7790 req->VolatileFileId,
7791 req->PersistentFileId,
7794 case FSCTL_SET_SPARSE:
7795 if (in_buf_len < sizeof(struct file_sparse)) {
7800 ret = fsctl_set_sparse(work, id,
7801 (struct file_sparse *)&req->Buffer[0]);
7805 case FSCTL_SET_ZERO_DATA:
7807 struct file_zero_data_information *zero_data;
7808 struct ksmbd_file *fp;
7809 loff_t off, len, bfz;
7811 if (!test_tree_conn_flag(work->tcon, KSMBD_TREE_CONN_FLAG_WRITABLE)) {
7813 "User does not have write permission\n");
7818 if (in_buf_len < sizeof(struct file_zero_data_information)) {
7824 (struct file_zero_data_information *)&req->Buffer[0];
7826 off = le64_to_cpu(zero_data->FileOffset);
7827 bfz = le64_to_cpu(zero_data->BeyondFinalZero);
7828 if (off < 0 || bfz < 0 || off > bfz) {
7835 fp = ksmbd_lookup_fd_fast(work, id);
7841 ret = ksmbd_vfs_zero_data(work, fp, off, len);
7842 ksmbd_fd_put(work, fp);
7848 case FSCTL_QUERY_ALLOCATED_RANGES:
7849 if (in_buf_len < sizeof(struct file_allocated_range_buffer)) {
7854 ret = fsctl_query_allocated_ranges(work, id,
7855 (struct file_allocated_range_buffer *)&req->Buffer[0],
7856 (struct file_allocated_range_buffer *)&rsp->Buffer[0],
7858 sizeof(struct file_allocated_range_buffer), &nbytes);
7859 if (ret == -E2BIG) {
7860 rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
7861 } else if (ret < 0) {
7866 nbytes *= sizeof(struct file_allocated_range_buffer);
7868 case FSCTL_GET_REPARSE_POINT:
7870 struct reparse_data_buffer *reparse_ptr;
7871 struct ksmbd_file *fp;
7873 reparse_ptr = (struct reparse_data_buffer *)&rsp->Buffer[0];
7874 fp = ksmbd_lookup_fd_fast(work, id);
7876 pr_err("not found fp!!\n");
7881 reparse_ptr->ReparseTag =
7882 smb2_get_reparse_tag_special_file(file_inode(fp->filp)->i_mode);
7883 reparse_ptr->ReparseDataLength = 0;
7884 ksmbd_fd_put(work, fp);
7885 nbytes = sizeof(struct reparse_data_buffer);
7888 case FSCTL_DUPLICATE_EXTENTS_TO_FILE:
7890 struct ksmbd_file *fp_in, *fp_out = NULL;
7891 struct duplicate_extents_to_file *dup_ext;
7892 loff_t src_off, dst_off, length, cloned;
7894 if (in_buf_len < sizeof(struct duplicate_extents_to_file)) {
7899 dup_ext = (struct duplicate_extents_to_file *)&req->Buffer[0];
7901 fp_in = ksmbd_lookup_fd_slow(work, dup_ext->VolatileFileHandle,
7902 dup_ext->PersistentFileHandle);
7904 pr_err("not found file handle in duplicate extent to file\n");
7909 fp_out = ksmbd_lookup_fd_fast(work, id);
7911 pr_err("not found fp\n");
7916 src_off = le64_to_cpu(dup_ext->SourceFileOffset);
7917 dst_off = le64_to_cpu(dup_ext->TargetFileOffset);
7918 length = le64_to_cpu(dup_ext->ByteCount);
7920 * XXX: It is not clear if FSCTL_DUPLICATE_EXTENTS_TO_FILE
7921 * should fall back to vfs_copy_file_range(). This could be
7922 * beneficial when re-exporting nfs/smb mount, but note that
7923 * this can result in partial copy that returns an error status.
7924 * If/when FSCTL_DUPLICATE_EXTENTS_TO_FILE_EX is implemented,
7925 * fall back to vfs_copy_file_range(), should be avoided when
7926 * the flag DUPLICATE_EXTENTS_DATA_EX_SOURCE_ATOMIC is set.
7928 cloned = vfs_clone_file_range(fp_in->filp, src_off,
7929 fp_out->filp, dst_off, length, 0);
7930 if (cloned == -EXDEV || cloned == -EOPNOTSUPP) {
7933 } else if (cloned != length) {
7934 cloned = vfs_copy_file_range(fp_in->filp, src_off,
7935 fp_out->filp, dst_off,
7937 if (cloned != length) {
7946 ksmbd_fd_put(work, fp_in);
7947 ksmbd_fd_put(work, fp_out);
7953 ksmbd_debug(SMB, "not implemented yet ioctl command 0x%x\n",
7959 rsp->CtlCode = cpu_to_le32(cnt_code);
7960 rsp->InputCount = cpu_to_le32(0);
7961 rsp->InputOffset = cpu_to_le32(112);
7962 rsp->OutputOffset = cpu_to_le32(112);
7963 rsp->OutputCount = cpu_to_le32(nbytes);
7964 rsp->StructureSize = cpu_to_le16(49);
7965 rsp->Reserved = cpu_to_le16(0);
7966 rsp->Flags = cpu_to_le32(0);
7967 rsp->Reserved2 = cpu_to_le32(0);
7968 inc_rfc1001_len(work->response_buf, 48 + nbytes);
7974 rsp->hdr.Status = STATUS_ACCESS_DENIED;
7975 else if (ret == -ENOENT)
7976 rsp->hdr.Status = STATUS_OBJECT_NAME_NOT_FOUND;
7977 else if (ret == -EOPNOTSUPP)
7978 rsp->hdr.Status = STATUS_NOT_SUPPORTED;
7979 else if (ret == -ENOSPC)
7980 rsp->hdr.Status = STATUS_BUFFER_TOO_SMALL;
7981 else if (ret < 0 || rsp->hdr.Status == 0)
7982 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
7983 smb2_set_err_rsp(work);
7988 * smb20_oplock_break_ack() - handler for smb2.0 oplock break command
7989 * @work: smb work containing oplock break command buffer
7993 static void smb20_oplock_break_ack(struct ksmbd_work *work)
7995 struct smb2_oplock_break *req = smb2_get_msg(work->request_buf);
7996 struct smb2_oplock_break *rsp = smb2_get_msg(work->response_buf);
7997 struct ksmbd_file *fp;
7998 struct oplock_info *opinfo = NULL;
8001 u64 volatile_id, persistent_id;
8002 char req_oplevel = 0, rsp_oplevel = 0;
8003 unsigned int oplock_change_type;
8005 volatile_id = req->VolatileFid;
8006 persistent_id = req->PersistentFid;
8007 req_oplevel = req->OplockLevel;
8008 ksmbd_debug(OPLOCK, "v_id %llu, p_id %llu request oplock level %d\n",
8009 volatile_id, persistent_id, req_oplevel);
8011 fp = ksmbd_lookup_fd_slow(work, volatile_id, persistent_id);
8013 rsp->hdr.Status = STATUS_FILE_CLOSED;
8014 smb2_set_err_rsp(work);
8018 opinfo = opinfo_get(fp);
8020 pr_err("unexpected null oplock_info\n");
8021 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
8022 smb2_set_err_rsp(work);
8023 ksmbd_fd_put(work, fp);
8027 if (opinfo->level == SMB2_OPLOCK_LEVEL_NONE) {
8028 rsp->hdr.Status = STATUS_INVALID_OPLOCK_PROTOCOL;
8032 if (opinfo->op_state == OPLOCK_STATE_NONE) {
8033 ksmbd_debug(SMB, "unexpected oplock state 0x%x\n", opinfo->op_state);
8034 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8038 if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
8039 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
8040 (req_oplevel != SMB2_OPLOCK_LEVEL_II &&
8041 req_oplevel != SMB2_OPLOCK_LEVEL_NONE)) {
8042 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8043 oplock_change_type = OPLOCK_WRITE_TO_NONE;
8044 } else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
8045 req_oplevel != SMB2_OPLOCK_LEVEL_NONE) {
8046 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8047 oplock_change_type = OPLOCK_READ_TO_NONE;
8048 } else if (req_oplevel == SMB2_OPLOCK_LEVEL_II ||
8049 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
8050 err = STATUS_INVALID_DEVICE_STATE;
8051 if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
8052 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
8053 req_oplevel == SMB2_OPLOCK_LEVEL_II) {
8054 oplock_change_type = OPLOCK_WRITE_TO_READ;
8055 } else if ((opinfo->level == SMB2_OPLOCK_LEVEL_EXCLUSIVE ||
8056 opinfo->level == SMB2_OPLOCK_LEVEL_BATCH) &&
8057 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
8058 oplock_change_type = OPLOCK_WRITE_TO_NONE;
8059 } else if (opinfo->level == SMB2_OPLOCK_LEVEL_II &&
8060 req_oplevel == SMB2_OPLOCK_LEVEL_NONE) {
8061 oplock_change_type = OPLOCK_READ_TO_NONE;
8063 oplock_change_type = 0;
8066 oplock_change_type = 0;
8069 switch (oplock_change_type) {
8070 case OPLOCK_WRITE_TO_READ:
8071 ret = opinfo_write_to_read(opinfo);
8072 rsp_oplevel = SMB2_OPLOCK_LEVEL_II;
8074 case OPLOCK_WRITE_TO_NONE:
8075 ret = opinfo_write_to_none(opinfo);
8076 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
8078 case OPLOCK_READ_TO_NONE:
8079 ret = opinfo_read_to_none(opinfo);
8080 rsp_oplevel = SMB2_OPLOCK_LEVEL_NONE;
8083 pr_err("unknown oplock change 0x%x -> 0x%x\n",
8084 opinfo->level, rsp_oplevel);
8088 rsp->hdr.Status = err;
8093 ksmbd_fd_put(work, fp);
8094 opinfo->op_state = OPLOCK_STATE_NONE;
8095 wake_up_interruptible_all(&opinfo->oplock_q);
8097 rsp->StructureSize = cpu_to_le16(24);
8098 rsp->OplockLevel = rsp_oplevel;
8101 rsp->VolatileFid = volatile_id;
8102 rsp->PersistentFid = persistent_id;
8103 inc_rfc1001_len(work->response_buf, 24);
8107 opinfo->op_state = OPLOCK_STATE_NONE;
8108 wake_up_interruptible_all(&opinfo->oplock_q);
8111 ksmbd_fd_put(work, fp);
8112 smb2_set_err_rsp(work);
8115 static int check_lease_state(struct lease *lease, __le32 req_state)
8117 if ((lease->new_state ==
8118 (SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE)) &&
8119 !(req_state & SMB2_LEASE_WRITE_CACHING_LE)) {
8120 lease->new_state = req_state;
8124 if (lease->new_state == req_state)
8131 * smb21_lease_break_ack() - handler for smb2.1 lease break command
8132 * @work: smb work containing lease break command buffer
8136 static void smb21_lease_break_ack(struct ksmbd_work *work)
8138 struct ksmbd_conn *conn = work->conn;
8139 struct smb2_lease_ack *req = smb2_get_msg(work->request_buf);
8140 struct smb2_lease_ack *rsp = smb2_get_msg(work->response_buf);
8141 struct oplock_info *opinfo;
8144 unsigned int lease_change_type;
8146 struct lease *lease;
8148 ksmbd_debug(OPLOCK, "smb21 lease break, lease state(0x%x)\n",
8149 le32_to_cpu(req->LeaseState));
8150 opinfo = lookup_lease_in_table(conn, req->LeaseKey);
8152 ksmbd_debug(OPLOCK, "file not opened\n");
8153 smb2_set_err_rsp(work);
8154 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8157 lease = opinfo->o_lease;
8159 if (opinfo->op_state == OPLOCK_STATE_NONE) {
8160 pr_err("unexpected lease break state 0x%x\n",
8162 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8166 if (check_lease_state(lease, req->LeaseState)) {
8167 rsp->hdr.Status = STATUS_REQUEST_NOT_ACCEPTED;
8169 "req lease state: 0x%x, expected state: 0x%x\n",
8170 req->LeaseState, lease->new_state);
8174 if (!atomic_read(&opinfo->breaking_cnt)) {
8175 rsp->hdr.Status = STATUS_UNSUCCESSFUL;
8179 /* check for bad lease state */
8180 if (req->LeaseState &
8181 (~(SMB2_LEASE_READ_CACHING_LE | SMB2_LEASE_HANDLE_CACHING_LE))) {
8182 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8183 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8184 lease_change_type = OPLOCK_WRITE_TO_NONE;
8186 lease_change_type = OPLOCK_READ_TO_NONE;
8187 ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8188 le32_to_cpu(lease->state),
8189 le32_to_cpu(req->LeaseState));
8190 } else if (lease->state == SMB2_LEASE_READ_CACHING_LE &&
8191 req->LeaseState != SMB2_LEASE_NONE_LE) {
8192 err = STATUS_INVALID_OPLOCK_PROTOCOL;
8193 lease_change_type = OPLOCK_READ_TO_NONE;
8194 ksmbd_debug(OPLOCK, "handle bad lease state 0x%x -> 0x%x\n",
8195 le32_to_cpu(lease->state),
8196 le32_to_cpu(req->LeaseState));
8198 /* valid lease state changes */
8199 err = STATUS_INVALID_DEVICE_STATE;
8200 if (req->LeaseState == SMB2_LEASE_NONE_LE) {
8201 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8202 lease_change_type = OPLOCK_WRITE_TO_NONE;
8204 lease_change_type = OPLOCK_READ_TO_NONE;
8205 } else if (req->LeaseState & SMB2_LEASE_READ_CACHING_LE) {
8206 if (lease->state & SMB2_LEASE_WRITE_CACHING_LE)
8207 lease_change_type = OPLOCK_WRITE_TO_READ;
8209 lease_change_type = OPLOCK_READ_HANDLE_TO_READ;
8211 lease_change_type = 0;
8215 switch (lease_change_type) {
8216 case OPLOCK_WRITE_TO_READ:
8217 ret = opinfo_write_to_read(opinfo);
8219 case OPLOCK_READ_HANDLE_TO_READ:
8220 ret = opinfo_read_handle_to_read(opinfo);
8222 case OPLOCK_WRITE_TO_NONE:
8223 ret = opinfo_write_to_none(opinfo);
8225 case OPLOCK_READ_TO_NONE:
8226 ret = opinfo_read_to_none(opinfo);
8229 ksmbd_debug(OPLOCK, "unknown lease change 0x%x -> 0x%x\n",
8230 le32_to_cpu(lease->state),
8231 le32_to_cpu(req->LeaseState));
8234 lease_state = lease->state;
8235 opinfo->op_state = OPLOCK_STATE_NONE;
8236 wake_up_interruptible_all(&opinfo->oplock_q);
8237 atomic_dec(&opinfo->breaking_cnt);
8238 wake_up_interruptible_all(&opinfo->oplock_brk);
8242 rsp->hdr.Status = err;
8246 rsp->StructureSize = cpu_to_le16(36);
8249 memcpy(rsp->LeaseKey, req->LeaseKey, 16);
8250 rsp->LeaseState = lease_state;
8251 rsp->LeaseDuration = 0;
8252 inc_rfc1001_len(work->response_buf, 36);
8256 opinfo->op_state = OPLOCK_STATE_NONE;
8257 wake_up_interruptible_all(&opinfo->oplock_q);
8258 atomic_dec(&opinfo->breaking_cnt);
8259 wake_up_interruptible_all(&opinfo->oplock_brk);
8262 smb2_set_err_rsp(work);
8266 * smb2_oplock_break() - dispatcher for smb2.0 and 2.1 oplock/lease break
8267 * @work: smb work containing oplock/lease break command buffer
8271 int smb2_oplock_break(struct ksmbd_work *work)
8273 struct smb2_oplock_break *req = smb2_get_msg(work->request_buf);
8274 struct smb2_oplock_break *rsp = smb2_get_msg(work->response_buf);
8276 switch (le16_to_cpu(req->StructureSize)) {
8277 case OP_BREAK_STRUCT_SIZE_20:
8278 smb20_oplock_break_ack(work);
8280 case OP_BREAK_STRUCT_SIZE_21:
8281 smb21_lease_break_ack(work);
8284 ksmbd_debug(OPLOCK, "invalid break cmd %d\n",
8285 le16_to_cpu(req->StructureSize));
8286 rsp->hdr.Status = STATUS_INVALID_PARAMETER;
8287 smb2_set_err_rsp(work);
8294 * smb2_notify() - handler for smb2 notify request
8295 * @work: smb work containing notify command buffer
8299 int smb2_notify(struct ksmbd_work *work)
8301 struct smb2_change_notify_req *req;
8302 struct smb2_change_notify_rsp *rsp;
8304 WORK_BUFFERS(work, req, rsp);
8306 if (work->next_smb2_rcv_hdr_off && req->hdr.NextCommand) {
8307 rsp->hdr.Status = STATUS_INTERNAL_ERROR;
8308 smb2_set_err_rsp(work);
8312 smb2_set_err_rsp(work);
8313 rsp->hdr.Status = STATUS_NOT_IMPLEMENTED;
8318 * smb2_is_sign_req() - handler for checking packet signing status
8319 * @work: smb work containing notify command buffer
8320 * @command: SMB2 command id
8322 * Return: true if packed is signed, false otherwise
8324 bool smb2_is_sign_req(struct ksmbd_work *work, unsigned int command)
8326 struct smb2_hdr *rcv_hdr2 = smb2_get_msg(work->request_buf);
8328 if ((rcv_hdr2->Flags & SMB2_FLAGS_SIGNED) &&
8329 command != SMB2_NEGOTIATE_HE &&
8330 command != SMB2_SESSION_SETUP_HE &&
8331 command != SMB2_OPLOCK_BREAK_HE)
8338 * smb2_check_sign_req() - handler for req packet sign processing
8339 * @work: smb work containing notify command buffer
8341 * Return: 1 on success, 0 otherwise
8343 int smb2_check_sign_req(struct ksmbd_work *work)
8345 struct smb2_hdr *hdr;
8346 char signature_req[SMB2_SIGNATURE_SIZE];
8347 char signature[SMB2_HMACSHA256_SIZE];
8351 hdr = smb2_get_msg(work->request_buf);
8352 if (work->next_smb2_rcv_hdr_off)
8353 hdr = ksmbd_req_buf_next(work);
8355 if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8356 len = get_rfc1002_len(work->request_buf);
8357 else if (hdr->NextCommand)
8358 len = le32_to_cpu(hdr->NextCommand);
8360 len = get_rfc1002_len(work->request_buf) -
8361 work->next_smb2_rcv_hdr_off;
8363 memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8364 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8366 iov[0].iov_base = (char *)&hdr->ProtocolId;
8367 iov[0].iov_len = len;
8369 if (ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, 1,
8373 if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8374 pr_err("bad smb2 signature\n");
8382 * smb2_set_sign_rsp() - handler for rsp packet sign processing
8383 * @work: smb work containing notify command buffer
8386 void smb2_set_sign_rsp(struct ksmbd_work *work)
8388 struct smb2_hdr *hdr;
8389 struct smb2_hdr *req_hdr;
8390 char signature[SMB2_HMACSHA256_SIZE];
8395 hdr = smb2_get_msg(work->response_buf);
8396 if (work->next_smb2_rsp_hdr_off)
8397 hdr = ksmbd_resp_buf_next(work);
8399 req_hdr = ksmbd_req_buf_next(work);
8401 if (!work->next_smb2_rsp_hdr_off) {
8402 len = get_rfc1002_len(work->response_buf);
8403 if (req_hdr->NextCommand)
8404 len = ALIGN(len, 8);
8406 len = get_rfc1002_len(work->response_buf) -
8407 work->next_smb2_rsp_hdr_off;
8408 len = ALIGN(len, 8);
8411 if (req_hdr->NextCommand)
8412 hdr->NextCommand = cpu_to_le32(len);
8414 hdr->Flags |= SMB2_FLAGS_SIGNED;
8415 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8417 iov[0].iov_base = (char *)&hdr->ProtocolId;
8418 iov[0].iov_len = len;
8420 if (work->aux_payload_sz) {
8421 iov[0].iov_len -= work->aux_payload_sz;
8423 iov[1].iov_base = work->aux_payload_buf;
8424 iov[1].iov_len = work->aux_payload_sz;
8428 if (!ksmbd_sign_smb2_pdu(work->conn, work->sess->sess_key, iov, n_vec,
8430 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
8434 * smb3_check_sign_req() - handler for req packet sign processing
8435 * @work: smb work containing notify command buffer
8437 * Return: 1 on success, 0 otherwise
8439 int smb3_check_sign_req(struct ksmbd_work *work)
8441 struct ksmbd_conn *conn = work->conn;
8443 struct smb2_hdr *hdr;
8444 struct channel *chann;
8445 char signature_req[SMB2_SIGNATURE_SIZE];
8446 char signature[SMB2_CMACAES_SIZE];
8450 hdr = smb2_get_msg(work->request_buf);
8451 if (work->next_smb2_rcv_hdr_off)
8452 hdr = ksmbd_req_buf_next(work);
8454 if (!hdr->NextCommand && !work->next_smb2_rcv_hdr_off)
8455 len = get_rfc1002_len(work->request_buf);
8456 else if (hdr->NextCommand)
8457 len = le32_to_cpu(hdr->NextCommand);
8459 len = get_rfc1002_len(work->request_buf) -
8460 work->next_smb2_rcv_hdr_off;
8462 if (le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8463 signing_key = work->sess->smb3signingkey;
8465 chann = lookup_chann_list(work->sess, conn);
8469 signing_key = chann->smb3signingkey;
8473 pr_err("SMB3 signing key is not generated\n");
8477 memcpy(signature_req, hdr->Signature, SMB2_SIGNATURE_SIZE);
8478 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8479 iov[0].iov_base = (char *)&hdr->ProtocolId;
8480 iov[0].iov_len = len;
8482 if (ksmbd_sign_smb3_pdu(conn, signing_key, iov, 1, signature))
8485 if (memcmp(signature, signature_req, SMB2_SIGNATURE_SIZE)) {
8486 pr_err("bad smb2 signature\n");
8494 * smb3_set_sign_rsp() - handler for rsp packet sign processing
8495 * @work: smb work containing notify command buffer
8498 void smb3_set_sign_rsp(struct ksmbd_work *work)
8500 struct ksmbd_conn *conn = work->conn;
8501 struct smb2_hdr *req_hdr, *hdr;
8502 struct channel *chann;
8503 char signature[SMB2_CMACAES_SIZE];
8509 hdr = smb2_get_msg(work->response_buf);
8510 if (work->next_smb2_rsp_hdr_off)
8511 hdr = ksmbd_resp_buf_next(work);
8513 req_hdr = ksmbd_req_buf_next(work);
8515 if (!work->next_smb2_rsp_hdr_off) {
8516 len = get_rfc1002_len(work->response_buf);
8517 if (req_hdr->NextCommand)
8518 len = ALIGN(len, 8);
8520 len = get_rfc1002_len(work->response_buf) -
8521 work->next_smb2_rsp_hdr_off;
8522 len = ALIGN(len, 8);
8525 if (conn->binding == false &&
8526 le16_to_cpu(hdr->Command) == SMB2_SESSION_SETUP_HE) {
8527 signing_key = work->sess->smb3signingkey;
8529 chann = lookup_chann_list(work->sess, work->conn);
8533 signing_key = chann->smb3signingkey;
8539 if (req_hdr->NextCommand)
8540 hdr->NextCommand = cpu_to_le32(len);
8542 hdr->Flags |= SMB2_FLAGS_SIGNED;
8543 memset(hdr->Signature, 0, SMB2_SIGNATURE_SIZE);
8544 iov[0].iov_base = (char *)&hdr->ProtocolId;
8545 iov[0].iov_len = len;
8546 if (work->aux_payload_sz) {
8547 iov[0].iov_len -= work->aux_payload_sz;
8548 iov[1].iov_base = work->aux_payload_buf;
8549 iov[1].iov_len = work->aux_payload_sz;
8553 if (!ksmbd_sign_smb3_pdu(conn, signing_key, iov, n_vec, signature))
8554 memcpy(hdr->Signature, signature, SMB2_SIGNATURE_SIZE);
8558 * smb3_preauth_hash_rsp() - handler for computing preauth hash on response
8559 * @work: smb work containing response buffer
8562 void smb3_preauth_hash_rsp(struct ksmbd_work *work)
8564 struct ksmbd_conn *conn = work->conn;
8565 struct ksmbd_session *sess = work->sess;
8566 struct smb2_hdr *req, *rsp;
8568 if (conn->dialect != SMB311_PROT_ID)
8571 WORK_BUFFERS(work, req, rsp);
8573 if (le16_to_cpu(req->Command) == SMB2_NEGOTIATE_HE &&
8575 ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
8576 conn->preauth_info->Preauth_HashValue);
8578 if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE && sess) {
8581 if (conn->binding) {
8582 struct preauth_session *preauth_sess;
8584 preauth_sess = ksmbd_preauth_session_lookup(conn, sess->id);
8587 hash_value = preauth_sess->Preauth_HashValue;
8589 hash_value = sess->Preauth_HashValue;
8593 ksmbd_gen_preauth_integrity_hash(conn, work->response_buf,
8598 static void fill_transform_hdr(void *tr_buf, char *old_buf, __le16 cipher_type)
8600 struct smb2_transform_hdr *tr_hdr = tr_buf + 4;
8601 struct smb2_hdr *hdr = smb2_get_msg(old_buf);
8602 unsigned int orig_len = get_rfc1002_len(old_buf);
8604 /* tr_buf must be cleared by the caller */
8605 tr_hdr->ProtocolId = SMB2_TRANSFORM_PROTO_NUM;
8606 tr_hdr->OriginalMessageSize = cpu_to_le32(orig_len);
8607 tr_hdr->Flags = cpu_to_le16(TRANSFORM_FLAG_ENCRYPTED);
8608 if (cipher_type == SMB2_ENCRYPTION_AES128_GCM ||
8609 cipher_type == SMB2_ENCRYPTION_AES256_GCM)
8610 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_GCM_NONCE);
8612 get_random_bytes(&tr_hdr->Nonce, SMB3_AES_CCM_NONCE);
8613 memcpy(&tr_hdr->SessionId, &hdr->SessionId, 8);
8614 inc_rfc1001_len(tr_buf, sizeof(struct smb2_transform_hdr));
8615 inc_rfc1001_len(tr_buf, orig_len);
8618 int smb3_encrypt_resp(struct ksmbd_work *work)
8620 char *buf = work->response_buf;
8623 int buf_size = 0, rq_nvec = 2 + (work->aux_payload_sz ? 1 : 0);
8625 if (ARRAY_SIZE(iov) < rq_nvec)
8628 work->tr_buf = kzalloc(sizeof(struct smb2_transform_hdr) + 4, GFP_KERNEL);
8632 /* fill transform header */
8633 fill_transform_hdr(work->tr_buf, buf, work->conn->cipher_type);
8635 iov[0].iov_base = work->tr_buf;
8636 iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
8637 buf_size += iov[0].iov_len - 4;
8639 iov[1].iov_base = buf + 4;
8640 iov[1].iov_len = get_rfc1002_len(buf);
8641 if (work->aux_payload_sz) {
8642 iov[1].iov_len = work->resp_hdr_sz - 4;
8644 iov[2].iov_base = work->aux_payload_buf;
8645 iov[2].iov_len = work->aux_payload_sz;
8646 buf_size += iov[2].iov_len;
8648 buf_size += iov[1].iov_len;
8649 work->resp_hdr_sz = iov[1].iov_len;
8651 rc = ksmbd_crypt_message(work, iov, rq_nvec, 1);
8655 memmove(buf, iov[1].iov_base, iov[1].iov_len);
8656 *(__be32 *)work->tr_buf = cpu_to_be32(buf_size);
8661 bool smb3_is_transform_hdr(void *buf)
8663 struct smb2_transform_hdr *trhdr = smb2_get_msg(buf);
8665 return trhdr->ProtocolId == SMB2_TRANSFORM_PROTO_NUM;
8668 int smb3_decrypt_req(struct ksmbd_work *work)
8670 struct ksmbd_session *sess;
8671 char *buf = work->request_buf;
8672 unsigned int pdu_length = get_rfc1002_len(buf);
8674 int buf_data_size = pdu_length - sizeof(struct smb2_transform_hdr);
8675 struct smb2_transform_hdr *tr_hdr = smb2_get_msg(buf);
8678 if (buf_data_size < sizeof(struct smb2_hdr)) {
8679 pr_err("Transform message is too small (%u)\n",
8681 return -ECONNABORTED;
8684 if (buf_data_size < le32_to_cpu(tr_hdr->OriginalMessageSize)) {
8685 pr_err("Transform message is broken\n");
8686 return -ECONNABORTED;
8689 sess = ksmbd_session_lookup_all(work->conn, le64_to_cpu(tr_hdr->SessionId));
8691 pr_err("invalid session id(%llx) in transform header\n",
8692 le64_to_cpu(tr_hdr->SessionId));
8693 return -ECONNABORTED;
8696 iov[0].iov_base = buf;
8697 iov[0].iov_len = sizeof(struct smb2_transform_hdr) + 4;
8698 iov[1].iov_base = buf + sizeof(struct smb2_transform_hdr) + 4;
8699 iov[1].iov_len = buf_data_size;
8700 rc = ksmbd_crypt_message(work, iov, 2, 0);
8704 memmove(buf + 4, iov[1].iov_base, buf_data_size);
8705 *(__be32 *)buf = cpu_to_be32(buf_data_size);
8710 bool smb3_11_final_sess_setup_resp(struct ksmbd_work *work)
8712 struct ksmbd_conn *conn = work->conn;
8713 struct ksmbd_session *sess = work->sess;
8714 struct smb2_hdr *rsp = smb2_get_msg(work->response_buf);
8716 if (conn->dialect < SMB30_PROT_ID)
8719 if (work->next_smb2_rcv_hdr_off)
8720 rsp = ksmbd_resp_buf_next(work);
8722 if (le16_to_cpu(rsp->Command) == SMB2_SESSION_SETUP_HE &&
8723 sess->user && !user_guest(sess->user) &&
8724 rsp->Status == STATUS_SUCCESS)